@joiner-platform/cli 0.0.0-stage → 0.1.1
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 +149 -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 +197 -0
- package/skills/tile-creator/references/assets.md +124 -0
- package/skills/tile-creator/references/backend-api.md +354 -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,131 @@
|
|
|
1
|
+
# Compact data before the live data limit
|
|
2
|
+
|
|
3
|
+
Add `onLiveDataLimitApproaching(ctx, { availableBytes, liveDataSize, maxLiveDataSize })`
|
|
4
|
+
to the backend config's `hooks`. The server-only hook can scan rows, assemble
|
|
5
|
+
an archive, store a file, and replace the rows with a file reference in one mutation.
|
|
6
|
+
|
|
7
|
+
## Archive the oldest messages
|
|
8
|
+
|
|
9
|
+
This example scans `messages` in ascending `sortKey` order, breaking ties by
|
|
10
|
+
`itemKey`. Give messages nonempty sort keys that increase with message time so
|
|
11
|
+
the scan returns the oldest messages first. `authors` contains their authors'
|
|
12
|
+
display profiles. Keep each message and profile bounded in the schema. Declare
|
|
13
|
+
the archive's file references so the store retains the file when the mutation
|
|
14
|
+
commits:
|
|
15
|
+
|
|
16
|
+
```typescript
|
|
17
|
+
archives: {
|
|
18
|
+
schema: table(z.object({
|
|
19
|
+
fileIds: z.array(z.string()),
|
|
20
|
+
messageCount: z.number(),
|
|
21
|
+
lastSortKey: z.string(),
|
|
22
|
+
})),
|
|
23
|
+
fileRefs: { strong: ["fileIds"] },
|
|
24
|
+
},
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Add the hook to `defineBackendConfig({ schema, mutators, hooks })`:
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
hooks: {
|
|
31
|
+
onLiveDataLimitApproaching: async (ctx, { availableBytes, liveDataSize, maxLiveDataSize }) => {
|
|
32
|
+
console.info("Live data limit approaching", {
|
|
33
|
+
availableBytes,
|
|
34
|
+
liveDataSize,
|
|
35
|
+
maxLiveDataSize,
|
|
36
|
+
});
|
|
37
|
+
const limit = availableBytes < 1_000_000 ? 100 : 50;
|
|
38
|
+
const messages = await ctx.table("messages")
|
|
39
|
+
.scan({ limit, reverse: false })
|
|
40
|
+
.entries()
|
|
41
|
+
.toArray();
|
|
42
|
+
if (messages.length === 0) return;
|
|
43
|
+
|
|
44
|
+
const authorIds = [...new Set(messages.map(([, message]) => message.authorId))];
|
|
45
|
+
const authors = await Promise.all(authorIds.map(async (id) => ({
|
|
46
|
+
id,
|
|
47
|
+
profile: (await ctx.table("authors").get(id)) ?? null,
|
|
48
|
+
})));
|
|
49
|
+
const archive = {
|
|
50
|
+
messages: messages.map(([key, value]) => ({
|
|
51
|
+
itemKey: key.itemKey,
|
|
52
|
+
sortKey: key.sortKey ?? "",
|
|
53
|
+
value,
|
|
54
|
+
})),
|
|
55
|
+
authors,
|
|
56
|
+
};
|
|
57
|
+
const bytes = new TextEncoder().encode(JSON.stringify(archive));
|
|
58
|
+
|
|
59
|
+
await Promise.all(messages.map(([key]) => ctx.table("messages").delete(key)));
|
|
60
|
+
const file = await ctx.files.store(bytes, { name: "messages.json" });
|
|
61
|
+
await ctx.table("archives").set({
|
|
62
|
+
itemKey: file.fileId,
|
|
63
|
+
sortKey: messages[0]![0].sortKey,
|
|
64
|
+
value: {
|
|
65
|
+
fileIds: [file.fileId],
|
|
66
|
+
messageCount: messages.length,
|
|
67
|
+
lastSortKey: messages[messages.length - 1]![0].sortKey ?? "",
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`reverse: false` explicitly selects ascending order; `reverse: true` would scan
|
|
75
|
+
in descending order. This archives the oldest messages and a snapshot of their
|
|
76
|
+
related author profiles. The authors remain live. This example archives 50
|
|
77
|
+
messages, or 100 when remaining quota falls below one million bytes.
|
|
78
|
+
Choose a batch size that fits the hook's execution, memory, key-count, and
|
|
79
|
+
file-size limits.
|
|
80
|
+
Keep the archive reference in the same visibility tier as its source rows.
|
|
81
|
+
|
|
82
|
+
The deletions above only change the pending mutation. `await ctx.files.store()`
|
|
83
|
+
uploads the bytes first, then the final database commit publishes the file
|
|
84
|
+
record and reference together with the deletions. If the upload, hook, or commit
|
|
85
|
+
fails, the original rows remain. Unretained bytes from an aborted upload are
|
|
86
|
+
eligible for normal file-storage cleanup. Always await the store call and
|
|
87
|
+
reference its returned `fileId` through a declared `fileRefs` field in the same
|
|
88
|
+
mutation. File uploads require an initiating user.
|
|
89
|
+
|
|
90
|
+
## When the hook runs
|
|
91
|
+
|
|
92
|
+
The server evaluates capacity after the normal mutations and hooks in an
|
|
93
|
+
operation group, including the file claims they made. A client push is one
|
|
94
|
+
group. The callback runs once when the group has increased live data and projected
|
|
95
|
+
usage is at least 80% of the configured limit. Later growing groups notify
|
|
96
|
+
again. No-op and shrinking groups do not notify, and writes inside this
|
|
97
|
+
callback do not recursively invoke it.
|
|
98
|
+
|
|
99
|
+
The input uses the same usage and limit names as `store.getDiagnostics()`:
|
|
100
|
+
|
|
101
|
+
- `liveDataSize`: projected live usage, including the triggering group's pending writes.
|
|
102
|
+
- `maxLiveDataSize`: the configured live data limit.
|
|
103
|
+
- `availableBytes`: nonnegative remaining capacity, `Math.max(0, maxLiveDataSize - liveDataSize)`.
|
|
104
|
+
|
|
105
|
+
All three describe the invocation snapshot, before this callback's writes.
|
|
106
|
+
They are UTF-8 BYTES, the same unit as the quota itself.
|
|
107
|
+
Later diagnostics can differ after the hook compacts data. Each live row counts
|
|
108
|
+
the UTF-8 byte length of `sortKey`, `storedTableName`, `itemKey`, and
|
|
109
|
+
`JSON.stringify(value)` added together — so non-ASCII text costs more than its
|
|
110
|
+
character count: 2 bytes for most accented Latin, 3 for CJK, 4 for emoji.
|
|
111
|
+
Appending 100 CJK characters to a stored string raises `liveDataSize` by 300,
|
|
112
|
+
not 100, and lowers `availableBytes` by the same amount.
|
|
113
|
+
File contents do not count toward this live data limit; file records and
|
|
114
|
+
references do. Legacy stores begin notifications after exact size accounting
|
|
115
|
+
is available.
|
|
116
|
+
|
|
117
|
+
The hook runs only on the server and preserves the triggering operation's
|
|
118
|
+
user and source. It can read and write application tables, store files, and
|
|
119
|
+
enqueue actions. Ordinary client mutators cannot call `ctx.files.store()`.
|
|
120
|
+
The hook cannot write platform-owned system tables. Normal mutation size,
|
|
121
|
+
key count, file ownership, file quotas, and live data limits still apply.
|
|
122
|
+
|
|
123
|
+
Callback writes commit atomically with their triggering group. If the callback
|
|
124
|
+
throws, that group's writes and queued work roll back.
|
|
125
|
+
|
|
126
|
+
This is an early warning. Existing quota checks run before the callback, so a
|
|
127
|
+
mutation that already exceeds the hard limit is rejected. A large push can
|
|
128
|
+
hit that limit before its final capacity check.
|
|
129
|
+
|
|
130
|
+
File creation has its own size and execution limits. See
|
|
131
|
+
[file uploads](file-uploads.md) before selecting batch sizes.
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
# Mutator Rules
|
|
2
|
+
|
|
3
|
+
Mutators run twice: optimistically on the client, then authoritatively on the server. They can also **replay** during rebase when other mutations arrive from the server. The rules below make replay and double-execution safe.
|
|
4
|
+
|
|
5
|
+
## 1. Use Explicit Values, Not Toggles
|
|
6
|
+
|
|
7
|
+
Replay sees the current state, not the state at the time the mutation was created. A toggle (`!current.done`) can flip the wrong way if another user changed the value in between.
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
// BAD: can flip the wrong way during rebase
|
|
11
|
+
await ctx.table("todos").set({ itemKey: id, value: { ...todo, done: !todo.done } });
|
|
12
|
+
|
|
13
|
+
// GOOD: pass the intended value
|
|
14
|
+
await ctx.table("todos").set({ itemKey: id, value: { ...todo, done: true } });
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## 2. Generate IDs Outside Mutators
|
|
18
|
+
|
|
19
|
+
Mutators run on both client and server. Generating IDs inside produces different IDs on each run, splitting the "same" mutation into two different rows.
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
// BAD: different ID on client vs server
|
|
23
|
+
addTodo: async (ctx, { text }) => {
|
|
24
|
+
const id = Math.random().toString();
|
|
25
|
+
await ctx.table("todos").set({ itemKey: id, value: { text } });
|
|
26
|
+
},
|
|
27
|
+
|
|
28
|
+
// GOOD: generate outside, pass in
|
|
29
|
+
const id = crypto.randomUUID();
|
|
30
|
+
await store.mutate.setTodo({ id, text: "Buy milk" });
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Same applies to `Date.now()` — pass timestamps in from the client instead of reading the clock inside the mutator.
|
|
34
|
+
|
|
35
|
+
That makes a timestamp deterministic, **not trusted**. A server
|
|
36
|
+
[action](actions.md) can derive `Date.now()` instead of accepting a caller's
|
|
37
|
+
clock, which is useful for honest-client behavior. It is not currently a hard
|
|
38
|
+
authorization boundary: an action writes through `ctx.mutate(...)`, and that
|
|
39
|
+
same schema mutator remains directly callable by clients. Do not claim that an
|
|
40
|
+
action-to-mutator design makes adversarial daily streaks, cooldowns, or
|
|
41
|
+
deadlines tamper-resistant. The platform needs a backend-enforced app-internal
|
|
42
|
+
mutator (or transactional action writes) before those rules can rely solely on
|
|
43
|
+
server-derived time.
|
|
44
|
+
|
|
45
|
+
Storage keys also have a character constraint: `itemKey`, `sortKey`, and sort
|
|
46
|
+
key namespaces may not contain `:` (the internal delimiter) or a null character
|
|
47
|
+
(`\0`). Use `/` or `-` when composing keys, for example
|
|
48
|
+
`` `${ctx.userId}/${dayKey}` ``. Invalid keys throw on the optimistic pass.
|
|
49
|
+
|
|
50
|
+
## 3. Read Before Writing
|
|
51
|
+
|
|
52
|
+
Don't assume what exists in storage. Read current state, then merge:
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
setTodo: async (ctx, input) => {
|
|
56
|
+
const existing = await ctx.table("todos").get(input.id);
|
|
57
|
+
await ctx.table("todos").set({
|
|
58
|
+
itemKey: input.id,
|
|
59
|
+
value: {
|
|
60
|
+
text: input.text ?? existing?.text ?? "",
|
|
61
|
+
completed: input.completed ?? existing?.completed ?? false,
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
},
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
This makes the mutator safe as both a create and an update, and safe to replay against state modified by other mutations.
|
|
68
|
+
|
|
69
|
+
Build the new value from the row you read; never edit the read row in place. On the client that row is the cached object itself, so an edit changes local state even if the mutation then fails on the server.
|
|
70
|
+
|
|
71
|
+
## Why These Matter
|
|
72
|
+
|
|
73
|
+
All three rules protect against the same failure mode: the mutator runs more than once (client + server + replay), and each run should converge on the same logical outcome. Break any of them and your local state diverges from the server's authoritative state, surfacing as "my change disappeared" or "duplicate entries" bugs.
|
|
74
|
+
|
|
75
|
+
## 4. Validate Before the `isServer` Gate
|
|
76
|
+
|
|
77
|
+
When a mutator can validate its input from public/own-private data, do that validation **above** any `if (!ctx.isServer) return;` so the throw runs on the client's optimistic pass.
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
// BAD: server-only throw silently disappears on the client
|
|
81
|
+
makeMove: async (ctx, input) => {
|
|
82
|
+
if (!ctx.isServer) return;
|
|
83
|
+
const game = await ctx.table("game").get("state");
|
|
84
|
+
if (game?.currentPlayer !== ctx.userId) throw new Error("Not your turn");
|
|
85
|
+
// ... rest of move logic
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
// GOOD: validation runs on both passes; bad calls reject the outer
|
|
89
|
+
// `await store.mutate.makeMove(...)` synchronously on the client
|
|
90
|
+
makeMove: async (ctx, input) => {
|
|
91
|
+
const game = await ctx.table("game").get("state");
|
|
92
|
+
if (game?.currentPlayer !== ctx.userId) throw new Error("Not your turn");
|
|
93
|
+
if (!ctx.isServer) return;
|
|
94
|
+
// ... server-only work that depends on serverOnly() data
|
|
95
|
+
},
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Why: server-side throws are silently rolled back
|
|
99
|
+
|
|
100
|
+
A `throw` inside `if (ctx.isServer) { ... }` does **not** reject the outer `await store.mutate.X(...)` promise, and it does **not** reject `.confirmed`. The SDK rolls back the optimistic mutation and resolves both promises with `undefined`. The user sees their action evaporate with no error.
|
|
101
|
+
|
|
102
|
+
To surface server-rejected mutations, either:
|
|
103
|
+
|
|
104
|
+
1. Restructure validation so it runs on the optimistic pass too (preferred — see above).
|
|
105
|
+
2. Repair local state in `store.onFailedMutation((info) => { ... })` — restore the draft the user typed, clear a spinner, reset a pending id. The platform already shows a toast and reports every background error for any tile that calls `Poe.setupStore()`, so do not add a second toast from `store.onBackgroundError`; reach for that hook only when you must handle the non-mutation error kinds with app-specific copy, and then pass `Poe.setupStore(config, { backgroundErrorToast: false })` so your UI replaces the platform toast instead of doubling it.
|
|
106
|
+
|
|
107
|
+
If you genuinely need to validate against server-only data (`serverOnly()` table, randomness, action results), the silent rollback is the only behavior available — accept it and repair local state in `onFailedMutation` or derive the UI from store state.
|
|
108
|
+
|
|
109
|
+
### What you can/can't read on the client
|
|
110
|
+
|
|
111
|
+
| Source | Client validation works? |
|
|
112
|
+
|--------|--------------------------|
|
|
113
|
+
| `ctx.table("name")` (public) | Yes |
|
|
114
|
+
| `ctx.privateOfUser(ctx.userId).table(...)` | Yes |
|
|
115
|
+
| `ctx.privateOfUser(otherUserId).table(...)` | Throws on client |
|
|
116
|
+
| `ctx.serverOnly().table(...)` | Throws on client |
|
|
117
|
+
|
|
118
|
+
So: turn order, slot/membership checks, phase gates → validate up top. Move legality (against a server-only board), randomness, action outputs → server-only.
|
|
119
|
+
|
|
120
|
+
### Worked example
|
|
121
|
+
|
|
122
|
+
```typescript
|
|
123
|
+
startRound: async (ctx) => {
|
|
124
|
+
// Public read — works on client + server, so this throw rejects the
|
|
125
|
+
// optimistic call synchronously.
|
|
126
|
+
const players = (await ctx.table("players").entries().toArray()).map(([, v]) => v);
|
|
127
|
+
const hasRedSpy = players.some((p) => p.team === "red" && p.role === "spymaster");
|
|
128
|
+
const hasBlueSpy = players.some((p) => p.team === "blue" && p.role === "spymaster");
|
|
129
|
+
if (!hasRedSpy || !hasBlueSpy) throw new Error("Both teams need a spymaster");
|
|
130
|
+
|
|
131
|
+
// Server-only randomness happens below the gate — never runs optimistically.
|
|
132
|
+
if (!ctx.isServer) return;
|
|
133
|
+
const seed = crypto.getRandomValues(new Uint32Array(1))[0]!;
|
|
134
|
+
await ctx.serverOnly().table("board").set({ itemKey: "state", value: layoutFor(seed) });
|
|
135
|
+
},
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
## 5. Return, Don't Throw, When the Goal Is Already Achieved
|
|
139
|
+
|
|
140
|
+
Rule 4's throws are for genuinely invalid actions that indicate a bug or stale UI ("not your turn", "only the host can start"). They are the wrong tool when the mutator's *desired end-state already holds* — because mutations replay. A pending mutation re-runs on every rebase (each server pull while it is unconfirmed), and the same action can race in from another client or a second device of the same user. In all of those replays, "the thing I was asked to do is already done" is normal, not an error.
|
|
141
|
+
|
|
142
|
+
Every replay throw is logged to the user's console as `"Synced State | Error rebasing mutation"` (and, if the server pass throws too, surfaces as a failed mutation). A start/init/transition mutator that throws "already started" turns routine at-least-once delivery into error spam.
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
// BAD: throws on every rebase after the game started (own replay OR a
|
|
146
|
+
// concurrent starter) — console errors in production for a non-event.
|
|
147
|
+
startMatch: async (ctx, input) => {
|
|
148
|
+
const match = await ctx.table("match").get("state");
|
|
149
|
+
if (match?.phase !== "lobby") throw new Error("Match already started");
|
|
150
|
+
// ...
|
|
151
|
+
},
|
|
152
|
+
|
|
153
|
+
// GOOD: idempotent at the goal level — already started means nothing to do.
|
|
154
|
+
startMatch: async (ctx, input) => {
|
|
155
|
+
const match = await ctx.table("match").get("state");
|
|
156
|
+
if (!match) {
|
|
157
|
+
// Client replay against a base that predates seeding: no-op. On the
|
|
158
|
+
// server the caller is always seated first, so a missing row there is a
|
|
159
|
+
// real invariant violation.
|
|
160
|
+
if (ctx.isServer) throw new Error("Join the lobby before starting");
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (match.phase !== "lobby") return; // already started — goal achieved
|
|
164
|
+
if (match.host !== ctx.userId) throw new Error("Only the host can start"); // still a real error
|
|
165
|
+
// ...
|
|
166
|
+
},
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Litmus test: would a second, delayed delivery of this exact mutation be *wrong* (a real conflict the user must see), or merely *redundant*? Throw for wrong; return for redundant.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Platform Capabilities
|
|
2
|
+
|
|
3
|
+
Platform capabilities are server-side services available via `ctx.platform.call()`. They provide environment variables, and the instance title. Talking to another store is not a platform capability; use `ctx.externalStore(...)` and `ctx.mutateExternal(...)` (see [external-stores.md](external-stores.md)). Neither path gives general HTTP access.
|
|
4
|
+
|
|
5
|
+
Prefer platform calls in [actions](actions.md). Platform calls from mutators are discouraged: server mutators are processed one at a time, so slow platform calls block mutation throughput. Server mutation attempts can also be retried on optimistic-lock conflict before commit, so a direct mutator platform call can run more than once or for an attempt that is later discarded. If a mutator truly needs a short one-off platform effect, call it only on the server behind `if (ctx.isServer) { ... }`, `await` it before the mutator returns, and make the call idempotent/read-only. On the client, `ctx.platform.call(...)` always throws. If you need a slow platform call, or a non-idempotent effect triggered by a client interaction, use a mutator to create a placeholder, then `ctx.enqueueAction(...)` to do the server-only work.
|
|
6
|
+
|
|
7
|
+
## Available Services
|
|
8
|
+
|
|
9
|
+
| Service | Example | Description |
|
|
10
|
+
|---------|---------|-------------|
|
|
11
|
+
| `systemTools.list` | `call("systemTools.list", {})` | List tools the LLM can call |
|
|
12
|
+
| `systemTools.call` | `call("systemTools.call", { toolName, toolInput })` | Execute a tool |
|
|
13
|
+
| `env.get` | `call("env.get", {})` | Get environment variables |
|
|
14
|
+
| `setSpaceTitle` | `call("setSpaceTitle", { title: "Alice vs Bob" })` | Set the user-facing title of the current app instance (`null` clears the rename). Fans out to every member's manager. |
|
|
15
|
+
|
|
16
|
+
## Usage in an Action
|
|
17
|
+
|
|
18
|
+
```typescript
|
|
19
|
+
import type { InferActionHandlers, PlatformCaller } from "joiner-sdk/v1/backend.js";
|
|
20
|
+
|
|
21
|
+
type TodoActions = InferActionHandlers<typeof todoSchema, PlatformCaller>;
|
|
22
|
+
|
|
23
|
+
const actions: TodoActions = {
|
|
24
|
+
generateWithAI: async (ctx, input) => {
|
|
25
|
+
const { BASE_URL } = await ctx.platform.call("env.get", {});
|
|
26
|
+
// ...use BASE_URL when constructing platform links
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Pass `PlatformCaller` as the second type parameter to `InferActionHandlers` for full autocomplete on `ctx.platform.call()`.
|
|
32
|
+
|
|
33
|
+
## Discouraged Mutator Usage
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
import type { InferMutatorHandlers, PlatformCaller } from "joiner-sdk/v1/backend.js";
|
|
37
|
+
|
|
38
|
+
type TodoMutators = InferMutatorHandlers<typeof todoSchema, PlatformCaller>;
|
|
39
|
+
|
|
40
|
+
const mutators: TodoMutators = {
|
|
41
|
+
setSpaceTitleFromTodo: async (ctx, input) => {
|
|
42
|
+
await ctx.table("todos").set({ itemKey: input.id, value: input.todo });
|
|
43
|
+
if (!ctx.isServer) return;
|
|
44
|
+
await ctx.platform.call("setSpaceTitle", { title: input.todo.text });
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Only use this discouraged pattern for short, one-off server-side effects that must be part of the mutator flow. Always `await ctx.platform.call(...)` before the mutator returns. The call must be idempotent/read-only because optimistic-lock conflicts can retry the server mutator attempt and rerun direct platform calls before any commit succeeds. Do not put slow platform calls, high-fanout work, or non-idempotent side effects directly in mutators.
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# Schema and bindings
|
|
2
|
+
|
|
3
|
+
Use named row and input schemas so table wrappers stay shallow and input/output
|
|
4
|
+
types remain concrete. Adapt this syntax example to the existing scaffold's
|
|
5
|
+
names and declarations; it supplies no application rules or authorization.
|
|
6
|
+
|
|
7
|
+
`synced-store/schema.ts`:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { defineSchema, table } from "joiner-sdk/v1/backend.js";
|
|
12
|
+
import { TILE_SCHEMA_VERSION } from "./tile-schema-version";
|
|
13
|
+
|
|
14
|
+
const recordRow = z.object({ text: z.string().max(500) });
|
|
15
|
+
const updateRecordInput = z.object({
|
|
16
|
+
id: z.string().min(1).max(100),
|
|
17
|
+
text: z.string().max(500),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
export const tileSchema = defineSchema({
|
|
21
|
+
schemaVersion: TILE_SCHEMA_VERSION,
|
|
22
|
+
tables: { records: { schema: table(recordRow) } },
|
|
23
|
+
mutators: { updateRecord: { input: updateRecordInput } },
|
|
24
|
+
});
|
|
25
|
+
export type TileSchema = typeof tileSchema;
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
A table entry wraps `table(rowSchema)` in `{ schema: ... }`; mutator input
|
|
29
|
+
takes the Zod schema directly. Keep the scaffold's version constant in its
|
|
30
|
+
client-safe file. Browser code imports `TileSchema` as a type, never the
|
|
31
|
+
backend schema as a runtime value. Preserve existing declarations and migrations.
|
|
32
|
+
For changes to persisted shapes, follow [schema migrations](schema-migrations.md).
|
|
33
|
+
|
|
34
|
+
Type handlers with `InferMutatorHandlers<TileSchema>` and readers with
|
|
35
|
+
`InferReadContext<TileSchema>` from `joiner-sdk/v1/client.js`. Read the
|
|
36
|
+
authenticated actor from `ctx.userId`, not `store.userId`. Table calls:
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
const current = await ctx.table("records").get(input.id);
|
|
40
|
+
await ctx.table("records").set({ itemKey: input.id, value: { text: input.text } });
|
|
41
|
+
await ctx.table("records").delete(input.id);
|
|
42
|
+
const records = await ctx.table("records").scan().values().toArray();
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
These are separate operation examples, not one handler. Validate actor,
|
|
46
|
+
membership, action and expected round/revision before committing game changes.
|
|
47
|
+
`itemKey` cannot contain `:`. Schema defaults do not make fields optional in
|
|
48
|
+
typed output rows: update affected seed data, fixtures and UI props together.
|
|
49
|
+
Decide public/private/server-only visibility and whether each table is bounded;
|
|
50
|
+
use [sort keys](sort-keys.md) for accumulating ordered history.
|
|
51
|
+
|
|
52
|
+
Keep the same browser-safe mutators and hooks in both configurations:
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
// synced-store/client-config.ts
|
|
56
|
+
import { defineClientConfig } from "joiner-sdk/v1/client.js";
|
|
57
|
+
import type { TileSchema } from "./schema";
|
|
58
|
+
import { TILE_SCHEMA_VERSION } from "./tile-schema-version";
|
|
59
|
+
import { tileMutators } from "./mutators";
|
|
60
|
+
import { tileHooks } from "./hooks";
|
|
61
|
+
|
|
62
|
+
export const tileClientConfig = defineClientConfig<TileSchema>({
|
|
63
|
+
schemaVersion: TILE_SCHEMA_VERSION,
|
|
64
|
+
mutators: tileMutators,
|
|
65
|
+
hooks: tileHooks,
|
|
66
|
+
});
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
// synced-store/backend-config.ts
|
|
71
|
+
import { defineBackendConfig } from "joiner-sdk/v1/backend.js";
|
|
72
|
+
import { tileSchema } from "./schema";
|
|
73
|
+
import { tileMutators } from "./mutators";
|
|
74
|
+
import { tileHooks } from "./hooks";
|
|
75
|
+
|
|
76
|
+
export const tileBackendConfig = defineBackendConfig({
|
|
77
|
+
schema: tileSchema,
|
|
78
|
+
mutators: tileMutators,
|
|
79
|
+
hooks: tileHooks,
|
|
80
|
+
});
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Merge the scaffold's other configuration fields, actions and hooks; these
|
|
84
|
+
examples show the schema/mutator/hook connection only. Do not import backend
|
|
85
|
+
configuration into the UI.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Schema Libraries
|
|
2
|
+
|
|
3
|
+
Synced-store uses any [Standard Schema](https://github.com/standard-schema/standard-schema)-compliant library (Zod, Valibot, ArkType) or plain JSON Schema. Schemas are used for **compile-time type inference only** — no runtime validation.
|
|
4
|
+
|
|
5
|
+
Zod is the default in most examples. When you need to avoid Zod's bundle size or prefer a different style, use one of these.
|
|
6
|
+
|
|
7
|
+
## Valibot
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
import * as v from "valibot";
|
|
11
|
+
import { defineSchema, table } from "joiner-sdk/v1/backend.js";
|
|
12
|
+
import { TILE_SCHEMA_VERSION } from "./tile-schema-version";
|
|
13
|
+
|
|
14
|
+
const schema = defineSchema({
|
|
15
|
+
schemaVersion: TILE_SCHEMA_VERSION,
|
|
16
|
+
tables: {
|
|
17
|
+
todos: { schema: table(v.object({ text: v.string(), done: v.boolean() })) },
|
|
18
|
+
},
|
|
19
|
+
mutators: {
|
|
20
|
+
setTodo: { description: "...", input: v.object({ id: v.string(), text: v.string() }) },
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## JSON Schema (no library needed)
|
|
26
|
+
|
|
27
|
+
Useful when you don't want to pull in a validation library, or when the schema is already expressed as JSON Schema elsewhere.
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
import { jsonSchema } from "joiner-sdk/v1/backend.js";
|
|
31
|
+
import { defineSchema, table } from "joiner-sdk/v1/backend.js";
|
|
32
|
+
import { TILE_SCHEMA_VERSION } from "./tile-schema-version";
|
|
33
|
+
|
|
34
|
+
const schema = defineSchema({
|
|
35
|
+
schemaVersion: TILE_SCHEMA_VERSION,
|
|
36
|
+
tables: {
|
|
37
|
+
todos: {
|
|
38
|
+
schema: table(jsonSchema<{ text: string; done: boolean }>({
|
|
39
|
+
type: "object",
|
|
40
|
+
properties: {
|
|
41
|
+
text: { type: "string" },
|
|
42
|
+
done: { type: "boolean" },
|
|
43
|
+
},
|
|
44
|
+
required: ["text", "done"],
|
|
45
|
+
})),
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The TypeScript generic on `jsonSchema<T>()` is the source of truth for types. The JSON Schema object itself is carried through for tooling (e.g. MCP tool definitions).
|
|
52
|
+
|
|
53
|
+
## When to pick which
|
|
54
|
+
|
|
55
|
+
- **Zod** — the default; richest ecosystem and best error messages. Costs ~280KB gzipped on the client if bundled — use type-only imports in `client-config.ts` to avoid this.
|
|
56
|
+
- **Valibot** — tree-shakable, much smaller bundle; same mental model as Zod.
|
|
57
|
+
- **JSON Schema** — zero runtime dependency; use when you want the schema to be consumed by external tools (or when the schema is hand-written elsewhere).
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# Schema Migrations
|
|
2
|
+
|
|
3
|
+
## The rule you must not break
|
|
4
|
+
|
|
5
|
+
**Once a tile has been published, any backwards-incompatible schema change requires a migration, shipped in the same change.** This is the single most-missed step. A bump without a migration is not a soft reset — it forces every existing client to clear its local data and dispose, which players experience as their in-progress game or room being wiped.
|
|
6
|
+
|
|
7
|
+
If you have changed `schema.ts`, ask: **would data written under the OLD schema still be valid under the NEW schema?**
|
|
8
|
+
|
|
9
|
+
- **No → backwards-incompatible → bump `TILE_SCHEMA_VERSION` AND write the migration.** You are here if you renamed a field, removed a field, changed a field's type or its allowed values, made an optional field required, changed how you compute `itemKey`/`sortKey`, split/merged tables, or changed the shape of any mutation's input.
|
|
10
|
+
- **Yes → backwards-compatible → do NOT bump the version.** Adding a brand-new table, a new mutator, or a new *optional* field (or a field with a default that old rows can omit) does not need a migration. Bumping needlessly would wipe instances for no reason.
|
|
11
|
+
- **Unsure → treat it as incompatible and write the migration.** The cost of an unnecessary migration is a few lines; the cost of a missing one is wiped user data.
|
|
12
|
+
|
|
13
|
+
Do not stop at bumping the version — the checklist for a live tile is:
|
|
14
|
+
|
|
15
|
+
1. Bump `TILE_SCHEMA_VERSION`.
|
|
16
|
+
2. Add the `migrations` entry with `migrateData` (and `migratePendingMutation` if input shapes changed).
|
|
17
|
+
3. Republish.
|
|
18
|
+
|
|
19
|
+
## When to bump the version
|
|
20
|
+
|
|
21
|
+
Only increment `TILE_SCHEMA_VERSION` for backwards-incompatible changes that require migrating existing persisted data or pending mutations. Adding a new mutator, a new table, or a new field with a default is backwards-compatible and does not need a bump. The version lives in its own constant file (set up from day zero — see [api-patterns.md](api-patterns.md)) so client and server read the same value without bundling Zod on the client:
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
tile-schema-version.ts ← export const TILE_SCHEMA_VERSION = 2;
|
|
25
|
+
schema.ts ← uses TILE_SCHEMA_VERSION in defineSchema()
|
|
26
|
+
client-config.ts ← uses TILE_SCHEMA_VERSION in defineClientConfig()
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
When you bump the version WITHOUT a matching migration, existing instances reload into the new code, which cannot read the old-shape data still in local storage — so that data is discarded (`onSchemaVersionMismatch` fires and the client disposes/rebuilds). To a player this looks like their game or room was wiped. This is exactly why a migration is mandatory for any incompatible change to a live tile.
|
|
30
|
+
|
|
31
|
+
## How upgrades roll out to users
|
|
32
|
+
|
|
33
|
+
Publishing a new version does **not** instantly upgrade everyone who has the tile open. Understanding the rollout is what lets you set the right expectations with players.
|
|
34
|
+
|
|
35
|
+
**The lifecycle of one upgrade:**
|
|
36
|
+
|
|
37
|
+
1. **You publish** a new version (bumped `TILE_SCHEMA_VERSION` + migration). The new bundle is now the latest published version, but nothing has changed yet for anyone who already has an instance open.
|
|
38
|
+
2. **Running instances keep running the OLD code until the server notices the publish.** How fast that happens depends on the instance's connection state. An instance open **on someone's screen** (foregrounded, connected) is not idle at the protocol level — its presence heartbeats count as server activity, so the server notices the new version within about 30 seconds (a server-side version-resolution cache bound) with no user action. An instance in a **backgrounded or disconnected** tab produces no server activity, so nothing happens while it just sits there.
|
|
39
|
+
3. **For a backgrounded/disconnected instance, the upgrade waits for its next "activity" against the server**: opening/reopening the instance, reconnecting after the connection dropped, running an action, or returning the app to the foreground (which triggers a repair pull). At that point the server notices the newer published version.
|
|
40
|
+
4. **The migration runs once, server-side, at that moment.** The server runs your `migrateData` over that instance's stored data in a single atomic step and bumps the instance's stored schema version. (A pure read/pull without any such trigger does not migrate.)
|
|
41
|
+
5. **The still-open old-code client detects the bumped version and updates itself.** The tile shows an **"Update required"** dialog over just that tile and reloads it into the new version against the now-migrated data, with no tap needed (the same way the root manager shell updates itself). If the reloaded tile is still on an old version, the dialog offers **Try again** instead of reloading in a loop. A user opening the tile fresh after you published gets the new version from the start on a first-time device; a device that opened the tile before may serve its cached previous bundle for that one open (bundle resolution is cache-first for load speed) and goes through the same automatic update as soon as it connects.
|
|
42
|
+
|
|
43
|
+
**Why a change you published last night can show up as an automatic update this morning:** an instance you left open overnight was backgrounded and its connection dropped (device sleep / backgrounding), so it produced no server activity and never re-checked for the new version (step 2). When you foregrounded the app in the morning, the repair pull ran (step 3), which triggered the migration (step 4) and then the automatic "Update required" reload (step 5). It was not a fixed polling delay — the rollout to a backgrounded instance simply waits for the next activity.
|
|
44
|
+
|
|
45
|
+
**What to tell your players (expectation-setting):**
|
|
46
|
+
|
|
47
|
+
- New and reopened sessions get the new version right away — either from the start, or (on a device that cached the previous bundle) via the same automatic "Update required" reload on open. Long-lived open sessions update within about half a minute while foregrounded, or the next time they come back to the app. No player action is needed, but anything on screen that isn't saved in the store is lost in the reload.
|
|
48
|
+
- Because the migration runs once server-side and every client then reloads into matching code, players keep their data across the upgrade — provided you shipped the migration. Skipping the migration is what turns an upgrade into a data wipe.
|
|
49
|
+
|
|
50
|
+
## Recovering from a failed migration
|
|
51
|
+
|
|
52
|
+
If a migration fails, its changes are rolled back and the instance remains
|
|
53
|
+
at its previous schema version. Subsequent attempts retry the migration and
|
|
54
|
+
can keep blocking sync. To recover affected instances, fix the failing
|
|
55
|
+
migration step and
|
|
56
|
+
[publish a new build](#how-upgrades-roll-out-to-users)
|
|
57
|
+
that completes within the
|
|
58
|
+
[applicable limits](architecture-scaling-and-performance.md#store-size-and-row-operations).
|
|
59
|
+
Reloading alone will not resolve a migration that consistently exceeds those limits.
|
|
60
|
+
|
|
61
|
+
For example, if `1to2` fails, correct `1to2` rather than only adding `2to3`.
|
|
62
|
+
Keep the same target schema version if the intended schema is unchanged;
|
|
63
|
+
instances that already reached it do not rerun that migration. Make sure
|
|
64
|
+
affected instances follow the corrected build, updating their release
|
|
65
|
+
channel or version pin as needed.
|
|
66
|
+
|
|
67
|
+
## Defining a Migration
|
|
68
|
+
|
|
69
|
+
Provide migrations for each version step:
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
import { defineMigration } from "joiner-sdk/v1/backend.js";
|
|
73
|
+
import { TILE_SCHEMA_VERSION } from "./tile-schema-version";
|
|
74
|
+
|
|
75
|
+
const migration1to2 = defineMigration(v1Mutators, v2Mutators, {
|
|
76
|
+
migrateData: async (ctx) => {
|
|
77
|
+
// Transform existing data
|
|
78
|
+
for await (const [key, value] of ctx.table("todos").scan().entries()) {
|
|
79
|
+
await ctx.table("todos").set({
|
|
80
|
+
...key,
|
|
81
|
+
value: { ...value, priority: 0 },
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
migratePendingMutation: {
|
|
86
|
+
// Transform in-flight mutations from old clients
|
|
87
|
+
addTodo: (args, emit) => {
|
|
88
|
+
emit("addTodo", { ...args, priority: 0 });
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const schema = defineSchema({
|
|
94
|
+
schemaVersion: TILE_SCHEMA_VERSION, // bumped to 2 in tile-schema-version.ts
|
|
95
|
+
migrations: { "1to2": migration1to2 },
|
|
96
|
+
// ...
|
|
97
|
+
});
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Stream row-local rewrites with `for await` so the migration does not retain every
|
|
101
|
+
input value. Await writes before advancing; the migration still commits atomically.
|
|
102
|
+
Batching writes after an unlimited `toArray()` does not bound the initial read.
|
|
103
|
+
Use `toArray()` for explicitly limited pages or bounded collections that need a
|
|
104
|
+
snapshot, sorting, or cross-row analysis. If the migration changes storage keys,
|
|
105
|
+
preserve its original-row snapshot or design a cursor strategy that cannot revisit
|
|
106
|
+
inserted rows or skip moved rows; do not mechanically replace that snapshot.
|
|
107
|
+
|
|
108
|
+
## Pending Mutation Handlers
|
|
109
|
+
|
|
110
|
+
Each mutation handler in `migratePendingMutation` can:
|
|
111
|
+
- **Transform args** — call `emit()` with modified input
|
|
112
|
+
- **Rename** — emit a different mutation name
|
|
113
|
+
- **Drop** — don't call `emit()`
|
|
114
|
+
- **Expand** — call `emit()` multiple times to produce several mutations from one
|
|
115
|
+
|
|
116
|
+
## Common pitfalls
|
|
117
|
+
|
|
118
|
+
- **`for (const [key, value] of entries)` — `key` is an `EntryKey`, not a string.** `ctx.table(...).scan().entries()` yields `[EntryKey, JSONValue]` where `EntryKey = { sortKey, itemKey }`. Both `set` and `delete` accept `string | EntryKey`, so the natural patterns are `set({ ...key, value })` and `delete(key)` — no manual extraction needed. Never cast with `key as unknown as string`: it bypasses the type system, and against older platform versions it stored `"[object Object]"` as the literal `itemKey` and corrupted the row.
|
|
119
|
+
- **`migrateData` and the row's `value.sortKey` are not the same as the storage `sortKey`.** Some apps store a fractional-index `sortKey` inside the row's value (used for client-side ordering) **and** use a different sort key as the KV storage key (used for scan ordering). Be explicit about which one you mean; reread the schema before writing the migration's `set(...)` call.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Searchable Tables
|
|
2
|
+
|
|
3
|
+
Add `searchable` to a table's schema definition to enable cross-app full-text search. Items are indexed automatically as they're created, updated, or deleted.
|
|
4
|
+
|
|
5
|
+
```typescript
|
|
6
|
+
tables: {
|
|
7
|
+
todos: {
|
|
8
|
+
schema: table(z.object({
|
|
9
|
+
id: z.string(),
|
|
10
|
+
title: z.string(),
|
|
11
|
+
createdAt: z.number(),
|
|
12
|
+
})),
|
|
13
|
+
searchable: { textField: "title", timestampField: "createdAt" },
|
|
14
|
+
},
|
|
15
|
+
}
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Options
|
|
19
|
+
|
|
20
|
+
- **`textField`** — the name of the string field to index for full-text search.
|
|
21
|
+
- **`timestampField`** — the name of the number field used to order results by recency.
|
|
22
|
+
|
|
23
|
+
Both fields must exist on the table's value schema. The indexer re-runs whenever a row is written or deleted.
|
|
24
|
+
|
|
25
|
+
## Querying
|
|
26
|
+
|
|
27
|
+
Searchable items are surfaced through the platform-wide search experience and through the MCP tool surface — an AI can search across all searchable tables in all apps the user has access to. There's no per-app search API on the store client; the platform owns the search UI and retrieval.
|