@joiner-platform/cli 0.1.17 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/package.json +2 -2
  2. package/skills/tile-creator/references/cli.md +1 -1
  3. package/skills/tile-creator/references/client-api.md +16 -6
  4. package/src/commands/init/scaffold.ts +2 -9
  5. package/src/commands/init/sdk-tarball-url.generated.ts +2 -2
  6. package/src/commands/init/template-names.ts +18 -0
  7. package/bundled-resources/poe-tile-templates/coverage.config.json +0 -6
  8. package/bundled-resources/poe-tile-templates/index.ts +0 -27
  9. package/bundled-resources/poe-tile-templates/package.json +0 -31
  10. package/bundled-resources/poe-tile-templates/scripts/cleanup.ts +0 -10
  11. package/bundled-resources/poe-tile-templates/scripts/generate.ts +0 -57
  12. package/bundled-resources/poe-tile-templates/scripts/install-diagnostics.ts +0 -52
  13. package/bundled-resources/poe-tile-templates/scripts/paths.ts +0 -7
  14. package/bundled-resources/poe-tile-templates/scripts/sdk-dependency-key.ts +0 -288
  15. package/bundled-resources/poe-tile-templates/scripts/verify-all-sdks.ts +0 -132
  16. package/bundled-resources/poe-tile-templates/scripts/verify-local-sdk-command.ts +0 -30
  17. package/bundled-resources/poe-tile-templates/scripts/verify-local-sdk-tarball.ts +0 -397
  18. package/bundled-resources/poe-tile-templates/tests/check-source.test.ts +0 -131
  19. package/bundled-resources/poe-tile-templates/tests/dev-script.test.slow.ts +0 -166
  20. package/bundled-resources/poe-tile-templates/tests/doctor-launcher.test.ts +0 -48
  21. package/bundled-resources/poe-tile-templates/tests/fixtures/customized-manager.ts +0 -67
  22. package/bundled-resources/poe-tile-templates/tests/fixtures/extended-mutators.ts.txt +0 -106
  23. package/bundled-resources/poe-tile-templates/tests/fixtures/multiplayer-verification.test.playwright.ts.txt +0 -103
  24. package/bundled-resources/poe-tile-templates/tests/fixtures/replace-starter-schema.ts +0 -67
  25. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/phaserjs.tsx.txt +0 -85
  26. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/preact.tsx.txt +0 -69
  27. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/react.tsx.txt +0 -73
  28. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/seating.ts.txt +0 -54
  29. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/solidjs.tsx.txt +0 -70
  30. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/vanilla-js.tsx.txt +0 -85
  31. package/bundled-resources/poe-tile-templates/tests/generated-templates.test.ts +0 -278
  32. package/bundled-resources/poe-tile-templates/tests/happy-dom-version.test.ts +0 -27
  33. package/bundled-resources/poe-tile-templates/tests/install-diagnostics.test.ts +0 -99
  34. package/bundled-resources/poe-tile-templates/tests/native-gesture-defaults.test.ts +0 -23
  35. package/bundled-resources/poe-tile-templates/tests/playwright-version.test.ts +0 -84
  36. package/bundled-resources/poe-tile-templates/tests/render-check-scaffold.test.ts +0 -56
  37. package/bundled-resources/poe-tile-templates/tests/sdk-dependency-key.test.ts +0 -129
  38. package/bundled-resources/poe-tile-templates/tests/visual-check.test.ts +0 -90
