@sssb/tools 0.0.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.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/bin/sssb.js +116 -0
  3. package/package.json +89 -5
  4. package/src/app-port.js +77 -0
  5. package/src/app.js +142 -0
  6. package/src/assembly-checks.d.ts +57 -0
  7. package/src/assembly-checks.js +259 -0
  8. package/src/commands/add-app.js +344 -0
  9. package/src/commands/check-demo-size.js +80 -0
  10. package/src/commands/check-doc-paths.js +48 -0
  11. package/src/commands/check-e2e.js +611 -0
  12. package/src/commands/check-fences.js +51 -0
  13. package/src/commands/check-real-env.js +165 -0
  14. package/src/commands/check-tmpdir-leak.js +78 -0
  15. package/src/commands/ci.js +350 -0
  16. package/src/commands/dev-tick.js +25 -0
  17. package/src/commands/doctor-checks.js +1396 -0
  18. package/src/commands/doctor-settings.js +583 -0
  19. package/src/commands/doctor-vitest.js +262 -0
  20. package/src/commands/doctor.js +1033 -0
  21. package/src/commands/e2e-profile.js +94 -0
  22. package/src/commands/guide.js +108 -0
  23. package/src/commands/launch-json.js +55 -0
  24. package/src/commands/pin.js +411 -0
  25. package/src/commands/port.js +22 -0
  26. package/src/commands/remove-items.js +191 -0
  27. package/src/commands/serve-standalone.js +78 -0
  28. package/src/commands/tick.js +27 -0
  29. package/src/doc-paths.d.ts +106 -0
  30. package/src/doc-paths.js +328 -0
  31. package/src/framework-guard.js +35 -0
  32. package/src/kit.d.ts +49 -0
  33. package/src/kit.js +216 -0
  34. package/src/next.d.ts +16 -0
  35. package/src/next.js +55 -0
  36. package/src/ports.d.ts +72 -0
  37. package/src/ports.js +307 -0
  38. package/src/prune-mantine-css.js +171 -0
  39. package/src/remove-items/code.patch +798 -0
  40. package/src/remove-items/database.patch +218 -0
  41. package/src/remove-items/exact-patch.js +122 -0
  42. package/src/testing/tmp-dir-marker.js +9 -0
  43. package/src/testing/tmp-dir-setup.d.ts +2 -0
  44. package/src/testing/tmp-dir-setup.js +9 -0
  45. package/src/testing/tmp-dir.d.ts +20 -0
  46. package/src/testing/tmp-dir.js +174 -0
  47. package/src/tick/dev-tick.js +128 -0
  48. package/src/tick/tick.js +317 -0
  49. package/src/tick/ticker-marker.d.ts +17 -0
  50. package/src/tick/ticker-marker.js +83 -0
  51. package/src/tick/ticker.d.ts +36 -0
  52. package/src/tick/ticker.js +142 -0
  53. package/src/vite.d.ts +38 -0
  54. package/src/vite.js +64 -0
  55. package/src/vitest.d.ts +38 -0
  56. package/src/vitest.js +82 -0
  57. package/tsconfig.base.json +33 -0
  58. package/README.md +0 -3
