@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.
Files changed (303) hide show
  1. package/README.md +30 -2
  2. package/bundled-resources/poe-tile-templates/base/CLAUDE.md +72 -0
  3. package/bundled-resources/poe-tile-templates/base/README.md +7 -0
  4. package/bundled-resources/poe-tile-templates/base/_bunfig.toml +8 -0
  5. package/bundled-resources/poe-tile-templates/base/_gitignore +18 -0
  6. package/bundled-resources/poe-tile-templates/base/client.ts +12 -0
  7. package/bundled-resources/poe-tile-templates/base/package.json +36 -0
  8. package/bundled-resources/poe-tile-templates/base/playwright.config.ts +38 -0
  9. package/bundled-resources/poe-tile-templates/base/scripts/check-source.ts +148 -0
  10. package/bundled-resources/poe-tile-templates/base/scripts/dev.ts +19 -0
  11. package/bundled-resources/poe-tile-templates/base/scripts/doctor.sh +29 -0
  12. package/bundled-resources/poe-tile-templates/base/scripts/visual-check.ts +64 -0
  13. package/bundled-resources/poe-tile-templates/base/synced-store/backend-config.ts +9 -0
  14. package/bundled-resources/poe-tile-templates/base/synced-store/client-config.ts +8 -0
  15. package/bundled-resources/poe-tile-templates/base/synced-store/data/items.ts +16 -0
  16. package/bundled-resources/poe-tile-templates/base/synced-store/mutators/index.ts +10 -0
  17. package/bundled-resources/poe-tile-templates/base/synced-store/mutators/remove-todo.ts +5 -0
  18. package/bundled-resources/poe-tile-templates/base/synced-store/mutators/set-todo.ts +20 -0
  19. package/bundled-resources/poe-tile-templates/base/synced-store/mutators/types.ts +5 -0
  20. package/bundled-resources/poe-tile-templates/base/synced-store/mutators.test.ts +138 -0
  21. package/bundled-resources/poe-tile-templates/base/synced-store/schema.ts +40 -0
  22. package/bundled-resources/poe-tile-templates/base/tests/e2e.test.playwright.ts +92 -0
  23. package/bundled-resources/poe-tile-templates/base/tests/mobile-viewport.test.playwright.ts +111 -0
  24. package/bundled-resources/poe-tile-templates/base/tests/render-check.test.playwright.ts +128 -0
  25. package/bundled-resources/poe-tile-templates/base/tests/screenshot.test.playwright.ts +86 -0
  26. package/bundled-resources/poe-tile-templates/base/tests/setup-dom.ts +70 -0
  27. package/bundled-resources/poe-tile-templates/base/tile/src/backend.ts +3 -0
  28. package/bundled-resources/poe-tile-templates/base/tile/styles.css +47 -0
  29. package/bundled-resources/poe-tile-templates/base/tsconfig.json +13 -0
  30. package/bundled-resources/poe-tile-templates/coverage.config.json +6 -0
  31. package/bundled-resources/poe-tile-templates/index.ts +27 -0
  32. package/bundled-resources/poe-tile-templates/package.json +31 -0
  33. package/bundled-resources/poe-tile-templates/phaserjs/package.partial.json +6 -0
  34. package/bundled-resources/poe-tile-templates/phaserjs/tile/index.html +14 -0
  35. package/bundled-resources/poe-tile-templates/phaserjs/tile/src/entry.ts +35 -0
  36. package/bundled-resources/poe-tile-templates/phaserjs/ui/App.test.happydom.tsx +98 -0
  37. package/bundled-resources/poe-tile-templates/phaserjs/ui/App.ts +180 -0
  38. package/bundled-resources/poe-tile-templates/phaserjs/ui/phaser-scene.ts +174 -0
  39. package/bundled-resources/poe-tile-templates/phaserjs/vite.config.ts +28 -0
  40. package/bundled-resources/poe-tile-templates/preact/package.partial.json +9 -0
  41. package/bundled-resources/poe-tile-templates/preact/postcss.config.js +5 -0
  42. package/bundled-resources/poe-tile-templates/preact/tile/index.html +14 -0
  43. package/bundled-resources/poe-tile-templates/preact/tile/src/entry.tsx +36 -0
  44. package/bundled-resources/poe-tile-templates/preact/tile/styles.css +51 -0
  45. package/bundled-resources/poe-tile-templates/preact/tsconfig.json +15 -0
  46. package/bundled-resources/poe-tile-templates/preact/ui/App.test.happydom.tsx +69 -0
  47. package/bundled-resources/poe-tile-templates/preact/ui/App.tsx +116 -0
  48. package/bundled-resources/poe-tile-templates/preact/vite.config.ts +18 -0
  49. package/bundled-resources/poe-tile-templates/react/package.partial.json +12 -0
  50. package/bundled-resources/poe-tile-templates/react/postcss.config.js +5 -0
  51. package/bundled-resources/poe-tile-templates/react/tile/index.html +14 -0
  52. package/bundled-resources/poe-tile-templates/react/tile/src/entry.tsx +38 -0
  53. package/bundled-resources/poe-tile-templates/react/tile/styles.css +51 -0
  54. package/bundled-resources/poe-tile-templates/react/tsconfig.json +14 -0
  55. package/bundled-resources/poe-tile-templates/react/ui/App.test.happydom.tsx +71 -0
  56. package/bundled-resources/poe-tile-templates/react/ui/App.tsx +110 -0
  57. package/bundled-resources/poe-tile-templates/react/vite.config.ts +21 -0
  58. package/bundled-resources/poe-tile-templates/scripts/cleanup.ts +10 -0
  59. package/bundled-resources/poe-tile-templates/scripts/generate.ts +57 -0
  60. package/bundled-resources/poe-tile-templates/scripts/install-diagnostics.ts +52 -0
  61. package/bundled-resources/poe-tile-templates/scripts/paths.ts +7 -0
  62. package/bundled-resources/poe-tile-templates/scripts/sdk-dependency-key.ts +288 -0
  63. package/bundled-resources/poe-tile-templates/scripts/verify-all-sdks.ts +132 -0
  64. package/bundled-resources/poe-tile-templates/scripts/verify-local-sdk-command.ts +30 -0
  65. package/bundled-resources/poe-tile-templates/scripts/verify-local-sdk-tarball.ts +397 -0
  66. package/bundled-resources/poe-tile-templates/solidjs/_bunfig.toml +14 -0
  67. package/bundled-resources/poe-tile-templates/solidjs/package.partial.json +13 -0
  68. package/bundled-resources/poe-tile-templates/solidjs/postcss.config.js +5 -0
  69. package/bundled-resources/poe-tile-templates/solidjs/tests/solid-plugin.ts +49 -0
  70. package/bundled-resources/poe-tile-templates/solidjs/tile/index.html +14 -0
  71. package/bundled-resources/poe-tile-templates/solidjs/tile/src/entry.tsx +36 -0
  72. package/bundled-resources/poe-tile-templates/solidjs/tile/styles.css +51 -0
  73. package/bundled-resources/poe-tile-templates/solidjs/tsconfig.json +15 -0
  74. package/bundled-resources/poe-tile-templates/solidjs/ui/App.test.happydom.tsx +70 -0
  75. package/bundled-resources/poe-tile-templates/solidjs/ui/App.tsx +129 -0
  76. package/bundled-resources/poe-tile-templates/solidjs/vite.config.ts +18 -0
  77. package/bundled-resources/poe-tile-templates/tests/check-source.test.ts +131 -0
  78. package/bundled-resources/poe-tile-templates/tests/dev-script.test.slow.ts +166 -0
  79. package/bundled-resources/poe-tile-templates/tests/fixtures/customized-manager.ts +67 -0
  80. package/bundled-resources/poe-tile-templates/tests/fixtures/extended-mutators.ts.txt +106 -0
  81. package/bundled-resources/poe-tile-templates/tests/fixtures/multiplayer-verification.test.playwright.ts.txt +103 -0
  82. package/bundled-resources/poe-tile-templates/tests/fixtures/replace-starter-schema.ts +67 -0
  83. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/phaserjs.tsx.txt +85 -0
  84. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/preact.tsx.txt +69 -0
  85. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/react.tsx.txt +73 -0
  86. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/seating.ts.txt +54 -0
  87. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/solidjs.tsx.txt +70 -0
  88. package/bundled-resources/poe-tile-templates/tests/fixtures/starter-demo/vanilla-js.tsx.txt +85 -0
  89. package/bundled-resources/poe-tile-templates/tests/generated-templates.test.ts +278 -0
  90. package/bundled-resources/poe-tile-templates/tests/happy-dom-version.test.ts +27 -0
  91. package/bundled-resources/poe-tile-templates/tests/install-diagnostics.test.ts +99 -0
  92. package/bundled-resources/poe-tile-templates/tests/native-gesture-defaults.test.ts +23 -0
  93. package/bundled-resources/poe-tile-templates/tests/playwright-version.test.ts +84 -0
  94. package/bundled-resources/poe-tile-templates/tests/render-check-scaffold.test.ts +56 -0
  95. package/bundled-resources/poe-tile-templates/tests/sdk-dependency-key.test.ts +129 -0
  96. package/bundled-resources/poe-tile-templates/tests/visual-check.test.ts +90 -0
  97. package/bundled-resources/poe-tile-templates/vanilla-js/package.partial.json +3 -0
  98. package/bundled-resources/poe-tile-templates/vanilla-js/tile/index.html +14 -0
  99. package/bundled-resources/poe-tile-templates/vanilla-js/tile/src/entry.ts +35 -0
  100. package/bundled-resources/poe-tile-templates/vanilla-js/ui/App.test.happydom.tsx +96 -0
  101. package/bundled-resources/poe-tile-templates/vanilla-js/ui/App.ts +113 -0
  102. package/bundled-resources/poe-tile-templates/vanilla-js/vite.config.ts +17 -0
  103. package/cli.ts +134 -0
  104. package/index.ts +96 -0
  105. package/package.json +48 -5
  106. package/skills/audio-generation/.generated-by-poe-templated-docs +0 -0
  107. package/skills/audio-generation/SKILL.md +125 -0
  108. package/skills/finish-prototype/.generated-by-poe-templated-docs +0 -0
  109. package/skills/finish-prototype/SKILL.md +22 -0
  110. package/skills/help-me-build/.generated-by-poe-templated-docs +0 -0
  111. package/skills/help-me-build/SKILL.md +56 -0
  112. package/skills/image-generation/.generated-by-poe-templated-docs +0 -0
  113. package/skills/image-generation/SKILL.md +128 -0
  114. package/skills/one-shot/.generated-by-poe-templated-docs +0 -0
  115. package/skills/one-shot/SKILL.md +22 -0
  116. package/skills/platform-prototype/.generated-by-poe-templated-docs +0 -0
  117. package/skills/platform-prototype/SKILL.md +60 -0
  118. package/skills/platform-subagent/.generated-by-poe-templated-docs +0 -0
  119. package/skills/platform-subagent/SKILL.md +16 -0
  120. package/skills/poe-tiles-cli/.generated-by-poe-templated-docs +0 -0
  121. package/skills/poe-tiles-cli/SKILL.md +609 -0
  122. package/skills/poe-tiles-cli/references/device-motion.md +40 -0
  123. package/skills/poe-tiles-cli/references/player-updates.md +41 -0
  124. package/skills/prototype/.generated-by-poe-templated-docs +0 -0
  125. package/skills/prototype/SKILL.md +148 -0
  126. package/skills/publish/.generated-by-poe-templated-docs +0 -0
  127. package/skills/publish/SKILL.md +73 -0
  128. package/skills/synced-store/.generated-by-poe-templated-docs +0 -0
  129. package/skills/synced-store/SKILL.md +583 -0
  130. package/skills/synced-store/references/actions.md +85 -0
  131. package/skills/synced-store/references/api-patterns.md +245 -0
  132. package/skills/synced-store/references/architecture-scaling-and-performance.md +280 -0
  133. package/skills/synced-store/references/client-api-reference.md +263 -0
  134. package/skills/synced-store/references/data-visibility.md +95 -0
  135. package/skills/synced-store/references/external-stores.md +162 -0
  136. package/skills/synced-store/references/file-uploads.md +216 -0
  137. package/skills/synced-store/references/getting-user-info-of-members.md +228 -0
  138. package/skills/synced-store/references/limitations.md +72 -0
  139. package/skills/synced-store/references/live-data-limit-hook.md +131 -0
  140. package/skills/synced-store/references/mutator-rules.md +169 -0
  141. package/skills/synced-store/references/platform.md +49 -0
  142. package/skills/synced-store/references/schema-and-bindings.md +85 -0
  143. package/skills/synced-store/references/schema-libraries.md +57 -0
  144. package/skills/synced-store/references/schema-migrations.md +119 -0
  145. package/skills/synced-store/references/searchable-tables.md +27 -0
  146. package/skills/synced-store/references/server-forking.md +115 -0
  147. package/skills/synced-store/references/singleton-tables.md +61 -0
  148. package/skills/synced-store/references/sort-keys.md +253 -0
  149. package/skills/synced-store/references/ui-patterns.md +95 -0
  150. package/skills/tile-creator/.generated-by-poe-templated-docs +0 -0
  151. package/skills/tile-creator/SKILL.md +196 -0
  152. package/skills/tile-creator/references/assets.md +124 -0
  153. package/skills/tile-creator/references/backend-api.md +308 -0
  154. package/skills/tile-creator/references/cli-limitations.md +64 -0
  155. package/skills/tile-creator/references/cli.md +604 -0
  156. package/skills/tile-creator/references/client-api.md +2407 -0
  157. package/skills/tile-creator/references/composing-apps.md +166 -0
  158. package/skills/tile-creator/references/e2e-tests.md +55 -0
  159. package/skills/tile-creator/references/game-ux-best-practices.md +57 -0
  160. package/skills/tile-creator/references/migrating-pre-rename-tiles.md +79 -0
  161. package/skills/tile-creator/references/multiplayer-api-recipe.md +205 -0
  162. package/skills/tile-creator/references/native-results.md +100 -0
  163. package/skills/tile-creator/references/platform-integration.md +201 -0
  164. package/skills/tile-creator/references/power-report.md +199 -0
  165. package/skills/tile-creator/references/publish-rollout.md +166 -0
  166. package/skills/tile-creator/references/publishing.md +33 -0
  167. package/skills/tile-creator/references/push-notification-guidelines.md +58 -0
  168. package/skills/tile-creator/references/render-check.md +266 -0
  169. package/skills/tile-creator/references/running-the-client-api-on-a-server-owned-by-the-user.md +95 -0
  170. package/skills/tile-creator/references/safe-area-insets.md +79 -0
  171. package/skills/tile-creator/references/sandbox-limitations.md +32 -0
  172. package/skills/tile-creator/references/scaffolded-tile-folder-structure.md +48 -0
  173. package/skills/tile-creator/references/scaffolding-a-new-app.md +202 -0
  174. package/skills/tile-creator/references/simulations.md +125 -0
  175. package/skills/tile-creator/references/synced-store-client-reference.md +92 -0
  176. package/skills/tile-creator/references/troubleshooting.md +22 -0
  177. package/skills/tile-creator/references/turn-based-mutator.md +43 -0
  178. package/skills/tile-creator/references/user-erasure.md +14 -0
  179. package/skills/tile-creator/references/vite-plugin.md +166 -0
  180. package/skills/tile-creator/references/workspace-retention.md +72 -0
  181. package/src/admin-conversions-client.ts +28 -0
  182. package/src/admin-reviews-client.ts +36 -0
  183. package/src/api.generated.ts +1527 -0
  184. package/src/auth-token.ts +198 -0
  185. package/src/bounded-read.ts +35 -0
  186. package/src/bun-version.ts +33 -0
  187. package/src/checkout-base.ts +207 -0
  188. package/src/cli-bun-version.ts +16 -0
  189. package/src/cli-env.ts +28 -0
  190. package/src/cli-name.ts +23 -0
  191. package/src/client.ts +2474 -0
  192. package/src/collect-files.ts +226 -0
  193. package/src/commands/accounts.ts +55 -0
  194. package/src/commands/admin-abandon-conversion.ts +60 -0
  195. package/src/commands/admin-reviews.ts +66 -0
  196. package/src/commands/admin.ts +219 -0
  197. package/src/commands/auth.ts +89 -0
  198. package/src/commands/checkout-prototype.ts +67 -0
  199. package/src/commands/creator-source-capability.ts +11 -0
  200. package/src/commands/doctor-bun.ts +145 -0
  201. package/src/commands/doctor-command.ts +64 -0
  202. package/src/commands/doctor-package-json.ts +47 -0
  203. package/src/commands/doctor-sdk-pin.ts +156 -0
  204. package/src/commands/doctor-store-keys-lexer.ts +213 -0
  205. package/src/commands/doctor-store-keys-scan.ts +262 -0
  206. package/src/commands/doctor-store-keys.ts +196 -0
  207. package/src/commands/doctor.ts +371 -0
  208. package/src/commands/init/blank-scaffold-templates.ts +397 -0
  209. package/src/commands/init/index.ts +170 -0
  210. package/src/commands/init/internal-toolchain.ts +49 -0
  211. package/src/commands/init/manager-test-template.ts +107 -0
  212. package/src/commands/init/multiplayer-test-template.ts +217 -0
  213. package/src/commands/init/name-input.tsx +167 -0
  214. package/src/commands/init/no-store-scaffold-templates.ts +281 -0
  215. package/src/commands/init/no-store-scaffold.ts +134 -0
  216. package/src/commands/init/package-json-scripts.ts +72 -0
  217. package/src/commands/init/scaffold.ts +960 -0
  218. package/src/commands/init/sdk-tarball-url.generated.ts +4 -0
  219. package/src/commands/init/sdk-tarball-url.ts +31 -0
  220. package/src/commands/init/template-picker.tsx +147 -0
  221. package/src/commands/inspect-child-entry.ts +107 -0
  222. package/src/commands/inspect-contract.ts +87 -0
  223. package/src/commands/inspect-freshness.ts +217 -0
  224. package/src/commands/inspect-lock.ts +201 -0
  225. package/src/commands/inspect-options.ts +360 -0
  226. package/src/commands/inspect-orchestrate.ts +375 -0
  227. package/src/commands/inspect-process.ts +172 -0
  228. package/src/commands/inspect-ready.ts +65 -0
  229. package/src/commands/inspect-report.ts +235 -0
  230. package/src/commands/inspect-run-state.ts +296 -0
  231. package/src/commands/inspect-run.ts +157 -0
  232. package/src/commands/inspect-watchdog.ts +74 -0
  233. package/src/commands/install-joiner.ts +208 -0
  234. package/src/commands/login.ts +308 -0
  235. package/src/commands/models.ts +40 -0
  236. package/src/commands/parse-options.ts +36 -0
  237. package/src/commands/remix-package-json.ts +64 -0
  238. package/src/commands/remix.ts +379 -0
  239. package/src/commands/sdk-url.ts +141 -0
  240. package/src/commands/simulations.ts +133 -0
  241. package/src/commands/skills.ts +108 -0
  242. package/src/commands/store-files.ts +92 -0
  243. package/src/commands/stores.ts +703 -0
  244. package/src/commands/tiles-channel-commands.ts +115 -0
  245. package/src/commands/tiles-checkout.ts +351 -0
  246. package/src/commands/tiles-gallery-command.ts +95 -0
  247. package/src/commands/tiles-get-helpers.ts +27 -0
  248. package/src/commands/tiles-inspect.ts +276 -0
  249. package/src/commands/tiles-power-command.ts +308 -0
  250. package/src/commands/tiles-power-format.ts +396 -0
  251. package/src/commands/tiles-power-versions.ts +299 -0
  252. package/src/commands/tiles-publish-helpers.ts +145 -0
  253. package/src/commands/tiles-upload-command.ts +277 -0
  254. package/src/commands/tiles-version-commands.ts +201 -0
  255. package/src/commands/tiles-visibility-command.ts +103 -0
  256. package/src/commands/tiles.ts +257 -0
  257. package/src/commands/upgrade.ts +307 -0
  258. package/src/commit-in-progress.ts +42 -0
  259. package/src/creator-source-context.ts +97 -0
  260. package/src/creator-source-publish.ts +52 -0
  261. package/src/deferred-assets.ts +125 -0
  262. package/src/distribution.ts +28 -0
  263. package/src/errors.ts +61 -0
  264. package/src/install-command.ts +43 -0
  265. package/src/output.ts +62 -0
  266. package/src/poe-tile-config-files.ts +100 -0
  267. package/src/poe-tile-config-players.ts +168 -0
  268. package/src/poe-tile-config-remix.ts +166 -0
  269. package/src/poe-tile-config.ts +831 -0
  270. package/src/power-report-client.ts +55 -0
  271. package/src/prototype-startup.ts +21 -0
  272. package/src/publish-change-summary.ts +55 -0
  273. package/src/publish-overrides-validation.ts +49 -0
  274. package/src/publish-pack.ts +167 -0
  275. package/src/publish-phases.ts +57 -0
  276. package/src/publish-retry.ts +51 -0
  277. package/src/publish-tile-from-config.ts +434 -0
  278. package/src/recorder-stream.ts +169 -0
  279. package/src/remix-provenance.ts +156 -0
  280. package/src/resolve-client-credential.ts +71 -0
  281. package/src/resolve-media-uploads.ts +147 -0
  282. package/src/sdk-dependency.ts +54 -0
  283. package/src/sdk-skills.ts +85 -0
  284. package/src/should-skip-client-setup.ts +20 -0
  285. package/src/simulation-snapshot.ts +123 -0
  286. package/src/simulation-types.ts +74 -0
  287. package/src/simulations-client.ts +112 -0
  288. package/src/source-bundle.ts +466 -0
  289. package/src/staged-publish-cleanup.ts +44 -0
  290. package/src/staged-publish-deferred.ts +160 -0
  291. package/src/staged-publish.ts +401 -0
  292. package/src/store-file-upload.ts +268 -0
  293. package/src/store-request.ts +168 -0
  294. package/src/tar-canonical.ts +41 -0
  295. package/src/tar-extensions.ts +159 -0
  296. package/src/tar-extract.ts +193 -0
  297. package/src/tar-parse.ts +224 -0
  298. package/src/tar.ts +231 -0
  299. package/src/template-check-scripts.ts +18 -0
  300. package/src/tile-gallery-client.ts +82 -0
  301. package/src/types.ts +258 -0
  302. package/src/upload-concurrency.ts +54 -0
  303. package/src/whole-tile.ts +52 -0
