@sssb/create 0.0.0-stage → 0.2.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 (85) hide show
  1. package/LICENSE +21 -0
  2. package/bin/create.js +135 -0
  3. package/package.json +22 -3
  4. package/src/args.js +270 -0
  5. package/src/files.js +660 -0
  6. package/src/generate.js +517 -0
  7. package/src/json.js +60 -0
  8. package/src/signals.js +72 -0
  9. package/src/template.js +496 -0
  10. package/src/yaml.js +17 -0
  11. package/template/app/DEMO-SIZE.md +55 -0
  12. package/template/app/config/app.ts +17 -0
  13. package/template/app/config/params.ts +70 -0
  14. package/template/app/infra/README.md +78 -0
  15. package/template/app/infra/app.ts +45 -0
  16. package/template/app/infra/cdk.json +9 -0
  17. package/template/app/infra/lib/tags.ts +35 -0
  18. package/template/app/infra/package.json +20 -0
  19. package/template/app/infra/tsconfig.json +13 -0
  20. package/template/app/messages/en.json +20 -0
  21. package/template/app/messages/es.json +20 -0
  22. package/template/app/next.config.ts +9 -0
  23. package/template/app/package.json +40 -0
  24. package/template/app/playwright.config.ts +50 -0
  25. package/template/app/playwright.demo.config.ts +10 -0
  26. package/template/app/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx +37 -0
  27. package/template/app/src/app/[locale]/(protected)/dashboard/page.tsx +21 -0
  28. package/template/app/src/app/[locale]/(protected)/header-glue.tsx +59 -0
  29. package/template/app/src/app/[locale]/(protected)/layout.tsx +43 -0
  30. package/template/app/src/app/[locale]/layout.tsx +55 -0
  31. package/template/app/src/app/[locale]/page.tsx +9 -0
  32. package/template/app/src/app/[locale]/signin/page.tsx +55 -0
  33. package/template/app/src/app/[locale]/signin/picker-glue.tsx +21 -0
  34. package/template/app/src/app/api/auth/dev-signin/route.ts +12 -0
  35. package/template/app/src/app/api/auth/org/route.ts +10 -0
  36. package/template/app/src/app/api/auth/signout/route.ts +9 -0
  37. package/template/app/src/app/api/items/route.ts +52 -0
  38. package/template/app/src/app/api/respond.ts +13 -0
  39. package/template/app/src/app/api/webhooks/cron/route.test.ts +59 -0
  40. package/template/app/src/app/api/webhooks/cron/route.ts +15 -0
  41. package/template/app/src/app/layout.tsx +7 -0
  42. package/template/app/src/app-config/abilities.ts +93 -0
  43. package/template/app/src/app-config/actors.ts +13 -0
  44. package/template/app/src/app-config/audit.ts +9 -0
  45. package/template/app/src/app-config/db/migrations/1001_items.ts +37 -0
  46. package/template/app/src/app-config/db/migrations/index.ts +11 -0
  47. package/template/app/src/app-config/db/rls-proofs.ts +81 -0
  48. package/template/app/src/app-config/db/schema.ts +23 -0
  49. package/template/app/src/app-config/digest.ts +10 -0
  50. package/template/app/src/app-config/identity.ts +8 -0
  51. package/template/app/src/app-config/inbound-email.ts +10 -0
  52. package/template/app/src/app-config/jobs.ts +28 -0
  53. package/template/app/src/app-config/messages.ts +18 -0
  54. package/template/app/src/app-config/notifications.ts +31 -0
  55. package/template/app/src/app-config/preset-operations.ts +9 -0
  56. package/template/app/src/app-config/presets.ts +18 -0
  57. package/template/app/src/app-config/seed.ts +7 -0
  58. package/template/app/src/app-config/simulator.ts +17 -0
  59. package/template/app/src/app-config/tours.ts +14 -0
  60. package/template/app/src/app-config/webhooks.ts +13 -0
  61. package/template/app/src/components/dashboard-screen.tsx +26 -0
  62. package/template/app/src/components/items-card.tsx +84 -0
  63. package/template/app/src/components/welcome-screen.tsx +20 -0
  64. package/template/app/src/demo-static/app.tsx +77 -0
  65. package/template/app/src/demo-static/index.html +12 -0
  66. package/template/app/src/demo-static/main.tsx +40 -0
  67. package/template/app/src/proxy.ts +9 -0
  68. package/template/app/src/seed/index.ts +93 -0
  69. package/template/app/src/sssb.conformance.test.ts +7 -0
  70. package/template/app/src/styles/index.css +1 -0
  71. package/template/app/tests/catalog.ts +15 -0
  72. package/template/app/tests/contract/rls-contract.test.ts +14 -0
  73. package/template/app/tests/demo-static/static-shell.spec.ts +32 -0
  74. package/template/app/tests/e2e/items.spec.ts +58 -0
  75. package/template/app/tsconfig.json +29 -0
  76. package/template/app/vite.demo.config.ts +8 -0
  77. package/template/guide.md +118 -0
  78. package/template/meta.json +633 -0
  79. package/template/root/_dot_editorconfig +12 -0
  80. package/template/root/_dot_husky/commit-msg +1 -0
  81. package/template/root/_dot_husky/pre-commit +1 -0
  82. package/template/root/_dot_nvmrc +1 -0
  83. package/template/root/_dot_prettierrc.json +5 -0
  84. package/template/root/commitlint.config.mjs +1 -0
  85. package/README.md +0 -3
