@sssb/create 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/create.js CHANGED
@@ -105,6 +105,7 @@ async function main() {
105
105
  ]
106
106
  console.log(`
107
107
  Created ${options.name} in ${result.root}: ${result.files.length} files, the app in apps/${options.slug}/.
108
+ Its port slot is "${result.port.name}": port ${result.port.default} in a main checkout, ${result.port.name.toUpperCase().replaceAll('-', '_')}_PORT overrides it.
108
109
 
109
110
  Next:
110
111
  cd ${shellQuoted(relative)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/create",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -8,10 +8,14 @@
8
8
  "directory": "packages/create"
9
9
  },
10
10
  "type": "module",
11
- "description": "SSSB's generator: `pnpm create @sssb <dir>` writes a new app workspace from SSSB's starter, its infra/ included, with the workspace's config on SSSB's presets, the owner files and a CI workflow calling SSSB's reusable checks. Plain JavaScript with no dependencies; it never depends on another SSSB package (ADR-0014, rule 4).",
11
+ "description": "SSSB's generator: `pnpm create @sssb <dir>` writes a new app workspace from SSSB's starter, its infra/ included, with the workspace's config on SSSB's presets, the owner files and a CI workflow calling SSSB's reusable checks; `@sssb/create/add-app` writes a further app into an existing one, for `sssb add-app`. Plain JavaScript with no dependencies; it never depends on another SSSB package (ADR-0014, rule 4).",
12
12
  "bin": {
13
13
  "sssb-create": "./bin/create.js"
14
14
  },
15
+ "exports": {
16
+ "./package.json": "./package.json",
17
+ "./add-app": "./src/add-app.js"
18
+ },
15
19
  "files": [
16
20
  "bin",
17
21
  "src",
package/src/add-app.js ADDED
@@ -0,0 +1,165 @@
1
+ // @ts-check
2
+ // AN APP ADDED TO AN EXISTING WORKSPACE: `sssb add-app <slug>`, @sssb/tools' command, imports this module from the
3
+ // @sssb/create the workspace installs (`@sssb/create/add-app`), so the template and the renames stay the generator's
4
+ // alone. The app is the template's, written as `generate` writes a new workspace's first app (generate.js' writeApp):
5
+ // under apps/<slug>/, renamed where its identity lives, with a port slot of its own, and taking each @sssb package as an
6
+ // app already in the workspace takes it. The workspace around it (its `sssb.apps`) is the command's to change.
7
+ import { randomBytes } from 'node:crypto'
8
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmdirSync, rmSync } from 'node:fs'
9
+ import path from 'node:path'
10
+ import { checkSlug, CreateError, displayName, titleCase } from './args.js'
11
+ import { checkPackageNames, SSSB_PACKAGES, writeApp } from './generate.js'
12
+ import { holdSignals, releaseSignals, signalsSettled } from './signals.js'
13
+ import { filesUnder, readTemplate } from './template.js'
14
+
15
+ export { checkSlug, CreateError, signalsSettled }
16
+
17
+ /**
18
+ * @typedef {{
19
+ * templateDir: string,
20
+ * root: string,
21
+ * slug: string,
22
+ * name?: string | null,
23
+ * port: { name: string, default: number },
24
+ * like: string,
25
+ * others?: string[],
26
+ * finish?: (appDir: string) => (() => void),
27
+ * }} AddAppOptions `root`: the workspace's root; `like`: an app of the workspace (absolute), whose manifests (its
28
+ * package.json, and its infra/'s when it has one) say how the new app's take each @sssb package, and `others`, more
29
+ * package directories to look in after it (a deployment outside the app); `port`: the new app's own slot, which the
30
+ * caller has checked against the workspace's other apps; `finish`: the caller's own change to the workspace, made
31
+ * under the same signal hold once the app is in place, returning how to undo it
32
+ */
33
+
34
+ /** @param {string} file */
35
+ const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'))
36
+
37
+ /**
38
+ * A dependency's specifier as a manifest in `toDir` must write it to name what it names from `fromDir`: a relative
39
+ * `file:` or `link:` path rebased, anything else (a range, a URL, an absolute path, `workspace:`) as it is.
40
+ * @param {string} spec
41
+ * @param {string} fromDir
42
+ * @param {string} toDir
43
+ */
44
+ export function rebaseSpec(spec, fromDir, toDir) {
45
+ const match = /^(file:|link:)(.+)$/.exec(spec)
46
+ if (!match?.[1] || !match[2] || path.isAbsolute(match[2])) return spec
47
+ const relative = path.relative(toDir, path.resolve(fromDir, match[2])).split(path.sep).join('/')
48
+ return `${match[1]}${relative.startsWith('.') ? relative : `./${relative}`}`
49
+ }
50
+
51
+ /**
52
+ * Each @sssb package a manifest takes, by its full name (the seam's alias, `@sssb/app-config`, among them: no package
53
+ * of SSSB's is named so, so nothing looks it up).
54
+ * @param {string} file
55
+ * @returns {{ dir: string, specs: Record<string, string>, eslint: string | undefined }}
56
+ */
57
+ function takes(file) {
58
+ const manifest = readJson(file)
59
+ /** @type {Record<string, string>} */
60
+ const specs = {}
61
+ for (const field of ['dependencies', 'devDependencies', 'peerDependencies']) {
62
+ for (const [name, spec] of Object.entries(manifest[field] ?? {})) {
63
+ if (name.startsWith('@sssb/') && typeof spec === 'string' && !(name in specs)) specs[name] = spec
64
+ }
65
+ }
66
+ const eslint = manifest.devDependencies?.eslint ?? manifest.dependencies?.eslint
67
+ return { dir: path.dirname(file), specs, eslint: typeof eslint === 'string' ? eslint : undefined }
68
+ }
69
+
70
+ /**
71
+ * Writes the template's app into the workspace at `root`, as apps/<slug>/. All or nothing: the app is written into a
72
+ * stage beside it (`apps/.sssb-add-app-<hex>/`) and renamed into place, then `finish` makes the caller's change; a
73
+ * failure, or a SIGINT, SIGTERM or SIGHUP that comes while it runs (dispatched once it returns: the work is
74
+ * synchronous), removes the app and undoes `finish`'s change. A caller that reports success awaits `signalsSettled()`
75
+ * first. Refuses a slug the generator refuses, and an apps/<slug> that exists.
76
+ * @param {AddAppOptions} options
77
+ * @returns {{ appDir: string, name: string, files: string[], notes: string[] }} `files` relative to `root`; `notes`,
78
+ * what the caller should tell the person (a package no app of the workspace takes, written at the template's range)
79
+ */
80
+ export function addApp({ templateDir, root, slug, name = null, port, like, others = [], finish }) {
81
+ checkSlug(slug)
82
+ const display = displayName(name ?? titleCase(slug))
83
+ const meta = readTemplate(templateDir)
84
+ checkPackageNames(slug, meta)
85
+ const appsDir = path.join(root, 'apps')
86
+ const appDir = path.join(appsDir, slug)
87
+ if (lstatSync(appDir, { throwIfNoEntry: false })) throw new CreateError(`${appDir} already exists`)
88
+
89
+ const appTakes = takes(path.join(like, 'package.json'))
90
+ const likeInfra = path.join(like, 'infra', 'package.json')
91
+ const infraTakes = existsSync(likeInfra) ? takes(likeInfra) : appTakes
92
+ const otherTakes = others
93
+ .map((dir) => path.join(dir, 'package.json'))
94
+ .filter((file) => existsSync(file))
95
+ .map(takes)
96
+ /** @type {string[]} */
97
+ const notes = []
98
+ /** @type {import('./generate.js').AppContext['spec']} */
99
+ const spec = (pkg, manifest) => {
100
+ if (!SSSB_PACKAGES.includes(pkg))
101
+ throw new CreateError(`the template depends on @sssb/${pkg}, an unknown package`)
102
+ const toDir = manifest === 'infra' ? path.join(appDir, 'infra') : appDir
103
+ // The manifest's own counterpart first, then the other one, then the caller's other packages: a workspace
104
+ // whose deployment is not inside its app (an infra/ at the root) names @sssb/cdk there.
105
+ const sources = manifest === 'infra' ? [infraTakes, appTakes] : [appTakes, infraTakes]
106
+ for (const source of [...sources, ...otherTakes]) {
107
+ const found = source.specs[`@sssb/${pkg}`]
108
+ if (found) return rebaseSpec(found, source.dir, toDir)
109
+ }
110
+ const range = `^${meta.version}`
111
+ notes.push(
112
+ `${path.relative(root, path.join(toDir, 'package.json'))} takes @sssb/${pkg} at ${range}: ` +
113
+ `no package of the workspace names @sssb/${pkg} to copy. Write it as your workspace takes SSSB's packages`,
114
+ )
115
+ return range
116
+ }
117
+ const eslint = appTakes.eslint ?? /** @type {string} */ (meta.ranges['eslint'])
118
+
119
+ // What this run made, kept after it returns: a signal that came while it ran is dispatched only then, and must still
120
+ // find the app, the caller's change and the apps/ directory it may have created (as `generate` keeps `moved`).
121
+ const made = {
122
+ apps: /** @type {string | undefined} */ (undefined),
123
+ stage: '',
124
+ app: '',
125
+ finished: /** @type {(() => void) | undefined} */ (undefined),
126
+ }
127
+ const undo = () => {
128
+ if (made.finished) {
129
+ const finished = made.finished
130
+ made.finished = undefined
131
+ finished()
132
+ }
133
+ if (made.stage) rmSync(made.stage, { recursive: true, force: true })
134
+ if (made.app) rmSync(made.app, { recursive: true, force: true })
135
+ if (made.apps) {
136
+ try {
137
+ rmdirSync(made.apps)
138
+ } catch {
139
+ // not empty, or gone: leave it
140
+ }
141
+ }
142
+ }
143
+ holdSignals(undo)
144
+ try {
145
+ made.apps = mkdirSync(appsDir, { recursive: true })
146
+ made.stage = path.join(appsDir, `.sssb-add-app-${randomBytes(4).toString('hex')}`)
147
+ writeApp(made.stage, { slug, name: display, meta, spec, eslint, port }, templateDir)
148
+ if (lstatSync(appDir, { throwIfNoEntry: false }))
149
+ throw new CreateError(`${appDir} appeared while the app was written`)
150
+ renameSync(made.stage, appDir)
151
+ made.stage = ''
152
+ made.app = appDir
153
+ if (finish) made.finished = finish(appDir)
154
+ const files = filesUnder(appDir).map((file) => path.relative(root, path.join(appDir, file)))
155
+ return { appDir, name: display, files, notes }
156
+ } catch (error) {
157
+ undo()
158
+ const err = /** @type {NodeJS.ErrnoException} */ (error)
159
+ if (!(error instanceof CreateError) && typeof err?.code === 'string' && typeof err.syscall === 'string')
160
+ throw new CreateError(`could not write the app: ${err.message}`)
161
+ throw error
162
+ } finally {
163
+ releaseSignals(undo)
164
+ }
165
+ }
package/src/args.js CHANGED
@@ -64,7 +64,7 @@ export const RESERVED_DATABASE_NAMES = new Set(
64
64
  * most 63 characters, not a word the engine reserves), as @sssb/cdk's `databaseNameFor` would at synth.