@@ -0,0 +1,960 @@
1
+ // owner: jyoung-q
2
+ /* biome-ignore-all lint/nursery/noExcessiveLinesPerFile: existing file exceeds 400 lines; add new tests or code to focused companion files instead. No new exceptions to this rule should be made. */
3
+ /**
4
+ * Core scaffolding logic for `poe-tiles tiles init`.
5
+ *
6
+ * Copies template files (base + framework overlay) into a target directory,
7
+ * merges package.json dependencies, and substitutes placeholders.
8
+ */
9
+
10
+ import {
11
+ existsSync,
12
+ mkdirSync,
13
+ readdirSync,
14
+ readFileSync,
15
+ rmSync,
16
+ statSync,
17
+ symlinkSync,
18
+ writeFileSync,
19
+ } from "node:fs";
20
+ import { dirname, join, resolve } from "node:path";
21
+ import { readCliEnv } from "../../cli-env.js";
22
+ import {
23
+ BLANK_APP_CONTRACT_TS,
24
+ BLANK_TEST_APP_PROPS_TS,
25
+ blankAppFor,
26
+ blankEntryFor,
27
+ blankHappyDomTestFor,
28
+ } from "./blank-scaffold-templates.js";
29
+ import { applyInternalToolchain } from "./internal-toolchain.js";
30
+ import { MANAGER_TEST_TS } from "./manager-test-template.js";
31
+ import { MULTIPLAYER_TEST_HELPERS_TS } from "./multiplayer-test-template.js";
32
+ import { applyNoStoreOverrides } from "./no-store-scaffold.js";
33
+ import {
34
+ applyInternalMonoRepoPlaywrightScripts,
35
+ applyInternalMonoRepoTypeCheckScripts,
36
+ } from "./package-json-scripts.js";
37
+ import { readSdkTarballUrl } from "./sdk-tarball-url.js";
38
+
39
+ export const TEMPLATES = [
40
+ "react",
41
+ "vanilla-js",
42
+ "solidjs",
43
+ "preact",
44
+ "phaserjs",
45
+ ] as const;
46
+ export type TemplateName = (typeof TEMPLATES)[number];
47
+
48
+ /**
49
+ * Allowed app-name shape and length cap. Re-exported from
50
+ * `poe-tile-config.ts` so the prompt/flag-validation path and the
51
+ * `validatePoeTileConfig` write path enforce the same constraint —
52
+ * otherwise a name accepted at the prompt could fail the post-scaffold
53
+ * config write and leave the user with a half-written project tree.
54
+ */
55
+ export {
56
+ TILE_HANDLE_MAX_LENGTH as VALID_NAME_MAX_LENGTH,
57
+ TILE_HANDLE_REGEX as VALID_NAME_RE,
58
+ } from "../../poe-tile-config.js";
59
+ export const INVALID_NAME_HINT =
60
+ "Use lowercase letters, numbers, and hyphens only. Must start and end with a letter or number; 1-100 characters.";
61
+
62
+ /**
63
+ * Per-template display metadata for the interactive picker. Order is
64
+ * controlled by `TEMPLATES`; this map is keyed by name so picker rows
65
+ * can render a one-line description and an optional "recommended" hint.
66
+ */
67
+ export const TEMPLATE_META: Record<
68
+ TemplateName,
69
+ { description: string; recommended?: boolean }
70
+ > = {
71
+ react: { description: "React 19 + Vite + Tailwind", recommended: true },
72
+ "vanilla-js": { description: "No framework, plain DOM" },
73
+ solidjs: { description: "SolidJS + Vite + Tailwind" },
74
+ preact: { description: "Preact + Vite (smallest bundle)" },
75
+ phaserjs: { description: "Phaser 3 game template" },
76
+ };
77
+
78
+ /**
79
+ * Resolve a resource directory the CLI reads at runtime (templates, SDK
80
+ * skills). In the monorepo, the resource lives at its canonical path under
81
+ * `packages/`. In the published package, scripts/pack-tarball.ts copies it to
82
+ * `packagePath` (relative to the package root) so the CLI works without the
83
+ * monorepo checked out. Keep the package paths in sync with pack-tarball.ts.
84
+ *
85
+ * Exported for unit testing — the in-monorepo branch is exercised by every
86
+ * scaffold call, but the package fallback is only exercised in installed
87
+ * packages and would otherwise be dead in CI.
88
+ */
89
+ export function resolveBundledResource(
90
+ packagePath: string,
91
+ monorepoRelativePath: string,
92
+ ): string {
93
+ const monorepo = resolve(
94
+ import.meta.dir,
95
+ "../../../../..",
96
+ monorepoRelativePath,
97
+ );
98
+ if (existsSync(monorepo)) return monorepo;
99
+ return resolve(import.meta.dir, "../../..", packagePath);
100
+ }
101
+
102
+ const templatesDir = resolveBundledResource(
103
+ "bundled-resources/poe-tile-templates",
104
+ "packages/poe-tile-templates",
105
+ );
106
+ const sdkSkillsDir = resolveBundledResource(
107
+ "skills",
108
+ "packages/poe-tiles-sdk/skills",
109
+ );
110
+
111
+ const DEFAULT_PROFILE_PICTURE_RELATIVE_PATH = "assets/icon.png";
112
+ const DEFAULT_PROFILE_PICTURE_PNG_BASE64 = [
113
+ "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAABS0lEQVR42u2b",
114
+ "0Q3DMAhEPUUX6H836RQdqNt1nVT9jVKpgQOOckj+JdwzSbCN15LJZLJCez7W",
115
+ "NkKkdYwU3RrGUeDb624ebUCghbcCESX6FxhUs54h/ltG/P2sU2UDi/gSCGzi",
116
+ "UyGwik+BwC4+HEIH8XsII8XDIXRJ/bBXoaN4WBZ0Fg+BMBoA4t2/XS8QER4/",
117
+ "5m+BR/wn4P2o9JMK4ChoS/AoPyYA6NmvBnAaQsTsnwke5ScdwPgMEADSv0A6",
118
+ "AKY6oBRAy4qw6+oPWhGOzgABEAABEAABcCyGMsRQLokR5WrUc0I3RJD1etT6",
119
+ "wAWACYJHvGtj1LN8jRL+q+/UbfEICF6f6YcjTBsi0KMxFATvKDkmt9QFleKp",
120
+ "jsizhYeIR2yUZAhv2SaDrBlGN0qNbpUb3SxJ0y47rldY3eK6L6AbI7ozpFtj",
121
+ "IDhLJpNV2RsBAManNH5fpwAAAABJRU5ErkJggg==",
122
+ ].join("");
123
+
124
+ const CLAUDE_SETTINGS = {
125
+ permissions: {
126
+ allow: [
127
+ "Read",
128
+ "Write",
129
+ "Edit",
130
+ "MultiEdit",
131
+ "Glob",
132
+ "Grep",
133
+ "LS",
134
+ "Skill(tile-creator)",
135
+ "Skill(synced-store)",
136
+ "Bash(bun run:*)",
137
+ "Bash(bun test:*)",
138
+ "Bash(bun install)",
139
+ "Bash(bun install:*)",
140
+ "Bash(bun add:*)",
141
+ "Bash(bun remove:*)",
142
+ "Bash(bunx tsc:*)",
143
+ "Bash(bunx vite:*)",
144
+ "Bash(bunx playwright:*)",
145
+ "Bash(./scripts/doctor.sh)",
146
+ "Bash(./scripts/doctor.sh:*)",
147
+ "Bash(bash ./scripts/doctor.sh)",
148
+ "Bash(bash ./scripts/doctor.sh:*)",
149
+ "Bash(poe-tiles:*)",
150
+ "Bash(POE_SERVER_URL=* poe-tiles:*)",
151
+ ],
152
+ deny: [],
153
+ ask: [],
154
+ },
155
+ };
156
+
157
+ function baseTemplateDir(): string {
158
+ return resolve(templatesDir, "base");
159
+ }
160
+
161
+ function frameworkTemplateDir(template: TemplateName): string {
162
+ return resolve(templatesDir, template);
163
+ }
164
+
165
+ export interface ScaffoldOptions {
166
+ appName: string;
167
+ template: TemplateName;
168
+ outputDir: string;
169
+ /** joiner-sdk version string. Defaults to "workspace:*". */
170
+ sdkVersion?: string;
171
+ /** Copy SDK skills for Claude and Codex. Defaults to false. */
172
+ includeSkill?: boolean;
173
+ /**
174
+ * Tune the scaffold for an app in the internal ai-app monorepo:
175
+ * - Force `sdkVersion = "workspace:*"` (overrides the published-tarball default).
176
+ * - Add `lint` + `format:check` scripts to package.json (required by
177
+ * `scripts/check-package-scripts.ts`).
178
+ * - Pin `zod` to the version syncpack enforces in the monorepo.
179
+ * - Generate a `tsconfig.json` that extends the monorepo root tsconfig
180
+ * so the app inherits `allowImportingTsExtensions`, etc. — and ships
181
+ * its own `exclude` so the app's own `bun run type-check` still picks
182
+ * up its files when the root tsconfig excludes the app directory.
183
+ * - Set the package name to `@poe-tile/<appName>`.
184
+ */
185
+ internalMonoRepo?: boolean;
186
+ /**
187
+ * Replace the todo-list example with a minimal multiplayer starter.
188
+ * The boilerplate (package.json, tsconfig, vite config, biome, index.html,
189
+ * styles.css, framework wiring) stays canonical from the template; the
190
+ * App-specific files provide typed system-table reads, deterministic seating
191
+ * hooks, and executable behavior tests that build green on day zero.
192
+ *
193
+ * Use this when an AI (or person) is going to write the app from scratch
194
+ * and just needs the toolchain wired up — avoids the "rewrite todo as you
195
+ * go and live with type-check failures while half-converted" problem.
196
+ */
197
+ blank?: boolean;
198
+ /**
199
+ * Experimental. Scaffold without synced-store: no `synced-store/`,
200
+ * `client.ts`, backend entry, mutator test, or e2e tests. The entry mounts
201
+ * the app without `setupStore` and the Vite build emits no backend
202
+ * artifact. Applied after `blank`, so the default scaffold is unchanged.
203
+ */
204
+ noStore?: boolean;
205
+ }
206
+
207
+ export function resolveScaffoldSdkVersion(
208
+ options: Pick<ScaffoldOptions, "internalMonoRepo" | "sdkVersion">,
209
+ env: NodeJS.ProcessEnv = process.env,
210
+ ): string {
211
+ if (options.internalMonoRepo) return "workspace:*";
212
+ if (options.sdkVersion) return options.sdkVersion;
213
+ return (
214
+ readCliEnv(env, "SDK_TARBALL_OVERRIDE") ??
215
+ readSdkTarballUrl() ??
216
+ "workspace:*"
217
+ );
218
+ }
219
+
220
+ /**
221
+ * Walk up from `startDir` until we find `.syncpackrc.json`, then return the
222
+ * `pinVersion` that syncpack enforces for `depName` (or `null` if no pin
223
+ * applies). Committed-mode scaffolds use this so we don't have to duplicate
224
+ * pinned versions in the CLI source — `.syncpackrc.json` is the single
225
+ * source of truth, and bumping a pin there automatically propagates to
226
+ * future scaffolds.
227
+ *
228
+ * Returns `null` when the config file isn't found (CLI run outside any
229
+ * monorepo) or the dep isn't pinned. Does not throw on parse errors —
230
+ * internal-mono-repo mode shouldn't fail noisily because syncpack happens to be
231
+ * misconfigured; the worst case is the scaffolded package.json keeps the
232
+ * template's bare range and the user runs `bun run syncpack:fix`.
233
+ *
234
+ * Exported for direct unit testing of the parse-error branch (which is
235
+ * hard to exercise via the public scaffold API since walk-up from a
236
+ * project-local tempDir always finds the real syncpackrc).
237
+ */
238
+
239
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Existing function exceeds the cognitive-complexity limit; keep the rule enabled for new code.
240
+ export function resolveSyncpackPin(
241
+ startDir: string,
242
+ depName: string,
243
+ ): string | null {
244
+ type SyncpackConfig = {
245
+ versionGroups?: Array<{ dependencies?: string[]; pinVersion?: string }>;
246
+ };
247
+ const candidate = join(startDir, ".syncpackrc.json");
248
+ if (existsSync(candidate)) {
249
+ let config: SyncpackConfig;
250
+ try {
251
+ config = JSON.parse(readFileSync(candidate, "utf-8")) as SyncpackConfig;
252
+ } catch {
253
+ return null;
254
+ }
255
+ for (const group of config.versionGroups ?? []) {
256
+ if (
257
+ typeof group.pinVersion === "string" &&
258
+ group.dependencies?.includes(depName)
259
+ ) {
260
+ return group.pinVersion;
261
+ }
262
+ }
263
+ return null;
264
+ }
265
+ const parent = dirname(startDir);
266
+ if (parent === startDir) return null;
267
+ return resolveSyncpackPin(parent, depName);
268
+ }
269
+
270
+ /** Recursively list all files in a directory (relative paths). */
271
+ function listFiles(dir: string, prefix = ""): string[] {
272
+ const results: string[] = [];
273
+ for (const entry of readdirSync(dir)) {
274
+ const fullPath = join(dir, entry);
275
+ const relativePath = prefix ? `${prefix}/${entry}` : entry;
276
+ if (statSync(fullPath).isDirectory()) {
277
+ results.push(...listFiles(fullPath, relativePath));
278
+ } else {
279
+ results.push(relativePath);
280
+ }
281
+ }
282
+ return results;
283
+ }
284
+
285
+ /** Apply placeholder substitution to file contents. */
286
+ function substitute(
287
+ content: string,
288
+ replacements: Record<string, string>,
289
+ ): string {
290
+ let result = content;
291
+ for (const [key, value] of Object.entries(replacements)) {
292
+ // Match both {{KEY}} and {{ KEY }} (biome formats JSX braces with spaces)
293
+ result = result.replaceAll(`{{${key}}}`, value);
294
+ result = result.replaceAll(`{{ ${key} }}`, value);
295
+ }
296
+ return result;
297
+ }
298
+
299
+ /** Deep-merge two package.json objects (only merges dependencies/devDependencies). */
300
+ function mergePackageJson(
301
+ base: Record<string, unknown>,
302
+ partial: Record<string, unknown>,
303
+ ): Record<string, unknown> {
304
+ const result = { ...base };
305
+ for (const key of ["dependencies", "devDependencies"] as const) {
306
+ if (partial[key]) {
307
+ result[key] = {
308
+ ...(result[key] as Record<string, string> | undefined),
309
+ ...(partial[key] as Record<string, string>),
310
+ };
311
+ }
312
+ }
313
+ return result;
314
+ }
315
+
316
+ /** Paths that use an underscore prefix in templates because the dot-prefixed
317
+ * version has special meaning to git or other tools. */
318
+ const DOTFILE_PREFIXES: Record<string, string> = {
319
+ "_bunfig.toml": "bunfig.toml",
320
+ _gitignore: ".gitignore",
321
+ _claude: ".claude",
322
+ };
323
+
324
+ /**
325
+ * The config `bun run type-check` points at: the app's `tsconfig.json` plus the
326
+ * `@playwright/test` path mapping the Playwright sources under `tests/` need
327
+ * (those are deliberately NOT excluded from type-checking — see
328
+ * `packages/poe-tile-templates/base/CLAUDE.md`).
329
+ *
330
+ * Hand-formatted (rather than `JSON.stringify`) so biome's JSON formatter
331
+ * accepts it as-is, exactly like `renderInternalMonoRepoTsconfig` below.
332
+ * `JSON.stringify` with tab indent always splits the one-element `paths` array
333
+ * across three lines, which biome reformats — and an app scaffolded with
334
+ * `--internal-mono-repo` is committed here and runs `biome format .`, so a
335
+ * machine-formatted file would fail the new app's own `format:check` on its
336
+ * first run. Any edit here must stay byte-identical to `biome format` output;
337
+ * `scaffold-biome-clean.test.ts` runs the real `biome check` over every emitted
338
+ * variant and holds that for this file and for the rest of the scaffold.
339
+ */
340
+ const TYPECHECK_TSCONFIG = `{
341
+ "extends": "./tsconfig.json",
342
+ "compilerOptions": {
343
+ "paths": {
344
+ "@playwright/test": ["./node_modules/@playwright/test"]
345
+ }
346
+ }
347
+ }
348
+ `;
349
+
350
+ /** Rename underscore-prefixed template paths to their dot-prefixed equivalents. */
351
+ function renameDotfiles(relativePath: string): string {
352
+ for (const [from, to] of Object.entries(DOTFILE_PREFIXES)) {
353
+ if (relativePath === from) return to;
354
+ if (relativePath.startsWith(`${from}/`))
355
+ return `${to}/${relativePath.slice(from.length + 1)}`;
356
+ }
357
+ return relativePath;
358
+ }
359
+
360
+ /** Copy files from a source directory to the output, applying substitutions. */
361
+ function copyTemplateFiles(
362
+ sourceDir: string,
363
+ outputDir: string,
364
+ replacements: Record<string, string>,
365
+ skipFiles: Set<string> = new Set(),
366
+ ): void {
367
+ for (const relativePath of listFiles(sourceDir)) {
368
+ if (skipFiles.has(relativePath)) continue;
369
+
370
+ const sourcePath = join(sourceDir, relativePath);
371
+
372
+ // Rename underscore-prefixed paths to dot-prefixed equivalents
373
+ // (git/tools interpret dotfiles specially, so templates use _ prefix)
374
+ const outputRelative = renameDotfiles(relativePath);
375
+ const outputPath = join(outputDir, outputRelative);
376
+
377
+ mkdirSync(dirname(outputPath), { recursive: true });
378
+
379
+ const content = readFileSync(sourcePath, "utf-8");
380
+ const sourceMode = statSync(sourcePath).mode;
381
+ writeFileSync(outputPath, substitute(content, replacements), {
382
+ mode: sourceMode,
383
+ });
384
+ }
385
+ }
386
+
387
+ function writeDefaultProfilePicture(outputDir: string): void {
388
+ const outputPath = join(outputDir, DEFAULT_PROFILE_PICTURE_RELATIVE_PATH);
389
+ if (existsSync(outputPath)) return;
390
+
391
+ mkdirSync(dirname(outputPath), { recursive: true });
392
+ writeFileSync(
393
+ outputPath,
394
+ Buffer.from(DEFAULT_PROFILE_PICTURE_PNG_BASE64, "base64"),
395
+ { mode: 0o644 },
396
+ );
397
+ }
398
+
399
+ function writeClaudeSettings(outputDir: string): void {
400
+ const outputPath = join(outputDir, ".claude/settings.json");
401
+ if (existsSync(outputPath)) return;
402
+
403
+ mkdirSync(dirname(outputPath), { recursive: true });
404
+ writeFileSync(
405
+ outputPath,
406
+ `${JSON.stringify(CLAUDE_SETTINGS, null, "\t")}\n`,
407
+ {
408
+ mode: 0o644,
409
+ },
410
+ );
411
+ }
412
+
413
+ function copyHostSkills(
414
+ outputDir: string,
415
+ replacements: Record<string, string>,
416
+ internalMonoRepo: boolean,
417
+ ): void {
418
+ if (!existsSync(sdkSkillsDir))
419
+ throw new Error("SDK skills are missing; reinstall the CLI.");
420
+ for (const host of internalMonoRepo ? [".claude"] : [".claude", ".agents"]) {
421
+ copyTemplateFiles(
422
+ sdkSkillsDir,
423
+ join(outputDir, host, "skills"),
424
+ replacements,
425
+ );
426
+ }
427
+ if (internalMonoRepo) {
428
+ mkdirSync(join(outputDir, ".agents"), { recursive: true });
429
+ symlinkSync("../.claude/skills", join(outputDir, ".agents/skills"), "dir");
430
+ }
431
+ }
432
+
433
+ export function scaffoldApp(options: ScaffoldOptions): void {
434
+ // Internal monorepo mode forces the workspace dependency. The environment
435
+ // override is reserved for isolated candidate-eval fixtures that pair an
436
+ // unreleased CLI with an unreleased SDK; normal creators never need it.
437
+ const sdkVersion = resolveScaffoldSdkVersion(options);
438
+ const { appName, template, outputDir } = options;
439
+ const baseDir = baseTemplateDir();
440
+ const frameworkDir = frameworkTemplateDir(template);
441
+
442
+ if (existsSync(outputDir)) {
443
+ throw new Error(`Directory already exists: ${outputDir}`);
444
+ }
445
+
446
+ const replacements: Record<string, string> = {
447
+ APP_NAME: appName,
448
+ POE_SDK_VERSION: sdkVersion,
449
+ };
450
+
451
+ // 1. Copy base files (skip package.json — we merge it separately)
452
+ copyTemplateFiles(
453
+ baseDir,
454
+ outputDir,
455
+ replacements,
456
+ new Set(["package.json"]),
457
+ );
458
+
459
+ // 2. Copy framework files (skip package.partial.json — merged below)
460
+ copyTemplateFiles(
461
+ frameworkDir,
462
+ outputDir,
463
+ replacements,
464
+ new Set(["package.partial.json"]),
465
+ );
466
+ writeFileSync(join(outputDir, "tsconfig.typecheck.json"), TYPECHECK_TSCONFIG);
467
+
468
+ writeDefaultProfilePicture(outputDir);
469
+ writeClaudeSettings(outputDir);
470
+ mkdirSync(join(outputDir, "tests"), { recursive: true });
471
+ writeFileSync(
472
+ join(outputDir, "tests/multiplayer.ts"),
473
+ MULTIPLAYER_TEST_HELPERS_TS,
474
+ );
475
+
476
+ if (options.includeSkill)
477
+ copyHostSkills(outputDir, replacements, options.internalMonoRepo ?? false);
478
+
479
+ // 4. Merge package.json: base + framework partial
480
+ const basePackage = JSON.parse(
481
+ substitute(
482
+ readFileSync(join(baseDir, "package.json"), "utf-8"),
483
+ replacements,
484
+ ),
485
+ ) as Record<string, unknown>;
486
+
487
+ const partialPath = join(frameworkDir, "package.partial.json");
488
+ const partialPackage = existsSync(partialPath)
489
+ ? (JSON.parse(readFileSync(partialPath, "utf-8")) as Record<
490
+ string,
491
+ unknown
492
+ >)
493
+ : {};
494
+
495
+ const mergedPackage = mergePackageJson(basePackage, partialPackage);
496
+ if (options.internalMonoRepo) {
497
+ applyInternalMonoRepoPackageJsonOverrides(
498
+ mergedPackage,
499
+ appName,
500
+ outputDir,
501
+ );
502
+ }
503
+ const outputPackagePath = join(outputDir, "package.json");
504
+ mkdirSync(dirname(outputPackagePath), { recursive: true });
505
+ writeFileSync(
506
+ outputPackagePath,
507
+ `${JSON.stringify(mergedPackage, null, "\t")}\n`,
508
+ );
509
+
510
+ if (options.internalMonoRepo) {
511
+ // Replace the throwaway-friendly tsconfig with one that extends the
512
+ // monorepo root. Without `extends`, tsc complains about TS imports
513
+ // referencing `.ts` files in workspace deps because the strictness
514
+ // flags it needs (`allowImportingTsExtensions`, etc.) live in the
515
+ // root tsconfig.
516
+ writeFileSync(
517
+ join(outputDir, "tsconfig.json"),
518
+ renderInternalMonoRepoTsconfig(template),
519
+ );
520
+ }
521
+
522
+ if (options.blank) {
523
+ applyBlankOverrides(outputDir, template, appName);
524
+ }
525
+ if (options.noStore) {
526
+ applyNoStoreOverrides(outputDir, template, appName);
527
+ }
528
+ if (options.internalMonoRepo)
529
+ symlinkSync("CLAUDE.md", join(outputDir, "AGENTS.md"));
530
+ else {
531
+ writeFileSync(
532
+ join(outputDir, "AGENTS.md"),
533
+ readFileSync(join(outputDir, "CLAUDE.md")),
534
+ );
535
+ writeFileSync(
536
+ join(outputDir, "scripts/check-bun.ts"),
537
+ readFileSync(new URL("../../bun-version.ts", import.meta.url)),
538
+ );
539
+ }
540
+ }
541
+
542
+ /** Mutate the merged package.json in place for internal-mono-repo-mode scaffolds. */
543
+ function applyInternalMonoRepoPackageJsonOverrides(
544
+ pkg: Record<string, unknown>,
545
+ appName: string,
546
+ outputDir: string,
547
+ ): void {
548
+ // Conventional package name in the monorepo.
549
+ pkg["name"] = `@poe-tile/${appName}`;
550
+ applyInternalToolchain(pkg);
551
+
552
+ const scripts = (pkg["scripts"] as Record<string, string> | undefined) ?? {};
553
+ // Required by `scripts/check-package-scripts.ts`, which enforces these
554
+ // exact strings. Throwaway apps don't hit that check so the base template
555
+ // doesn't include them. (No `--vcs-use-ignore-file=false`: the git ignore
556
+ // file is what keeps the gitignored `dist/` out of the lint walk.)
557
+ scripts["lint"] = "biome lint --error-on-warnings .";
558
+ scripts["format:check"] = "biome format .";
559
+ applyInternalMonoRepoTypeCheckScripts(scripts);
560
+ applyInternalMonoRepoPlaywrightScripts({ outputDir, scripts });
561
+ pkg["scripts"] = scripts;
562
+
563
+ // Apply every syncpack pin that targets a dep already present in this
564
+ // package.json after restoring the repository's dependency ranges.
565
+ // `.syncpackrc.json` lives at the monorepo root; walk up from the new
566
+ // app's parent directory to find it. (We use the parent because
567
+ // `outputDir` itself doesn't exist on disk yet at this point.)
568
+ const searchFrom = dirname(outputDir);
569
+ const deps = pkg["dependencies"] as Record<string, string> | undefined;
570
+ const devDeps = pkg["devDependencies"] as Record<string, string> | undefined;
571
+ for (const bag of [deps, devDeps]) {
572
+ if (!bag) continue;
573
+ for (const depName of Object.keys(bag)) {
574
+ const pin = resolveSyncpackPin(searchFrom, depName);
575
+ if (pin) bag[depName] = pin;
576
+ }
577
+ }
578
+ }
579
+
580
+ /**
581
+ * Replace the todo-list example code with a minimal multiplayer starter that
582
+ * builds green. Used by `--blank` mode. After this runs:
583
+ *
584
+ * - synced-store/schema.ts defines a minimal players table
585
+ * - synced-store/hooks.ts deterministically assigns X, O, then spectators
586
+ * - synced-store/data/index.ts exports shared read context/table aliases
587
+ * - client.ts re-exports the starter schema and exact inferred context
588
+ * - tile/src/{entry,backend}.{ts,tsx} import the new generic config names
589
+ * - ui/App.{tsx,ts} renders a "Hello, <appName>" placeholder
590
+ * - tests exercise two-client/system-table behavior and Happy DOM matchers,
591
+ * plus executable browser smoke and multiplayer tests
592
+ */
593
+ function applyBlankOverrides(
594
+ outputDir: string,
595
+ template: TemplateName,
596
+ appName: string,
597
+ ): void {
598
+ const isTsx = template !== "vanilla-js" && template !== "phaserjs";
599
+ const uiExt = isTsx ? "tsx" : "ts";
600
+ const entryExt = isTsx ? "tsx" : "ts";
601
+
602
+ // --- synced-store ---
603
+ rmSync(join(outputDir, "synced-store/data"), {
604
+ recursive: true,
605
+ force: true,
606
+ });
607
+ rmSync(join(outputDir, "synced-store/mutators"), {
608
+ recursive: true,
609
+ force: true,
610
+ });
611
+ mkdirSync(join(outputDir, "synced-store/data"), { recursive: true });
612
+ mkdirSync(join(outputDir, "synced-store/mutators"), { recursive: true });
613
+ writeFileSync(join(outputDir, "synced-store/schema.ts"), BLANK_SCHEMA_TS);
614
+ writeFileSync(
615
+ join(outputDir, "synced-store/data/index.ts"),
616
+ BLANK_DATA_INDEX_TS,
617
+ );
618
+ writeFileSync(
619
+ join(outputDir, "synced-store/mutators/index.ts"),
620
+ BLANK_MUTATORS_INDEX_TS,
621
+ );
622
+ writeFileSync(join(outputDir, "synced-store/hooks.ts"), BLANK_HOOKS_TS);
623
+ writeFileSync(
624
+ join(outputDir, "synced-store/client-config.ts"),
625
+ BLANK_CLIENT_CONFIG_TS,
626
+ );
627
+ writeFileSync(
628
+ join(outputDir, "synced-store/backend-config.ts"),
629
+ BLANK_BACKEND_CONFIG_TS,
630
+ );
631
+
632
+ // --- client.ts (re-exports) ---
633
+ writeFileSync(join(outputDir, "client.ts"), BLANK_CLIENT_TS);
634
+
635
+ // --- tile/src/backend.ts (re-exports backend config under new name) ---
636
+ writeFileSync(join(outputDir, "tile/src/backend.ts"), BLANK_TILE_BACKEND_TS);
637
+
638
+ // --- tile/src/entry.{tsx,ts} (per-framework boot) ---
639
+ writeFileSync(
640
+ join(outputDir, `tile/src/entry.${entryExt}`),
641
+ blankEntryFor(template),
642
+ );
643
+
644
+ // --- ui/App.{tsx,ts} (per-framework hello world) ---
645
+ writeFileSync(
646
+ join(outputDir, `ui/App.${uiExt}`),
647
+ blankAppFor({ template, appName }),
648
+ );
649
+ writeFileSync(join(outputDir, "ui/app-contract.ts"), BLANK_APP_CONTRACT_TS);
650
+ // Phaser's overlay has a todo-specific scene module. The blank App does not
651
+ // use it, but tsconfig still includes it, so remove the stale source.
652
+ if (template === "phaserjs") {
653
+ rmSync(join(outputDir, "ui/phaser-scene.ts"), { force: true });
654
+ }
655
+
656
+ // --- tests (colocated with source) ---
657
+ writeFileSync(
658
+ join(outputDir, "synced-store/mutators.test.ts"),
659
+ BLANK_MUTATORS_TEST_TS,
660
+ );
661
+ writeFileSync(
662
+ join(outputDir, "synced-store/manager.test.ts"),
663
+ MANAGER_TEST_TS,
664
+ );
665
+ // Every framework template ships ui/App.test.happydom.tsx (even
666
+ // vanilla-js — the JSX-free file uses .tsx so a single hardcoded path
667
+ // in package.json's test script works for all templates). Writing to
668
+ // `${uiExt}` would leave a stale .tsx alongside a new .ts and break
669
+ // type-check + test in vanilla-js --blank.
670
+ writeFileSync(
671
+ join(outputDir, "ui/App.test.happydom.tsx"),
672
+ blankHappyDomTestFor(template),
673
+ );
674
+ writeFileSync(
675
+ join(outputDir, "tests/app-test-props.ts"),
676
+ BLANK_TEST_APP_PROPS_TS,
677
+ );
678
+ writeFileSync(
679
+ join(outputDir, "tests/e2e.test.playwright.ts"),
680
+ blankE2ETest(appName),
681
+ );
682
+
683
+ // `tile/styles.css` is intentionally NOT overridden — blank scaffolds
684
+ // inherit the base template's mobile-webview defaults. See
685
+ // docs/mobile-webview/layout-and-interaction.md.
686
+ }
687
+
688
+ const BLANK_SCHEMA_TS = `import { defineSchema, table } from "joiner-sdk/v1/backend.js";
689
+ import { z } from "zod";
690
+
691
+ // The player rows make the scaffold's multiplayer and system-table examples
692
+ // executable on day zero. Replace or extend them with your app's state.
693
+ const playerRow = z.object({
694
+ userId: z.string(),
695
+ mark: z.enum(["X", "O"]).nullable(),
696
+ });
697
+
698
+ export const tileSchema = defineSchema({
699
+ schemaVersion: 1,
700
+ tables: { players: { schema: table(playerRow) } },
701
+ mutators: {},
702
+ });
703
+
704
+ export type AppSchema = typeof tileSchema;
705
+ `;
706
+
707
+ const BLANK_DATA_INDEX_TS = `import type {
708
+ InferReadContext,
709
+ InferSchemaTableTypes,
710
+ } from "joiner-sdk/v1/client.js";
711
+ import type { AppSchema } from "../schema";
712
+
713
+ export type AppTableTypes = InferSchemaTableTypes<AppSchema>;
714
+ export type AppReadContext = InferReadContext<AppSchema>;
715
+ `;
716
+
717
+ const BLANK_MUTATORS_INDEX_TS = `import type { InferMutatorHandlers } from "joiner-sdk/v1/client.js";
718
+ import type { AppSchema } from "../schema";
719
+
720
+ // Add each handler in its own file under synced-store/mutators/ and compose
721
+ // them here. Put read-only ctx helpers in synced-store/data/ so actions,
722
+ // queries, and mutators can share them.
723
+ // See poe-tiles/spy-words for an end-to-end example (mutator validation
724
+ // order, isServer gating).
725
+ // For onAddUsers/onRemoveUser hook wiring, see poe-tiles/chat.
726
+ export const tileMutators: InferMutatorHandlers<AppSchema> = {};
727
+ `;
728
+
729
+ const BLANK_HOOKS_TS = `import type { InferSystemHooks } from "joiner-sdk/v1/client.js";
730
+ import type { AppSchema } from "./schema";
731
+
732
+ // Deterministic hooks belong in this shared client-safe module and must be
733
+ // wired into both client-config.ts and backend-config.ts.
734
+ export const tileHooks: InferSystemHooks<AppSchema> = {
735
+ onAddUsers: async (ctx, { userId }) => {
736
+ if (await ctx.table("players").has(userId)) return;
737
+
738
+ const players = await ctx.table("players").scan().values().toArray();
739
+ const usedMarks = new Set(players.map((player) => player.mark));
740
+ const mark = !usedMarks.has("X") ? "X" : !usedMarks.has("O") ? "O" : null;
741
+ await ctx.table("players").set({
742
+ itemKey: userId,
743
+ value: { userId, mark },
744
+ });
745
+ },
746
+ };
747
+ `;
748
+
749
+ const BLANK_CLIENT_CONFIG_TS = `import { defineClientConfig } from "joiner-sdk/v1/client.js";
750
+ import { tileHooks } from "./hooks";
751
+ import { tileMutators } from "./mutators/index";
752
+ import type { tileSchema } from "./schema";
753
+
754
+ export const tileClientConfig = defineClientConfig<typeof tileSchema>({
755
+ mutators: tileMutators,
756
+ hooks: tileHooks,
757
+ schemaVersion: 1,
758
+ });
759
+ `;
760
+
761
+ const BLANK_BACKEND_CONFIG_TS = `import { defineBackendConfig } from "joiner-sdk/v1/backend.js";
762
+ import { tileHooks } from "./hooks";
763
+ import { tileMutators } from "./mutators/index";
764
+ import { tileSchema } from "./schema";
765
+
766
+ export const tileBackendConfig = defineBackendConfig({
767
+ schema: tileSchema,
768
+ mutators: tileMutators,
769
+ hooks: tileHooks,
770
+ actions: {},
771
+ });
772
+ `;
773
+
774
+ const BLANK_CLIENT_TS = `import type { InferPoeStoreClient } from "joiner-sdk/v1/client.js";
775
+ import type { AppSchema } from "./synced-store/schema";
776
+
777
+ export type { AppSchema, tileSchema } from "./synced-store/schema";
778
+ export type AppStoreClient = InferPoeStoreClient<AppSchema>;
779
+ export { tileClientConfig } from "./synced-store/client-config";
780
+ export type { AppReadContext, AppTableTypes } from "./synced-store/data/index";
781
+ export { tileHooks } from "./synced-store/hooks";
782
+ export { tileMutators } from "./synced-store/mutators/index";
783
+ `;
784
+
785
+ const BLANK_TILE_BACKEND_TS = `import { tileBackendConfig } from "../../synced-store/backend-config";
786
+
787
+ export default tileBackendConfig;
788
+ `;
789
+
790
+ const BLANK_MUTATORS_TEST_TS = `import { expect, test } from "bun:test";
791
+ import { createPoeTileTestHarness } from "joiner-sdk/v1/test-utils.js";
792
+ import type { AppReadContext } from "../client";
793
+ import { tileBackendConfig } from "./backend-config";
794
+ import type { AppSchema } from "./schema";
795
+
796
+ async function readRoster(ctx: AppReadContext) {
797
+ return {
798
+ users: await ctx.table("$users").scan().values().toArray(),
799
+ userInfo: await ctx.table("$userInfo").scan().values().toArray(),
800
+ permissions: await ctx.table("$permissions").scan().values().toArray(),
801
+ };
802
+ }
803
+
804
+ test("clients observe shared membership, profile information, and removal", async () => {
805
+ const harness = createPoeTileTestHarness<AppSchema>({
806
+ store: { backendConfig: tileBackendConfig },
807
+ });
808
+ try {
809
+ const { store: alice } = await harness.createClient({
810
+ userId: "alice",
811
+ userInfo: {
812
+ displayName: "Alice Example",
813
+ profilePicture: "https://example.com/alice.png",
814
+ },
815
+ });
816
+ const { store: bob } = await harness.createClient({ userId: "bob" });
817
+ await harness.createClient({ userId: "carol" });
818
+
819
+ const roster = await alice.query(readRoster);
820
+ expect(roster.users.map((user) => user.userId)).toEqual([
821
+ "alice",
822
+ "bob",
823
+ "carol",
824
+ ]);
825
+ expect(
826
+ roster.userInfo.find((info) => info.userId === "alice"),
827
+ ).toMatchObject({
828
+ displayName: "Alice Example",
829
+ profilePicture: "https://example.com/alice.png",
830
+ });
831
+ expect(
832
+ roster.userInfo.find((info) => info.userId === "bob")?.displayName,
833
+ ).toBe("bob");
834
+ expect(roster.permissions).toEqual([]);
835
+ expect(await bob.query(readRoster)).toEqual(roster);
836
+ await harness.removeUser({ userId: "carol" });
837
+ // Read both clients concurrently: awaiting inside the loop would
838
+ // serialize the round-trips, and the repo's noAwaitInLoops rule
839
+ // rejects it.
840
+ const removedRows = await Promise.all(
841
+ [alice, bob].map((store) =>
842
+ store.query((ctx: AppReadContext) => ctx.table("$users").get("carol")),
843
+ ),
844
+ );
845
+ for (const row of removedRows) {
846
+ expect(row).toMatchObject({ removedAt: expect.any(Number) });
847
+ }
848
+ } finally {
849
+ harness.dispose();
850
+ }
851
+ });
852
+ `;
853
+
854
+ function blankE2ETest(appName: string): string {
855
+ return `import { existsSync } from "node:fs";
856
+ import { dirname, join } from "node:path";
857
+ import { fileURLToPath } from "node:url";
858
+ import { expect, test } from "@playwright/test";
859
+ import {
860
+ TestServer,
861
+ waitForBlobFrame,
862
+ } from "joiner-sdk/v1/test-utils/playwright.js";
863
+ import { openTwoUserTile } from "./multiplayer";
864
+
865
+ const __dirname = dirname(fileURLToPath(import.meta.url));
866
+ const DIST_DIR = join(__dirname, "../dist");
867
+
868
+ const server = new TestServer();
869
+
870
+ test.beforeAll(async () => {
871
+ if (!existsSync(join(DIST_DIR, "index.html"))) {
872
+ throw new Error('dist/index.html not found. Run "bun run build" first.');
873
+ }
874
+ await server.start();
875
+ await server.registerTile({
876
+ typeId: "${appName}",
877
+ content: { type: "directory", dir: DIST_DIR },
878
+ });
879
+ });
880
+
881
+ test.afterAll(() => {
882
+ server.close();
883
+ });
884
+
885
+ // Adapt this browser journey when replacing the starter UI.
886
+ test.describe("${appName} smoke", () => {
887
+ test("app loads and renders the placeholder heading", async ({ page }) => {
888
+ await page.goto(
889
+ server.sessionUrl({
890
+ tileTypeId: "${appName}",
891
+ instanceId: "${appName}-smoke",
892
+ userId: "alice",
893
+ clientId: "client-alice",
894
+ }),
895
+ );
896
+ const frame = await waitForBlobFrame(page);
897
+ await expect(frame.locator("#app-heading")).toBeVisible({
898
+ timeout: 15_000,
899
+ });
900
+ });
901
+
902
+ test("two users open the same tile instance", async ({ browser }) => {
903
+ const sessions = await openTwoUserTile({
904
+ server,
905
+ browser,
906
+ tileTypeId: "${appName}",
907
+ instanceId: "${appName}-two-users",
908
+ readySelector: "#app-heading",
909
+ });
910
+ try {
911
+ await expect(sessions.alice.frame.locator("#app-heading")).toBeVisible();
912
+ await expect(sessions.bob.frame.locator("#app-heading")).toBeVisible();
913
+ } finally {
914
+ await sessions.close();
915
+ }
916
+ });
917
+ });
918
+ `;
919
+ }
920
+
921
+ /**
922
+ * Generate a internal-mono-repo-mode tsconfig that extends the monorepo root.
923
+ *
924
+ * Hand-formatted (rather than `JSON.stringify`) so biome's JSON formatter
925
+ * accepts it as-is — biome wants short arrays inlined, but JSON.stringify
926
+ * with tab indent always splits arrays across lines.
927
+ */
928
+ function renderInternalMonoRepoTsconfig(template: TemplateName): string {
929
+ let jsxImportSource: string | null = null;
930
+ if (template === "react") jsxImportSource = "react";
931
+ else if (template === "preact") jsxImportSource = "preact";
932
+ else if (template === "solidjs") jsxImportSource = "solid-js";
933
+
934
+ const lines: string[] = ["{"];
935
+ lines.push(`\t"extends": "../../tsconfig.json",`);
936
+ lines.push(`\t"compilerOptions": {`);
937
+ if (jsxImportSource !== null) {
938
+ const jsxMode = template === "solidjs" ? "preserve" : "react-jsx";
939
+ lines.push(`\t\t"jsx": "${jsxMode}",`);
940
+ lines.push(`\t\t"jsxImportSource": "${jsxImportSource}",`);
941
+ }
942
+ // The root's types plus `vite/client`, which types Vite's `?url`, `?raw`
943
+ // and `?worker` imports, so tile code never needs a `@ts-expect-error`
944
+ // for them (the template tsconfigs list it for the same reason).
945
+ lines.push(
946
+ `\t\t"types": ["bun-types", "@cloudflare/workers-types", "vite/client"]`,
947
+ );
948
+ lines.push(`\t},`);
949
+ lines.push(
950
+ `\t"include": ["tile/src", "synced-store", "ui", "tests", "client.ts"],`,
951
+ );
952
+ // The root tsconfig may exclude this app's directory because another JSX
953
+ // runtime owns the root type-check. Override here so the app's own
954
+ // type-check still sees its files. Deliberately does NOT exclude
955
+ // `tests/**/*.playwright.ts` or `tests/multiplayer.ts` — those are
956
+ // type-checked on purpose (see packages/poe-tile-templates/base/tsconfig.json).
957
+ lines.push(`\t"exclude": ["node_modules", "dist"]`);
958
+ lines.push(`}`);
959
+ return `${lines.join("\n")}\n`;
960
+ }