@@ -0,0 +1,259 @@
1
+ // @ts-check
2
+ // Checks over a synthesized CloudFormation assembly: pure functions over the template's `Resources` and over
3
+ // the Lambda bundles staged on disk, so an adopter whose infra does not use SSSB's construct can run them on
4
+ // their own assembly. This package never imports `@sssb/kit` and has no dependency on aws-cdk-lib.
5
+ import { existsSync, readFileSync } from 'node:fs'
6
+ import path from 'node:path'
7
+
8
+ /** @typedef {import('./assembly-checks.d.ts').Resources} Resources */
9
+ /** @typedef {import('./assembly-checks.d.ts').Resource} Resource */
10
+ /** @typedef {{ Effect?: unknown, Action?: unknown, NotAction?: unknown, Resource?: unknown }} Statement */
11
+
12
+ /**
13
+ * The code staged for each Lambda whose asset has an `index.mjs` or `index.js`, keyed by logical id. For
14
+ * a NodejsFunction that is what esbuild produced during the synth, with the tsconfig the stack passed, not a
15
+ * re-creation of it. CDK's own provider handler ships a ready-made `index.js`, and is read like any other. A
16
+ * placeholder asset with neither is left out.
17
+ * @type {import('./assembly-checks.d.ts').lambdaBundles}
18
+ */
19
+ export function lambdaBundles(resources, assemblyDir) {
20
+ /** @type {Map<string, string>} */
21
+ const found = new Map()
22
+ for (const [id, r] of Object.entries(resources)) {
23
+ if (r.Type !== 'AWS::Lambda::Function') continue
24
+ const key = /** @type {{ S3Key?: unknown } | undefined} */ (r.Properties?.Code)?.S3Key
25
+ if (typeof key !== 'string') continue
26
+ const staged = path.join(assemblyDir, `asset.${key.replace(/\.zip$/, '')}`)
27
+ const entry = ['index.mjs', 'index.js'].map((file) => path.join(staged, file)).find((file) => existsSync(file))
28
+ if (entry) found.set(id, readFileSync(entry, 'utf8'))
29
+ }
30
+ return found
31
+ }
32
+
33
+ /** @type {import('./assembly-checks.d.ts').lambdaFunction} */
34
+ export function lambdaFunction(resources, namePrefix) {
35
+ const found = Object.entries(resources).find(
36
+ ([id, r]) => r.Type === 'AWS::Lambda::Function' && id.startsWith(namePrefix) && !id.includes('Provider'),
37
+ )
38
+ if (!found) throw new Error(`no ${namePrefix} function in the synthesized stack`)
39
+ const props = found[1].Properties ?? {}
40
+ const variables = /** @type {{ Variables?: Record<string, unknown> } | undefined} */ (props.Environment)?.Variables
41
+ return { id: found[0], inVpc: props.VpcConfig !== undefined, env: variables ?? {} }
42
+ }
43
+
44
+ /**
45
+ * Requiring the path comments makes the check fail CLOSED: a minified bundle carries no such comments, and
46
+ * so fails here instead of passing every check that reads them.
47
+ * @type {import('./assembly-checks.d.ts').migratorBundleProblems}
48
+ */
49
+ export function migratorBundleProblems({ code, sources, migrations }) {
50
+ if (code === undefined) return ['the migrator is not bundled by this synth']
51
+ /** @type {string[]} */
52
+ const problems = []
53
+ if (code.includes('test-fixture')) problems.push('the migrator’s bundle holds code from a test-fixture directory')
54
+ for (const source of sources) {
55
+ if (!code.includes(`// ${source}\n`)) {
56
+ problems.push(`the migrator's bundle names ${source} (an unminified bundle, built from the app's seam)`)
57
+ }
58
+ }
59
+ for (const name of migrations) {
60
+ if (!code.includes(`"${name}"`)) problems.push(`the migrator's bundle carries the app's migration ${name}`)
61
+ }
62
+ return problems
63
+ }
64
+
65
+ /**
66
+ * The server must come up in `real` mode and carry no switch that turns on simulated or e2e behaviour. The
67
+ * absence of the other two is judged by presence, not value: `DEMO_MODE: 'false'` is still a switch a later
68
+ * change could flip.
69
+ * @type {import('./assembly-checks.d.ts').failClosedEnvironmentProblems}
70
+ */
71
+ export function failClosedEnvironmentProblems(env) {
72
+ /** @type {string[]} */
73
+ const problems = []
74
+ if (env.APP_MODE !== 'real') problems.push(`APP_MODE is ${JSON.stringify(env.APP_MODE)}, not 'real'`)
75
+ for (const name of ['DEMO_MODE', 'E2E_BUILD']) {
76
+ if (name in env) problems.push(`${name} is set in the final environment`)
77
+ }
78
+ return problems
79
+ }
80
+
81
+ /**
82
+ * The permission documents a resource carries: a policy's, a managed policy's, or a role's inline ones.
83
+ * @param {Resource} resource
84
+ * @returns {unknown[]}
85
+ */
86
+ function policyDocuments(resource) {
87
+ if (resource.Type === 'AWS::IAM::Policy' || resource.Type === 'AWS::IAM::ManagedPolicy') {
88
+ return [resource.Properties?.PolicyDocument]
89
+ }
90
+ if (resource.Type === 'AWS::IAM::Role') {
91
+ const inline = /** @type {{ PolicyDocument?: unknown }[] | undefined} */ (resource.Properties?.Policies) ?? []
92
+ return inline.map((policy) => policy.PolicyDocument)
93
+ }
94
+ return []
95
+ }
96
+
97
+ /**
98
+ * Whether an IAM action pattern can name one of `service`'s actions. IAM matches `*` and `?` anywhere in
99
+ * an action, so `*`, `rds-data:*` and `rds*:Execute*` all reach `rds-data:ExecuteStatement`.
100
+ * @param {string} action
101
+ * @param {string} service
102
+ */
103
+ function reaches(action, service) {
104
+ const prefix = action.includes(':') ? action.slice(0, action.indexOf(':')) : action
105
+ const pattern = prefix
106
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
107
+ .replace(/\*/g, '.*')
108
+ .replace(/\?/g, '.')
109
+ return new RegExp(`^${pattern}$`, 'i').test(service)
110
+ }
111
+
112
+ /**
113
+ * Every Allow statement in the stack's IAM policies, managed policies and roles' inline policies that can
114
+ * grant one of `service`'s actions (`rds-data`, `secretsmanager`): by naming one, by a wildcard that
115
+ * reaches one (`*` reaches every service), or by `NotAction`, which grants everything it does not name.
116
+ * Roles' trust policies grant nothing and are not read.
117
+ * @param {Resources} all
118
+ * @param {string} service
119
+ * @returns {Statement[]}
120
+ */
121
+ function grantsOf(all, service) {
122
+ return Object.values(all)
123
+ .flatMap(policyDocuments)
124
+ .flatMap(
125
+ (document) =>
126
+ /** @type {Statement[]} */ (
127
+ /** @type {{ Statement?: unknown[] } | undefined} */ (document)?.Statement ?? []
128
+ ),
129
+ )
130
+ .filter((s) => s.Effect !== 'Deny')
131
+ .filter((s) => {
132
+ if (s.NotAction !== undefined) return true
133
+ const actions = Array.isArray(s.Action) ? s.Action : [s.Action]
134
+ return actions.some((action) => typeof action === 'string' && reaches(action, service))
135
+ })
136
+ }
137
+
138
+ /**
139
+ * The AWS-managed policies a role may attach: the check cannot read their contents, so it allows only the
140
+ * two Lambda execution policies CDK attaches (logs, and network interfaces on `pg`), which grant neither
141
+ * service. A managed policy defined in the stack is read like any other (grantsOf).
142
+ */
143
+ const KNOWN_AWS_POLICIES = ['service-role/AWSLambdaBasicExecutionRole', 'service-role/AWSLambdaVPCAccessExecutionRole']
144
+
145
+ /**
146
+ * @param {Resources} all
147
+ * @returns {string[]}
148
+ */
149
+ function unreadablePolicies(all) {
150
+ const inStack = new Set(
151
+ Object.entries(all)
152
+ .filter(([, r]) => r.Type === 'AWS::IAM::ManagedPolicy')
153
+ .map(([id]) => id),
154
+ )
155
+ return Object.entries(all)
156
+ .filter(([, r]) => r.Type === 'AWS::IAM::Role')
157
+ .flatMap(([id, r]) =>
158
+ /** @type {unknown[] | undefined} */ (r.Properties?.ManagedPolicyArns ?? [])
159
+ .filter((arn) => {
160
+ const text = JSON.stringify(arn)
161
+ const ref = /** @type {{ Ref?: string }} */ (arn).Ref
162
+ if (ref !== undefined && inStack.has(ref)) return false
163
+ return !KNOWN_AWS_POLICIES.some((name) =>
164
+ new RegExp(`:iam::aws:policy/${name}"[\\]}]*$`).test(text),
165
+ )
166
+ })
167
+ .map((arn) => `${id}: ${JSON.stringify(arn)}`),
168
+ )
169
+ }
170
+
171
+ /**
172
+ * The cluster's own secret: the attachment CDK makes for the cluster, and the secret it attaches.
173
+ * @param {Resources} all
174
+ * @param {string} clusterId
175
+ * @returns {string[]}
176
+ */
177
+ function databaseSecretIds(all, clusterId) {
178
+ return Object.entries(all)
179
+ .filter(
180
+ ([, r]) =>
181
+ r.Type === 'AWS::SecretsManager::SecretTargetAttachment' &&
182
+ JSON.stringify(r.Properties?.TargetId) === JSON.stringify({ Ref: clusterId }),
183
+ )
184
+ .flatMap(([id, r]) => {
185
+ const secret = /** @type {{ Ref?: string } | undefined} */ (r.Properties?.SecretId)?.Ref
186
+ return secret ? [id, secret] : [id]
187
+ })
188
+ }
189
+
190
+ /**
191
+ * Whether every resource `statement` grants refers to one of `ids`, and none is a wildcard.
192
+ * @param {Statement} statement
193
+ * @param {readonly string[]} ids
194
+ */
195
+ function namesOnly(statement, ids) {
196
+ const granted = Array.isArray(statement.Resource) ? statement.Resource : [statement.Resource ?? '*']
197
+ return granted.every((resource) => {
198
+ const text = JSON.stringify(resource)
199
+ return !text.includes('*') && ids.some((id) => text.includes(`"Ref":"${id}"`))
200
+ })
201
+ }
202
+
203
+ /**
204
+ * The template's database cluster, by logical id. Throws when there is none: every check that reasons about
205
+ * "the cluster's own" anything is meaningless without one.
206
+ * @param {Resources} all
207
+ * @returns {[string, Resource]}
208
+ */
209
+ function clusterOf(all) {
210
+ const found = Object.entries(all).find(([, r]) => r.Type === 'AWS::RDS::DBCluster')
211
+ if (!found) throw new Error('no AWS::RDS::DBCluster in the synthesized stack')
212
+ return found
213
+ }
214
+
215
+ /** @type {import('./assembly-checks.d.ts').secretGrantProblems} */
216
+ export function secretGrantProblems(resources) {
217
+ const [clusterId] = clusterOf(resources)
218
+ /** @type {string[]} */
219
+ const problems = []
220
+ // The database secret is read by name, on every shape: never a wildcard, never another secret.
221
+ const secretIds = databaseSecretIds(resources, clusterId)
222
+ const secretGrants = grantsOf(resources, 'secretsmanager')
223
+ if (!(secretIds.length > 0 && secretGrants.length > 0 && secretGrants.every((s) => namesOnly(s, secretIds)))) {
224
+ problems.push('every Secrets Manager grant names the cluster’s own secret alone')
225
+ }
226
+ const unreadable = unreadablePolicies(resources)
227
+ if (unreadable.length > 0) {
228
+ problems.push(`no role attaches an AWS-managed policy the check cannot read: ${unreadable.join('; ')}`)
229
+ }
230
+ return problems
231
+ }
232
+
233
+ /** @type {import('./assembly-checks.d.ts').dataApiShapeProblems} */
234
+ export function dataApiShapeProblems(resources) {
235
+ const [clusterId, cluster] = clusterOf(resources)
236
+ /** @type {string[]} */
237
+ const problems = secretGrantProblems(resources)
238
+ // Every statement that can grant a Data API action (see grantsOf) names this cluster, and nothing
239
+ // wider: the grant plus the secret is the whole way in on this shape.
240
+ const dataApiGrants = grantsOf(resources, 'rds-data')
241
+ if (!dataApiGrants.some((s) => JSON.stringify(s.Action).includes('rds-data:ExecuteStatement'))) {
242
+ problems.push('a role is granted rds-data:ExecuteStatement')
243
+ }
244
+ if (!dataApiGrants.every((s) => namesOnly(s, [clusterId]))) {
245
+ problems.push('every rds-data grant is scoped to this cluster alone')
246
+ }
247
+ // Nothing reaches the database over the network on this shape: its security group admits nobody.
248
+ const dbGroups = JSON.stringify(cluster.Properties?.VpcSecurityGroupIds ?? [])
249
+ const ingress = Object.entries(resources).filter(
250
+ ([id, r]) =>
251
+ (r.Type === 'AWS::EC2::SecurityGroupIngress' &&
252
+ dbGroups.includes(JSON.stringify(r.Properties?.GroupId ?? null))) ||
253
+ (r.Type === 'AWS::EC2::SecurityGroup' &&
254
+ dbGroups.includes(`"${id}"`) &&
255
+ /** @type {unknown[] | undefined} */ (r.Properties?.SecurityGroupIngress ?? []).length > 0),
256
+ )
257
+ if (ingress.length > 0) problems.push('the database security group admits no inbound traffic')
258
+ return problems
259
+ }
@@ -0,0 +1,344 @@
1
+ // @ts-check
2
+ // `sssb add-app <slug> [--name "<Name>"] [--port <port>] [--slot <name>] [--create <dir>]`: a second app (or a third)
3
+ // in an existing workspace, written from SSSB's starter under apps/<slug>/ with the generator's renames, a port slot of
4
+ // its own, and each @sssb package taken as the workspace's first app takes it; then named in the root's `sssb.apps`,
5
+ // the one list of apps every SSSB tool reads. It prints what is left to the person (the root scripts and the CI
6
+ // workflow name one app on purpose), and `sssb doctor` names anything else.
7
+ //
8
+ // WHERE THE STARTER COMES FROM: the @sssb/create the workspace installs (`pnpm add -D -w @sssb/create@<version>`, at
9
+ // the @sssb packages' one version), which carries the starter as its packed template and the renames as its code
10
+ // (`@sssb/create/add-app`). Reached from the workspace root, as rule 4 reaches @sssb/kit from the app: no SSSB package
11
+ // depends on another (ADR-0014 part 10). `--create <dir>` names an unpacked @sssb/create instead.
12
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
13
+ import path from 'node:path'
14
+ import { pathToFileURL } from 'node:url'
15
+ import { readJson, takeOption, UsageError, workspaceApps, workspaceRootOf } from '../app.js'
16
+ import { parsePortDeclaration, portForRoot, readPortDeclaration } from '../ports.js'
17
+ import { workspacePackages } from './doctor-checks.js'
18
+
19
+ const USAGE = 'usage: sssb add-app <slug> [--name "<Name>"] [--port <port>] [--slot <name>] [--create <dir>]'
20
+
21
+ /**
22
+ * `@sssb/create/add-app`'s `addApp`, as this command calls it (the generator is plain JavaScript with no types of its
23
+ * own, and no SSSB package depends on another).
24
+ * @typedef {(options: {
25
+ * templateDir: string,
26
+ * root: string,
27
+ * slug: string,
28
+ * name: string | null,
29
+ * port: { name: string, default: number },
30
+ * like: string,
31
+ * others: string[],
32
+ * finish: (appDir: string) => () => void,
33
+ * }) => { appDir: string, name: string, files: string[], notes: string[] }} AddApp
34
+ */
35
+
36
+ /** The first main-checkout port offered to a new app's slot, and the step between offers (3700, 3800, ...). */
37
+ const FIRST_DEFAULT = 3700
38
+ const DEFAULT_STEP = 100
39
+ const LAST_DEFAULT = 9900
40
+
41
+ /** @SSSB/tools' own version: the @sssb packages are one fixed group, released together at one version. */
42
+ const TOOLS_VERSION = readJson(path.resolve(import.meta.dirname, '..', '..', 'package.json')).version
43
+
44
+ /**
45
+ * The @sssb/create to write the app with, checked: an unpacked package of that name, at @sssb/tools' version, holding
46
+ * its packed template.
47
+ * @param {string} root
48
+ * @param {string | undefined} option `--create <dir>`
49
+ * @returns {{ dir: string, templateDir: string, module: string }}
50
+ */
51
+ export function createPackage(root, option) {
52
+ const dir = option === undefined ? path.join(root, 'node_modules', '@sssb', 'create') : path.resolve(option)
53
+ const manifestFile = path.join(dir, 'package.json')
54
+ if (!existsSync(manifestFile)) {
55
+ throw new UsageError(
56
+ option === undefined
57
+ ? `sssb add-app: the workspace does not install @sssb/create, whose packed template is the app it writes. ` +
58
+ `Install it at your SSSB version, then run this again:\n pnpm add -D -w @sssb/create@${TOOLS_VERSION}`
59
+ : `sssb add-app: --create ${option} is not a package (no package.json at ${dir})`,
60
+ )
61
+ }
62
+ const manifest = readJson(manifestFile)
63
+ if (manifest.name !== '@sssb/create')
64
+ throw new UsageError(`sssb add-app: ${dir} holds ${manifest.name ?? 'an unnamed package'}, not @sssb/create`)
65
+ if (manifest.version !== TOOLS_VERSION) {
66
+ throw new UsageError(
67
+ `sssb add-app: @sssb/create ${manifest.version} writes the starter of @sssb ${manifest.version}, and this ` +
68
+ `@sssb/tools is ${TOOLS_VERSION}: the @sssb packages are released together, so install ` +
69
+ `@sssb/create@${TOOLS_VERSION}`,
70
+ )
71
+ }
72
+ const entry = manifest.exports?.['./add-app']
73
+ if (typeof entry !== 'string')
74
+ throw new UsageError(`sssb add-app: @sssb/create ${manifest.version} exports no ./add-app`)
75
+ const templateDir = path.join(dir, 'template')
76
+ if (!existsSync(path.join(templateDir, 'meta.json'))) {
77
+ throw new UsageError(
78
+ `sssb add-app: ${dir} holds no packed template (template/meta.json): only a packed @sssb/create carries ` +
79
+ 'the starter (a checkout of SSSB has none until `pnpm pack` builds it)',
80
+ )
81
+ }
82
+ return { dir, templateDir, module: path.join(dir, entry) }
83
+ }
84
+
85
+ /**
86
+ * The new app's port slot: `--slot` (else the slug) and `--port` (else the first of 3700, 3800, ... that no app of the
87
+ * workspace binds in a main checkout and SSSB keeps for nothing of its own), checked as `sssb doctor` checks slots.
88
+ * @param {{ root: string, apps: string[], slug: string, slot?: string, port?: string }} options `apps` absolute
89
+ * @returns {{ name: string, default: number }}
90
+ */
91
+ export function newPortSlot({ root, apps, slug, slot, port }) {
92
+ const name = slot ?? slug
93
+ /** @type {Map<string, string>} */
94
+ const names = new Map()
95
+ /** @type {Map<number, string>} */
96
+ const defaults = new Map()
97
+ for (const app of apps) {
98
+ let declared
99
+ try {
100
+ declared = readPortDeclaration(app)
101
+ } catch (error) {
102
+ throw new UsageError(
103
+ `sssb add-app: ${error instanceof Error ? error.message.replace(/^ports: /, '') : error}`,
104
+ )
105
+ }
106
+ if (declared === undefined) continue
107
+ const where = path.relative(root, app)
108
+ names.set(typeof declared === 'string' ? declared : declared.name, where)
109
+ defaults.set(portForRoot(path.sep, declared, {}), where)
110
+ }
111
+ const holder = names.get(name)
112
+ if (holder !== undefined)
113
+ throw new UsageError(`sssb add-app: ${holder} already declares the port slot "${name}": pass --slot <name>`)
114
+ /**
115
+ * @param {number} value
116
+ * @returns {{ name: string, default: number } | UsageError}
117
+ */
118
+ const check = (value) => {
119
+ try {
120
+ return /** @type {{ name: string, default: number }} */ (parsePortDeclaration({ name, default: value }))
121
+ } catch (error) {
122
+ return new UsageError(
123
+ `sssb add-app: ${error instanceof Error ? error.message.replace(/^ports: /, '') : String(error)}`,
124
+ )
125
+ }
126
+ }
127
+ if (port !== undefined) {
128
+ if (!/^\d+$/.test(port)) throw new UsageError(`sssb add-app: --port ${port} is not a port number`)
129
+ const value = Number(port)
130
+ const result = check(value)
131
+ if (result instanceof UsageError) throw result
132
+ if (defaults.has(value))
133
+ throw new UsageError(`sssb add-app: ${defaults.get(value)} binds port ${value} in a main checkout already`)
134
+ return result
135
+ }
136
+ /** @type {UsageError | undefined} */
137
+ let first
138
+ for (let value = FIRST_DEFAULT; value <= LAST_DEFAULT; value += DEFAULT_STEP) {
139
+ if (defaults.has(value)) continue
140
+ const result = check(value)
141
+ if (!(result instanceof UsageError)) return result
142
+ first ??= result
143
+ }
144
+ // Every offer refused: a name the slot cannot carry refuses them all, so the first refusal says why.
145
+ throw new UsageError(
146
+ first === undefined
147
+ ? 'sssb add-app: no free default port from 3700 to 9900 (pass --port <port>)'
148
+ : `${first.message} (pass --slot <name>)`,
149
+ )
150
+ }
151
+
152
+ /**
153
+ * The indent a JSON file is written with (its first indented line's), so the root package.json keeps its own.
154
+ * @param {string} text
155
+ */
156
+ const indentOf = (text) => /\n([ \t]+)"/.exec(text)?.[1] ?? ' '
157
+
158
+ /**
159
+ * What is left to the person once the app is written: what the workspace names one app in by design (the root's
160
+ * scripts, the CI workflow's synth) and what does not cover the new one.
161
+ * @param {string} root
162
+ * @param {{ slug: string, appDir: string, like: string }} added
163
+ * @returns {string[]}
164
+ */
165
+ export function leftToDo(root, { slug, appDir, like }) {
166
+ /** @type {string[]} */
167
+ const left = []
168
+ const rel = (/** @type {string} */ dir) => path.relative(root, dir).split(path.sep).join('/')
169
+ const packages = new Set(workspacePackages(root))
170
+ const uncovered = [appDir, path.join(appDir, 'infra'), path.join(appDir, 'src', 'app-config')].filter(
171
+ (dir) => existsSync(path.join(dir, 'package.json')) && !packages.has(dir),
172
+ )
173
+ if (uncovered.length > 0)
174
+ left.push(`pnpm-workspace.yaml's packages do not cover ${uncovered.map(rel).join(', ')}: add globs that do`)
175
+
176
+ const likeName = readJson(path.join(like, 'package.json')).name
177
+ const scripts = /** @type {Record<string, string>} */ (readJson(path.join(root, 'package.json')).scripts ?? {})
178
+ const naming = Object.entries(scripts)
179
+ .filter(([, text]) => typeof text === 'string')
180
+ .filter(
181
+ ([, text]) =>
182
+ new RegExp(`--filter[= ](['"]?)${likeName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\1(\\s|$)`).test(
183
+ text,
184
+ ) ||
185
+ (rel(like) !== '' && text.includes(`./${rel(like)}`)),
186
+ )
187
+ .map(([script]) => script)
188
+ if (naming.length > 0) {
189
+ left.push(
190
+ `the root's ${naming.join(', ')} script(s) run ${likeName} alone; add ones for ${slug} if you want them ` +
191
+ `(say, "dev:${slug}": "pnpm --filter ${slug} dev")`,
192
+ )
193
+ }
194
+
195
+ const workflows = path.join(root, '.github', 'workflows')
196
+ if (existsSync(workflows)) {
197
+ for (const file of readdirSync(workflows).filter((name) => /\.ya?ml$/.test(name))) {
198
+ const text = readFileSync(path.join(workflows, file), 'utf8')
199
+ const synth = /^\s*synth:\s*['"]?(\S+?)['"]?\s*(?:#.*)?$/m.exec(text)?.[1]
200
+ if (synth && rel(like) !== '' && synth.includes(rel(like)) && !synth.includes('*')) {
201
+ left.push(
202
+ `.github/workflows/${file} synthesizes ${synth} alone: make its \`synth\` a selector that takes ` +
203
+ "every added app's infra/ too (./apps/*/infra takes every app's)",
204
+ )
205
+ }
206
+ }
207
+ }
208
+ // jscpd measures duplication across every app's src/ together, and the new app is the starter: as long as another
209
+ // app still holds the starter's code, the copy fails its threshold. That is jscpd being right, so it is said, not
210
+ // silenced.
211
+ const jscpd = path.join(root, '.jscpd.json')
212
+ if (existsSync(jscpd) && /apps\/\*/.test(readFileSync(jscpd, 'utf8'))) {
213
+ left.push(
214
+ `\`pnpm jscpd\` fails while ${rel(appDir)} is the starter and ${rel(like) || 'your first app'} still holds ` +
215
+ `starter code: make the apps your own, or, while you do, add "${rel(appDir)}/src/**" to .jscpd.json's ` +
216
+ '`ignore` and take it out again once the app is its own',
217
+ )
218
+ }
219
+ const manifest = readJson(path.join(root, 'package.json'))
220
+ if (manifest.devDependencies?.['@sssb/create'] ?? manifest.dependencies?.['@sssb/create']) {
221
+ left.push(
222
+ '`pnpm knip` calls @sssb/create unused (nothing imports it): `pnpm remove -w @sssb/create` once your apps ' +
223
+ "are written, or add it to knip.json's root ignoreDependencies to keep it",
224
+ )
225
+ }
226
+ return left
227
+ }
228
+
229
+ /** @param {string[]} args */
230
+ export async function run(args) {
231
+ const name = takeOption(args, '--name')
232
+ const port = takeOption(args, '--port')
233
+ const slot = takeOption(args, '--slot')
234
+ const create = takeOption(args, '--create')
235
+ const [slug, ...rest] = args
236
+ if (slug === undefined || slug.startsWith('-') || rest.length > 0)
237
+ throw new UsageError(
238
+ `sssb add-app: ${slug === undefined ? 'name the app' : `unexpected ${rest[0] ?? slug}`}\n${USAGE}`,
239
+ )
240
+
241
+ const root = workspaceRootOf(process.cwd())
242
+ const apps = workspaceApps(root).map((app) => path.join(root, app))
243
+ const like = apps.find((app) => {
244
+ const manifest = readJson(path.join(app, 'package.json'))
245
+ return Boolean(manifest.dependencies?.['@sssb/kit'] ?? manifest.devDependencies?.['@sssb/kit'])
246
+ })
247
+ if (like === undefined) {
248
+ throw new UsageError(
249
+ `sssb add-app: ${root} has no app that takes @sssb/kit (\`sssb.apps\` in its package.json, or apps/<name>) ` +
250
+ 'to add one beside: a new workspace is `pnpm create @sssb <dir>`',
251
+ )
252
+ }
253
+ const { templateDir, module } = createPackage(root, create)
254
+ const generator =
255
+ /** @type {{ addApp: AddApp, checkSlug: (slug: string) => void, signalsSettled: () => Promise<void> }} */ (
256
+ await import(pathToFileURL(module).href)
257
+ )
258
+ /** @type {<T>(work: () => T) => T} the generator's refusals, as this command's */
259
+ const asUsage = (work) => {
260
+ try {
261
+ return work()
262
+ } catch (error) {
263
+ if (error instanceof Error && error.name === 'CreateError')
264
+ throw new UsageError(`sssb add-app: ${error.message}`)
265
+ throw error
266
+ }
267
+ }
268
+ asUsage(() => generator.checkSlug(slug))
269
+ const appDir = path.join(root, 'apps', slug)
270
+ // The new app's package names may be neither a package of the workspace nor a dependency one of them takes: pnpm
271
+ // mistakes a workspace package for the dependency of the same name (the generator refuses its own template's
272
+ // dependencies; these are the workspace's own, the adopter's additions among them).
273
+ const packages = workspacePackages(root)
274
+ const manifests = [root, ...packages]
275
+ .map((dir) => path.join(dir, 'package.json'))
276
+ .filter((file) => existsSync(file))
277
+ .map((file) => readJson(file))
278
+ const names = new Set(manifests.map((manifest) => manifest.name))
279
+ const dependencies = new Set(
280
+ manifests.flatMap((manifest) =>
281
+ ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].flatMap((field) =>
282
+ Object.keys(manifest[field] ?? {}),
283
+ ),
284
+ ),
285
+ )
286
+ for (const taken of [slug, `${slug}-infra`, `${slug}-app-config`]) {
287
+ if (names.has(taken))
288
+ throw new UsageError(`sssb add-app: the workspace already has a package named ${taken}: pick another slug`)
289
+ if (dependencies.has(taken))
290
+ throw new UsageError(
291
+ `sssb add-app: a package of the workspace depends on ${taken}, which the new app's package would be ` +
292
+ 'named: pnpm mistakes one for the other. Pick another slug',
293
+ )
294
+ }
295
+ // Nor the slug of an app already here, whatever its packages are called: the slug names the session cookie, the
296
+ // contract database and the deployment's stack.
297
+ for (const app of apps) {
298
+ const config = path.join(app, 'config', 'app.ts')
299
+ const declared = existsSync(config)
300
+ ? /export const APP_SLUG = '([^']+)'/.exec(readFileSync(config, 'utf8'))?.[1]
301
+ : undefined
302
+ if (declared === slug)
303
+ throw new UsageError(
304
+ `sssb add-app: ${path.relative(root, app)} is the app "${slug}" (its config/app.ts APP_SLUG), and the ` +
305
+ 'slug names the session cookie, the contract database and the stack: pick another slug',
306
+ )
307
+ }
308
+ const portSlot = newPortSlot({ root, apps, slug, slot, port })
309
+ // The one list of apps: named in `sssb.apps` when the root keeps one (else apps/* is the list, and holds it). Written
310
+ // by the generator's `finish`, under its signal hold, so an interrupted run takes the entry back with the app.
311
+ const manifestFile = path.join(root, 'package.json')
312
+ const entry = path.relative(root, appDir).split(path.sep).join('/')
313
+ let listed = false
314
+ const finish = () => {
315
+ const text = readFileSync(manifestFile, 'utf8')
316
+ const manifest = JSON.parse(text)
317
+ const apps = manifest.sssb?.apps
318
+ if (!Array.isArray(apps) || apps.includes(entry)) return () => {}
319
+ manifest.sssb.apps = [...apps, entry]
320
+ writeFileSync(manifestFile, `${JSON.stringify(manifest, null, indentOf(text))}\n`)
321
+ listed = true
322
+ return () => writeFileSync(manifestFile, text)
323
+ }
324
+ const others = [root, ...packages].filter((dir) => dir !== like)
325
+ const added = asUsage(() =>
326
+ generator.addApp({ templateDir, root, slug, name: name ?? null, port: portSlot, like, others, finish }),
327
+ )
328
+ // A Ctrl-C that came while the app was written is dispatched now, undoes it and ends the process, before anything
329
+ // says it was added.
330
+ await generator.signalsSettled()
331
+
332
+ const left = [...added.notes, ...leftToDo(root, { slug, appDir, like })]
333
+ console.log(`
334
+ Added ${added.name} in ${entry}/: ${added.files.length} files, from @sssb/create ${TOOLS_VERSION}'s template.
335
+ Its port slot is "${portSlot.name}": port ${portSlot.default} in a main checkout, ${portSlot.name
336
+ .toUpperCase()
337
+ .replaceAll('-', '_')}_PORT overrides it.${listed ? ` The root's sssb.apps names it.` : ''}
338
+
339
+ Next:
340
+ pnpm install
341
+ pnpm exec sssb doctor (it names anything else the workspace still needs for ${slug})
342
+ ${left.length > 0 ? `\nLeft to you:\n${left.map((line) => ` - ${line}`).join('\n')}\n` : ''}`)
343
+ return 0
344
+ }