@@ -1,166 +0,0 @@
1
- // owner: jyoung-q
2
- /**
3
- * Verifies the template's `bun run dev` script:
4
- * - boots a TestServer + reload-injecting proxy
5
- * - injects a /__dev_reload_ws client into the top-level HTML
6
- * - broadcasts "reload" when dist/ changes (after vite rebuilds)
7
- *
8
- * Prerequisites: `bun run generate` to scaffold templates into
9
- * generated-apps/template-<name>/, and `bun install --ignore-scripts` at
10
- * the monorepo root so workspace deps resolve.
11
- *
12
- * Slow because each iteration spawns vite + waits for a real rebuild.
13
- */
14
-
15
- import { afterAll, expect, test } from "bun:test";
16
- import { type Subprocess, spawn } from "bun";
17
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
18
- import { join } from "node:path";
19
- import { GENERATED_APPS_DIR } from "../scripts/paths.ts";
20
-
21
- const TEMPLATE = "react";
22
- const APP_DIR = join(GENERATED_APPS_DIR, `template-${TEMPLATE}`);
23
- const TYPE_ID = `template-${TEMPLATE}`;
24
-
25
- if (!existsSync(APP_DIR)) {
26
- throw new Error(
27
- `Generated app not found: ${APP_DIR}\nRun "bun run generate" in poe-tile-templates first.`,
28
- );
29
- }
30
-
31
- const dev: Subprocess<"ignore", "pipe", "pipe"> = spawn({
32
- cmd: ["bun", "scripts/dev.ts"],
33
- cwd: APP_DIR,
34
- stdout: "pipe",
35
- stderr: "pipe",
36
- env: { ...process.env, FORCE_COLOR: "0" },
37
- });
38
-
39
- // Drain stderr into a buffer so timeout errors below can include it. Without
40
- // this, a TestServer/proxy boot error printed to stderr is invisible in the
41
- // failure message — we'd only see whatever stdout had buffered.
42
- let stderrBuffer = "";
43
- void (async () => {
44
- const reader = (dev.stderr as ReadableStream<Uint8Array>).getReader();
45
- const stderrDecoder = new TextDecoder();
46
- try {
47
- while (true) {
48
- // biome-ignore lint/performance/noAwaitInLoops: Existing sequential async loops need case-by-case review; keep rule enabled for new code.
49
- const { done, value } = await reader.read();
50
- if (done) break;
51
- stderrBuffer += stderrDecoder.decode(value, { stream: true });
52
- }
53
- } catch {
54
- // stream closed during shutdown — fine.
55
- }
56
- })();
57
-
58
- afterAll(() => {
59
- dev.kill("SIGINT");
60
- });
61
-
62
- // Tiered readUntil: each call advances `stdoutBuffer` and waits up to
63
- // `timeoutMs` for `pattern`. Splitting the boot wait into multiple tiers
64
- // (vite first build → testserver listening → URL printed) means the next CI
65
- // flake fails at one specific tier and pinpoints which boot phase blew its
66
- // budget, instead of the previous "the whole 10s envelope expired somewhere
67
- // in there" failure. The shared `stdoutBuffer` is intentional: a fast tier
68
- // might finish before its log line is read, so the next tier's match may
69
- // already be in the buffer from a previous read.
70
- const decoder = new TextDecoder();
71
- let stdoutBuffer = "";
72
- const stdoutReader = (dev.stdout as ReadableStream<Uint8Array>).getReader();
73
-
74
- async function readUntil(
75
- pattern: RegExp,
76
- timeoutMs: number,
77
- tierName: string,
78
- ): Promise<RegExpMatchArray> {
79
- let match = stdoutBuffer.match(pattern);
80
- if (match) return match;
81
- const deadline = Date.now() + timeoutMs;
82
- while (Date.now() < deadline) {
83
- const remaining = deadline - Date.now();
84
- // biome-ignore lint/performance/noAwaitInLoops: Existing sequential async loops need case-by-case review; keep rule enabled for new code.
85
- const result = await Promise.race([
86
- stdoutReader.read(),
87
- new Promise<null>((r) =>
88
- // biome-ignore lint: real I/O timeout — slow test waits on child-process stdout
89
- setTimeout(() => r(null), remaining),
90
- ),
91
- ]);
92
- if (result === null) break;
93
- if (result.done) break;
94
- stdoutBuffer += decoder.decode(result.value, { stream: true });
95
- match = stdoutBuffer.match(pattern);
96
- if (match) return match;
97
- }
98
- throw new Error(
99
- `Timed out at tier "${tierName}" waiting for /${pattern.source}/ in dev output (${timeoutMs}ms).\n` +
100
- `Stdout buffered:\n${stdoutBuffer}\n` +
101
- `Stderr buffered:\n${stderrBuffer}`,
102
- );
103
- }
104
-
105
- // Skipped 2026-05-07: chronic CI flake on the "vite first build" tier
106
- // (8000ms budget). Tracked in PR #2962. Re-observed in PRs #2963 (which
107
- // added the tier wait + stderr capture) and #2973 (passed on no-cache,
108
- // failed on cached for the same commit, strong flake signal). Un-skip
109
- // once the underlying boot-time variance is fixed; the test still runs
110
- // locally for development.
111
- test.skip("dev script boots, injects reload script, broadcasts on rebuild", async () => {
112
- // Tiered boot wait: vite first build (cold prod bundle, the historically
113
- // slow phase per PR #2816) gets the largest budget; subsequent phases
114
- // should be near-instant. Total envelope still ~11s so the test stays
115
- // "fast" per PRINCIPLES.md.
116
- await readUntil(/\[dev\] vite first build done/, 8_000, "vite first build");
117
- await readUntil(
118
- /\[dev\] testserver listening/,
119
- 1_500,
120
- "testserver listening",
121
- );
122
- const urlMatch = await readUntil(
123
- /URL:\s+(http:\/\/\S+)/,
124
- 1_500,
125
- "proxy URL printed",
126
- );
127
- const url = urlMatch[1]!;
128
- expect(url).toContain(`/room/${TYPE_ID}/dev/tile/${TYPE_ID}/dev`);
129
-
130
- const html = await fetch(url).then((r) => r.text());
131
- expect(html).toContain("/__dev_reload_ws");
132
- expect(html).toContain("location.reload()");
133
-
134
- const wsUrl = new URL(url);
135
- wsUrl.protocol = "ws:";
136
- wsUrl.pathname = "/__dev_reload_ws";
137
- wsUrl.search = "";
138
-
139
- const ws = new WebSocket(wsUrl.toString());
140
- const reloadMessage = new Promise<string>((resolve, reject) => {
141
- ws.addEventListener("message", (e) => resolve(String(e.data)));
142
- ws.addEventListener("error", () => reject(new Error("ws error")));
143
- });
144
- await new Promise<void>((resolve, reject) => {
145
- ws.addEventListener("open", () => resolve());
146
- ws.addEventListener("error", () => reject(new Error("ws connect failed")));
147
- });
148
-
149
- const appPath = join(APP_DIR, "ui/App.tsx");
150
- const original = readFileSync(appPath, "utf-8");
151
- writeFileSync(appPath, `${original}\n// dev-reload-test ${Date.now()}\n`);
152
-
153
- try {
154
- const message = await Promise.race([
155
- reloadMessage,
156
- new Promise<never>((_, r) =>
157
- // biome-ignore lint: real I/O timeout — slow test waits on vite rebuild + ws broadcast
158
- setTimeout(() => r(new Error("reload not received in 10s")), 10_000),
159
- ),
160
- ]);
161
- expect(message).toBe("reload");
162
- } finally {
163
- writeFileSync(appPath, original);
164
- ws.close();
165
- }
166
- }, 20_000);
@@ -1,48 +0,0 @@
1
- import { afterEach, expect, test } from "bun:test";
2
- import {
3
- chmodSync,
4
- copyFileSync,
5
- mkdirSync,
6
- mkdtempSync,
7
- realpathSync,
8
- rmSync,
9
- writeFileSync,
10
- } from "node:fs";
11
- import { tmpdir } from "node:os";
12
- import { join } from "node:path";
13
-
14
- const roots: string[] = [];
15
- afterEach(() => {
16
- for (const root of roots.splice(0))
17
- rmSync(root, { recursive: true, force: true });
18
- });
19
-
20
- test("doctor runs the npm CLI's poe-tiles bin when only Bun is installed", () => {
21
- // A tile scaffolded with `bunx @joiner-platform/cli create` has no
22
- // poe-tiles on PATH and no monorepo checkout around it.
23
- const root = realpathSync(mkdtempSync(join(tmpdir(), "doctor-launcher-")));
24
- roots.push(root);
25
- const scripts = join(root, "tile/scripts");
26
- mkdirSync(scripts, { recursive: true });
27
- copyFileSync(
28
- join(import.meta.dir, "../base/scripts/doctor.sh"),
29
- join(scripts, "doctor.sh"),
30
- );
31
- const bin = join(root, "bin");
32
- mkdirSync(bin);
33
- for (const name of ["bun", "bunx"]) {
34
- writeFileSync(join(bin, name), `#!/bin/sh\necho "${name} $*"\n`);
35
- chmodSync(join(bin, name), 0o755);
36
- }
37
-
38
- const result = Bun.spawnSync(["bash", join(scripts, "doctor.sh")], {
39
- env: { PATH: `${bin}:/usr/bin:/bin` },
40
- stdout: "pipe",
41
- stderr: "pipe",
42
- });
43
-
44
- expect(result.stderr.toString()).toBe("");
45
- expect(result.stdout.toString().trim()).toBe(
46
- `bunx --bun --package @joiner-platform/cli poe-tiles doctor --cwd ${join(root, "tile")}`,
47
- );
48
- });
@@ -1,67 +0,0 @@
1
- // owner: jyoung-q
2
- import { mkdirSync, writeFileSync } from "node:fs";
3
- import { join } from "node:path";
4
-
5
- /** Exercise the emitted manager example with a non-empty app schema and handler. */
6
- export function writeCustomizedManagerFixture({
7
- dir,
8
- managerExample,
9
- }: {
10
- dir: string;
11
- managerExample: string;
12
- }): void {
13
- mkdirSync(dir, { recursive: true });
14
- writeFileSync(
15
- join(dir, "schema.ts"),
16
- `
17
- import { z } from "zod";
18
- import { defineSchema, table } from "joiner-sdk/v1/backend.js";
19
- export const tileSchema = defineSchema({
20
- schemaVersion: 1,
21
- tables: { moves: { schema: table(z.object({ count: z.number() })) } },
22
- mutators: { recordMove: { input: z.object({ count: z.number() }) } },
23
- });
24
- `,
25
- );
26
- writeFileSync(join(dir, "hooks.ts"), "export const tileHooks = {};\n");
27
- writeFileSync(
28
- join(dir, "mutators.ts"),
29
- `
30
- import type { InferMutatorHandlers } from "joiner-sdk/v1/client.js";
31
- import { tileSchema } from "./schema";
32
- export const tileMutators: InferMutatorHandlers<typeof tileSchema> = {
33
- recordMove: async (ctx, input) => {
34
- await ctx.table("moves").set({ itemKey: ctx.userId, value: input });
35
- },
36
- };
37
- `,
38
- );
39
- writeFileSync(
40
- join(dir, "manager.test.ts"),
41
- managerExample +
42
- `
43
- test("the customized app mutation survives the manager example", async () => {
44
- const h = await createPoeTileInManagerTestHarness({
45
- tile: { typeId: "customized-app", clientConfig, backendConfig },
46
- users: ["alice", "bob"],
47
- });
48
- try {
49
- await (await h.tile("alice").poe.store.mutate.recordMove({ count: 7 })).confirmed;
50
- const bob = h.tile("bob").poe.store;
51
- await bob.pull();
52
- const result = await bob.query((ctx) => ctx.table("moves").get("alice"));
53
- expect(result).toEqual({ count: 7 });
54
- const count: number | undefined = result?.count;
55
- expect(count).toBe(7);
56
- await h.removeUser({ userId: "bob", removedBy: "alice" });
57
- const alice = h.tile("alice").poe.store;
58
- await alice.pull();
59
- expect(await alice.query(async (ctx) => (await ctx.table("$users").get("bob"))?.removedAt)).toBeDefined();
60
- await h.addUser({ userId: "bob", addedBy: "alice" });
61
- await bob.pull();
62
- expect(await bob.query((ctx) => ctx.table("moves").get("alice"))).toEqual({ count: 7 });
63
- } finally { h.dispose(); }
64
- });
65
- `,
66
- );
67
- }
@@ -1,106 +0,0 @@
1
- import { expect, test } from "bun:test";
2
- import { z } from "zod";
3
- import { defineBackendConfig, defineSchema, table } from "joiner-sdk/v1/backend.js";
4
- import { defineClientConfig, type InferMutatorHandlers, type InferSyncedStoreClient, type PoeAPI } from "joiner-sdk/v1/client.js";
5
- import { createPoeTileTestHarness, createPoeTileInManagerTestHarness, waitForKeyMatch } from "joiner-sdk/v1/test-utils.js";
6
- import { tileSchema } from "../synced-store/schema";
7
-
8
- // Extend the installed starter, rather than checking a schema unrelated to it.
9
- const extendedSchema = defineSchema({
10
- ...tileSchema,
11
- tables: {
12
- ...tileSchema.tables,
13
- players: {
14
- schema: table(z.object({
15
- userId: z.string(),
16
- mark: z.enum(["X", "O"]).nullable(),
17
- score: z.number(),
18
- })),
19
- },
20
- },
21
- mutators: {
22
- setScore: { input: z.object({ score: z.number() }) },
23
- },
24
- });
25
- type ExtendedSchema = typeof extendedSchema;
26
- const mutators: InferMutatorHandlers<ExtendedSchema> = {
27
- setScore: async (ctx, { score }) => {
28
- await ctx.table("players").set({
29
- itemKey: ctx.userId,
30
- value: { userId: ctx.userId, mark: null, score },
31
- });
32
- },
33
- };
34
- const backendConfig = defineBackendConfig({ schema: extendedSchema, mutators });
35
- function createStore() {
36
- return createPoeTileTestHarness<ExtendedSchema>({ store: { backendConfig } });
37
- }
38
- type TodoStore = Awaited<ReturnType<ReturnType<typeof createStore>["createClient"]>>["store"];
39
- function getPlayer(store: TodoStore, userId: string) {
40
- return store.query((ctx) => ctx.table("players").get(userId));
41
- }
42
- type Player = NonNullable<Awaited<ReturnType<typeof getPlayer>>>;
43
- type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends
44
- (<T>() => T extends B ? 1 : 2) ? true : false;
45
- type PlayerRow = { userId: string; mark: "X" | "O" | null; score: number };
46
- // Store reads return rows whose top-level properties are readonly.
47
- const exactRow: Equal<Player, { readonly userId: string; readonly mark: "X" | "O" | null; readonly score: number }> = true;
48
- const exactInput: Equal<Parameters<TodoStore["mutate"]["setScore"]>[0], { score: number }> = true;
49
- void exactRow;
50
- void exactInput;
51
-
52
- // Negative checks without a suppression comment, which the scaffold's
53
- // type-check rejects: each type is false when the argument is refused.
54
- type Accepts<Param, Arg> = [Arg] extends [Param] ? true : false;
55
- // The extended mutator accepts a numeric score, not text.
56
- const rejectsTextScore: Accepts<Parameters<TodoStore["mutate"]["setScore"]>[0], { score: "high" }> = false;
57
- // Readers receive transactions, not store instances.
58
- type ReaderContext = Parameters<Parameters<TodoStore["query"]>[0]>[0];
59
- const rejectsTransactionAsStore: Accepts<Parameters<typeof getPlayer>[0], ReaderContext> = false;
60
- void rejectsTextScore;
61
- void rejectsTransactionAsStore;
62
-
63
- test("installed manager harness preserves the supplied config's Poe client type", async () => {
64
- const h = await createPoeTileInManagerTestHarness({
65
- tile: {
66
- typeId: "typed-manager",
67
- clientConfig: defineClientConfig<ExtendedSchema>({ schemaVersion: 1, mutators }),
68
- backendConfig,
69
- },
70
- users: ["alice", "bob"],
71
- });
72
- try {
73
- const alice = h.tile("alice").poe;
74
- const exactClient: Equal<typeof alice, PoeAPI<InferSyncedStoreClient<ExtendedSchema>>> = true;
75
- void exactClient;
76
- await (await alice.store.mutate.setScore({ score: 4 })).confirmed;
77
- const bob = h.tile("bob").poe.store;
78
- const matched = await waitForKeyMatch(bob, {
79
- table: "players", key: "alice", match: (player) => player.score === 4,
80
- });
81
- const exactMatch: Equal<typeof matched, PlayerRow> = true;
82
- void exactMatch;
83
- expect(await getPlayer(bob, "alice")).toEqual({ userId: "alice", mark: null, score: 4 });
84
- } finally {
85
- h.dispose();
86
- }
87
- });
88
-
89
- test("an extended scaffold mutator keeps exact input and row types through installed harness clients", async () => {
90
- const harness = createStore();
91
- try {
92
- const { store: alice } = await harness.createClient({ userId: "alice" });
93
- const { store: bob } = await harness.createClient({ userId: "bob" });
94
- const result = await alice.mutate.setScore({ score: 3 });
95
- await result.confirmed;
96
- await waitForKeyMatch(bob, {
97
- table: "players", key: "alice", match: (player) => player.score === 3,
98
- });
99
- expect(await getPlayer(bob, "alice")).toEqual({ userId: "alice", mark: null, score: 3 });
100
- // A new client reads authoritative data, not the writer's optimistic overlay.
101
- const { store: reopened } = await harness.createClient({ userId: "observer" });
102
- expect(await getPlayer(reopened, "alice")).toEqual({ userId: "alice", mark: null, score: 3 });
103
- } finally {
104
- harness.dispose();
105
- }
106
- });
@@ -1,103 +0,0 @@
1
- import { expect, test } from "@playwright/test";
2
- import { fileURLToPath } from "node:url";
3
- import {
4
- TestServer,
5
- waitForBlobFrame,
6
- } from "joiner-sdk/v1/test-utils/playwright.js";
7
- import { openTwoUserTile, waitForVisualReady } from "./multiplayer";
8
-
9
- test("visual readiness ignores looping decoration but bounds unfinished finite animations", async ({
10
- page,
11
- }) => {
12
- await page.setContent('<main id="ready">Ready</main>');
13
- await page.evaluate(() => {
14
- const element = document.querySelector("main")!;
15
- element.animate([{ opacity: 1 }, { opacity: 0.8 }], {
16
- duration: 1000,
17
- iterations: Infinity,
18
- });
19
- const finite = element.animate(
20
- [{ transform: "scale(1)" }, { transform: "scale(.9)" }],
21
- { duration: 1000, iterations: 2 },
22
- );
23
- finite.pause();
24
- });
25
- // The browser predicate can consume the deadline before Playwright formats
26
- // our diagnostic. Assert bounded rejection, then successful recovery below.
27
- await expect(
28
- waitForVisualReady({
29
- frame: page.mainFrame(),
30
- readySelector: "#ready",
31
- timeoutMs: 100,
32
- }),
33
- ).rejects.toThrow();
34
- await page.evaluate(() => {
35
- for (const animation of document.getAnimations()) {
36
- if (Number.isFinite(animation.effect?.getComputedTiming().endTime))
37
- animation.finish();
38
- }
39
- });
40
- await waitForVisualReady({
41
- frame: page.mainFrame(),
42
- readySelector: "#ready",
43
- timeoutMs: 1000,
44
- });
45
- expect(
46
- await page.evaluate(() =>
47
- document
48
- .getAnimations()
49
- .some((animation) => animation.playState === "running"),
50
- ),
51
- ).toBe(true);
52
- });
53
-
54
- test("both members are admitted before either client waits for a shared readiness state", async ({
55
- browser,
56
- }) => {
57
- const server = new TestServer();
58
- await server.start();
59
- try {
60
- const tileTypeId = "multiplayer-fixture-probe";
61
- await server.registerTile({
62
- typeId: tileTypeId,
63
- content: {
64
- type: "directory",
65
- dir: fileURLToPath(new URL("../dist", import.meta.url)),
66
- },
67
- });
68
- const users = await openTwoUserTile({
69
- server,
70
- browser,
71
- tileTypeId,
72
- instanceId: crypto.randomUUID(),
73
- readySelector:
74
- '[data-testid="connected-player-count"]:text-is("2 connected players")',
75
- contextOptions: {
76
- viewport: { width: 390, height: 760 },
77
- colorScheme: "dark",
78
- },
79
- });
80
- try {
81
- expect(users.alice.page.viewportSize()).toEqual({
82
- width: 390,
83
- height: 760,
84
- });
85
- expect(users.alice.context).not.toBe(users.bob.context);
86
- expect(
87
- new URL(users.alice.page.url()).searchParams.get("use_indexed_db"),
88
- ).toBe("1");
89
- await users.alice.page.reload();
90
- const returned = await waitForBlobFrame(users.alice.page);
91
- await expect(
92
- returned.locator('[data-testid="connected-player-count"]'),
93
- ).toHaveText("2 connected players");
94
- await expect(
95
- users.bob.frame.locator('[data-testid="connected-player-count"]'),
96
- ).toHaveText("2 connected players");
97
- } finally {
98
- await users.close();
99
- }
100
- } finally {
101
- await server.closeAndWaitForTesting();
102
- }
103
- });
@@ -1,67 +0,0 @@
1
- // owner: jyoung-q
2
- import assert from "node:assert/strict";
3
- import { copyFileSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
- import { join } from "node:path";
5
- import type { TemplateName } from "../..";
6
-
7
- /** Demo-specific assertions belong to scaffold maintenance, not generated apps. */
8
- export function installStarterDemoTests(
9
- appDir: string,
10
- template: TemplateName,
11
- ) {
12
- copyFileSync(
13
- join(import.meta.dir, "starter-demo", `${template}.tsx.txt`),
14
- join(appDir, "ui/starter-demo.test.happydom.tsx"),
15
- );
16
- copyFileSync(
17
- join(import.meta.dir, "starter-demo/seating.ts.txt"),
18
- join(appDir, "synced-store/starter-demo.test.ts"),
19
- );
20
- }
21
-
22
- /** Replace the app-owned schema without editing any generated tests. */
23
- export function replaceStarterSchema(appDir: string, template: TemplateName) {
24
- rmSync(join(appDir, "ui/starter-demo.test.happydom.tsx"));
25
- rmSync(join(appDir, "synced-store/starter-demo.test.ts"));
26
- const extension = ["react", "preact", "solidjs"].includes(template)
27
- ? "tsx"
28
- : "ts";
29
- for (const [path, edits] of [
30
- [
31
- "synced-store/schema.ts",
32
- [
33
- [
34
- "players: { schema: table(playerRow) }",
35
- "participants: { schema: table(playerRow) }",
36
- ],
37
- [
38
- 'mark: z.enum(["X", "O"]).nullable(),',
39
- 'symbol: z.enum(["X", "O"]).nullable(),\n\tscore: z.number(),',
40
- ],
41
- ],
42
- ],
43
- [
44
- "synced-store/hooks.ts",
45
- [
46
- ['table("players")', 'table("participants")'],
47
- ["player.mark", "player.symbol"],
48
- [
49
- "value: { userId, mark },",
50
- "value: { userId, symbol: mark, score: 0 },",
51
- ],
52
- ],
53
- ],
54
- [`ui/App.${extension}`, [['table("players")', 'table("participants")']]],
55
- ] as const) {
56
- const file = join(appDir, path);
57
- let source = readFileSync(file, "utf8");
58
- for (const [before, after] of edits) {
59
- assert(
60
- source.includes(before),
61
- `Missing starter extension point: ${path}: ${before}`,
62
- );
63
- source = source.replaceAll(before, after);
64
- }
65
- writeFileSync(file, source);
66
- }
67
- }
@@ -1,85 +0,0 @@
1
- // owner: jyoung-q
2
- import { expect, test } from "bun:test";
3
- import { mountApp } from "./App";
4
- import { createPoeTileTestHarness, tick } from "joiner-sdk/v1/test-utils.js";
5
- import type { AppReadContext } from "../client";
6
- import { tileBackendConfig } from "../synced-store/backend-config";
7
- import type { AppSchema } from "../synced-store/schema";
8
- import { createTestAppProps } from "../tests/app-test-props";
9
-
10
- async function waitFor(
11
- assertion: () => void,
12
- timeoutMs = 2_000,
13
- ): Promise<void> {
14
- const startedAt = Date.now();
15
- while (true) {
16
- try {
17
- assertion();
18
- return;
19
- } catch (error) {
20
- if (Date.now() - startedAt >= timeoutMs) throw error;
21
- await tick();
22
- }
23
- }
24
- }
25
-
26
- test("renders with a real two-client store and configured DOM matchers", async () => {
27
- const harness = createPoeTileTestHarness<AppSchema>({
28
- store: { backendConfig: tileBackendConfig },
29
- });
30
- let container: HTMLElement = document.createElement("div");
31
- try {
32
- const aliceClient = await harness.createClient({ userId: "alice" });
33
- const { store: alice } = aliceClient;
34
- await harness.createClient({ userId: "bob" });
35
- document.body.appendChild(container);
36
- mountApp(container, createTestAppProps(aliceClient));
37
-
38
- await waitFor(() => {
39
- expect(container.querySelector("#app-heading")).toHaveTextContent(
40
- "Hello",
41
- );
42
- });
43
- await waitFor(() => {
44
- expect(
45
- container.querySelector('[data-testid="connected-player-count"]'),
46
- ).toHaveTextContent("2 connected players");
47
- });
48
-
49
- const control = document.createElement("button");
50
- control.disabled = true;
51
- control.setAttribute("data-state", "ready");
52
- container.appendChild(control);
53
- expect(control).toBeInTheDocument();
54
- expect(control).toBeDisabled();
55
- expect(control).toHaveAttribute("data-state", "ready");
56
- expect(control).not.toHaveAttribute("aria-hidden");
57
-
58
- await harness.addUser({ userId: "carol" });
59
- const spectator = await alice.query((ctx: AppReadContext) =>
60
- ctx.table("players").get("carol"),
61
- );
62
- expect(spectator).toEqual({ userId: "carol", mark: null });
63
- await waitFor(() => {
64
- expect(
65
- container.querySelector('[data-testid="connected-player-count"]'),
66
- ).toHaveTextContent("3 connected players");
67
- });
68
-
69
- await harness.removeUser({ userId: "carol" });
70
- await waitFor(() => {
71
- expect(
72
- container.querySelector('[data-testid="connected-player-count"]'),
73
- ).toHaveTextContent("2 connected players");
74
- });
75
- expect(await alice.query((ctx: AppReadContext) =>
76
- ctx.table("$users").get("carol"),
77
- )).toMatchObject({ removedAt: expect.any(Number) });
78
- expect(await alice.query((ctx: AppReadContext) =>
79
- ctx.table("players").get("carol"),
80
- )).toEqual({ userId: "carol", mark: null });
81
- } finally {
82
- container.remove();
83
- harness.dispose();
84
- }
85
- });