@@ -0,0 +1,496 @@
1
+ // @ts-check
2
+ // THE TEMPLATE (ADR-0014 D4: the starter IS the template). One function builds it from SSSB's repository, used by the
3
+ // package's `prepack`, which writes `template/` into the tarball (never committed: no second copy of the starter lives
4
+ // in the repository), by the bin run from a checkout (into a temporary directory), and by the repository's tests,
5
+ // which generate from the live tree without packing. So what the tests prove is what is packed.
6
+ //
7
+ // template/meta.json what the generator needs from the repository once it is no longer beside it: the version,
8
+ // the reusable workflow's repository and commit, the toolchain (packageManager, engines, the
9
+ // ranges of the tools the workspace installs), the build-script approvals, the seam's
10
+ // specifiers, the framework's cutover rows, the action pins its own workflow uses, and the
11
+ // names of SSSB's Claude Code marketplace and plugin, which its settings enable at that commit
12
+ // template/app/ apps/starter, its infra/ included: the files git tracks there, as they are in the working tree
13
+ // template/root/ the workspace-level files that are generic and copied as they are (tracked too)
14
+ // template/guide.md @sssb/kit's app guide, which the workspace carries a stamped copy of (`sssb guide`)
15
+ //
16
+ // TRACKED FILES ONLY (`git ls-files`), so nothing local reaches a packed template: not build output, and not a file
17
+ // nobody meant to share (an `.npmrc` with a token, a key, an editor's settings or swap file). A symlink is refused,
18
+ // not followed or dropped: what it points at is outside what git tracks. A checkout without git cannot build one.
19
+ //
20
+ // A leading `.` in a path segment is stored as `_dot_`, because npm's packing drops some dotfiles (`.gitignore`,
21
+ // `.npmrc`) and the template must not depend on which.
22
+ import { execFileSync } from 'node:child_process'
23
+ import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
24
+ import path from 'node:path'
25
+ import { CreateError } from './args.js'
26
+
27
+ /** The starter, the app the template is built from (ADR-0014 D4). */
28
+ const STARTER = 'apps/starter'
29
+
30
+ /**
31
+ * Packing pins the reusable workflow at a commit GitHub must have, and the template must be that commit's. Set to `1`,
32
+ * packing goes on with an unpushed commit or uncommitted template sources (with a warning): for a tarball that never
33
+ * reaches GitHub's runners, as pack and consume's.
34
+ */
35
+ export const UNPUSHED_PIN_ENV = 'SSSB_CREATE_UNPUSHED_PIN'
36
+
37
+ /**
38
+ * git, in the repository, with its failure as a CreateError (no git, not a checkout, an unknown commit).
39
+ * @param {string} repoRoot
40
+ * @param {string[]} args
41
+ */
42
+ function git(repoRoot, args) {
43
+ try {
44
+ return execFileSync('git', args, { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
45
+ } catch (error) {
46
+ const err = /** @type {NodeJS.ErrnoException & { stderr?: string }} */ (error)
47
+ const why = err.code === 'ENOENT' ? 'git is not installed' : (err.stderr ?? '').trim() || err.message
48
+ throw new CreateError(`\`git ${args.join(' ')}\` failed in ${repoRoot}: ${why}`)
49
+ }
50
+ }
51
+
52
+ /**
53
+ * The files git tracks under each of `paths`, relative to the repository, refusing what the template cannot carry
54
+ * faithfully: a symlink or submodule, an unmerged file, a tracked file missing from (or a symlink in) the working tree.
55
+ * @param {string} repoRoot
56
+ * @param {string[]} paths
57
+ */
58
+ function trackedFiles(repoRoot, paths) {
59
+ if (!existsSync(path.join(repoRoot, '.git')))
60
+ throw new CreateError(`${repoRoot} is not a git checkout: the template is built from the files git tracks`)
61
+ /** @type {Set<string>} */
62
+ const files = new Set()
63
+ /** @type {string[]} */
64
+ const problems = []
65
+ for (const entry of git(repoRoot, ['ls-files', '--stage', '-z', '--', ...paths]).split('\0')) {
66
+ if (entry === '') continue
67
+ const [info = '', file = ''] = entry.split('\t')
68
+ const [mode, , stage] = info.split(' ')
69
+ if (stage !== '0') problems.push(`${file} is unmerged`)
70
+ else if (mode === '120000') problems.push(`${file} is a symlink`)
71
+ else if (mode === '160000') problems.push(`${file} is a submodule`)
72
+ else {
73
+ const stat = lstatSync(path.join(repoRoot, file), { throwIfNoEntry: false })
74
+ if (!stat) problems.push(`${file} is tracked but missing from the working tree`)
75
+ else if (!stat.isFile()) problems.push(`${file} is not a regular file in the working tree`)
76
+ else files.add(file)
77
+ }
78
+ }
79
+ if (problems.length > 0)
80
+ throw new CreateError(`the template cannot be built:\n ${[...new Set(problems)].join('\n ')}`)
81
+ return [...files].sort()
82
+ }
83
+
84
+ /** What a template directory holds, beside its files. */
85
+ export const META_FILE = 'meta.json'
86
+ export const GUIDE_FILE = 'guide.md'
87
+
88
+ /**
89
+ * The workspace-level files copied as they are: each is generic (it names nothing of this repository's), which the
90
+ * generator's no-survivor test holds. Everything else at the workspace root is generated (files.js).
91
+ */
92
+ export const ROOT_FILES = [
93
+ '.editorconfig',
94
+ '.nvmrc',
95
+ '.prettierrc.json',
96
+ '.husky/pre-commit',
97
+ '.husky/commit-msg',
98
+ 'commitlint.config.mjs',
99
+ ]
100
+
101
+ /**
102
+ * The tools the workspace root installs, at this repository's ranges: what its scripts and root configs run (lint,
103
+ * typecheck, the Vitest configs and coverage, knip, jscpd, the hooks), and esbuild and tsx, which the app's infra/
104
+ * synth needs at the workspace root (`SssbApp` bundles the migrator with the root's esbuild; cdk.json runs tsx).
105
+ */
106
+ const ROOT_DEV_DEPENDENCIES = [
107
+ '@commitlint/cli',
108
+ '@commitlint/config-conventional',
109
+ '@eslint/js',
110
+ '@testing-library/jest-dom',
111
+ '@types/node',
112
+ '@types/react',
113
+ '@types/react-dom',
114
+ '@vitest/coverage-v8',
115
+ 'concurrently',
116
+ 'esbuild',
117
+ 'eslint',
118
+ 'happy-dom',
119
+ 'husky',
120
+ 'jscpd',
121
+ 'knip',
122
+ 'lint-staged',
123
+ 'prettier',
124
+ 'tsx',
125
+ 'typescript',
126
+ 'typescript-eslint',
127
+ 'vitest',
128
+ ]
129
+
130
+ /** The actions the generated workflow's own jobs use, pinned as SSSB's reusable workflow pins them. */
131
+ const ACTIONS = ['actions/checkout', 'pnpm/action-setup', 'actions/setup-node']
132
+
133
+ /**
134
+ * @typedef {{
135
+ * version: string,
136
+ * workflow: { repository: string, ref: string },
137
+ * packageManager: string,
138
+ * engines: Record<string, string>,
139
+ * ranges: Record<string, string>,
140
+ * allowBuilds: Record<string, boolean>,
141
+ * minimumReleaseAge: number | null,
142
+ * seamSpecifiers: string[],
143
+ * cutoverRows: { id: string, what: string }[],
144
+ * actions: Record<string, string>,
145
+ * gitleaksVersion: string,
146
+ * dependencyNames: string[],
147
+ * plugin: { marketplace: string, name: string },
148
+ * }} TemplateMeta
149
+ */
150
+
151
+ /**
152
+ * A path as the template stores it.
153
+ * @param {string} relative
154
+ */
155
+ const toStored = (relative) =>
156
+ relative
157
+ .split('/')
158
+ .map((segment) => (segment.startsWith('.') ? `_dot_${segment.slice(1)}` : segment))
159
+ .join('/')
160
+
161
+ /**
162
+ * A stored path as the workspace gets it.
163
+ * @param {string} stored
164
+ */
165
+ export const fromStored = (stored) =>
166
+ stored
167
+ .split('/')
168
+ .map((segment) => (segment.startsWith('_dot_') ? `.${segment.slice('_dot_'.length)}` : segment))
169
+ .join('/')
170
+
171
+ /**
172
+ * Every file under a directory, as `/`-separated paths relative to it.
173
+ * @param {string} dir
174
+ * @returns {string[]}
175
+ */
176
+ export function filesUnder(dir) {
177
+ /** @type {string[]} */
178
+ const out = []
179
+ /** @param {string} relative */
180
+ const walk = (relative) => {
181
+ for (const entry of readdirSync(path.join(dir, relative), { withFileTypes: true })) {
182
+ const child = relative ? `${relative}/${entry.name}` : entry.name
183
+ if (entry.isDirectory()) walk(child)
184
+ else if (entry.isFile()) out.push(child)
185
+ }
186
+ }
187
+ walk('')
188
+ return out.sort()
189
+ }
190
+
191
+ /** @param {string} file */
192
+ const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'))
193
+
194
+ /**
195
+ * The `owner/name` a package.json's `repository.url` names on GitHub.
196
+ * @param {string} manifestFile
197
+ */
198
+ function githubRepository(manifestFile) {
199
+ const url = readJson(manifestFile)?.repository?.url
200
+ const match = typeof url === 'string' ? /github\.com[/:]([^/]+\/[^/.]+)(?:\.git)?$/.exec(url) : null
201
+ if (!match?.[1]) throw new CreateError(`${manifestFile}: its repository.url names no GitHub repository`)
202
+ return match[1]
203
+ }
204
+
205
+ /**
206
+ * The commit the template is built at, which must hold the reusable workflow it pins.
207
+ * @param {string} repoRoot
208
+ */
209
+ function workflowCommit(repoRoot) {
210
+ const ref = git(repoRoot, ['rev-parse', 'HEAD']).trim()
211
+ try {
212
+ git(repoRoot, ['cat-file', '-e', `${ref}:.github/workflows/app-checks.yml`])
213
+ } catch {
214
+ throw new CreateError(`commit ${ref} holds no .github/workflows/app-checks.yml, so it cannot be the pinned ref`)
215
+ }
216
+ return ref
217
+ }
218
+
219
+ /**
220
+ * The `owner/name` path a remote's URL names, lowercased, or null for a URL that is not a network remote: scp-like
221
+ * (`git@github.com:o/n.git`, or through an ssh host alias, `git@github-work:o/n.git`) or a URL with a scheme
222
+ * (`https://github.com/o/n`, `ssh://git@ssh.github.com:443/o/n`). The host is not read: an ssh alias can be named
223
+ * anything, so any remote at the path counts, a fork (another owner's path) never.
224
+ * @param {string} url
225
+ */
226
+ export function remotePath(url) {
227
+ const match = /^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(.+)$/i.exec(url) ?? /^(?:[^@/:]+@)?[^/:]+:(?!\/\/)(.+)$/.exec(url)
228
+ // Trailing slashes trimmed by a loop: `/\/+$/` backtracks quadratically on a long run of slashes followed by
229
+ // anything else, and the URL is the caller's.
230
+ let end = match?.[1]?.length ?? 0
231
+ while (end > 0 && match?.[1]?.[end - 1] === '/') end--
232
+ return match?.[1]
233
+ ? match[1]
234
+ .slice(0, end)
235
+ .replace(/\.git$/i, '')
236
+ .replace(/^\/+/, '')
237
+ .toLowerCase()
238
+ : null
239
+ }
240
+
241
+ /**
242
+ * Why the pinned commit may not be on GitHub, or null when it is: a workspace pinned to a commit GitHub does not have
243
+ * fails its first CI run (`uses:` cannot resolve). On GitHub means: contained in a remote-tracking branch of a remote
244
+ * of this checkout whose path is `repository` (remotePath), as of the last fetch (no network).
245
+ * @param {{ repoRoot: string, ref: string, repository: string }} options
246
+ * @returns {string | null}
247
+ */
248
+ export function unpushedPin({ repoRoot, ref, repository }) {
249
+ /** @type {Set<string>} */
250
+ const remotes = new Set()
251
+ for (const line of git(repoRoot, ['remote', '-v']).split('\n')) {
252
+ const [remote, url] = line.split(/\s+/)
253
+ if (remote && remotePath(url ?? '') === repository.toLowerCase()) remotes.add(remote)
254
+ }
255
+ if (remotes.size === 0)
256
+ return `no remote of this checkout is github.com/${repository}, so commit ${ref} cannot be shown to be there`
257
+ let branches
258
+ try {
259
+ branches = git(repoRoot, ['branch', '--remotes', '--contains', ref, '--format=%(refname)']).split('\n')
260
+ } catch {
261
+ return `commit ${ref} is not in this checkout, so it cannot be shown to be on github.com/${repository}`
262
+ }
263
+ if (branches.some((branch) => [...remotes].some((remote) => branch.startsWith(`refs/remotes/${remote}/`))))
264
+ return null
265
+ return (
266
+ `commit ${ref} is on no branch of ${[...remotes].join(', ')} (github.com/${repository}) as of the last ` +
267
+ "fetch: a workspace pinned to it fails its first CI run, because GitHub cannot resolve the workflow's `uses:`"
268
+ )
269
+ }
270
+
271
+ /**
272
+ * SSSB's Claude Code plugin (ADR-0014 P13): the marketplace at the repository's root, and the plugin it lists, which
273
+ * the workspace's `.claude/settings.json` enables from that marketplace pinned at the workflow commit. The template
274
+ * reads their names; the files themselves are installed by Claude Code from GitHub at the pin.
275
+ */
276
+ const MARKETPLACE_FILE = '.claude-plugin/marketplace.json'
277
+ const PLUGIN_DIR = 'plugins/sssb'
278
+ const PLUGIN_FILE = `${PLUGIN_DIR}/.claude-plugin/plugin.json`
279
+
280
+ /**
281
+ * What the template copies from the working tree, and what the workspace's settings pin at the template's commit (the
282
+ * plugin), which must be that commit's at pack time.
283
+ */
284
+ const TEMPLATE_SOURCES = [STARTER, 'packages/kit/src/guide.md', MARKETPLACE_FILE, PLUGIN_DIR]
285
+
286
+ /**
287
+ * Why the template's sources may not be the commit it pins, or null when they are: the template is copied from the
288
+ * working tree, but the pin (and the release it ships in) is HEAD, so a change not committed (staged or not), an
289
+ * untracked file, or a deleted one under them makes a tarball whose template no commit holds.
290
+ * @param {string} repoRoot
291
+ * @returns {string | null}
292
+ */
293
+ export function uncommittedSources(repoRoot) {
294
+ const entries = git(repoRoot, [
295
+ 'status',
296
+ '--porcelain=v1',
297
+ '-z',
298
+ '--untracked-files=all',
299
+ '--',
300
+ ...TEMPLATE_SOURCES,
301
+ ]).split('\0')
302
+ // Every entry is `XY <path>`, whatever its status letters (matching them instead would let one git adds, or one left
303
+ // out, as T, a type change, once was, pass as clean); a rename's or copy's (R or C in either column) is followed by
304
+ // its old path, an entry with no status of its own. @sssb/kit's stamp-release.mjs reads its status the same way.
305
+ /** @type {string[]} */
306
+ const changed = []
307
+ for (let i = 0; i < entries.length; i++) {
308
+ const entry = /** @type {string} */ (entries[i])
309
+ if (entry === '') continue
310
+ if (entry.length < 4 || entry[2] !== ' ')
311
+ throw new CreateError(`git status printed ${JSON.stringify(entry)}, not \`XY <path>\``)
312
+ changed.push(entry.slice(3))
313
+ if (/[RC]/.test(entry.slice(0, 2))) i++
314
+ }
315
+ return changed.length === 0
316
+ ? null
317
+ : `the template's sources differ from HEAD, which it pins (commit them, or remove what is untracked):\n ${changed.join('\n ')}`
318
+ }
319
+
320
+ /**
321
+ * pnpm-workspace.yaml's `allowBuilds` approvals, as the repository grants them: each package's name and whether its
322
+ * install script may run. The block's comments speak for this repository, so they stay here.
323
+ * @param {string} text
324
+ * @returns {Record<string, boolean>}
325
+ */
326
+ function allowBuilds(text) {
327
+ const block = /^allowBuilds:\n((?:[ #].*\n|\n)*?)(?=^\S|(?![\s\S]))/m.exec(text)?.[1]
328
+ if (!block) throw new CreateError("could not read allowBuilds from the repository's pnpm-workspace.yaml")
329
+ /** @type {Record<string, boolean>} */
330
+ const approvals = {}
331
+ for (const line of block.split('\n')) {
332
+ if (line.trim() === '' || line.trim().startsWith('#')) continue
333
+ const entry = /^ +'?(@?[a-z0-9][a-z0-9._/-]*)'?: (true|false)$/.exec(line)
334
+ if (!entry?.[1])
335
+ throw new CreateError(`pnpm-workspace.yaml's allowBuilds has an entry this cannot read: ${line}`)
336
+ approvals[entry[1]] = entry[2] === 'true'
337
+ }
338
+ return approvals
339
+ }
340
+
341
+ /**
342
+ * @param {string} workflow the text of a workflow
343
+ * @returns {Record<string, string>} each action's `uses:` value, pin and version comment included
344
+ */
345
+ function actionPins(workflow) {
346
+ /** @type {Record<string, string>} */
347
+ const pins = {}
348
+ for (const action of ACTIONS) {
349
+ const match = new RegExp(`uses: (${action.replace('/', '\\/')}@[0-9a-f]{40} # \\S+)`).exec(workflow)
350
+ if (!match?.[1]) throw new CreateError(`app-checks.yml pins no ${action} by commit SHA`)
351
+ pins[action] = match[1]
352
+ }
353
+ return pins
354
+ }
355
+
356
+ /**
357
+ * The resolution of a workspace shaped as the generator writes one: pack and consume's lockfile seed, which its
358
+ * generated shape installs from (a superset of the generated workspace's: the seed also holds the pages shape's second
359
+ * app and sibling package). Not this repository's own pnpm-lock.yaml, which holds this repository's own tooling too
360
+ * (`events`, `history`, `open` and `cookies` among it), none of which a generated workspace installs.
361
+ */
362
+ const WORKSPACE_LOCKFILE = 'scripts/pack-and-consume/consumer-lock.yaml'
363
+
364
+ /**
365
+ * The unscoped names of every package a generated workspace installs (WORKSPACE_LOCKFILE): a slug that is one of them
366
+ * would make the app's package share its name with a dependency, and pnpm then mistakes one for the other (it gave an
367
+ * app named `ws` the `ws` package's optional peers). Scoped names cannot be a slug.
368
+ * @param {string} lockfile the text of a pnpm lockfile
369
+ */
370
+ function dependencyNames(lockfile) {
371
+ const section = /^packages:\n([\s\S]*?)(?=^\S|(?![\s\S]))/m.exec(lockfile)?.[1]
372
+ if (!section) throw new CreateError(`could not read the packages of the repository's ${WORKSPACE_LOCKFILE}`)
373
+ /** @type {Set<string>} */
374
+ const names = new Set()
375
+ for (const match of section.matchAll(/^ {2}'?([a-z0-9][^@'\s/]*)@/gm)) if (match[1]) names.add(match[1])
376
+ return [...names].sort()
377
+ }
378
+
379
+ /**
380
+ * The marketplace's name and the plugin's, as the workspace's settings name them (`enabledPlugins` takes
381
+ * `<plugin>@<marketplace>`): the plugin's manifest names it, and the marketplace must list it by that name.
382
+ * @param {(relative: string) => string} at
383
+ */
384
+ function pluginNames(at) {
385
+ const marketplace = readJson(at(MARKETPLACE_FILE))
386
+ const plugin = readJson(at(PLUGIN_FILE))
387
+ if (typeof marketplace?.name !== 'string' || typeof plugin?.name !== 'string')
388
+ throw new CreateError(`${MARKETPLACE_FILE} or ${PLUGIN_FILE} has no name`)
389
+ const listed = (Array.isArray(marketplace.plugins) ? marketplace.plugins : []).find(
390
+ (/** @type {{ name?: unknown }} */ entry) => entry?.name === plugin.name,
391
+ )
392
+ if (!listed) throw new CreateError(`${MARKETPLACE_FILE} does not list the plugin ${PLUGIN_DIR} (${plugin.name})`)
393
+ return { marketplace: marketplace.name, name: plugin.name }
394
+ }
395
+
396
+ /**
397
+ * Builds the template from SSSB's repository into `outDir`, which is replaced.
398
+ * @param {{ repoRoot: string, outDir: string, workflowRef?: string, warn?: (message: string) => void }} options
399
+ * `workflowRef` instead of the repository's HEAD (which must hold the reusable workflow); `warn` hears of the
400
+ * starter's untracked files, which are left out
401
+ * @returns {TemplateMeta}
402
+ */
403
+ export function buildTemplate(options) {
404
+ try {
405
+ return writeTemplate(options)
406
+ } catch (error) {
407
+ // A file the template reads that is not there, a directory it cannot write: a message, not a stack trace.
408
+ const err = /** @type {NodeJS.ErrnoException} */ (error)
409
+ if (error instanceof CreateError || typeof err?.code !== 'string' || typeof err.syscall !== 'string')
410
+ throw error
411
+ throw new CreateError(`could not build the template: ${err.message}`)
412
+ }
413
+ }
414
+
415
+ /** @param {Parameters<typeof buildTemplate>[0]} options */
416
+ function writeTemplate({ repoRoot, outDir, workflowRef, warn = () => {} }) {
417
+ const at = (/** @type {string} */ relative) => path.join(repoRoot, relative)
418
+ const starter = at(STARTER)
419
+ if (!existsSync(path.join(starter, 'package.json'))) throw new CreateError(`${starter} is not the starter app`)
420
+ const tracked = trackedFiles(repoRoot, [STARTER, ...ROOT_FILES])
421
+ const missing = ROOT_FILES.filter((file) => !tracked.includes(file))
422
+ if (missing.length > 0) throw new CreateError(`the repository does not track ${missing.join(', ')}`)
423
+ const untracked = git(repoRoot, ['ls-files', '--others', '--exclude-standard', '-z', '--', STARTER])
424
+ .split('\0')
425
+ .filter(Boolean)
426
+ if (untracked.length > 0)
427
+ warn(
428
+ `left out of the template, because git does not track them (git add them to include them):\n ${untracked.join('\n ')}`,
429
+ )
430
+
431
+ rmSync(outDir, { recursive: true, force: true })
432
+ mkdirSync(outDir, { recursive: true })
433
+ for (const file of tracked) {
434
+ const target = file.startsWith(`${STARTER}/`)
435
+ ? path.join(outDir, 'app', toStored(file.slice(STARTER.length + 1)))
436
+ : path.join(outDir, 'root', toStored(file))
437
+ mkdirSync(path.dirname(target), { recursive: true })
438
+ cpSync(at(file), target)
439
+ }
440
+
441
+ const root = readJson(at('package.json'))
442
+ /** @type {Record<string, string>} */
443
+ const ranges = {}
444
+ for (const name of ROOT_DEV_DEPENDENCIES) {
445
+ const range = root.devDependencies?.[name] ?? root.dependencies?.[name]
446
+ if (typeof range !== 'string') throw new CreateError(`the repository's package.json has no range for ${name}`)
447
+ ranges[name] = range
448
+ }
449
+ const workspace = readFileSync(at('pnpm-workspace.yaml'), 'utf8')
450
+ const releaseAge = /^minimumReleaseAge:\s*(\d+)\s*$/m.exec(workspace)?.[1]
451
+ const appChecks = readFileSync(at('.github/workflows/app-checks.yml'), 'utf8')
452
+ const gitleaksVersion = /gitleaks\/releases\/download\/v(\d+\.\d+\.\d+)\//.exec(
453
+ readFileSync(at('.github/workflows/checks.yml'), 'utf8'),
454
+ )?.[1]
455
+ if (!gitleaksVersion) throw new CreateError("could not read the gitleaks version from the repository's checks.yml")
456
+
457
+ /** @type {TemplateMeta} */
458
+ const meta = {
459
+ version: readJson(at('packages/create/package.json')).version,
460
+ workflow: {
461
+ repository: githubRepository(at('packages/create/package.json')),
462
+ ref: workflowRef ?? workflowCommit(repoRoot),
463
+ },
464
+ packageManager: root.packageManager,
465
+ engines: root.engines,
466
+ ranges,
467
+ allowBuilds: allowBuilds(workspace),
468
+ minimumReleaseAge: releaseAge === undefined ? null : Number(releaseAge),
469
+ seamSpecifiers: readJson(at('packages/kit/src/testing/seam-specifiers.json')).specifiers,
470
+ cutoverRows: readJson(at('packages/kit/src/cutover/rows.json'))
471
+ .rows.filter((/** @type {{ scope?: string }} */ row) => row.scope === undefined)
472
+ .map((/** @type {{ id: string, what: string }} */ row) => ({ id: row.id, what: row.what })),
473
+ actions: actionPins(appChecks),
474
+ gitleaksVersion,
475
+ dependencyNames: dependencyNames(readFileSync(at(WORKSPACE_LOCKFILE), 'utf8')),
476
+ plugin: pluginNames(at),
477
+ }
478
+ // The app guide @sssb/kit ships (`@sssb/kit/guide.md`), which the workspace carries a stamped copy of (`sssb
479
+ // guide`); `sssb doctor` fails a workspace without it. The kit is of the generator's version (one fixed group).
480
+ cpSync(at('packages/kit/src/guide.md'), path.join(outDir, GUIDE_FILE))
481
+ writeFileSync(path.join(outDir, META_FILE), `${JSON.stringify(meta, null, 4)}\n`)
482
+ return meta
483
+ }
484
+
485
+ /**
486
+ * A built template's meta, checked for the files the generator reads.
487
+ * @param {string} templateDir
488
+ * @returns {TemplateMeta}
489
+ */
490
+ export function readTemplate(templateDir) {
491
+ const file = path.join(templateDir, META_FILE)
492
+ if (!existsSync(file)) throw new CreateError(`${templateDir} is not a built template (no ${META_FILE})`)
493
+ for (const part of ['app/', 'root/', GUIDE_FILE])
494
+ if (!existsSync(path.join(templateDir, part))) throw new CreateError(`${templateDir} has no ${part}`)
495
+ return readJson(file)
496
+ }
package/src/yaml.js ADDED
@@ -0,0 +1,17 @@
1
+ // @ts-check
2
+ // YAML scalars as the generator writes them: quoted so any value reads back as itself, and quoted the way the
3
+ // workspace's own Prettier would quote it, so `prettier --check .` stays green. Prettier's YAML printer keeps single
4
+ // quotes (the workspace's `singleQuote`) unless the value has an apostrophe and nothing double quotes would have to
5
+ // escape; then it writes double quotes, where the apostrophe needs no doubling.
6
+ import { CreateError } from './args.js'
7
+
8
+ /**
9
+ * A quoted YAML scalar holding exactly `value`.
10
+ * @param {string} value
11
+ */
12
+ export function yamlString(value) {
13
+ // A line break inside a quoted scalar folds into a space; a control character is not a path or a name.
14
+ if (/\p{Cc}/u.test(value)) throw new CreateError(`${JSON.stringify(value)} holds a control character`)
15
+ if (value.includes("'") && !/["\\]/.test(value)) return `"${value}"`
16
+ return `'${value.replaceAll("'", "''")}'`
17
+ }
@@ -0,0 +1,55 @@
1
+ # Demo size budget
2
+
3
+ The static demo (`pnpm build:demo-static`) is one HTML file you can hand someone, and `pnpm check:demo-size`
4
+ fails if it grows past a byte budget. The number is the argument of `check:demo-size` in this app's
5
+ `package.json`, and it is this app's own: the command, `sssb check-demo-size` (from `@sssb/tools`), is SSSB's,
6
+ holds no number, and says what to look at first when the gate goes red.
7
+
8
+ ## What this number is for
9
+
10
+ The starter ships it roomy on purpose, sized for an app's own screens and not as a pacing gate: room to grow
11
+ the starter to the size of SSSB's showcase, rounded up, before it asks anything of you. It still fails on gross
12
+ bloat, and on the pruning of Mantine's stylesheet stopping (the number sits below what the starter measured
13
+ before the CSS was pruned, below). Bloat in the framework of any size shows up in the showcase first, which is
14
+ why this one can be roomy. If you want a pacing gate, set the number to what your app measures plus the
15
+ headroom you want.
16
+
17
+ ## How to change it
18
+
19
+ Re-set the number in `package.json` and add an entry under "Changes" below in the same commit: what grew or
20
+ shrank, by how much, and how much headroom you left on purpose. Newest first. The command is SSSB's and holds
21
+ no app's number, so this file is where the history lives.
22
+
23
+ ## Changes
24
+
25
+ None yet.
26
+
27
+ ## How it started (SSSB's history for the starter)
28
+
29
+ Raised 2026-11-17, 820000 → 840000, for React 19.3. React's own code grew the starter's demo 29331 bytes, from
30
+ 727778 to 757109, and the showcase's by 29332, to 833906. The number above is room to grow the starter to the
31
+ size of SSSB's showcase, rounded up, and 820000 no longer was, so it moved to the showcase's new size rounded
32
+ up. It leaves 82891 bytes (9.8%), and it still sits below the unpruned starter (908510 bytes, which exits 1).
33
+
34
+ Re-based 2026-11-16, 880000 → 820000. Since the first commit (844820 bytes) the starter's demo had grown
35
+ 10061 bytes, and a starter-derived app with one small screen sat at 99.3% of the budget. Per merge: demo
36
+ presets (jpslav/keel#26) +8706, the Simulator's people-and-orgs work (jpslav/keel#15) +769, actors that start with the page (jpslav/keel#16)
37
+ +388, the mechanical bundle (jpslav/keel#19) +198. Two things were removed:
38
+
39
+ - 3248 bytes were incidental. SSSB's four preset operation definitions were module-level constants, so valibot
40
+ and four schemas rode in every app's bundle although the demo never validates a preset. They are built by
41
+ function now, and `tests/tooling/static-demo-bundle.test.ts` holds it.
42
+ - 130247 bytes were Mantine's stylesheet. The apps import `@mantine/core/styles.css` whole, 273 KB for ~100
43
+ components, of which the demo's bundle reaches 33. The static demo's build now drops every rule whose hashed
44
+ class is in no shipped file (the Mantine pruning in `@sssb/tools`' Vite preset, which each app's
45
+ `vite.demo.config.ts` uses):
46
+ 14-15% of the file.
47
+
48
+ What stays is the presets themselves: net of the trim about 5.5 KB on the starter, real code (the static
49
+ twin's replay, the operation registry, the seam module with `extends`) plus its copy and its tour.
50
+
51
+ `pnpm build:demo-static`, bytes: 844820 at the first commit, 854881 before the re-base, 721386 after it. The
52
+ budget is 820000, which leaves 98614 bytes (12.0%).
53
+
54
+ The budget went DOWN, so the bytes saved are not slack: they are the margin above, on purpose. If the pruning
55
+ or the lazy definitions regress, the number turns red, which is the point of it.
@@ -0,0 +1,17 @@
1
+ /**
2
+ * App identity — the single source of truth for MECHANICAL identifiers.
3
+ *
4
+ * Doctrine: identifiers that a tool, protocol, or platform keys on and that can COLLIDE across
5
+ * apps (session/viewpoint cookies, the fake-auth JWT issuer, the service-token audience, infra
6
+ * resource names) DERIVE from this slug, so an adopter renames the app in exactly ONE place.
7
+ * Identifiers that are purely origin- or process-scoped are instead given NEUTRAL names that
8
+ * never need renaming. Human-facing DISPLAY copy lives in `messages/*.json`, never here.
9
+ *
10
+ * `pnpm create @sssb` sets this value when it generates the app (along with the display copy and the few
11
+ * files that name the app's directory).
12
+ *
13
+ * It is also what lets two apps in one workspace run side by side in one browser: the slug prefixes the
14
+ * session cookie (`starter_session` here), so signing into one app never signs you into — or out
15
+ * of — another whose slug differs.
16
+ */
17
+ export const APP_SLUG = 'starter'
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Single source of truth for deployment and external-service parameters.
3
+ *
4
+ * Every PLACEHOLDER_ value maps to a row in docs/cutover-checklist.md describing what fills it and
5
+ * when. Fields ending in `Name` are the names of secrets (env var / Secrets Manager entry) — secret
6
+ * VALUES never live in the repo.
7
+ *
8
+ * WHAT IS LINT-ENFORCED (`sssb/no-process-env`, @sssb/eslint-plugin): `process.env` is read ONLY
9
+ * inside SSSB's own adapters (@sssb/kit/adapters) and an app's own real adapters (apps/<app>/src/adapters/real, which
10
+ * may not read the run mode) — every other module imports the resolved value (this file for
11
+ * deployment/service params; `isSimulated`/`isDemoMode` from @sssb/kit/adapters for run mode). Exemptions:
12
+ * instrumentation files (NEXT_PUBLIC needs literal inlining) and the two secret readers
13
+ * (service-auth/{webhook,mailgun}.ts). This file may not read process.env itself (the ban covers config/).
14
+ * An app-owned adapter's non-secret parameters and secret NAMES are recorded here too, with their cutover
15
+ * rows (SSSB's recipe for an app-owned adapter, docs/recipes/app-owned-adapter.md in SSSB's repository).
16
+ * NOT enforced: that a param's literal VALUE appears nowhere else in the repo — that stays a convention,
17
+ * not a scanner.
18
+ */
19
+
20
+ export const params = {
21
+ aws: {
22
+ // cutover: cloud-accounts
23
+ devAccountId: 'PLACEHOLDER_AWS_DEV_ACCOUNT_ID',
24
+ prodAccountId: 'PLACEHOLDER_AWS_PROD_ACCOUNT_ID',
25
+ region: 'PLACEHOLDER_AWS_REGION',
26
+ },
27
+ domains: {
28
+ // cutover: domains-and-certs — first deploys use *.cloudfront.net
29
+ staging: 'PLACEHOLDER_STAGING_DOMAIN',
30
+ production: 'PLACEHOLDER_PRODUCTION_DOMAIN',
31
+ demo: 'PLACEHOLDER_DEMO_DOMAIN',
32
+ certificateArn: 'PLACEHOLDER_ACM_CERTIFICATE_ARN',
33
+ },
34
+ database: {
35
+ // cutover: data-api — how the app reaches Postgres; infra/ (SssbApp) builds the matching network shape
36
+ // and sets DATABASE_TRANSPORT from it.
37
+ // 'pg' (the default): node-postgres from a Lambda inside the database's VPC. 'data-api' (opt-in):
38
+ // the RDS Data API from a Lambda outside any VPC, with no NAT (ADR-0002, addendum 2026-11-16).
39
+ transport: 'pg' as 'pg' | 'data-api',
40
+ },
41
+ clerk: {
42
+ // cutover: auth-dev (development instance), auth-prod (production instance)
43
+ publishableKeyName: 'PLACEHOLDER_CLERK_PUBLISHABLE_KEY_NAME',
44
+ secretKeyName: 'PLACEHOLDER_CLERK_SECRET_KEY_NAME',
45
+ },
46
+ mailgun: {
47
+ // cutover: email-outbound
48
+ domain: 'PLACEHOLDER_MAILGUN_DOMAIN',
49
+ apiKeyName: 'PLACEHOLDER_MAILGUN_API_KEY_NAME',
50
+ // cutover: email-inbound — the HMAC signing key Mailgun signs inbound webhooks with
51
+ webhookSigningKeyName: 'PLACEHOLDER_MAILGUN_WEBHOOK_SIGNING_KEY_NAME',
52
+ },
53
+ sentry: {
54
+ // cutover: errors — the Sentry wiring is inert until a DSN is set
55
+ dsn: 'PLACEHOLDER_SENTRY_DSN',
56
+ org: 'PLACEHOLDER_SENTRY_ORG',
57
+ project: 'PLACEHOLDER_SENTRY_PROJECT',
58
+ },
59
+ posthog: {
60
+ // cutover: analytics — real adapter is enabled in staging/prod only
61
+ projectKey: 'PLACEHOLDER_POSTHOG_PROJECT_KEY',
62
+ host: 'PLACEHOLDER_POSTHOG_HOST',
63
+ },
64
+ anthropic: {
65
+ // cutover: llm-key — unlocks `pnpm llm:record`
66
+ apiKeyName: 'PLACEHOLDER_ANTHROPIC_API_KEY_NAME',
67
+ },
68
+ } as const
69
+
70
+ export type Params = typeof params