~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

An example app, Kicker, runs against this host in examples/kicker

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:examples/kicker
docs/design/README.md+1−0
@@ -51,6 +51,7 @@ accounts on their own PDSes, anywhere on the network.
| `packages/sdk` | `@opensocial/sdk`, for apps on group hosts: a group's spaces read and written with atproto's lex-space, and the host's own methods, as a member ([the SDK](../reference/sdk.md)) |
| `Dockerfile`, `deploy/` | one image of the host, the console and the command, and the compose file that runs it ([deploying](../deploying.md)) |
| `lexicons/` | the schemas of the records and methods. The host checks every `fyi.opensocial.*` method's parameters and input against its schema before the handler runs. It also checks a record of our own collections that an app writes as a group before it keeps it. |
| `examples/` | apps built on a group host, run against this repository's host. `examples/kicker` is a skate club's members-only site, published as its group's site, with no server of its own. |
## The pages
examples/kicker/harness/e2e/flows.spec.mjsnew+261−0
@@ -0,0 +1,261 @@
// The site as people use it, with nothing but the group host behind it:
// each signs in on it with OAuth at their own PDS, granting the writes the
// site declares, and each write here is made at their PDS, in their own
// repo in the place's spaces, and read back through the host.
import { test, expect } from '@playwright/test';
import { portrait, poster } from '../posters.mjs';
import { serviceAuth } from '../world.mjs';
const world = JSON.parse(process.env.E2E_WORLD);
const who = Object.fromEntries(world.accounts.map((a) => [a.handle.split('.')[0], a]));
test.describe.configure({ mode: 'serial' });
/// How wide the picture `img` was drawn, once loaded: 0 until it is.
const drawn = (img) => img.evaluate((el) => (el.complete ? el.naturalWidth : 0)).catch(() => 0);
/// `page` signed in on the site as `name`, with the host's dialog, at
/// their own PDS, approving what the site asks.
const signIn = async (page, name) => {
await page.goto(world.site);
const site = page.frameLocator('#os-page');
await site.getByRole('button', { name: 'Sign in' }).click();
const dialog = page.getByRole('dialog', { name: 'Sign in with your Atmosphere account' });
await dialog.getByLabel('Handle').fill(who[name].handle);
await dialog.getByRole('button', { name: 'Sign in' }).click();
await page.waitForURL((u) => u.origin === new URL(world.pds).origin);
await page.getByRole('textbox', { name: 'Password' }).fill(who[name].password);
await page.getByRole('button', { name: 'Sign in' }).click();
await page.getByRole('button', { name: /^(accept|authorize|allow)$/i }).click();
await page.waitForURL((u) => u.origin === new URL(world.site).origin);
await expect(site.getByRole('button', { name: 'Sign out' })).toBeVisible();
return site;
};
test('signed out, the place shows its landing, and the way in', async ({ page }) => {
await page.goto(world.site);
const site = page.frameLocator('#os-page');
await expect(site.getByText('214 Lantern Alley')).toBeVisible();
await expect(site.getByRole('button', { name: 'Sign in' })).toBeVisible();
await expect(site.getByRole('link', { name: 'Events' })).toHaveCount(0);
await expect(page).toHaveTitle('Board');
});
test('someone asking to join is not let in yet', async ({ page }) => {
const site = await signIn(page, 'erin');
await expect(site.getByText('Not a member yet')).toBeVisible();
await expect(site.getByText('@erin.test')).toBeVisible();
await expect(site.getByRole('link', { name: 'Events' })).toHaveCount(0);
});
test('a member pins a note, answers an event and writes her card', async ({ page }) => {
const site = await signIn(page, 'dan');
await expect(site.getByText("Beginners' Sunday is back")).toBeVisible();
await site.getByRole('button', { name: 'Pin a note' }).click();
const pinning = site.getByRole('dialog', { name: 'Pin a note' });
await pinning.getByLabel('Note').fill('Spare bolts live in the second drawer.');
await pinning.getByRole('button', { name: 'Pin', exact: true }).click();
await expect(pinning).toBeHidden();
await expect(site.getByText('Spare bolts live in the second drawer.')).toBeVisible();
// Moving between rooms keeps the page: the app switches the room in
// place, loading nothing again.
const app = page.frames().find((f) => f.url().includes('/_site/'));
await app.evaluate(() => (window.stayed = true));
await site.getByRole('link', { name: 'Events' }).click();
await expect(page).toHaveTitle('Events');
await expect(page).toHaveURL(/\/events\/$/);
expect(await app.evaluate(() => window.stayed)).toBe(true);
// A member, no host, has no way to publish one.
await expect(site.getByRole('button', { name: 'New event' })).toHaveCount(0);
// Its poster, from its host's PDS through the place's host, is drawn.
const card = site.locator('li', { hasText: 'Curb jam' });
await expect.poll(() => drawn(card.getByRole('img'))).toBeGreaterThan(0);
await card.getByRole('button').click();
const jam = site.getByRole('dialog', { name: 'Event' });
await expect(jam.getByRole('heading', { name: 'Curb jam' })).toBeVisible();
await expect(jam.getByRole('img', { name: /A poster for Curb jam/ })).toBeVisible();
await jam.getByRole('button', { name: 'Going' }).click();
await expect(jam.getByRole('button', { name: 'Going' })).toHaveAttribute('aria-pressed', 'true');
await expect(jam).toContainText('@dan.test');
await jam.getByRole('button', { name: 'Close' }).click();
await expect(jam).toBeHidden();
await site.getByRole('link', { name: 'People' }).click();
await site.getByRole('button', { name: 'Edit your card' }).click();
const editing = site.getByRole('dialog', { name: 'Edit your card' });
await editing.getByLabel('About').fill('Mostly curbs, some bowls.');
// A picture on it, uploaded to dan's own PDS and read back through the host.
await editing.getByLabel('Your picture').setInputFiles({
name: 'dan.svg',
mimeType: 'image/svg+xml',
buffer: Buffer.from(portrait('dan', 'pink', 'blue'))
});
await editing.getByRole('button', { name: 'Save' }).click();
await expect(editing).toBeHidden();
const dan = site.locator('.rows li', { hasText: '@dan.test' });
await expect(dan).toContainText('Mostly curbs, some bowls.');
await expect.poll(() => drawn(dan.locator('img'))).toBeGreaterThan(0);
// Its words changed again, its picture stays; taken off, it is gone.
await site.getByRole('button', { name: 'Edit your card' }).click();
await editing.getByLabel('About').fill('Curbs, bowls, and filming.');
await editing.getByRole('button', { name: 'Save' }).click();
await expect(dan).toContainText('Curbs, bowls, and filming.');
await expect.poll(() => drawn(dan.locator('img'))).toBeGreaterThan(0);
await site.getByRole('button', { name: 'Edit your card' }).click();
await editing.getByLabel('Take my picture off').check();
await editing.getByRole('button', { name: 'Save' }).click();
await expect(editing).toBeHidden();
await expect(dan.locator('img')).toHaveCount(0);
});
test('a host publishes an event', async ({ page }) => {
const site = await signIn(page, 'bob');
await site.getByRole('link', { name: 'Events' }).click();
await site.getByRole('button', { name: 'New event' }).click();
const making = site.getByRole('dialog', { name: 'New event' });
await making.getByLabel('Name').fill('Bowl day');
await making.getByLabel('Starts').fill('2099-05-01T18:00');
// Its poster, uploaded to bob's own PDS with the event.
await making.getByLabel('Poster or photo').setInputFiles({
name: 'bowl.svg',
mimeType: 'image/svg+xml',
buffer: Buffer.from(poster('Bowl day', 'teal', 'pink'))
});
await making.getByLabel('What it shows').fill('A poster for bowl day.');
await making.getByRole('button', { name: 'Publish' }).click();
await expect(making).toBeHidden();
const card = site.locator('li', { hasText: 'Bowl day' });
await expect(card.getByRole('img', { name: 'A poster for bowl day.' })).toBeVisible();
await expect.poll(() => drawn(card.getByRole('img'))).toBeGreaterThan(0);
});
test('a member reads a discussion, and replies to a reply in it', async ({ page }) => {
const site = await signIn(page, 'dan');
await site.getByRole('link', { name: 'Discussion' }).click();
await expect(page).toHaveTitle('Discussion');
// Each with how many replies it has, all counted in one read.
const ramp = site.locator('li.topic', { hasText: 'Should we build a mini ramp' });
await expect(ramp).toContainText('3 replies');
await expect(site.locator('li.topic', { hasText: 'A video night' })).toContainText('2 replies');
// The most lately active first: the video night's replies came last.
await expect(site.locator('li.topic').first()).toContainText('A video night');
await ramp.getByRole('link').click();
await expect(page).toHaveTitle('Should we build a mini ramp in the back lot?');
await expect(page).toHaveURL(/\/discussion\/did:[^/]+\/[^/]+$/);
await expect(site.getByRole('heading', { name: '3 replies' })).toBeVisible();
// Oldest first, each under what it answers: bob's under dan's, alice's not.
const fund = site.locator('li.reply', { hasText: 'twenty for plywood' });
await expect(fund).toContainText('coping from my old ramp');
await expect(fund).not.toContainText('Thursday');
const coping = site.locator('li.reply', { hasText: 'coping from my old ramp' }).last();
await coping.getByRole('button', { name: 'Reply' }).click();
await coping.getByLabel('Your reply').fill('Count me in for Sunday.');
await coping.locator('.reply-form').getByRole('button', { name: 'Reply' }).click();
await expect(coping.locator('li.reply', { hasText: 'Count me in' })).toBeVisible();
await expect(site.getByRole('heading', { name: '4 replies' })).toBeVisible();
await site.getByRole('link', { name: 'All discussions' }).click();
await expect(ramp).toContainText('4 replies');
// Replied to, it is the most lately active now, the last reply just now.
await expect(site.locator('li.topic').first()).toContainText('Should we build a mini ramp');
await expect(ramp).toContainText('last reply just now');
});
test('a member starts a discussion', async ({ page }) => {
const site = await signIn(page, 'carol');
await site.getByRole('link', { name: 'Discussion' }).click();
await site.getByRole('button', { name: 'Start a discussion' }).click();
const starting = site.getByRole('dialog', { name: 'Start a discussion' });
await starting.getByLabel('What about').fill('Who has a key for the side door?');
await starting.getByRole('button', { name: 'Start' }).click();
await expect(starting).toBeHidden();
const started = site.locator('li.topic', { hasText: 'Who has a key for the side door?' });
await expect(started).toContainText('No replies yet');
});
/// `lxm` of the group host, asked as alice, who moderates the place.
const asAlice = async (lxm, params) => {
const token = await serviceAuth(world.pds, who.alice, world.hostDid, lxm);
const query = new URLSearchParams({ group: world.place, ...params });
const res = await fetch(`${world.host}/xrpc/${lxm}?${query}`, {
headers: { authorization: `Bearer ${token}` }
});
return await res.json();
};
/// The URI of the note on the board whose words begin `text`.
const noteUri = async (text) => {
const space = `at://${world.place}/space/com.example.place.room/self`;
const collection = 'com.example.place.note';
const { records } = await asAlice('fyi.opensocial.listSpaceRecords', { space, collection });
return records.find((r) => r.value.text.startsWith(text)).uri;
};
/// What the group host's queue holds of `uri`, of the subjects `status`.
const queued = async (uri, status = 'open') => {
const { subjects } = await asAlice('fyi.opensocial.listSubjects', { status });
return subjects.find((s) => s.subject.uri === uri);
};
test("a member reports a note, into the group host's queue", async ({ page }) => {
const site = await signIn(page, 'carol');
const bolts = site.locator('li.note', { hasText: 'Spare bolts live in the second drawer.' });
await bolts.getByRole('button', { name: 'What to do with this note' }).click();
await site.getByRole('menuitem', { name: 'Report' }).click();
const reporting = site.getByRole('dialog', { name: 'Report this note' });
await reporting.getByLabel('Why').selectOption({ label: 'Spam' });
await reporting.getByLabel('In your words').fill('Is this an ad?');
await reporting.getByRole('button', { name: 'Report' }).click();
await expect(reporting.getByText('Sent to the moderators.')).toBeVisible();
// The way to the console is a moderator's alone.
await expect(reporting.getByRole('link', { name: 'Review it in the console' })).toHaveCount(0);
await reporting.getByRole('button', { name: 'Done' }).click();
const reported = await queued(await noteUri('Spare bolts live'));
expect(reported?.reportCount).toBe(1);
});
test('a note the moderators marked is folded, and one they hid is gone', async ({ page }) => {
const site = await signIn(page, 'dan');
const bike = site.locator('li.note', { hasText: 'Marked by the moderators' });
await expect(bike).toContainText('Off-topic');
await expect(bike).not.toContainText('road bike');
await bike.getByRole('button', { name: 'Show it' }).click();
await expect(bike).toContainText('Selling my old road bike');
// Hidden, it is not on the board at all, nor any sign it was.
await expect(site.getByText('Cheap bearings')).toHaveCount(0);
await expect(site.getByText(/hidden/i)).toHaveCount(0);
});
test('its author appeals, and a moderator reviews it in the console', async ({ page }) => {
const uri = await noteUri('Selling my old road bike');
expect(await queued(uri, 'resolved')).toBeTruthy();
let site = await signIn(page, 'carol');
const bike = site.locator('li.note', { hasText: 'Selling my old road bike' });
await expect(bike).toContainText('Off-topic');
await bike.getByRole('button', { name: 'What to do with this note' }).click();
await site.getByRole('menuitem', { name: 'Appeal' }).click();
const appealing = site.getByRole('dialog', { name: 'Appeal' });
await appealing.getByLabel('Your appeal').fill('Plenty of us ride here; it is a fair offer.');
await appealing.getByRole('button', { name: 'Send' }).click();
await expect(appealing.getByText('Sent.')).toBeVisible();
await appealing.getByRole('button', { name: 'Done' }).click();
// The appeal opened it again, in front of the moderators.
expect(await queued(uri)).toBeTruthy();
await site.getByRole('button', { name: 'Sign out' }).click();
await expect(site.getByRole('button', { name: 'Sign in' })).toBeVisible();
site = await signIn(page, 'alice');
const marked = site.locator('li.note', { hasText: 'Selling my old road bike' });
await marked.getByRole('button', { name: 'What to do with this note' }).click();
await expect(site.getByRole('menuitem', { name: 'Review in the console' })).toHaveAttribute(
'href',
`${world.console}/g/kicker.groups.test/moderation?review=${encodeURIComponent(uri)}`
);
// A moderator sees what is hidden from members, and that it is.
const ink = site.locator('li.note', { hasText: 'Cheap bearings' });
await expect(ink).toContainText('Hidden from members by the moderators.');
});
examples/kicker/harness/e2e/playwright.config.mjsnew+36−0
@@ -0,0 +1,36 @@
// The site used as people use it: signed in on it with OAuth at their own
// PDS, through the page the group host serves around it, end to end.
//
// just e2e a world of its own, the place made in it, and the flows
//
// The flows go in order in one worker, each going on from where the one
// before left the world.
import { defineConfig } from '@playwright/test';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { resolving } from '../world.mjs';
const root = resolve(fileURLToPath(new URL('.', import.meta.url)), '../..');
export default defineConfig({
testDir: '.',
testMatch: 'flows.spec.mjs',
globalSetup: './setup.mjs',
outputDir: join(root, 'target/e2e/results'),
workers: 1,
timeout: 60_000,
expect: { timeout: 15_000 },
reporter: [['list']],
use: {
browserName: 'chromium',
viewport: { width: 1280, height: 800 },
locale: 'en-US',
// The site is reached as the PDS reaches it: over https, at a name
// beside the console's, with the harness's own certificate.
ignoreHTTPSErrors: true,
launchOptions: { args: [resolving] },
trace: 'retain-on-failure',
screenshot: 'only-on-failure'
}
});
examples/kicker/harness/e2e/setup.mjsnew+34−0
@@ -0,0 +1,34 @@
// Before the flows: a world (../world.mjs), the place made in it
// (../seed.mjs), and its site behind an https front at a name beside the
// console's, as the PDS reaches it to read the site's OAuth client. Where
// everything is goes to the flows in E2E_WORLD. Returns the teardown.
import { siteFront, start, tlsFront } from '../world.mjs';
import { seed } from '../seed.mjs';
export default async function setup() {
const w = await start({
accounts: ['alice', 'bob', 'carol', 'dan', 'erin'],
front: tlsFront
});
try {
const { place, handle } = await seed(w);
const site = await siteFront(w.net, new URL(w.host).port, 'kicker.group-host.internal', handle);
process.env.E2E_WORLD = JSON.stringify({
pds: w.net.pds,
host: w.host,
hostDid: w.did,
console: w.base,
place,
accounts: w.net.accounts,
site: site.url
});
return () => {
site.proxy.kill('SIGTERM');
w.stop();
};
} catch (e) {
w.stop();
throw e;
}
}
examples/kicker/harness/bootstrap.shnew+75−0
@@ -0,0 +1,75 @@
#!/usr/bin/env bash
# `just bootstrap`: everything the site's world runs beside it.
#
# .deps/atproto the spaces alpha's dev-env (the reference PDS with spaces),
# at the commit group-host's CI tests against
# (harness/alpha.sh), kept out of git
#
# Then the packages: the group host's console and the SDK it builds on, the
# site's, and the harness's. The group host itself is this repository,
# built by `just host` before each world. The dev-env is built once, and
# again only when alpha.sh's commit changes. ATPROTO_DEV_ENV, set, names a
# built dev-env to use instead of building one (another checkout's .deps, say).
#
# Needs git, Rust (rustup), and Node at .node-version's version with corepack.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
REPO="$(cd "$ROOT/../.." && pwd)"
DEPS="${KICKER_DEPS:-$ROOT/.deps}"
say() { printf '\n== %s\n' "$*"; }
fail() { printf 'bootstrap: %s\n' "$*" >&2; exit 1; }
need() { command -v "$1" >/dev/null || fail "$1 is needed: $2"; }
# The space alpha group-host's CI tests against.
ATPROTO_COMMIT="$(sed -n 's/^ATPROTO_COMMIT=//p' "$REPO/harness/alpha.sh")"
[ -n "$ATPROTO_COMMIT" ] || fail "no ATPROTO_COMMIT in $REPO/harness/alpha.sh"
need git "https://git-scm.com"
need rustup "https://rustup.rs"
need node "Node $(cat "$REPO/.node-version")"
need corepack "it comes with Node"
[ "$(node -p 'process.versions.node')" = "$(cat "$REPO/.node-version")" ] ||
fail "Node $(cat "$REPO/.node-version") is needed, not $(node -p 'process.versions.node')"
if [ -n "${ATPROTO_DEV_ENV:-}" ]; then
say "the spaces alpha's dev-env, from $ATPROTO_DEV_ENV"
else
say "the spaces alpha's dev-env, at ${ATPROTO_COMMIT:0:7}"
A="$DEPS/atproto"
if [ "$(cat "$A/.built" 2>/dev/null)" = "$ATPROTO_COMMIT" ]; then echo "built already"; else
if [ ! -d "$A/.git" ]; then
mkdir -p "$A"
git -C "$A" init -q
git -C "$A" remote add origin https://github.com/bluesky-social/atproto.git
fi
git -C "$A" fetch -q --depth 1 origin "$ATPROTO_COMMIT" 2>/dev/null || git -C "$A" fetch -q origin
git -C "$A" checkout -q --force "$ATPROTO_COMMIT"
git -C "$A" clean -qfd
(
cd "$A"
export COREPACK_ENABLE_DOWNLOAD_PROMPT=0
corepack pnpm install --frozen-lockfile --ignore-scripts
corepack pnpm run build:tooling --force
corepack pnpm --filter '@atproto/dev-env^...' --filter @atproto/dev-env run --if-present prebuild
corepack pnpm exec tsc --build packages/dev-env/tsconfig.build.json
# The PDS serves its sign-in pages from this bundle, and will not start without it.
corepack pnpm --filter @atproto/oauth-provider-ui run build:ui
# SQLite's native module, which the install above skips building.
sqlite="$(dirname "$(node -p "require.resolve('better-sqlite3/package.json', { paths: ['$A/packages/pds'] })")")"
[ -f "$sqlite/build/Release/better_sqlite3.node" ] || (cd "$sqlite" && npm run install)
)
echo "$ATPROTO_COMMIT" >"$A/.built"
fi
fi
say "the packages: the console's, the SDK's, the site's and the harness's"
(cd "$REPO/packages/sdk" && npm ci --no-audit --no-fund)
(cd "$REPO/web" && npm ci --no-audit --no-fund)
(cd "$ROOT/site" && npm ci --no-audit --no-fund)
(cd "$ROOT/harness" && npm ci --no-audit --no-fund)
say "done"
echo "Run the site with \`just dev\`, its flows with \`just e2e\`."
examples/kicker/harness/dev.mjsnew+82−0
@@ -0,0 +1,82 @@
// `just dev`: the site to use by hand, over a world of its own (world.mjs):
// the reference PDS with alice to erin, the group host and its console,
// and the place made in it (seed.mjs). Places are named under
// places.localtest.me, so Kicker's address, where its site is, opens in
// a browser: https://kicker.places.localtest.me. Stops on ctrl-c, and
// forgets everything.
//
// The site is an OAuth client of the PDS, which fetches its metadata from
// an https name the browser trusts: portless gives both
// (https://github.com/vercel-labs/portless), its proxy on port 443 for
// every name under localtest.me, with a local CA the PDS is told to trust.
import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { root, start } from './world.mjs';
import { seed } from './seed.mjs';
const DOMAIN = 'localtest.me';
/// The console's name, and the one places are named under: its wildcard
/// sends each place's address to the host, as a deployment's does.
const [CONSOLE, PLACES] = ['places-console', 'places'];
const portless = join(root, 'harness/node_modules/.bin/portless');
const state = process.env.PORTLESS_STATE_DIR ?? join(homedir(), '.portless');
const port = (() => {
try {
return readFileSync(join(state, 'proxy.port'), 'utf8').trim();
} catch {
return '';
}
})();
if (port !== '443') {
console.error(`portless's https proxy is not on port 443. Start it, once a boot (it asks for your password):
cd harness && PORTLESS_TLD=localhost,${DOMAIN} PORTLESS_WILDCARD=1 PORTLESS_SYNC_HOSTS=0 npx portless proxy start -p 443
and \`npx portless trust\` once, if your browser does not trust its certificate.`);
process.exit(1);
}
const alias = (name, port) =>
execFileSync(portless, ['alias', name, String(port), '--force'], { stdio: 'ignore' });
const handleDomain = `.${PLACES}.${DOMAIN}`;
const w = await start({
accounts: ['alice', 'bob', 'carol', 'dan', 'erin'],
front: async (consolePort) => (alias(CONSOLE, consolePort), `https://${CONSOLE}.${DOMAIN}`),
pdsEnv: { NODE_EXTRA_CA_CERTS: join(state, 'ca.pem') },
handleDomain
});
alias(PLACES, new URL(w.host).port);
const stop = () => {
try {
for (const name of [CONSOLE, PLACES])
execFileSync(portless, ['alias', '--remove', name], { stdio: 'ignore' });
} finally {
w.stop();
process.exit(0);
}
};
process.on('SIGINT', stop);
process.on('SIGTERM', stop);
try {
const { handle } = await seed(w, { handleDomain });
const people = w.net.accounts.map((a) => ` ${a.handle.padEnd(12)} ${a.password}`).join('\n');
console.log(`
The site https://${handle}
The console ${w.base} (the group host's)
The host ${w.host} (${w.did})
The PDS ${w.net.pds}
Sign in on the site as any of them, at the PDS's own page:
${people}
alice runs Kicker; bob hosts its events; carol and dan are members;
erin is asking to join, which alice approves in the console.
ctrl-c stops it all.`);
} catch (e) {
console.error(e);
stop();
}
examples/kicker/harness/layers.mjsnew+43−0
@@ -0,0 +1,43 @@
// The site's components' layers, atomic design's: atoms, molecules built of
// atoms, organisms of those, and templates laying organisms out. A
// component uses its own layer and those below it, never one above, so
// each layer can be understood, and changed, knowing only what is under it.
// The rooms (site/src/rooms) fill the template, and may use any of them.
//
// node harness/layers.mjs
//
// Prints each import that reaches up as `file:line: what`, failing if any.
import { readdirSync, readFileSync } from 'node:fs';
import { dirname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const lib = join(root, 'site/src/lib');
const layers = ['atoms', 'molecules', 'organisms', 'templates'];
const files = (d) =>
readdirSync(d, { withFileTypes: true }).flatMap((e) =>
e.isDirectory() ? files(join(d, e.name)) : [join(d, e.name)]
);
const problems = [];
for (const [rank, layer] of layers.entries()) {
for (const file of files(join(lib, layer))) {
const lines = readFileSync(file, 'utf8').split('\n');
lines.forEach((line, i) => {
for (const [, path] of line.matchAll(/(?:from|import)\s+['"]([^'"]+)['"]/g)) {
if (!path.startsWith('.')) continue;
const used = layers.indexOf(relative(lib, resolve(dirname(file), path)).split('/')[0]);
if (used > rank)
problems.push(
`${relative(root, file)}:${i + 1}: ${layer} use only ${layers.slice(0, rank + 1).join(', ')}, not ${layers[used]}`
);
}
});
}
}
for (const p of problems) console.log(p);
if (problems.length) process.exit(1);
console.log(`site: ${layers.join(' < ')}, each using only its own layer and those below`);
examples/kicker/harness/look.mjsnew+102−0
@@ -0,0 +1,102 @@
// `just look`: the site's pages as pictures in target/look, signed in as
// `--as` (a handle's first label, alice by default), over a world of their
// own with the place made in it: desktop in light, phone in dark.
//
// node harness/look.mjs [--as alice]
import { chromium } from '@playwright/test';
import { mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { resolving, root, siteFront, start, tlsFront } from './world.mjs';
import { seed } from './seed.mjs';
const at = process.argv.indexOf('--as');
const name = at === -1 ? 'alice' : process.argv[at + 1];
const out = join(root, 'target/look');
mkdirSync(out, { recursive: true });
const w = await start({ accounts: ['alice', 'bob', 'carol', 'dan', 'erin'], front: tlsFront });
try {
const { handle } = await seed(w);
const site = await siteFront(w.net, new URL(w.host).port, 'kicker.group-host.internal', handle);
w.stop.proxy = site.proxy;
const account = w.net.accounts.find((a) => a.handle.startsWith(`${name}.`));
const browser = await chromium.launch({ args: [resolving] });
for (const [view, options] of [
['desktop-light', { viewport: { width: 1200, height: 900 }, colorScheme: 'light' }],
['phone-dark', { viewport: { width: 390, height: 844 }, colorScheme: 'dark', isMobile: true }]
]) {
const page = await (
await browser.newContext({ ...options, ignoreHTTPSErrors: true })
).newPage();
await page.goto(site.url);
const frame = page.frameLocator('#os-page');
// The landing, as anyone signed out sees it.
await frame.getByRole('button', { name: 'Sign in' }).waitFor();
await page.waitForTimeout(300);
const landing = join(out, `landing-${view}.png`);
await page.screenshot({ path: landing });
console.log(landing);
await frame.getByRole('button', { name: 'Sign in' }).click();
const dialog = page.getByRole('dialog', { name: 'Sign in with your Atmosphere account' });
await dialog.getByLabel('Handle').fill(account.handle);
await dialog.getByRole('button', { name: 'Sign in' }).click();
await page.waitForURL((u) => u.origin === new URL(w.net.pds).origin);
await page.getByRole('textbox', { name: 'Password' }).fill(account.password);
await page.getByRole('button', { name: 'Sign in' }).click();
await page.getByRole('button', { name: /^(accept|authorize|allow)$/i }).click();
await page.waitForURL((u) => u.origin === new URL(site.url).origin);
await frame.getByRole('button', { name: 'Sign out' }).waitFor();
// Each room whole, then a discussion opened from its list.
const whole = async (file, ready) => {
await ready();
await page.waitForTimeout(300);
// The frame fills the window; its page scrolls inside it.
const height = await frame.locator('body').evaluate((b) => b.scrollHeight);
await page.setViewportSize({
width: options.viewport.width,
height: Math.max(height, options.viewport.height)
});
await page.screenshot({ path: file });
await page.setViewportSize(options.viewport);
console.log(file);
};
for (const path of ['', 'events/', 'discussion/', 'people/']) {
await page.goto(`${site.url}/${path}`);
const file = join(out, `${path.replace('/', '') || 'board'}-as-${name}-${view}.png`);
await whole(file, () => frame.locator('h1').waitFor());
}
await page.goto(`${site.url}/discussion/`);
await frame.getByRole('link', { name: 'Should we build a mini ramp in the back lot?' }).click();
await whole(join(out, `thread-as-${name}-${view}.png`), () =>
frame.locator('li.reply').first().waitFor()
);
// The dialogs, as seen: an event opened, and pinning a note.
for (const [path, open, shot] of [
['events/', () => frame.locator('li', { hasText: 'Curb jam' }).getByRole('button'), 'event'],
['', () => frame.getByRole('button', { name: 'Pin a note' }), 'pin']
]) {
await page.goto(`${site.url}/${path}`);
await frame.locator('h1').waitFor();
await open().click();
await frame.locator('dialog[open]').waitFor();
await page.waitForTimeout(300);
const file = join(out, `${shot}-dialog-as-${name}-${view}.png`);
await page.screenshot({ path: file });
console.log(file);
}
// A note's menu, opened: the off-topic one, which every view has.
await page.goto(site.url);
const marked = frame.locator('li.note', { hasText: 'Off-topic' });
await marked.getByRole('button', { name: 'What to do with this note' }).click();
await frame.getByRole('menu').waitFor();
const menu = join(out, `menu-as-${name}-${view}.png`);
await page.screenshot({ path: menu });
console.log(menu);
}
await browser.close();
site.proxy.kill('SIGTERM');
} finally {
w.stop();
}
process.exit(0);
examples/kicker/harness/package-lock.jsonnew+9506−0
A large diff, not shown.
examples/kicker/harness/package.jsonnew+13−0
@@ -0,0 +1,13 @@
{
"name": "kicker-harness",
"private": true,
"description": "The world the site runs in, the reference PDS and PLC and a group host, and its flows",
"type": "module",
"dependencies": {
"@atproto/dev-env": "0.6.26"
},
"devDependencies": {
"@playwright/test": "1.58.2",
"portless": "0.15.7"
}
}
examples/kicker/harness/pds.mjsnew+214−0
@@ -0,0 +1,214 @@
// Runs the reference PDS (@atproto/pds, through @atproto/dev-env) and a PLC
// directory on free ports, makes test accounts, prints one JSON line naming
// them (and where the codes the PDS mails are read), and stops when stdin
// closes.
//
// node harness/pds.mjs [--accounts alice,bob]
//
// ATPROTO_DEV_ENV names a built dev-env package to run: an atproto
// checkout's packages/dev-env on the spaces alpha, as `just bootstrap`
// builds it into .deps/atproto, which is taken where ATPROTO_DEV_ENV is not
// set. The alpha's PDS migrates an account's database each time it opens
// it; here only the first time.
//
// The console is an OAuth client, which the PDS reaches only over https at a
// hostname. So the harness makes a certificate for CONSOLE_HOST, trusts it,
// and resolves that name to 127.0.0.1; the flows put harness/tls-proxy.mjs
// in front of the console with it.
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { existsSync, mkdtempSync, readFileSync, realpathSync } from 'node:fs';
import { createRequire } from 'node:module';
import { AsyncLocalStorage } from 'node:async_hooks';
import { execFileSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import dns from 'node:dns';
import tls from 'node:tls';
import http from 'node:http';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
/// The group host this example sits in.
const groupHost = resolve(root, '../..');
// The PDS's better-sqlite3 is built for the Node the repository's .node-version names.
const pinned = readFileSync(join(groupHost, '.node-version'), 'utf8').trim();
if (process.versions.node.split('.')[0] !== pinned.split('.')[0]) {
console.error(
`harness/pds.mjs runs on Node ${pinned}, as .node-version says, not ${process.version}`
);
process.exit(1);
}
const bootstrapped = join(root, '.deps/atproto/packages/dev-env');
const devEnv =
process.env.ATPROTO_DEV_ENV ??
(existsSync(join(bootstrapped, 'dist')) ? bootstrapped : undefined);
const { TestNetworkNoAppView } = await import(
devEnv ? pathToFileURL(resolve(root, devEnv, 'dist/index.js')).href : '@atproto/dev-env'
);
if (devEnv) await migrateOnce(resolve(root, devEnv));
/// Has the dev-env's PDS migrate each account's database on its first
/// opening alone, rather than on every one.
async function migrateOnce(dir) {
const index = createRequire(join(dir, 'package.json')).resolve('@atproto/pds');
const dist = dirname(realpathSync(index));
const load = (file) => import(pathToFileURL(join(dist, file)).href);
const { ActorStore } = await load('actor-store/actor-store.js');
const { Migrator } = await load('db/migrator.js');
const opened = new Set();
const again = new AsyncLocalStorage();
const open = ActorStore.prototype.openDb;
ActorStore.prototype.openDb = async function (did) {
const { dbLocation } = await this.getLocation(did);
const db = await again.run(opened.has(dbLocation), () => open.call(this, did));
opened.add(dbLocation);
return db;
};
const migrate = Migrator.prototype.migrateToLatestOrThrow;
Migrator.prototype.migrateToLatestOrThrow = function () {
return again.getStore() ? Promise.resolve([]) : migrate.call(this);
};
}
const CONSOLE_HOST = 'console.group-host.internal';
// Names beside it, as a group's site is reached in harness/e2e: the PDS
// fetches a site's OAuth client there.
const BESIDE = '.group-host.internal';
const certs = mkdtempSync(join(tmpdir(), 'group-host-tls-'));
const cert = join(certs, 'cert.pem');
const key = join(certs, 'key.pem');
execFileSync(
'openssl',
[
'req',
'-x509',
'-newkey',
'ec',
'-pkeyopt',
'ec_paramgen_curve:prime256v1',
'-nodes',
'-keyout',
key,
'-out',
cert,
'-days',
'7',
'-subj',
`/CN=${CONSOLE_HOST}`,
'-addext',
`subjectAltName=DNS:${CONSOLE_HOST},DNS:*${BESIDE}`
],
{ stdio: 'ignore' }
);
tls.setDefaultCACertificates([...tls.getCACertificates('default'), readFileSync(cert, 'utf8')]);
const lookup = dns.lookup;
dns.lookup = (hostname, options, callback) => {
if (typeof options === 'function') [callback, options] = [options, {}];
if (!hostname.endsWith(BESIDE)) return lookup(hostname, options, callback);
return options?.all
? callback(null, [{ address: '127.0.0.1', family: 4 }])
: callback(null, '127.0.0.1', 4);
};
const at = process.argv.indexOf('--accounts');
const names = (at === -1 ? 'alice,bob' : process.argv[at + 1]).split(',');
const net = await TestNetworkNoAppView.create({ pds: { hostname: 'localhost' } });
const accounts = [];
for (const name of names) {
const password = 'password';
const res = await fetch(`${net.pds.url}/xrpc/com.atproto.server.createAccount`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ email: `${name}@test.com`, handle: `${name}.test`, password })
});
if (!res.ok) throw new Error(`createAccount ${name}: ${await res.text()}`);
const { did, handle } = await res.json();
accounts.push({ handle, did, password });
}
// The space types the host keeps, published as lexicons from an account
// of their own, which the PDS is told to resolve every lexicon from (as
// PDS_LEXICON_AUTHORITY_DID would tell it): the PDS grants a `space:`
// scope, as a site that writes asks for, only for a space whose
// declaration it can read.
{
const { readdirSync, statSync } = await import('node:fs');
const all = (dir) =>
readdirSync(dir).flatMap((f) => {
const path = join(dir, f);
return statSync(path).isDirectory() ? all(path) : f.endsWith('.json') ? [path] : [];
});
// The site's space types, and the group host's (its members space).
const spaces = [join(root, 'lexicons'), join(groupHost, 'lexicons')]
.flatMap(all)
.map((f) => JSON.parse(readFileSync(f, 'utf8')))
.filter((doc) => doc.defs?.main?.type === 'space');
const made = await fetch(`${net.pds.url}/xrpc/com.atproto.server.createAccount`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
email: 'lexicons@test.com',
handle: 'lexicons.test',
password: 'password'
})
}).then((r) => r.json());
for (const doc of spaces) {
const res = await fetch(`${net.pds.url}/xrpc/com.atproto.repo.createRecord`, {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: `Bearer ${made.accessJwt}` },
body: JSON.stringify({
repo: made.did,
collection: 'com.atproto.lexicon.schema',
rkey: doc.id,
validate: false,
record: { $type: 'com.atproto.lexicon.schema', ...doc }
})
});
if (!res.ok) throw new Error(`publishing ${doc.id}: ${await res.text()}`);
}
net.pds.ctx.cfg.lexicon.didAuthority = made.did;
}
// The codes the PDS mails to let an account's identity move (an account
// moving to a group host asks for one), kept by address and served at
// `mail`, as the account's inbox would have them.
const codes = new Map();
const mailer = net.pds.ctx.mailer;
const sendPlcOperation = mailer.sendPlcOperation.bind(mailer);
mailer.sendPlcOperation = async (params, opts) => {
codes.set(opts.to, params.token);
return sendPlcOperation(params, opts);
};
const inbox = http.createServer((req, res) => {
const code = codes.get(new URL(req.url, 'http://inbox').searchParams.get('to'));
res.writeHead(code ? 200 : 404, { 'content-type': 'application/json' });
res.end(JSON.stringify(code ? { code } : { error: 'NoMail' }));
});
await new Promise((resolve) => inbox.listen(0, '127.0.0.1', resolve));
const described = await fetch(`${net.pds.url}/xrpc/com.atproto.server.describeServer`).then((r) =>
r.json()
);
console.log(
JSON.stringify({
pds: net.pds.url,
plc: net.plc.url,
spaces: described.spacesAlpha === true,
mail: `http://127.0.0.1:${inbox.address().port}`,
console: { host: CONSOLE_HOST, cert, key },
accounts
})
);
const shutdown = async () => {
inbox.close();
await net.close();
process.exit(0);
};
process.stdin.on('end', shutdown);
process.stdin.on('close', shutdown);
process.stdin.resume();
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
examples/kicker/harness/posters.mjsnew+81−0
examples/kicker/harness/seed.mjsnew+377−0
examples/kicker/harness/world.mjsnew+200−0
examples/kicker/lexicons/com/example/place/calendar.jsonnew+15−0
examples/kicker/lexicons/com/example/place/card.jsonnew+41−0
examples/kicker/lexicons/com/example/place/event.jsonnew+61−0
examples/kicker/lexicons/com/example/place/note.jsonnew+38−0
examples/kicker/lexicons/com/example/place/reply.jsonnew+36−0
examples/kicker/lexicons/com/example/place/room.jsonnew+17−0
examples/kicker/lexicons/com/example/place/rsvp.jsonnew+37−0
examples/kicker/lexicons/com/example/place/topic.jsonnew+31−0
examples/kicker/site/src/lib/atoms/Avatar.sveltenew+16−0
examples/kicker/site/src/lib/atoms/Handle.sveltenew+6−0
examples/kicker/site/src/lib/atoms/Picture.sveltenew+14−0
examples/kicker/site/src/lib/molecules/Dialog.sveltenew+20−0
examples/kicker/site/src/lib/molecules/Empty.sveltenew+14−0
examples/kicker/site/src/lib/molecules/EventCard.sveltenew+32−0
examples/kicker/site/src/lib/molecules/MemberRow.sveltenew+23−0
examples/kicker/site/src/lib/molecules/Menu.sveltenew+39−0
examples/kicker/site/src/lib/molecules/NoteCard.sveltenew+45−0
examples/kicker/site/src/lib/molecules/Post.sveltenew+47−0
examples/kicker/site/src/lib/molecules/RoomHead.sveltenew+12−0
examples/kicker/site/src/lib/molecules/RsvpButtons.sveltenew+28−0
examples/kicker/site/src/lib/organisms/AppealDialog.sveltenew+41−0
examples/kicker/site/src/lib/organisms/CardDialog.sveltenew+65−0
examples/kicker/site/src/lib/organisms/EventDialog.sveltenew+43−0
examples/kicker/site/src/lib/organisms/EventList.sveltenew+27−0
examples/kicker/site/src/lib/organisms/Landing.sveltenew+24−0
examples/kicker/site/src/lib/organisms/NewEventDialog.sveltenew+59−0
examples/kicker/site/src/lib/organisms/NewTopicDialog.sveltenew+35−0
examples/kicker/site/src/lib/organisms/NoteBoard.sveltenew+87−0
examples/kicker/site/src/lib/organisms/PeopleList.sveltenew+14−0
examples/kicker/site/src/lib/organisms/PinNoteDialog.sveltenew+38−0
examples/kicker/site/src/lib/organisms/ReplyForm.sveltenew+23−0
examples/kicker/site/src/lib/organisms/ReplyTree.sveltenew+62−0
examples/kicker/site/src/lib/organisms/ReportDialog.sveltenew+78−0
examples/kicker/site/src/lib/organisms/SiteHeader.sveltenew+27−0
examples/kicker/site/src/lib/organisms/Thread.sveltenew+35−0
examples/kicker/site/src/lib/organisms/TopicList.sveltenew+41−0
examples/kicker/site/src/lib/templates/Place.sveltenew+11−0
examples/kicker/site/src/lib/about.jsnew+10−0
examples/kicker/site/src/lib/dates.jsnew+49−0
examples/kicker/site/src/lib/forms.svelte.jsnew+27−0
examples/kicker/site/src/lib/kept.svelte.jsnew+25−0
examples/kicker/site/src/lib/place.jsnew+205−0
examples/kicker/site/src/lib/route.svelte.jsnew+72−0
examples/kicker/site/src/lib/views.jsnew+126−0
examples/kicker/site/src/lib/views.test.jsnew+148−0
examples/kicker/site/src/rooms/Board.sveltenew+85−0
examples/kicker/site/src/rooms/Discussion.sveltenew+201−0
examples/kicker/site/src/rooms/Events.sveltenew+133−0
examples/kicker/site/src/rooms/People.sveltenew+57−0
examples/kicker/site/src/app.cssnew+731−0
731 lines changed: not loaded until asked for.
examples/kicker/site/src/App.sveltenew+50−0
examples/kicker/site/src/main.jsnew+7−0
examples/kicker/site/src/tokens.cssnew+150−0
examples/kicker/site/index.htmlnew+15−0
examples/kicker/site/package-lock.jsonnew+1316−0
1316 lines changed: not loaded until asked for.
examples/kicker/site/package.jsonnew+21−0
examples/kicker/site/vite.config.jsnew+10−0
examples/kicker/.gitignorenew+5−0
examples/kicker/AGENTS.mdnew+28−0
examples/kicker/CLAUDE.mdnew+1−0
examples/kicker/DESIGN.mdnew+76−0
examples/kicker/Justfilenew+37−0
examples/kicker/README.mdnew+89−0
.dockerignore+1−0
AGENTS.md+5−0