65
65
  * @param {string} slug
66
66
  */
67
- function checkSlug(slug) {
67
+ export function checkSlug(slug) {
68
68
  if (!SLUG.test(slug))
69
69
  throw new CreateError(`"${slug}" is not a valid slug: lowercase letters, digits and dashes, from a letter`)
70
70
  const database = slug.replaceAll('-', '_')
@@ -77,7 +77,7 @@ function checkSlug(slug) {
77
77
  * The slug's title case, the default display name (`acme-research` is "Acme Research").
78
78
  * @param {string} slug
79
79
  */
80
- function titleCase(slug) {
80
+ export function titleCase(slug) {
81
81
  return slug
82
82
  .split('-')
83
83
  .filter(Boolean)
package/src/files.js CHANGED
@@ -110,6 +110,15 @@ export function pnpmWorkspace(c) {
110
110
  "# part 5). Without it a package that takes the framework and links no seam silently shares an app's; after",
111
111
  '# changing it, reinstall from a fresh lockfile. `pnpm exec sssb doctor` checks it.',
112
112
  'dedupePeerDependents: false',
113
+ '',
114
+ "# @sssb/eslint-plugin's preset needs eslint-plugin-react and eslint-plugin-jsx-a11y, whose latest releases still",
115
+ '# declare eslint 9 as their highest peer. The preset runs them under eslint 10 (it is what SSSB lints with), so',
116
+ '# the warning on every first install is noise. These two entries, and only these, allow it; delete them once',
117
+ '# both plugins list eslint 10 (`pnpm peers check` shows what is left).',
118
+ 'peerDependencyRules:',
119
+ ' allowedVersions:',
120
+ " 'eslint-plugin-react>eslint': '10'",
121
+ " 'eslint-plugin-jsx-a11y>eslint': '10'",
113
122
  ]
114
123
  if (c.meta.minimumReleaseAge !== null) {
115
124
  lines.push(
@@ -230,25 +239,26 @@ export const ROOT_TSCONFIG = formatJson({
230
239
  include: ['*.ts'],
231
240
  })
232
241
 
233
- /** @param {Context} c */
234
- export function vitestConfig(c) {
235
- return `import { fileURLToPath } from 'node:url'
236
- import { appTestProject } from '@sssb/tools/vitest'
242
+ /**
243
+ * The workspace's unit run: a Vitest project per app the root's `sssb.apps` names, from SSSB's preset, so a second app
244
+ * joins it by its entry there (`sssb add-app` writes one).
245
+ */
246
+ export const VITEST_CONFIG = `import { fileURLToPath } from 'node:url'
247
+ import { workspaceAppProjects } from '@sssb/tools/vitest'
237
248
  import { defineConfig, type ViteUserConfig } from 'vitest/config'
238
249
 
239
250
  const at = (relative: string) => fileURLToPath(new URL(relative, import.meta.url))
240
251
 
241
252
  /**
242
- * The workspace's apps. ONE PROJECT PER APP, from SSSB's preset (@sssb/tools/vitest): the framework reads the app's
243
- * registrations through the bare specifier \`@sssb/app-config/*\`, which one project can resolve for one app only, so
244
- * each app's project passes its own seam. Each app's conformance suite (src/sssb.conformance.test.ts) runs in its
245
- * project like any other test; \`pnpm exec sssb doctor\` fails if this config stops running it.
253
+ * ONE PROJECT PER APP, from SSSB's preset (@sssb/tools/vitest), for every app the root package.json's \`sssb.apps\`
254
+ * names: the framework reads the app's registrations through the bare specifier \`@sssb/app-config/*\`, which one
255
+ * project can resolve for one app only, so each app's project passes its own seam. Each app's conformance suite
256
+ * (src/sssb.conformance.test.ts) runs in its project like any other test; \`pnpm exec sssb doctor\` fails if this
257
+ * config stops running it.
246
258
  */
247
- const APPS = ['${c.slug}']
248
-
249
259
  export default defineConfig(async (): Promise<ViteUserConfig> => ({
250
260
  test: {
251
- projects: await Promise.all(APPS.map((app) => appTestProject({ appDir: at(\`./apps/\${app}\`) }))),
261
+ projects: await workspaceAppProjects({ root: at('.') }),
252
262
  coverage: {
253
263
  provider: 'v8',
254
264
  include: ['apps/*/src/**/*.{ts,tsx}', 'packages/*/src/**/*.{ts,tsx}'],
@@ -259,34 +269,31 @@ export default defineConfig(async (): Promise<ViteUserConfig> => ({
259
269
  },
260
270
  }))
261
271
  `
262
- }
263
272
 
264
- /** @param {Context} c */
265
- export function vitestContractConfig(c) {
266
- return `import { fileURLToPath } from 'node:url'
267
- import { appTestProject } from '@sssb/tools/vitest'
273
+ /** The workspace's contract run: the same project per app, narrowed to its tests/contract. */
274
+ export const VITEST_CONTRACT_CONFIG = `import { fileURLToPath } from 'node:url'
275
+ import { workspaceAppProjects } from '@sssb/tools/vitest'
268
276
  import { defineConfig, type ViteUserConfig } from 'vitest/config'
269
277
 
270
278
  const at = (relative: string) => fileURLToPath(new URL(relative, import.meta.url))
271
279
 
272
- const APPS = ['${c.slug}']
273
-
274
280
  /**
275
281
  * The contract tests: each app's tests/contract (SSSB's contract runner, @sssb/kit/testing/contract) against real
276
- * Postgres, a database of the app's own. The preset's project per app, narrowed to tests/contract, in Node, one file at
277
- * a time, because every app's embedded Postgres takes the one port (CONTRACT_DATABASE_URL names a server instead; CI
278
- * passes its service container's). The unit config never reaches tests/contract.
282
+ * Postgres, a database of the app's own. The preset's project for every app the root package.json's \`sssb.apps\`
283
+ * names, narrowed to tests/contract, in Node, one file at a time, because every app's embedded Postgres takes the one
284
+ * port (CONTRACT_DATABASE_URL names a server instead; CI passes its service container's). The unit config never
285
+ * reaches tests/contract.
279
286
  */
280
- const contract = async (app: string) => {
281
- const project = await appTestProject({ appDir: at(\`./apps/\${app}\`) })
282
- return { ...project, test: { ...project.test, environment: 'node', include: ['tests/contract/**/*.test.ts'] } }
283
- }
284
-
285
287
  export default defineConfig(async (): Promise<ViteUserConfig> => ({
286
- test: { fileParallelism: false, projects: await Promise.all(APPS.map(contract)) },
288
+ test: {
289
+ fileParallelism: false,
290
+ projects: (await workspaceAppProjects({ root: at('.') })).map((project) => ({
291
+ ...project,
292
+ test: { ...project.test, environment: 'node', include: ['tests/contract/**/*.test.ts'] },
293
+ })),
294
+ },
287
295
  }))
288
296
  `
289
- }
290
297
 
291
298
  /** @param {Context} c */
292
299
  export function knipJson(c) {
@@ -426,7 +433,8 @@ export function workflow(c) {
426
433
  return `# This workspace's checks. SSSB's checks for the app are SSSB's REUSABLE WORKFLOW, called here pinned to a commit
427
434
  # of SSSB's repository (a tag can be moved; a commit cannot). Require the check \`sssb / all-checks\` in your branch
428
435
  # protection or ruleset: it fails unless every one of SSSB's jobs ran and passed, so a skipped or renamed job cannot
429
- # slip out of the requirement. Raise the pin when you upgrade the @sssb packages (the release notes name the commit).
436
+ # slip out of the requirement. Raise the pin when you upgrade the @sssb packages: \`pnpm exec sssb pin\` raises it, and
437
+ # the plugin marketplace's in .claude/settings.json, to the installed @sssb/kit's release commit.
430
438
  #
431
439
  # The reusable workflow takes no secrets: never pass it \`secrets: inherit\`. If this repository is private and in an
432
440
  # organization, the organization must allow public reusable workflows in its Actions settings.
@@ -512,7 +520,8 @@ export function claudeSettings(c) {
512
520
  export const CLAUDE_MD = `# Agent guide
513
521
 
514
522
  SSSB's app guide, the rules every app on SSSB follows, from the copy \`pnpm exec sssb guide\` keeps (after an upgrade,
515
- \`pnpm exec sssb doctor\` fails until it is refreshed):
523
+ \`pnpm exec sssb doctor\` fails until it is refreshed, and \`pnpm exec sssb pin\` raises the CI workflow's and the plugin
524
+ marketplace's pins to the release's commit):
516
525
 
517
526
  @.claude/sssb-guide.md
518
527
 
@@ -592,13 +601,18 @@ the e2e suites, the static demo and the offline CDK synth. Only the secret scan
592
601
 
593
602
  ## Building on SSSB
594
603
 
595
- SSSB's guide for an app built on it, at the commit this workspace pins, says what is yours and what is SSSB's, how
596
- the app registers through its seam, which generated content to replace first, how to cut over to real accounts, and
597
- how to upgrade:
604
+ SSSB's guide for an app built on it, at the commit this workspace pins, walks you from here: which generated content
605
+ to replace first, a first entity through the app's seam, cutting over to real accounts, and upgrading:
598
606
  [\`docs/adopting.md\`](${sssbDoc(c, 'blob', 'docs/adopting.md')}).
607
+ Its reference says the rest, what is yours and what is SSSB's among it:
608
+ [\`docs/adopting-reference.md\`](${sssbDoc(c, 'blob', 'docs/adopting-reference.md')}).
599
609
  The worked example of every capability is SSSB's own reference app:
600
610
  [\`apps/showcase\`](${sssbDoc(c, 'tree', 'apps/showcase')}).
601
611
 
612
+ The app starts with one worked example, an Items list (a tenant-scoped table with row-level security, a paged route, a
613
+ card and its tests). When you have read it, \`pnpm exec sssb remove-items --app ${app(c)} --drop-migrations\` takes it out in one step
614
+ (\`--dry-run\` says what it will do; SSSB's reference, under "To remove the Items slice", says when to leave the flag off).
615
+
602
616
  ## Layout
603
617
 
604
618
  - \`${app(c)}/\`: the app. Its \`src/app-config/\` is the seam SSSB's framework (\`@sssb/kit\`) reads the app's
@@ -627,7 +641,8 @@ the commands an app author runs, namespaced as \`/${c.meta.plugin.name}:<command
627
641
  (\`claude --version\`; \`claude update\`).
628
642
  - **Install the plugin once per clone**, after trusting the folder (enabling it does not install it):
629
643
  \`claude plugin install ${c.meta.plugin.name}@${c.meta.plugin.marketplace} --scope project\`.
630
- - **Raise the marketplace's \`ref\` with the workflow's pin** when you upgrade (below).
644
+ - **Raise the marketplace's \`ref\` with the workflow's pin** when you upgrade: \`pnpm exec sssb pin\` raises both
645
+ (below).
631
646
 
632
647
  ## CI, and the settings only you can make
633
648
 
@@ -650,10 +665,12 @@ ${
650
665
  ## Upgrading SSSB
651
666
 
652
667
  The \`@sssb/*\` packages are released together at one version. Each release's notes open with "Upgrading to this
653
- release", the commands that move them together, refresh \`.claude/sssb-guide.md\` and raise the workflow's pin and
654
- the plugin marketplace's \`ref\` in \`.claude/settings.json\` to the release's commit. SSSB's guide says why each step is
655
- there:
668
+ release", the commands that move them together, refresh \`.claude/sssb-guide.md\` (\`pnpm exec sssb guide\`) and raise
669
+ the workflow's pin and the plugin marketplace's \`ref\` in \`.claude/settings.json\` to the release's commit
670
+ (\`pnpm exec sssb pin\`, which reads it from the installed \`@sssb/kit\`). SSSB's guide lists the steps:
656
671
  [\`docs/adopting.md\`, "Upgrading by release"](${sssbDoc(c, 'blob', 'docs/adopting.md')}#upgrading-by-release).
672
+ Its reference says why each is there:
673
+ [\`docs/adopting-reference.md\`, "Upgrading, step by step"](${sssbDoc(c, 'blob', 'docs/adopting-reference.md')}#upgrading-step-by-step).
657
674
  \`pnpm exec sssb doctor\` fails when the installed packages are out of step, and reports a pin that is not the release
658
675
  commit the installed \`@sssb/kit\` names.
659
676
  `