@joiner-platform/cli 0.0.0-stage → 0.1.0
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.
- package/README.md +30 -2
- package/bundled-resources/poe-tile-templates/base/CLAUDE.md +72 -0
- package/bundled-resources/poe-tile-templates/base/README.md +7 -0
- package/bundled-resources/poe-tile-templates/base/_bunfig.toml +8 -0
- package/bundled-resources/poe-tile-templates/base/_gitignore +18 -0
- package/bundled-resources/poe-tile-templates/base/client.ts +12 -0
- package/bundled-resources/poe-tile-templates/base/package.json +36 -0
- package/bundled-resources/poe-tile-templates/base/playwright.config.ts +38 -0
- package/bundled-resources/poe-tile-templates/base/scripts/check-source.ts +148 -0
- package/bundled-resources/poe-tile-templates/base/scripts/dev.ts +19 -0
- package/bundled-resources/poe-tile-templates/base/scripts/doctor.sh +29 -0
- package/bundled-resources/poe-tile-templates/base/scripts/visual-check.ts +64 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/backend-config.ts +9 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/client-config.ts +8 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/data/items.ts +16 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/mutators/index.ts +10 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/mutators/remove-todo.ts +5 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/mutators/set-todo.ts +20 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/mutators/types.ts +5 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/mutators.test.ts +138 -0
- package/bundled-resources/poe-tile-templates/base/synced-store/schema.ts +40 -0
- package/bundled-resources/poe-tile-templates/base/tests/e2e.test.playwright.ts +92 -0
- package/bundled-resources/poe-tile-templates/base/tests/mobile-viewport.test.playwright.ts +111 -0
- package/bundled-resources/poe-tile-templates/base/tests/render-check.test.playwright.ts +128 -0
- package/bundled-resources/poe-tile-templates/base/tests/screenshot.test.playwright.ts +86 -0
- package/bundled-resources/poe-tile-templates/base/tests/setup-dom.ts +70 -0
- package/bundled-resources/poe-tile-templates/base/tile/src/backend.ts +3 -0
- package/bundled-resources/poe-tile-templates/base/tile/styles.css +47 -0
- package/bundled-resources/poe-tile-templates/base/tsconfig.json +13 -0
- package/bundled-resources/poe-tile-templates/coverage.config.json +6 -0
- package/bundled-resources/poe-tile-templates/index.ts +27 -0
- package/bundled-resources/poe-tile-templates/package.json +31 -0
- package/bundled-resources/poe-tile-templates/phaserjs/package.partial.json +6 -0
- package/bundled-resources/poe-tile-templates/phaserjs/tile/index.html +14 -0
- package/bundled-resources/poe-tile-templates/phaserjs/tile/src/entry.ts +35 -0
- package/bundled-resources/poe-tile-templates/phaserjs/ui/App.test.happydom.tsx +98 -0
- package/bundled-resources/poe-tile-templates/phaserjs/ui/App.ts +180 -0
- package/bundled-resources/poe-tile-templates/phaserjs/ui/phaser-scene.ts +174 -0
- package/bundled-resources/poe-tile-templates/phaserjs/vite.config.ts +28 -0
- package/bundled-resources/poe-tile-templates/preact/package.partial.json +9 -0
- package/bundled-resources/poe-tile-templates/preact/postcss.config.js +5 -0
- package/bundled-resources/poe-tile-templates/preact/tile/index.html +14 -0
- package/bundled-resources/poe-tile-templates/preact/tile/src/entry.tsx +36 -0
- package/bundled-resources/poe-tile-templates/preact/tile/styles.css +51 -0
- package/bundled-resources/poe-tile-templates/preact/tsconfig.json +15 -0
- package/bundled-resources/poe-tile-templates/preact/ui/App.test.happydom.tsx +69 -0
- package/bundled-resources/poe-tile-templates/preact/ui/App.tsx +116 -0
- package/bundled-resources/poe-tile-templates/preact/vite.config.ts +18 -0
- package/bundled-resources/poe-tile-templates/react/package.partial.json +12 -0
- package/bundled-resources/poe-tile-templates/react/postcss.config.js +5 -0
- package/bundled-resources/poe-tile-templates/react/tile/index.html +14 -0
- package/bundled-resources/poe-tile-templates/react/tile/src/entry.tsx +38 -0
- package/bundled-resources/poe-tile-templates/react/tile/styles.css +51 -0
- package/bundled-resources/poe-tile-templates/react/tsconfig.json +14 -0
- package/bundled-resources/poe-tile-templates/react/ui/App.test.happydom.tsx +71 -0
- package/bundled-resources/poe-tile-templates/react/ui/App.tsx +110 -0
- package/bundled-resources/poe-tile-templates/react/vite.config.ts +21 -0
- package/bundled-resources/poe-tile-templates/scripts/cleanup.ts +10 -0
- package/bundled-resources/poe-tile-templates/scripts/generate.ts +57 -0
- package/bundled-resources/poe-tile-templates/scripts/install-diagnostics.ts +52 -0
- package/bundled-resources/poe-tile-templates/scripts/paths.ts +7 -0
- package/bundled-resources/poe-tile-templates/scripts/sdk-dependency-key.ts +288 -0
- package/bundled-resources/poe-tile-templates/scripts/verify-all-sdks.ts +132 -0
- package/bundled-resources/poe-tile-templates/scripts/verify-local-sdk-command.ts +30 -0
- package/bundled-resources/poe-tile-templates/scripts/verify-local-sdk-tarball.ts +397 -0
- package/bundled-resources/poe-tile-templates/solidjs/_bunfig.toml +14 -0
- package/bundled-resources/poe-tile-templates/solidjs/package.partial.json +13 -0
- package/bundled-resources/poe-tile-templates/solidjs/postcss.config.js +5 -0
- package/bundled-resources/poe-tile-templates/solidjs/tests/solid-plugin.ts +49 -0
- package/bundled-resources/poe-tile-templates/solidjs/tile/index.html +14 -0
- package/bundled-resources/poe-tile-templates/solidjs/tile/src/entry.tsx +36 -0
- package/bundled-resources/poe-tile-templates/solidjs/tile/styles.css +51 -0
- package/bundled-resources/poe-tile-templates/solidjs/tsconfig.json +15 -0
- package/bundled-resources/poe-tile-templates/solidjs/ui/App.test.happydom.tsx +70 -0
- package/bundled-resources/poe-tile-templates/solidjs/ui/App.tsx +129 -0
- package/bundled-resources/poe-tile-templates/solidjs/vite.config.ts +18 -0
- package/bundled-resources/poe-tile-templates/tests/check-source.test.ts +131 -0
- package/bundled-resources/poe-tile-templates/tests/dev-script.test.slow.ts +166 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/customized-manager.ts +67 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/extended-mutators.ts.txt +106 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/multiplayer-verification.test.playwright.ts.txt +103 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/replace-starter-schema.ts +67 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/phaserjs.tsx.txt +85 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/preact.tsx.txt +69 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/react.tsx.txt +73 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/seating.ts.txt +54 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/solidjs.tsx.txt +70 -0
- package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/vanilla-js.tsx.txt +85 -0
- package/bundled-resources/poe-tile-templates/tests/generated-templates.test.ts +278 -0
- package/bundled-resources/poe-tile-templates/tests/happy-dom-version.test.ts +27 -0
- package/bundled-resources/poe-tile-templates/tests/install-diagnostics.test.ts +99 -0
- package/bundled-resources/poe-tile-templates/tests/native-gesture-defaults.test.ts +23 -0
- package/bundled-resources/poe-tile-templates/tests/playwright-version.test.ts +84 -0
- package/bundled-resources/poe-tile-templates/tests/render-check-scaffold.test.ts +56 -0
- package/bundled-resources/poe-tile-templates/tests/sdk-dependency-key.test.ts +129 -0
- package/bundled-resources/poe-tile-templates/tests/visual-check.test.ts +90 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/package.partial.json +3 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/tile/index.html +14 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/tile/src/entry.ts +35 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/ui/App.test.happydom.tsx +96 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/ui/App.ts +113 -0
- package/bundled-resources/poe-tile-templates/vanilla-js/vite.config.ts +17 -0
- package/cli.ts +134 -0
- package/index.ts +96 -0
- package/package.json +48 -5
- package/skills/audio-generation/.generated-by-poe-templated-docs +0 -0
- package/skills/audio-generation/SKILL.md +125 -0
- package/skills/finish-prototype/.generated-by-poe-templated-docs +0 -0
- package/skills/finish-prototype/SKILL.md +22 -0
- package/skills/help-me-build/.generated-by-poe-templated-docs +0 -0
- package/skills/help-me-build/SKILL.md +56 -0
- package/skills/image-generation/.generated-by-poe-templated-docs +0 -0
- package/skills/image-generation/SKILL.md +128 -0
- package/skills/one-shot/.generated-by-poe-templated-docs +0 -0
- package/skills/one-shot/SKILL.md +22 -0
- package/skills/platform-prototype/.generated-by-poe-templated-docs +0 -0
- package/skills/platform-prototype/SKILL.md +60 -0
- package/skills/platform-subagent/.generated-by-poe-templated-docs +0 -0
- package/skills/platform-subagent/SKILL.md +16 -0
- package/skills/poe-tiles-cli/.generated-by-poe-templated-docs +0 -0
- package/skills/poe-tiles-cli/SKILL.md +609 -0
- package/skills/poe-tiles-cli/references/device-motion.md +40 -0
- package/skills/poe-tiles-cli/references/player-updates.md +41 -0
- package/skills/prototype/.generated-by-poe-templated-docs +0 -0
- package/skills/prototype/SKILL.md +148 -0
- package/skills/publish/.generated-by-poe-templated-docs +0 -0
- package/skills/publish/SKILL.md +73 -0
- package/skills/synced-store/.generated-by-poe-templated-docs +0 -0
- package/skills/synced-store/SKILL.md +583 -0
- package/skills/synced-store/references/actions.md +85 -0
- package/skills/synced-store/references/api-patterns.md +245 -0
- package/skills/synced-store/references/architecture-scaling-and-performance.md +280 -0
- package/skills/synced-store/references/client-api-reference.md +263 -0
- package/skills/synced-store/references/data-visibility.md +95 -0
- package/skills/synced-store/references/external-stores.md +162 -0
- package/skills/synced-store/references/file-uploads.md +216 -0
- package/skills/synced-store/references/getting-user-info-of-members.md +228 -0
- package/skills/synced-store/references/limitations.md +72 -0
- package/skills/synced-store/references/live-data-limit-hook.md +131 -0
- package/skills/synced-store/references/mutator-rules.md +169 -0
- package/skills/synced-store/references/platform.md +49 -0
- package/skills/synced-store/references/schema-and-bindings.md +85 -0
- package/skills/synced-store/references/schema-libraries.md +57 -0
- package/skills/synced-store/references/schema-migrations.md +119 -0
- package/skills/synced-store/references/searchable-tables.md +27 -0
- package/skills/synced-store/references/server-forking.md +115 -0
- package/skills/synced-store/references/singleton-tables.md +61 -0
- package/skills/synced-store/references/sort-keys.md +253 -0
- package/skills/synced-store/references/ui-patterns.md +95 -0
- package/skills/tile-creator/.generated-by-poe-templated-docs +0 -0
- package/skills/tile-creator/SKILL.md +196 -0
- package/skills/tile-creator/references/assets.md +124 -0
- package/skills/tile-creator/references/backend-api.md +308 -0
- package/skills/tile-creator/references/cli-limitations.md +64 -0
- package/skills/tile-creator/references/cli.md +604 -0
- package/skills/tile-creator/references/client-api.md +2407 -0
- package/skills/tile-creator/references/composing-apps.md +166 -0
- package/skills/tile-creator/references/e2e-tests.md +55 -0
- package/skills/tile-creator/references/game-ux-best-practices.md +57 -0
- package/skills/tile-creator/references/migrating-pre-rename-tiles.md +79 -0
- package/skills/tile-creator/references/multiplayer-api-recipe.md +205 -0
- package/skills/tile-creator/references/native-results.md +100 -0
- package/skills/tile-creator/references/platform-integration.md +201 -0
- package/skills/tile-creator/references/power-report.md +199 -0
- package/skills/tile-creator/references/publish-rollout.md +166 -0
- package/skills/tile-creator/references/publishing.md +33 -0
- package/skills/tile-creator/references/push-notification-guidelines.md +58 -0
- package/skills/tile-creator/references/render-check.md +266 -0
- package/skills/tile-creator/references/running-the-client-api-on-a-server-owned-by-the-user.md +95 -0
- package/skills/tile-creator/references/safe-area-insets.md +79 -0
- package/skills/tile-creator/references/sandbox-limitations.md +32 -0
- package/skills/tile-creator/references/scaffolded-tile-folder-structure.md +48 -0
- package/skills/tile-creator/references/scaffolding-a-new-app.md +202 -0
- package/skills/tile-creator/references/simulations.md +125 -0
- package/skills/tile-creator/references/synced-store-client-reference.md +92 -0
- package/skills/tile-creator/references/troubleshooting.md +22 -0
- package/skills/tile-creator/references/turn-based-mutator.md +43 -0
- package/skills/tile-creator/references/user-erasure.md +14 -0
- package/skills/tile-creator/references/vite-plugin.md +166 -0
- package/skills/tile-creator/references/workspace-retention.md +72 -0
- package/src/admin-conversions-client.ts +28 -0
- package/src/admin-reviews-client.ts +36 -0
- package/src/api.generated.ts +1527 -0
- package/src/auth-token.ts +198 -0
- package/src/bounded-read.ts +35 -0
- package/src/bun-version.ts +33 -0
- package/src/checkout-base.ts +207 -0
- package/src/cli-bun-version.ts +16 -0
- package/src/cli-env.ts +28 -0
- package/src/cli-name.ts +23 -0
- package/src/client.ts +2474 -0
- package/src/collect-files.ts +226 -0
- package/src/commands/accounts.ts +55 -0
- package/src/commands/admin-abandon-conversion.ts +60 -0
- package/src/commands/admin-reviews.ts +66 -0
- package/src/commands/admin.ts +219 -0
- package/src/commands/auth.ts +89 -0
- package/src/commands/checkout-prototype.ts +67 -0
- package/src/commands/creator-source-capability.ts +11 -0
- package/src/commands/doctor-bun.ts +145 -0
- package/src/commands/doctor-command.ts +64 -0
- package/src/commands/doctor-package-json.ts +47 -0
- package/src/commands/doctor-sdk-pin.ts +156 -0
- package/src/commands/doctor-store-keys-lexer.ts +213 -0
- package/src/commands/doctor-store-keys-scan.ts +262 -0
- package/src/commands/doctor-store-keys.ts +196 -0
- package/src/commands/doctor.ts +371 -0
- package/src/commands/init/blank-scaffold-templates.ts +397 -0
- package/src/commands/init/index.ts +170 -0
- package/src/commands/init/internal-toolchain.ts +49 -0
- package/src/commands/init/manager-test-template.ts +107 -0
- package/src/commands/init/multiplayer-test-template.ts +217 -0
- package/src/commands/init/name-input.tsx +167 -0
- package/src/commands/init/no-store-scaffold-templates.ts +281 -0
- package/src/commands/init/no-store-scaffold.ts +134 -0
- package/src/commands/init/package-json-scripts.ts +72 -0
- package/src/commands/init/scaffold.ts +960 -0
- package/src/commands/init/sdk-tarball-url.generated.ts +4 -0
- package/src/commands/init/sdk-tarball-url.ts +31 -0
- package/src/commands/init/template-picker.tsx +147 -0
- package/src/commands/inspect-child-entry.ts +107 -0
- package/src/commands/inspect-contract.ts +87 -0
- package/src/commands/inspect-freshness.ts +217 -0
- package/src/commands/inspect-lock.ts +201 -0
- package/src/commands/inspect-options.ts +360 -0
- package/src/commands/inspect-orchestrate.ts +375 -0
- package/src/commands/inspect-process.ts +172 -0
- package/src/commands/inspect-ready.ts +65 -0
- package/src/commands/inspect-report.ts +235 -0
- package/src/commands/inspect-run-state.ts +296 -0
- package/src/commands/inspect-run.ts +157 -0
- package/src/commands/inspect-watchdog.ts +74 -0
- package/src/commands/install-joiner.ts +208 -0
- package/src/commands/login.ts +308 -0
- package/src/commands/models.ts +40 -0
- package/src/commands/parse-options.ts +36 -0
- package/src/commands/remix-package-json.ts +64 -0
- package/src/commands/remix.ts +379 -0
- package/src/commands/sdk-url.ts +141 -0
- package/src/commands/simulations.ts +133 -0
- package/src/commands/skills.ts +108 -0
- package/src/commands/store-files.ts +92 -0
- package/src/commands/stores.ts +703 -0
- package/src/commands/tiles-channel-commands.ts +115 -0
- package/src/commands/tiles-checkout.ts +351 -0
- package/src/commands/tiles-gallery-command.ts +95 -0
- package/src/commands/tiles-get-helpers.ts +27 -0
- package/src/commands/tiles-inspect.ts +276 -0
- package/src/commands/tiles-power-command.ts +308 -0
- package/src/commands/tiles-power-format.ts +396 -0
- package/src/commands/tiles-power-versions.ts +299 -0
- package/src/commands/tiles-publish-helpers.ts +145 -0
- package/src/commands/tiles-upload-command.ts +277 -0
- package/src/commands/tiles-version-commands.ts +201 -0
- package/src/commands/tiles-visibility-command.ts +103 -0
- package/src/commands/tiles.ts +257 -0
- package/src/commands/upgrade.ts +307 -0
- package/src/commit-in-progress.ts +42 -0
- package/src/creator-source-context.ts +97 -0
- package/src/creator-source-publish.ts +52 -0
- package/src/deferred-assets.ts +125 -0
- package/src/distribution.ts +28 -0
- package/src/errors.ts +61 -0
- package/src/install-command.ts +43 -0
- package/src/output.ts +62 -0
- package/src/poe-tile-config-files.ts +100 -0
- package/src/poe-tile-config-players.ts +168 -0
- package/src/poe-tile-config-remix.ts +166 -0
- package/src/poe-tile-config.ts +831 -0
- package/src/power-report-client.ts +55 -0
- package/src/prototype-startup.ts +21 -0
- package/src/publish-change-summary.ts +55 -0
- package/src/publish-overrides-validation.ts +49 -0
- package/src/publish-pack.ts +167 -0
- package/src/publish-phases.ts +57 -0
- package/src/publish-retry.ts +51 -0
- package/src/publish-tile-from-config.ts +434 -0
- package/src/recorder-stream.ts +169 -0
- package/src/remix-provenance.ts +156 -0
- package/src/resolve-client-credential.ts +71 -0
- package/src/resolve-media-uploads.ts +147 -0
- package/src/sdk-dependency.ts +54 -0
- package/src/sdk-skills.ts +85 -0
- package/src/should-skip-client-setup.ts +20 -0
- package/src/simulation-snapshot.ts +123 -0
- package/src/simulation-types.ts +74 -0
- package/src/simulations-client.ts +112 -0
- package/src/source-bundle.ts +466 -0
- package/src/staged-publish-cleanup.ts +44 -0
- package/src/staged-publish-deferred.ts +160 -0
- package/src/staged-publish.ts +401 -0
- package/src/store-file-upload.ts +268 -0
- package/src/store-request.ts +168 -0
- package/src/tar-canonical.ts +41 -0
- package/src/tar-extensions.ts +159 -0
- package/src/tar-extract.ts +193 -0
- package/src/tar-parse.ts +224 -0
- package/src/tar.ts +231 -0
- package/src/template-check-scripts.ts +18 -0
- package/src/tile-gallery-client.ts +82 -0
- package/src/types.ts +258 -0
- package/src/upload-concurrency.ts +54 -0
- package/src/whole-tile.ts +52 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# Forking Mutator Logic with `ctx.isServer`
|
|
2
|
+
|
|
3
|
+
Mutators run on both the client (optimistically) and the server (authoritatively). `ctx.isServer` lets you branch behavior between those two runs. Use it sparingly — the whole point of mutators is that the two runs converge.
|
|
4
|
+
|
|
5
|
+
## Legitimate Uses
|
|
6
|
+
|
|
7
|
+
### Pending Indicators
|
|
8
|
+
|
|
9
|
+
Show a "pending" state on the client that disappears when the server confirms:
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
sendMessage: async (ctx, input) => {
|
|
13
|
+
await ctx.table("messages").set({
|
|
14
|
+
itemKey: input.id,
|
|
15
|
+
value: {
|
|
16
|
+
text: input.text,
|
|
17
|
+
isPending: !ctx.isServer, // true on client, false on server
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
},
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The optimistic client write sets `isPending: true`; when the server run lands, its write replaces the row with `isPending: false`. The UI can render a subtle "sending..." indicator on pending items.
|
|
24
|
+
|
|
25
|
+
### Server-Only Writes
|
|
26
|
+
|
|
27
|
+
Writes to `ctx.serverOnly()` throw on the client. Guard them:
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
joinRound: async (ctx, input) => {
|
|
31
|
+
await ctx.table("players").set({
|
|
32
|
+
itemKey: ctx.userId,
|
|
33
|
+
value: { name: input.name, score: 0 },
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
if (ctx.isServer) {
|
|
37
|
+
await ctx.serverOnly().table("audit").set({
|
|
38
|
+
itemKey: ctx.userId,
|
|
39
|
+
value: { joinedAt: Date.now() },
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Cross-User Private Writes
|
|
46
|
+
|
|
47
|
+
`ctx.privateOfUser(otherUserId)` throws on the client when the target isn't `ctx.userId` (see [data-visibility.md](data-visibility.md) access matrix). Guard with `ctx.isServer`:
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
startRound: async (ctx) => {
|
|
51
|
+
// Validate on both sides so invalid calls fail fast on the caller's UI.
|
|
52
|
+
const players = (await ctx.table("players").entries().toArray()).map(([, v]) => v);
|
|
53
|
+
const redSpymaster = players.find((p) => p.team === "red" && p.role === "spymaster");
|
|
54
|
+
if (!redSpymaster) throw new Error("need a red spymaster");
|
|
55
|
+
|
|
56
|
+
// Cross-user private writes (and any non-deterministic generation) are
|
|
57
|
+
// server-only. The caller's UI shows a brief "starting..." state until
|
|
58
|
+
// the server-confirmed writes arrive.
|
|
59
|
+
if (!ctx.isServer) return;
|
|
60
|
+
|
|
61
|
+
const colors = assignColors(); // Math.random — server-only is fine
|
|
62
|
+
for (const { index, color } of colors) {
|
|
63
|
+
await ctx.privateOfUser(redSpymaster.userId).table("cardColors").set({
|
|
64
|
+
itemKey: String(index),
|
|
65
|
+
value: { index, color },
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Skip Optimistic Entirely When the Outcome Depends on Unreadable Data
|
|
72
|
+
|
|
73
|
+
Sometimes a mutator's outcome depends on data the caller can't read — another user's `privateOfUser` scope, or a `serverOnly` table. The client can't compute the full result, so any optimistic write is partial and the UI has to render an ambiguous in-between state. Usually cleaner to skip optimistic entirely:
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
revealCard: async (ctx, input) => {
|
|
77
|
+
// Validate on both sides so stale clicks (wrong phase / inactive team)
|
|
78
|
+
// fail fast on the caller's UI.
|
|
79
|
+
const phase = await ctx.table("game").get("phase");
|
|
80
|
+
if (phase !== "guessing") throw new Error(`bad phase: ${phase}`);
|
|
81
|
+
// ... other validation
|
|
82
|
+
|
|
83
|
+
// Outcome depends on reading a spymaster's private scope — caller can't.
|
|
84
|
+
// Skip optimistic; the click takes ~1 round-trip but the state transition
|
|
85
|
+
// is a single clean step (unrevealed → fully-resolved) instead of a
|
|
86
|
+
// half-filled flicker.
|
|
87
|
+
if (!ctx.isServer) return;
|
|
88
|
+
|
|
89
|
+
const color = await ctx.privateOfUser(spymasterId).table("cardColors").get(...);
|
|
90
|
+
await ctx.table("cards").set({ itemKey, value: { revealed: true, revealedAs: color } });
|
|
91
|
+
// ... update scores / switch turn / check winner
|
|
92
|
+
},
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
The alternative is to write a structured "pending" marker like in the [Pending Indicators](#pending-indicators) pattern — use that only when the UI benefits enough from immediate feedback to justify rendering a partial state explicitly. Never write a half-filled state (e.g., `revealed: true` but `revealedAs: null`) without a marker field the UI checks.
|
|
96
|
+
|
|
97
|
+
### Not Needed For `ctx.enqueueAction`
|
|
98
|
+
|
|
99
|
+
`ctx.enqueueAction(...)` is already a no-op on the client — call it unconditionally, no `ctx.isServer` guard required. The action only runs on the server after the triggering mutation commits.
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
// ✅ No guard needed
|
|
103
|
+
ctx.enqueueAction("generateWithAI", { id, prompt });
|
|
104
|
+
|
|
105
|
+
// ❌ Redundant — enqueueAction is already a client no-op
|
|
106
|
+
if (ctx.isServer) {
|
|
107
|
+
ctx.enqueueAction("generateWithAI", { id, prompt });
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Don't Do This
|
|
112
|
+
|
|
113
|
+
- **Don't put expensive client-only work inside `!ctx.isServer`.** If the work is client-only, do it in the UI layer, not inside the mutator.
|
|
114
|
+
- **Don't fork to work around non-determinism — usually.** If you're tempted to use `Date.now()` or `Math.random()` in one branch, pass the value as mutator input instead (the caller generates once; both client and server runs see the same value). **Exception:** when the non-deterministic value must stay hidden from the caller — e.g., generating a Spy Words color assignment a guesser is about to click through. Passing the seed as input would let the caller read it from their own local mutation log. In that case, put the generation behind `if (!ctx.isServer) return;` (see [Skip Optimistic Entirely](#skip-optimistic-entirely-when-the-outcome-depends-on-unreadable-data) above) and accept the ~1 round-trip latency.
|
|
115
|
+
- **Don't use `ctx.isServer` to reach different data conclusions** (e.g. reading different tables on client vs server). The two runs must converge on the same state.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# Singleton Tables
|
|
2
|
+
|
|
3
|
+
`singletonTable()` defines a table whose keys are statically known and each has its own type. Use it for typed app settings, config, or any table where the set of keys is fixed.
|
|
4
|
+
|
|
5
|
+
This differs from `table()` (collection of same-shape values, dynamic keys) and from the "singleton row" usage of `table()` (one row under a fixed key).
|
|
6
|
+
|
|
7
|
+
## Typed-Key Form
|
|
8
|
+
|
|
9
|
+
Each call to `item(key, schema)` declares one key and its value type:
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
import { defineSchema, singletonTable, item } from "joiner-sdk/v1/backend.js";
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
import { TILE_SCHEMA_VERSION } from "./tile-schema-version";
|
|
15
|
+
|
|
16
|
+
const schema = defineSchema({
|
|
17
|
+
schemaVersion: TILE_SCHEMA_VERSION,
|
|
18
|
+
tables: {
|
|
19
|
+
settings: {
|
|
20
|
+
schema: singletonTable(
|
|
21
|
+
item("theme", z.enum(["light", "dark"])),
|
|
22
|
+
item("itemsPerPage", z.number()),
|
|
23
|
+
),
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
mutators: { /* ... */ },
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
// Reads are type-narrowed per key:
|
|
30
|
+
await ctx.table("settings").get("theme"); // "light" | "dark" | undefined
|
|
31
|
+
await ctx.table("settings").get("itemsPerPage"); // number | undefined
|
|
32
|
+
await ctx.table("settings").get("invalid"); // TYPE ERROR — unknown key
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Single-Row Form
|
|
36
|
+
|
|
37
|
+
For a single logical record (e.g. a game-state row), use `table(valueSchema)` with a fixed itemKey:
|
|
38
|
+
|
|
39
|
+
```typescript
|
|
40
|
+
import { z } from "zod";
|
|
41
|
+
import { defineSchema, table } from "joiner-sdk/v1/backend.js";
|
|
42
|
+
import { TILE_SCHEMA_VERSION } from "./tile-schema-version";
|
|
43
|
+
|
|
44
|
+
const schema = defineSchema({
|
|
45
|
+
schemaVersion: TILE_SCHEMA_VERSION,
|
|
46
|
+
tables: {
|
|
47
|
+
game: { schema: table(z.object({ status: z.string(), turn: z.number() })) },
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
await ctx.table("game").get("game");
|
|
52
|
+
await ctx.table("game").set({ itemKey: "game", value: { status: "active", turn: 1 } });
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`singletonTable()` only accepts `item(key, schema)` arguments — there is no no-key form that takes a raw schema.
|
|
56
|
+
|
|
57
|
+
## When to Use Which
|
|
58
|
+
|
|
59
|
+
- **Collection of items** (todos, moves, messages): `table(valueSchema)` — keys are dynamic strings.
|
|
60
|
+
- **Typed settings bag** (per-key types differ): `singletonTable(item(...), item(...), ...)`.
|
|
61
|
+
- **Single logical record** with one shape: `table(valueSchema)` with a fixed itemKey like `"game"`.
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
# Sort Keys
|
|
2
|
+
|
|
3
|
+
A `sortKey` gives a table row an explicit ordering position, separate from its identity (`itemKey`). It exists to make unbounded, accumulating data that is mostly presented as one ordered list cheap to read a page at a time and cheap to sync, without ever loading the whole table into memory or shipping it all to every client.
|
|
4
|
+
|
|
5
|
+
This is the difference between a "toy" history table (fine while small, falls over once it accumulates) and a production one. If you are building anything that appends rows forever, read this before you design the schema.
|
|
6
|
+
|
|
7
|
+
## Do you actually need one?
|
|
8
|
+
|
|
9
|
+
Use a `sortKey` whenever **both** are true:
|
|
10
|
+
|
|
11
|
+
1. The table accumulates an unbounded, ever-growing number of rows (not a fixed small set), **and**
|
|
12
|
+
2. The rows are mostly presented as one ordered list — newest-first, chronological, or sequence position.
|
|
13
|
+
|
|
14
|
+
Pagination does not need to exist yet. Assigning sort keys during schema design keeps the data lazily loadable when the list grows; omitting them makes every row always-loaded.
|
|
15
|
+
|
|
16
|
+
A safety cap or per-user quota does not make a naturally accumulating history bounded for this decision. Those limits protect storage; sort keys protect each client's initial load and memory use.
|
|
17
|
+
|
|
18
|
+
Examples:
|
|
19
|
+
|
|
20
|
+
- A message or activity history appended in chronological order.
|
|
21
|
+
- A social or photo feed of user posts, normally shown newest-first.
|
|
22
|
+
|
|
23
|
+
A todo list, a per-user score row, a settings singleton, a lobby of ≤200 players — none of these need a sortKey. Their row count stays small and bounded, so a plain `scan()` over the whole table is simpler, correct, and fast. Adding a `sortKey` (and the `pullWindows` / `firstRenderBytes` tuning it unlocks) to a small table adds real complexity for zero benefit.
|
|
24
|
+
|
|
25
|
+
Rule of thumb: **if you'd be comfortable holding every row of the table in memory at once, you don't need a sortKey.**
|
|
26
|
+
|
|
27
|
+
## Identity vs. ordering: two independent axes
|
|
28
|
+
|
|
29
|
+
Every row is addressed by two independent components:
|
|
30
|
+
|
|
31
|
+
- **`itemKey`** — identity. Uniquely identifies the row within the table. This is what `get(itemKey)`, `has(itemKey)`, `delete(itemKey)`, and `set({ itemKey })` operate on.
|
|
32
|
+
- **`sortKey`** — ordering only. Determines where the row sorts relative to its siblings. Not part of identity. Two different rows may not share an `itemKey`, but they can carry unrelated `sortKey`s, or none.
|
|
33
|
+
|
|
34
|
+
Scans always return entries ordered by `(sortKey, itemKey)` ascending. A row written with no `sortKey` defaults to `""`, so all no-sortKey rows sort together, ahead of any row that has one.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
// entries() / scan() ordering — sorted by (sortKey, itemKey):
|
|
38
|
+
// { sortKey: "", itemKey: "b" } ← no sortKey → "" sorts first
|
|
39
|
+
// { sortKey: "", itemKey: "c" }
|
|
40
|
+
// { sortKey: "msg/0", itemKey: "..." }
|
|
41
|
+
// { sortKey: "msg/1", itemKey: "..." }
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`EntryKey` (what `scan().entries()` and `scan().keys()` yield) is `{ sortKey?: string; itemKey: string }`. You can pass an `EntryKey` straight back into `set`/`delete` for read-modify-write loops.
|
|
45
|
+
|
|
46
|
+
## Attaching a sortKey with `.set()`
|
|
47
|
+
|
|
48
|
+
`sortKey` is a field on the `.set()` params, alongside `itemKey` and `value`:
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
await ctx.table("messages").set({
|
|
52
|
+
sortKey, // ordering position (see getNextSortKey below)
|
|
53
|
+
itemKey, // identity
|
|
54
|
+
value,
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Precedence when resolving the sortKey (see `resolveTableSetKey`):
|
|
59
|
+
|
|
60
|
+
1. An explicit `params.sortKey` wins.
|
|
61
|
+
2. Otherwise, if `itemKey` is itself an `EntryKey` carrying a `sortKey`, that is used.
|
|
62
|
+
3. Otherwise `sortKey` defaults to `""`.
|
|
63
|
+
|
|
64
|
+
So `set({ itemKey: someEntryKey, value })` preserves that entry's existing sortKey; passing an explicit `sortKey` overrides it.
|
|
65
|
+
|
|
66
|
+
### Changing a row's sortKey is just another `.set()`
|
|
67
|
+
|
|
68
|
+
Calling `.set()` for an existing `itemKey` with a **different** `sortKey` automatically re-homes the row: the client emits a tombstone at the old position and writes the new one (tombstone-on-move). You don't delete-then-recreate — one `set({ itemKey, sortKey: newSortKey, value })` moves it. Identity (`itemKey`) is preserved; only the ordering position changes.
|
|
69
|
+
|
|
70
|
+
### Validation limits
|
|
71
|
+
|
|
72
|
+
- `sortKey` and `itemKey` may not contain `:` (the internal storage-key delimiter) or a null character `\0`. Both throw at `.set()` time, on the optimistic client pass, so a bad key rejects the `await store.mutate.*` synchronously rather than silently rolling back on the server.
|
|
73
|
+
- Standard [key/value size limits](limitations.md) still apply; `sortKey` is excluded from the key-length limit.
|
|
74
|
+
- All data sharing one `sortKey` forms one atomic logical pull group. Synced-store may stream a large group through several response messages targeted below 8 MiB each, safely under the 32 MiB server-to-client ceiling; the client buffers every fragment and exposes the group only when complete. Pull byte budgets never select only part of a group. Use a distinct sort key for each independently pageable unit. See [synced-store limits](limitations.md).
|
|
75
|
+
|
|
76
|
+
## Generating sort keys: `ctx.getNextSortKey({ namespace })`
|
|
77
|
+
|
|
78
|
+
**Do not hand-roll sort keys from `Date.now()`.** Clock skew across devices produces collisions and out-of-order keys; a mutator re-running on the server or during rebase would read a different clock than the optimistic client pass. Instead, generate them inside a mutator:
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const sortKey = await ctx.getNextSortKey({ namespace: "msg" });
|
|
82
|
+
await ctx.table("messages").set({ sortKey, itemKey: input.id, value: msg });
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Behavior (verified across in-memory, Bun, QuickJS, and Cloudflare backends):
|
|
86
|
+
|
|
87
|
+
- **Format:** `{namespace}/{sortableNumber}`, e.g. `msg/0`, `msg/1`, … The suffix is a sortable-string encoding of a monotonic counter, so lexical order equals numeric order. The first key in a namespace has counter `0`.
|
|
88
|
+
- **Monotonic and unique**, even for multiple calls within one mutator (a per-transaction counter guarantees consecutive calls advance without an intervening write) and across separate mutations.
|
|
89
|
+
- **Safe under concurrency and offline writes.** Multiple clients (including offline ones that reconnect) writing to the same namespace converge to a consistent order. Only direct `{namespace}/{counter}` children seed the counter; nested descendants are ignored.
|
|
90
|
+
- **The counter never rewinds after deletion.** Delete the row at `msg/1` and the next generated key is still `msg/2`, never a reused `msg/1`. This keeps ordering stable and prevents a resurrected key from colliding with a tombstone.
|
|
91
|
+
- **Namespaces are independent counters.** `getNextSortKey({ namespace: "a" })` and `{ namespace: "a/thread" }` advance separately. A namespace must be non-empty and may not contain `:`. Custom direct-child keys are unsupported and can cause server rejection; custom nested descendants do not affect the parent counter.
|
|
92
|
+
|
|
93
|
+
The namespace is not just cosmetic — it's the unit that `pullWindows` targets (below). Choose one deliberately (e.g. `"msg"` for chat messages) and use it consistently in both the mutator and the schema.
|
|
94
|
+
|
|
95
|
+
### Migrating existing rows
|
|
96
|
+
|
|
97
|
+
Adding a sort key to future writes does not change rows already stored with the default empty sort key; those rows remain eager and outside the ordered history. When adopting sort keys for an existing table, run a schema/data migration or explicitly rebuild every existing row with a nonempty key. Assign keys in the intended historical order, in the namespace covered by the configured pull window.
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
## Scanning ordered data
|
|
101
|
+
|
|
102
|
+
All scans sort by `(sortKey, itemKey)`. On top of that:
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
// Latest N (newest-first): descending order, capped
|
|
106
|
+
table.scan({ limit: 50, reverse: true });
|
|
107
|
+
|
|
108
|
+
// Oldest N: ascending, capped
|
|
109
|
+
table.scan({ limit: 50 });
|
|
110
|
+
|
|
111
|
+
// Paginate forward from a known entry (its EntryKey is the cursor):
|
|
112
|
+
table.scan({ limit: 50, cursor: lastEntryKey });
|
|
113
|
+
|
|
114
|
+
// Range within a namespace (prefix on the sortKey):
|
|
115
|
+
table.scan({ prefix: { sortKey: "msg/" }, limit: 50 });
|
|
116
|
+
|
|
117
|
+
// One complete sort-key group (all rows whose sortKey is exactly "msg/042"):
|
|
118
|
+
table.scan({ exactSortKey: "msg/042" });
|
|
119
|
+
|
|
120
|
+
// A window centered on an anchor (e.g. jumping to a search hit): up to 5
|
|
121
|
+
// before the anchor, the anchor if present, then up to 45 after — ascending.
|
|
122
|
+
table.scan({ cursor: { sortKey, itemKey }, aroundCursor: { before: 5, after: 45 } });
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Details:
|
|
126
|
+
|
|
127
|
+
- **`cursor`** is an `EntryKey` **or** a sentinel: `"$first"` (before every entry) / `"$last"` (after every entry). In forward mode `limit` returns entries strictly past the cursor; with `reverse` it returns entries strictly before it. Sentinels resolve symmetrically — `{ cursor: "$last", limit: 5, reverse: true }` is the last 5 in descending order.
|
|
128
|
+
- **`exactSortKey`** selects one complete sort-key group and lets server-side scans use the exact `(sortKey, tableName)` index range instead of scanning every row in the table. It is mutually exclusive with `prefix.sortKey`. Use `exactSortKey: ""` to select only rows with no explicit sort key; an empty prefix would match every row.
|
|
129
|
+
- **`reverse`** flips the returned order to descending. `{ limit: 5, reverse: true }` gives the newest 5 in descending order; the same set ascending (no manual reverse) is `{ cursor: "$last", aroundCursor: { before: 5, after: 0 } }`.
|
|
130
|
+
- **`aroundCursor: { before, after }`** returns a bidirectional window. Requires `cursor`; mutually exclusive with `limit`; `before`/`after` must be ≥ 0. **Client-only** — it runs in queries and `subscribeToTable`, but a **server-side** scan (inside a mutator or action) throws, because the bidirectional slice needs a full-table load that conflicts with the server's streaming scan model. If you truly need context around an anchor server-side, compose two `{ cursor, limit }` scans (one forward, one `reverse`) and merge.
|
|
131
|
+
|
|
132
|
+
### `itemKey`-prefix scans are unaffected by sort keys
|
|
133
|
+
|
|
134
|
+
`prefix.sortKey` and `prefix.itemKey` are **independent filters** on `scan({ prefix })`. Adding a `sortKey` to some or all rows in a table does **not** change what an `itemKey`-prefix scan returns:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
// This keeps returning exactly the same rows whether or not those rows
|
|
138
|
+
// also carry a sortKey. The two prefix axes are orthogonal.
|
|
139
|
+
table.scan({ prefix: { itemKey: "bet-" } });
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
So a table that already partitions rows by an `itemKey` naming convention can start attaching sort keys for ordering without breaking any existing identity-prefix reads. You can also combine both axes in one scan (`prefix: { itemKey, sortKey }`) — a row must match both to be returned.
|
|
143
|
+
|
|
144
|
+
## The performance model: eager vs. lazy download
|
|
145
|
+
|
|
146
|
+
This is the reason sort keys exist, and the part most people miss.
|
|
147
|
+
|
|
148
|
+
- **Rows with no sortKey (`""`) are downloaded eagerly.** They are exempt from the pull byte-budget (they "freeload" — counted as 0 bytes) and sync to every client on every pull regardless of any `pullWindows` / `firstRenderBytes` config. Good for small, always-needed state (a game's config singleton, current status, roster).
|
|
149
|
+
- **Rows with a sortKey are downloaded lazily.** They are subject to the byte budget and to windowing — streamed progressively, in the order and quantity the schema's `pullWindows` / `firstRenderBytes` and the client's budget allow.
|
|
150
|
+
|
|
151
|
+
Giving a table's rows a sortKey is precisely **what makes them lazy**. That is why the feature only pays off for large, unbounded tables: on a small table you'd just be opting rows out of the eager fast-path for no reason.
|
|
152
|
+
|
|
153
|
+
**Mixing eager and lazy rows in one store is expected.** Always-needed data with the empty sort key (`sortKey: ""`) can always live alongside lazily loaded rows with nonempty sort keys. For example, keep a small config/status row eager while an unbounded message history uses `msg/...` sort keys and pull windows.
|
|
154
|
+
|
|
155
|
+
## Schema-level pull tuning
|
|
156
|
+
|
|
157
|
+
Two optional fields on `defineSchema({ ... })` control how sortKey'd data streams. Both are advanced — only configure them once a table's row count can grow unbounded.
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
defineSchema({
|
|
161
|
+
schemaVersion: 1,
|
|
162
|
+
// Load newest messages first; older ones stream in / load-more on demand.
|
|
163
|
+
pullWindows: [{ namespace: "msg", direction: "descending" }],
|
|
164
|
+
// Cap the initial synchronous payload so first render isn't blocked on history.
|
|
165
|
+
firstRenderBytes: 5_000,
|
|
166
|
+
tables: { /* ... */ },
|
|
167
|
+
mutators: { /* ... */ },
|
|
168
|
+
});
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### `pullWindows: PullWindow[]`
|
|
172
|
+
|
|
173
|
+
Each window is `{ namespace?, direction?, cursor?, loaded_range? }`:
|
|
174
|
+
|
|
175
|
+
- **`namespace`** — scopes the window to sortKeys matching `${namespace}/*` (range `["${namespace}/", "${namespace}/"]`), matching the `namespace` you pass to `getNextSortKey`. Omit for an unbounded window over all sortKeys. Required for `outward`.
|
|
176
|
+
- **`direction`** — `"ascending"` (oldest→newest, the default), `"descending"` (newest→oldest), or `"outward"` (stream both directions from an anchor, splitting the budget fairly).
|
|
177
|
+
- **`cursor`** — where streaming starts for ascending/descending. Defaults to `"$first"` (ascending) / `"$last"` (descending). Supports shorthand: `"$first"`/`"$last"` (global start/end), `"msg/$first"`/`"msg/$last"` (namespace start/end), or a literal sortKey. Omitted for `outward` (its runtime cursor comes from the anchor).
|
|
178
|
+
|
|
179
|
+
- **In practice, use one pull window per schema.** The API accepts an array, but its windows run sequentially against one shared byte budget, cannot be loaded independently, and may overlap.
|
|
180
|
+
- **Use one namespace for one ordered stream.** For a feed, give each post a new `feed/...` sort key and reuse that exact key for bounded associated rows such as a capped comment preview, so they occupy the same atomic lazy-loaded position. An unbounded comment history must not share the post's key; paginate it separately.
|
|
181
|
+
|
|
182
|
+
**`outward` windows need a runtime anchor.** The anchor sortKey is supplied by the platform at open time — `Poe.open({ anchorSortKey })` or `<poe-tile anchor-sort-key={...}>` — not in the schema. Use it to jump into the middle of a long history (e.g. opening a chat at a specific message from a search result) and stream context in both directions. A missing/empty anchor makes the outward window inactive for that pull. All outward windows in a schema share the one session anchor.
|
|
183
|
+
|
|
184
|
+
**Default when omitted:** `pullWindows` defaults to `[{}]` — a single unbounded window covering every sortKey. That syncs all sortKey'd data (budget permitting), which is usually what you want until a table gets large.
|
|
185
|
+
|
|
186
|
+
### `firstRenderBytes`
|
|
187
|
+
|
|
188
|
+
Targets how many bytes of non-empty-sortKey data are bundled into the first server page, so first paint doesn't block on the whole history. It defaults to 25,000 bytes and can be overridden per schema. The complete `""` group is included first and consumes zero budget; the framework then includes complete logical sort-key groups in pull-window order until the next group would exceed the target. The target is not a hard logical-group cap and a selected group may exceed it; transport fragmentation is independent and invisible to the client API. Remaining groups stream afterward.
|
|
189
|
+
|
|
190
|
+
For a cold non-creator launch, `waitForBootstrap()` resolves after that first server page is applied. It is not universally a server-readiness boundary: a compatible local cache can resolve it earlier, and creator/prepared instances can bootstrap immediately. Use `waitForServerData()` or `waitForInitialPull()` when code specifically needs server-origin data or completion of the full initial pull.
|
|
191
|
+
|
|
192
|
+
### Footgun: explicit `pullWindows` silently drops rows outside every window
|
|
193
|
+
|
|
194
|
+
Once you specify `pullWindows` explicitly, you **replace** the default `[{}]`. Any row whose sortKey falls outside every configured window's namespace **will not sync to the client** — no error, it just isn't there.
|
|
195
|
+
|
|
196
|
+
The classic mistake: a store has a `config`/status row written with a sortKey like `"config"`, plus a big `mem/…` history table. Someone adds `pullWindows: [{ namespace: "mem", direction: "descending" }]` to window the history — and the `config` row, whose sortKey `"config"` is outside the `"mem/"` namespace, stops syncing. The UI is then stuck on an empty/uninitialized state in production, with everything looking fine in tests that share client/server state.
|
|
197
|
+
|
|
198
|
+
Two ways to avoid it:
|
|
199
|
+
|
|
200
|
+
1. **Keep always-needed rows sortKey-free** (write them with no `sortKey`, so they're eager and window-exempt), and only give ordered-history rows a sortKey. This is the cleanest split.
|
|
201
|
+
2. Or, if an always-needed row must carry a sortKey, **add a window that covers it** — e.g. include an unbounded `{}` window or a window for its namespace alongside the history window.
|
|
202
|
+
|
|
203
|
+
When you narrow `pullWindows`, enumerate every sortKey'd row in the store and confirm each still falls inside some window.
|
|
204
|
+
|
|
205
|
+
## Client-side pagination / "load more"
|
|
206
|
+
|
|
207
|
+
Once a schema windows its history, the store exposes read state and a pull trigger for scroll-to-load UIs:
|
|
208
|
+
|
|
209
|
+
- **`store.moreDataAvailable`** — `true` when more sortKey'd data exists beyond what the last pull loaded. It only reflects truncation for a returning member, not the genesis creator: the first client created for a store is bootstrapped as its creator, and that path doesn't surface budget-exhaustion on the flag.
|
|
210
|
+
- **`store.moreOlderDataAvailable` / `store.moreNewerDataAvailable`** — directional variants for `outward` windows (older = smaller sortKeys, newer = larger).
|
|
211
|
+
- **`store.loadMore(arg?)`** — fetch more, resolving when the pull completes:
|
|
212
|
+
- `loadMore()` — bump the byte budget by the default amount.
|
|
213
|
+
- `loadMore(50_000)` — bump the budget by 50KB.
|
|
214
|
+
- `loadMore("start")` / `loadMore("end")` — hint the active `outward` window to extend toward older / newer sortKeys on the next pull (budget unchanged).
|
|
215
|
+
- `loadMore({ direction: "start", additionalBytes: 20_000 })` — combine both.
|
|
216
|
+
|
|
217
|
+
Concurrent `loadMore` calls are deduped: a second call while one is in flight returns the first call's promise and ignores its own args. Await before re-calling if you need precise control.
|
|
218
|
+
|
|
219
|
+
## Worked pattern: a chat-style message log
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
// schema.ts — window newest-first; keep the small "room settings" row eager.
|
|
223
|
+
export const chatSchema = defineSchema({
|
|
224
|
+
schemaVersion: 1,
|
|
225
|
+
pullWindows: [{ namespace: "msg", direction: "descending" }],
|
|
226
|
+
firstRenderBytes: 8_000,
|
|
227
|
+
tables: {
|
|
228
|
+
// Big, append-only, ordered: every row gets a "msg/…" sortKey → lazy.
|
|
229
|
+
messages: { schema: table(messageSchema) },
|
|
230
|
+
// Small, always needed: NO sortKey → eager, window-exempt.
|
|
231
|
+
settings: { schema: table(settingsSchema) },
|
|
232
|
+
},
|
|
233
|
+
mutators: { postMessage: { input: postInputSchema } },
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// mutators/post-message.ts
|
|
237
|
+
export const postMessage: TileMutator<"postMessage"> = async (ctx, input) => {
|
|
238
|
+
const sortKey = await ctx.getNextSortKey({ namespace: "msg" });
|
|
239
|
+
await ctx.table("messages").set({
|
|
240
|
+
sortKey,
|
|
241
|
+
itemKey: input.id, // stable identity generated at the call site
|
|
242
|
+
value: { id: input.id, text: input.text, userId: ctx.userId, at: input.at },
|
|
243
|
+
});
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
// UI: newest page first, then scroll up to load older.
|
|
247
|
+
const latest = await store.query((tx) =>
|
|
248
|
+
tx.table("messages").scan({ limit: 50, reverse: true }).entries().toArray(),
|
|
249
|
+
);
|
|
250
|
+
if (store.moreDataAvailable) await store.loadMore();
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
The `settings` row rides the eager fast-path and is always present on first render; the `messages` history streams newest-first within the byte budget and pages in on demand — no client ever holds the entire message history in memory.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Synced-Store UI Subscription Patterns
|
|
2
|
+
|
|
3
|
+
## Table of Contents
|
|
4
|
+
- [React / Preact](#react--preact)
|
|
5
|
+
- [SolidJS](#solidjs)
|
|
6
|
+
- [System Tables](#system-tables)
|
|
7
|
+
- [Store Client API](#store-client-api)
|
|
8
|
+
|
|
9
|
+
## React / Preact
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
import { useState, useEffect } from "react"; // or "preact/hooks"
|
|
13
|
+
import type { TileStoreClient, ItemType } from "../client";
|
|
14
|
+
|
|
15
|
+
export function App({ store }: { store: TileStoreClient }) {
|
|
16
|
+
const [items, setItems] = useState<ItemType[]>([]);
|
|
17
|
+
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
const unsubscribe = store.subscribe(
|
|
20
|
+
(tx) => tx.table("items").entries().toArray(),
|
|
21
|
+
(entries) => {
|
|
22
|
+
setItems(entries.map(([, v]) => v as ItemType).sort((a, b) => a.order - b.order));
|
|
23
|
+
},
|
|
24
|
+
);
|
|
25
|
+
return unsubscribe;
|
|
26
|
+
}, [store]);
|
|
27
|
+
|
|
28
|
+
// Mutate — fire-and-forget (optimistic)
|
|
29
|
+
const addItem = () => {
|
|
30
|
+
store.mutate.setItem({ id: crypto.randomUUID(), text: "new" });
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
return <ul>{items.map(i => <li key={i.id}>{i.text}</li>)}</ul>;
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
**Provider pattern** (React): Create a context + hook so components don't receive `store` as a prop:
|
|
38
|
+
```typescript
|
|
39
|
+
const StoreContext = createContext<TileStoreClient | null>(null);
|
|
40
|
+
export const useStore = () => useContext(StoreContext)!;
|
|
41
|
+
// Wrap in entry.tsx: <StoreContext.Provider value={store}><App /></StoreContext.Provider>
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## SolidJS
|
|
45
|
+
|
|
46
|
+
```typescript
|
|
47
|
+
import { createStore, reconcile } from "solid-js/store";
|
|
48
|
+
import { onMount, onCleanup, For } from "solid-js";
|
|
49
|
+
|
|
50
|
+
export function App(props: { store: TileStoreClient }) {
|
|
51
|
+
const [state, setState] = createStore<{ items: ItemType[] }>({ items: [] });
|
|
52
|
+
|
|
53
|
+
onMount(() => {
|
|
54
|
+
const unsub = props.store.subscribeToTable("items", (entries) => {
|
|
55
|
+
const items = (entries as [{ itemKey: string }, ItemType][])
|
|
56
|
+
.map(([, v]) => v)
|
|
57
|
+
.sort((a, b) => a.order - b.order);
|
|
58
|
+
setState("items", reconcile(items, { key: "id" }));
|
|
59
|
+
});
|
|
60
|
+
onCleanup(() => unsub());
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
return <For each={state.items}>{(item) => <div>{item.text}</div>}</For>;
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
**Key difference**: SolidJS uses `subscribeToTable(name, callback)` instead of `subscribe(query, callback)`. Use `reconcile()` with a key to preserve DOM nodes across updates (see `docs/solidjs-best-practices.md`).
|
|
68
|
+
|
|
69
|
+
## System Tables
|
|
70
|
+
|
|
71
|
+
For member profiles, membership roster, current-user lookup in the UI, and permission checks, see [getting-user-info-of-members.md](getting-user-info-of-members.md) — covers `$userInfo`, `$users`, `$permissions`, and the `getUserInfo` helper.
|
|
72
|
+
|
|
73
|
+
## Store Client API
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
// Mutations (optimistic, returns confirmation promise)
|
|
77
|
+
const { confirmed } = await store.mutate.myMutator(input);
|
|
78
|
+
await confirmed; // wait for server acknowledgement
|
|
79
|
+
|
|
80
|
+
// Queries
|
|
81
|
+
const value = await store.query((tx) => tx.table("items").get("key"));
|
|
82
|
+
|
|
83
|
+
// Subscriptions (React)
|
|
84
|
+
const unsub = store.subscribe(
|
|
85
|
+
(tx) => tx.table("items").entries().toArray(),
|
|
86
|
+
(result) => { /* called when a tracked item row changes */ },
|
|
87
|
+
);
|
|
88
|
+
unsub(); // cleanup
|
|
89
|
+
|
|
90
|
+
// Subscriptions (SolidJS)
|
|
91
|
+
const unsub = store.subscribeToTable("items", (entries, changes) => {
|
|
92
|
+
// entries: full snapshot
|
|
93
|
+
// changes: { added: string[], modified: string[], removed: string[] }
|
|
94
|
+
});
|
|
95
|
+
```
|
|
File without changes
|