@sssb/create 0.0.0 → 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 -5
  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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rice University
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/bin/create.js ADDED
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // `@sssb/create` (ADR-0014, step P12): `pnpm create @sssb <dir>` or `npm create @sssb <dir>`. A new SSSB app workspace
4
+ // from the template packed into this package (template/, src/template.js). Run from a checkout of SSSB's repository,
5
+ // where nothing was packed, it builds the template from that checkout first.
6
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs'
7
+ import { tmpdir } from 'node:os'
8
+ import path from 'node:path'
9
+ import { createInterface } from 'node:readline/promises'
10
+ import { CreateError, parseArgs, PLACEHOLDER_OWNER, PLACEHOLDER_REPO, USAGE } from '../src/args.js'
11
+ import { generate } from '../src/generate.js'
12
+ import { holdSignals, releaseSignals, signalsSettled } from '../src/signals.js'
13
+ import { buildTemplate, META_FILE, unpushedPin } from '../src/template.js'
14
+
15
+ const PACKAGE = path.resolve(import.meta.dirname, '..')
16
+
17
+ /** @param {import('../src/args.js').Options} options */
18
+ async function confirmed(options) {
19
+ if (options.yes || !process.stdin.isTTY) return true
20
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
21
+ const answer = await rl.question(`Create the ${options.name} workspace in ${path.resolve(options.dir)}? [Y/n] `)
22
+ rl.close()
23
+ return !/^n/i.test(answer.trim())
24
+ }
25
+
26
+ /**
27
+ * A path as a POSIX shell reads it back: as it is when it holds nothing the shell would act on, else single-quoted.
28
+ * @param {string} text
29
+ */
30
+ const shellQuoted = (text) => (/^[\w@%+=:,./-]+$/.test(text) ? text : `'${text.replaceAll("'", `'\\''`)}'`)
31
+
32
+ /**
33
+ * The template inside a checkout of SSSB's repository, built into a temporary directory that `run` gets and that is
34
+ * removed after, however `run` ends. Warns, loudly, when the commit it pins is not on GitHub: the workspace's first
35
+ * CI run would fail to resolve SSSB's workflow.
36
+ * @template T
37
+ * @param {string | null} workflowRef
38
+ * @param {(templateDir: string) => T} run
39
+ * @returns {T}
40
+ */
41
+ function fromCheckout(workflowRef, run) {
42
+ const repoRoot = path.resolve(PACKAGE, '..', '..')
43
+ if (!existsSync(path.join(repoRoot, 'apps', 'starter', 'package.json')))
44
+ throw new CreateError(
45
+ `this package has no template (${path.join(PACKAGE, 'template')}) and is not in SSSB's repository`,
46
+ )
47
+ // Held before the directory is made: a signal during the (synchronous) build would otherwise end the process by
48
+ // its default action, before the `finally` below, and leave the directory in the temporary one (signals.js).
49
+ let scratch = ''
50
+ const undo = () => {
51
+ if (scratch) rmSync(scratch, { recursive: true, force: true })
52
+ }
53
+ holdSignals(undo)
54
+ try {
55
+ scratch = mkdtempSync(path.join(tmpdir(), 'sssb-create-template-'))
56
+ const meta = buildTemplate({
57
+ repoRoot,
58
+ outDir: scratch,
59
+ ...(workflowRef ? { workflowRef } : {}),
60
+ warn: (message) => console.warn(`@sssb/create: ${message}`),
61
+ })
62
+ const problem = unpushedPin({ repoRoot, ref: meta.workflow.ref, repository: meta.workflow.repository })
63
+ if (problem) console.warn(`\n@sssb/create: WARNING: ${problem}. Push it, or pass --workflow-ref <sha>.\n`)
64
+ return run(scratch)
65
+ } finally {
66
+ undo()
67
+ releaseSignals(undo)
68
+ }
69
+ }
70
+
71
+ async function main() {
72
+ const options = parseArgs(process.argv.slice(2))
73
+ if (options.help) {
74
+ console.log(USAGE)
75
+ return 0
76
+ }
77
+ if (!(await confirmed(options))) {
78
+ console.log('nothing written.')
79
+ return 0
80
+ }
81
+
82
+ /** @param {string} templateDir */
83
+ const create = (templateDir) =>
84
+ generate({
85
+ templateDir,
86
+ target: options.dir,
87
+ slug: options.slug,
88
+ name: options.name,
89
+ repo: options.repo,
90
+ owners: options.owners,
91
+ sssb: options.sssb,
92
+ workflowRef: options.workflowRef,
93
+ })
94
+ const packed = path.join(PACKAGE, 'template')
95
+ const result = existsSync(path.join(packed, META_FILE)) ? create(packed) : fromCheckout(options.workflowRef, create)
96
+ // A Ctrl-C (or SIGTERM, SIGHUP) that came while the template was built or the workspace written is dispatched
97
+ // before this resolves, undoes them and ends the process (signals.js), before anything says it was created.
98
+ await signalsSettled()
99
+
100
+ const fromHere = path.relative(process.cwd(), result.root)
101
+ const relative = fromHere === '' ? '.' : fromHere.startsWith('..') ? result.root : fromHere
102
+ const placeholders = [
103
+ ...(options.repo === null ? [`${PLACEHOLDER_OWNER}/${PLACEHOLDER_REPO} (--repo)`] : []),
104
+ ...(options.owners.length === 0 ? ['the code owner in CODEOWNERS (--owner)'] : []),
105
+ ]
106
+ console.log(`
107
+ Created ${options.name} in ${result.root}: ${result.files.length} files, the app in apps/${options.slug}/.
108
+
109
+ Next:
110
+ cd ${shellQuoted(relative)}
111
+ git init
112
+ pnpm install
113
+ pnpm --filter './apps/*' exec playwright install chromium
114
+ pnpm verify
115
+
116
+ \`pnpm dev\` then runs the app, seeded and offline, with no credentials.
117
+
118
+ On GitHub, require the check \`sssb / all-checks\` on your default branch (it fails unless every one of SSSB's
119
+ checks ran and passed), and turn on private vulnerability reporting. README.md lists the rest, and links SSSB's
120
+ guide to building on it.${placeholders.length > 0 ? `\nStill to fill in: ${placeholders.join('; ')}.` : ''}`)
121
+ return 0
122
+ }
123
+
124
+ main().then(
125
+ (status) => process.exit(status),
126
+ async (error) => {
127
+ // A failure a signal caused (a Ctrl-C reaches git, which the template build runs, too) ends as that signal.
128
+ await signalsSettled()
129
+ if (error instanceof CreateError) {
130
+ console.error(`@sssb/create: ${error.message}\n\n${USAGE}`)
131
+ process.exit(1)
132
+ }
133
+ throw error
134
+ },
135
+ )
package/package.json CHANGED
@@ -1,8 +1,25 @@
1
1
  {
2
2
  "name": "@sssb/create",
3
- "version": "0.0.0",
4
- "description": "Reserved for SSSB, a web app foundation maintained by SafeInsights. Not yet released.",
3
+ "version": "0.2.0",
5
4
  "license": "MIT",
6
- "repository": { "type": "git", "url": "git+https://github.com/safeinsights/sssb.git" },
7
- "files": ["README.md"]
8
- }
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/safeinsights/sssb.git",
8
+ "directory": "packages/create"
9
+ },
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).",
12
+ "bin": {
13
+ "sssb-create": "./bin/create.js"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "src",
18
+ "template",
19
+ "!src/**/*.test.*"
20
+ ],
21
+ "engines": {
22
+ "node": ">=24"
23
+ },
24
+ "scripts": {}
25
+ }
package/src/args.js ADDED
@@ -0,0 +1,270 @@
1
+ // @ts-check
2
+ // `@sssb/create`'s command line: one positional (the directory to create) and flags for everything else.
3
+ //
4
+ // The directory is the one argument the generator cannot do without, so it is positional. The rest is either
5
+ // derivable (the slug from the directory's name, the display name from the slug) or the adopter's identity (the
6
+ // repository and its code owners), and each of those wants its name at the call site: `--name "Acme Research"` says
7
+ // which of two strings is which.
8
+ import path from 'node:path'
9
+
10
+ export const PLACEHOLDER_OWNER = 'PLACEHOLDER_GITHUB_OWNER'
11
+ export const PLACEHOLDER_REPO = 'PLACEHOLDER_GITHUB_REPO'
12
+
13
+ export const USAGE = `usage: pnpm create @sssb <dir> [options] (npm create @sssb <dir> -- [options])
14
+
15
+ Creates a new SSSB app workspace in <dir>, which must not exist or be empty: the app under apps/<slug>/ (with its
16
+ own infra/), the workspace's config on SSSB's presets, the owner files and a CI workflow calling SSSB's checks.
17
+
18
+ --slug <slug> the app's slug: lowercase letters, digits and dashes, from a letter. It names the app's
19
+ directory (apps/<slug>), its package, its cookies and its database (default: <dir>'s
20
+ name, lowercased)
21
+ --name "<Name>" the app's display name, in its copy and titles (default: the slug, title-cased)
22
+ --repo <owner/name> the GitHub repository the workspace will live in, for the security, conduct and issue
23
+ links (default: ${PLACEHOLDER_OWNER}/${PLACEHOLDER_REPO}, for you to replace)
24
+ --owner <@handle> a code owner for CODEOWNERS, a user or an @org/team; repeat for several (default: a
25
+ placeholder, for you to replace)
26
+ --sssb <version|dir> the @sssb/* packages to depend on, at this generator's version: that version, exact or
27
+ with ^ or ~ (default: ^<this generator's version>), or a directory of their packed tarballs
28
+ (sssb-kit-*.tgz and the rest), which are then depended on by file: path
29
+ --workflow-ref <sha> the commit of SSSB's reusable workflow to pin (default: the commit this generator was
30
+ packed from)
31
+ --yes do not ask before writing
32
+ --help print this`
33
+
34
+ /** A failure with a message for the person at the terminal; the CLI prints it (with the usage) and exits 1. */
35
+ export class CreateError extends Error {
36
+ /** @param {string} message */
37
+ constructor(message) {
38
+ super(message)
39
+ this.name = 'CreateError'
40
+ }
41
+ }
42
+
43
+ /** What a slug is: lowercase letters, digits and dashes, from a letter (@sssb/cdk's SLUG). */
44
+ const SLUG = /^[a-z][a-z0-9-]*$/
45
+
46
+ /**
47
+ * Names Aurora PostgreSQL refuses as a database name, a copy of @sssb/cdk's list (its database-name.js), so a slug the
48
+ * construct would refuse at synth is refused here, where it is chosen. The generator depends on no SSSB package;
49
+ * tests/tooling/create-args.test.ts holds the two lists equal.
50
+ */
51
+ export const RESERVED_DATABASE_NAMES = new Set(
52
+ (
53
+ 'all analyse analyze and any array as asc asymmetric both case cast check collate column constraint create ' +
54
+ 'current_catalog current_date current_role current_time current_timestamp current_user default deferrable ' +
55
+ 'desc distinct do else end except false fetch for foreign from grant group having in initially intersect ' +
56
+ 'into lateral leading limit localtime localtimestamp not null offset on only or order placing primary ' +
57
+ 'references returning select session_user some symmetric system_user table then to trailing true union ' +
58
+ 'unique user using variadic when where window with postgres rdsadmin template0 template1'
59
+ ).split(' '),
60
+ )
61
+
62
+ /**
63
+ * Refuses a slug the app could not carry: the slug's shape, and the database it names (each dash an underscore, at
64
+ * most 63 characters, not a word the engine reserves), as @sssb/cdk's `databaseNameFor` would at synth.
65
+ * @param {string} slug
66
+ */
67
+ function checkSlug(slug) {
68
+ if (!SLUG.test(slug))
69
+ throw new CreateError(`"${slug}" is not a valid slug: lowercase letters, digits and dashes, from a letter`)
70
+ const database = slug.replaceAll('-', '_')
71
+ if (database.length > 63) throw new CreateError(`"${slug}" is too long: its database name may have 63 characters`)
72
+ if (RESERVED_DATABASE_NAMES.has(database))
73
+ throw new CreateError(`"${slug}" names the database "${database}", a word Aurora PostgreSQL reserves`)
74
+ }
75
+
76
+ /**
77
+ * The slug's title case, the default display name (`acme-research` is "Acme Research").
78
+ * @param {string} slug
79
+ */
80
+ function titleCase(slug) {
81
+ return slug
82
+ .split('-')
83
+ .filter(Boolean)
84
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
85
+ .join(' ')
86
+ }
87
+
88
+ /** The widest a display name may be, in columns (a wide character counts two): its longest line stays in 120. */
89
+ const NAME_COLUMNS = 60
90
+
91
+ /**
92
+ * The columns a string takes on a line, as Prettier counts them: a wide character (CJK, an emoji) takes two, a
93
+ * combining mark or a joiner none.
94
+ * @param {string} text
95
+ */
96
+ export function columns(text) {
97
+ let width = 0
98
+ for (const char of text) {
99
+ if (/^(?:\p{M}|\u200D|\uFE0F)$/u.test(char)) continue
100
+ const wide =
101
+ /\p{Extended_Pictographic}/u.test(char) ||
102
+ /[\u1100-\u115F\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{20000}-\u{3FFFD}]/u.test(
103
+ char,
104
+ )
105
+ width += wide ? 2 : 1
106
+ }
107
+ return width
108
+ }
109
+
110
+ /**
111
+ * The characters a display name may hold. It lands in TypeScript and JSON strings, an HTML `<title>`, markdown (a
112
+ * heading, the middle of a sentence) and the app's message catalogs, which next-intl reads as ICU messages; each of the
113
+ * characters left out means something in one of them (`* \` [ ] < > |` in markdown or HTML, `{ }` and `<tag>` in ICU,
114
+ * `\` and `$` in strings). `_`, `~`, `#` and `&` are let in where they mean nothing (displayName's NAME_RULES).
115
+ */
116
+ const NAME_CHARACTERS = /[^\p{L}\p{M}\p{N}\p{Extended_Pictographic} '’".,&()!?:/+%;=~_#-]/gu
117
+
118
+ /**
119
+ * Where `_`, `~`, `#` and `&` would mean something in markdown, each with why. `#` at the start is the start rule's.
120
+ * @type {[RegExp, string][]}
121
+ */
122
+ const NAME_RULES = [
123
+ [/(?<![\p{L}\p{N}])_|_(?![\p{L}\p{N}])/u, 'has a "_" that is not inside a word (markdown reads it as emphasis)'],
124
+ [/~.*~/u, 'has more than one "~" (markdown reads a pair as strikethrough)'],
125
+ [/\s#+$/u, 'ends in a "#" of its own (a markdown heading drops it)'],
126
+ // `&copy;`, `&#169;`: markdown reads a character reference as the character. Only `;` ends one, so `R&D` is text;
127
+ // `&#` is refused whatever follows.
128
+ [/&(?:#|[\p{L}\p{N}]+;)/u, 'has an "&" that markdown reads as a character reference (as in "&amp;" or "&#38;")'],
129
+ ]
130
+
131
+ /** The joiners an emoji sequence is built with (a zero-width joiner, an emoji presentation selector). */
132
+ const JOINERS = /\u200D|\uFE0F/gu
133
+
134
+ /**
135
+ * The display name, as every file it lands in can carry it, Prettier-stable: control characters (a newline, a tab, a
136
+ * bidirectional override) refused, whitespace trimmed and each run of it made one space, only the characters
137
+ * NAME_CHARACTERS allows and where NAME_RULES allows them, from a letter or a digit (a leading `-`, `1.` or `#` would make a markdown line a list or a
138
+ * heading), no `''` (an ICU message reads it as one apostrophe), at most NAME_COLUMNS wide.
139
+ * @param {string} raw
140
+ * @returns {string}
141
+ */
142
+ export function displayName(raw) {
143
+ if (/[\p{Cc}\u2028\u2029\u202A-\u202E\u2066-\u2069]/u.test(raw))
144
+ throw new CreateError(
145
+ `--name ${JSON.stringify(raw)} holds a control character (a newline, a tab): one line of text`,
146
+ )
147
+ const name = raw.trim().replace(/\s+/gu, ' ')
148
+ if (name === '') throw new CreateError('--name is empty')
149
+ const refused = [...new Set(name.replace(JOINERS, '').match(NAME_CHARACTERS) ?? [])]
150
+ if (refused.length > 0) {
151
+ throw new CreateError(
152
+ `--name "${name}" uses ${refused.map((char) => `"${char}"`).join(' ')}: a display name is letters, digits, ` +
153
+ `spaces and . , ' ’ " & ( ) ! ? : / + % ; = ~ _ # -, because the others mean something in the ` +
154
+ 'markdown, HTML and message catalogs it lands in',
155
+ )
156
+ }
157
+ if (!/^[\p{L}\p{N}]/u.test(name))
158
+ throw new CreateError(`--name "${name}" must start with a letter or a digit (it starts lines of markdown)`)
159
+ for (const [pattern, why] of NAME_RULES) if (pattern.test(name)) throw new CreateError(`--name "${name}" ${why}`)
160
+ if (name.includes("''"))
161
+ throw new CreateError(`--name "${name}" has two apostrophes in a row, which the app's messages read as one`)
162
+ if (columns(name) > NAME_COLUMNS) {
163
+ throw new CreateError(
164
+ `--name "${name}" is too long: at most ${NAME_COLUMNS} columns, a wide character counting two`,
165
+ )
166
+ }
167
+ return name
168
+ }
169
+
170
+ /**
171
+ * The GitHub repository, `owner/name`, in the characters GitHub allows.
172
+ * @param {string} repo
173
+ */
174
+ function checkRepo(repo) {
175
+ const match = /^([A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))\/([A-Za-z0-9._-]{1,100})$/.exec(repo)
176
+ if (!match || match[2] === '.' || match[2] === '..' || /\.git$/i.test(repo))
177
+ throw new CreateError(`--repo "${repo}" is not a GitHub repository: owner/name, as in acme/research`)
178
+ }
179
+
180
+ /**
181
+ * A code owner as CODEOWNERS names one: `@user` or `@org/team`. The `@` is added when it is left off.
182
+ * @param {string} owner
183
+ */
184
+ function normalOwner(owner) {
185
+ const handle = owner.startsWith('@') ? owner : `@${owner}`
186
+ if (!/^@[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})(?:\/[A-Za-z0-9._-]+)?$/.test(handle))
187
+ throw new CreateError(`--owner "${owner}" is not a GitHub user or team: @user or @org/team`)
188
+ return handle
189
+ }
190
+
191
+ /**
192
+ * @typedef {{
193
+ * dir: string,
194
+ * slug: string,
195
+ * name: string,
196
+ * repo: string | null,
197
+ * owners: string[],
198
+ * sssb: string | null,
199
+ * workflowRef: string | null,
200
+ * yes: boolean,
201
+ * help: boolean,
202
+ * }} Options
203
+ */
204
+
205
+ /**
206
+ * @param {string[]} argv
207
+ * @returns {Options}
208
+ */
209
+ export function parseArgs(argv) {
210
+ /** @type {{ dir: string | null, slug: string | null, name: string | null, repo: string | null, owners: string[], sssb: string | null, workflowRef: string | null, yes: boolean, help: boolean }} */
211
+ const options = {
212
+ dir: null,
213
+ slug: null,
214
+ name: null,
215
+ repo: null,
216
+ owners: [],
217
+ sssb: null,
218
+ workflowRef: null,
219
+ yes: false,
220
+ help: false,
221
+ }
222
+ /** @type {Record<string, (value: string) => void>} */
223
+ const takesValue = {
224
+ '--slug': (value) => (options.slug = value),
225
+ '--name': (value) => (options.name = value),
226
+ '--repo': (value) => (options.repo = value),
227
+ '--owner': (value) => options.owners.push(value),
228
+ '--sssb': (value) => (options.sssb = value),
229
+ '--workflow-ref': (value) => (options.workflowRef = value),
230
+ }
231
+ /** @type {Set<string>} */
232
+ const seen = new Set()
233
+ for (let index = 0; index < argv.length; index += 1) {
234
+ const arg = /** @type {string} */ (argv[index])
235
+ // `npm create @sssb <dir> -- --slug x` hands the `--` through; nothing here is a positional after it.
236
+ if (arg === '--') continue
237
+ const [flag, inline] = arg.startsWith('--') && arg.includes('=') ? arg.split(/=(.*)/s, 2) : [arg, undefined]
238
+ const setter = flag === undefined ? undefined : takesValue[flag]
239
+ if (setter && flag) {
240
+ if (flag !== '--owner' && seen.has(flag)) throw new CreateError(`${flag} given twice`)
241
+ seen.add(flag)
242
+ const value = inline ?? argv[index + 1]
243
+ if (value === undefined || value === '' || (inline === undefined && value.startsWith('--')))
244
+ throw new CreateError(`${flag} needs a value`)
245
+ setter(value)
246
+ if (inline === undefined) index += 1
247
+ } else if (arg === '--yes' || arg === '-y') options.yes = true
248
+ else if (arg === '--help' || arg === '-h') options.help = true
249
+ else if (arg.startsWith('-')) throw new CreateError(`unknown option ${arg}`)
250
+ else if (options.dir === null) options.dir = arg
251
+ else throw new CreateError(`unexpected argument "${arg}": the display name is a flag, --name "${arg}"`)
252
+ }
253
+ if (options.help) return { ...options, dir: options.dir ?? '', slug: '', name: '', help: true }
254
+ if (options.dir === null) throw new CreateError('name the directory to create')
255
+
256
+ const slug = options.slug ?? path.basename(path.resolve(options.dir)).toLowerCase()
257
+ if (options.slug === null && !SLUG.test(slug))
258
+ throw new CreateError(`the directory's name "${slug}" is not a valid slug: pass one with --slug`)
259
+ checkSlug(slug)
260
+ if (options.repo !== null) checkRepo(options.repo)
261
+ if (options.workflowRef !== null && !/^[0-9a-f]{40}$/.test(options.workflowRef))
262
+ throw new CreateError(`--workflow-ref "${options.workflowRef}" is not a full commit SHA (40 hex characters)`)
263
+ return {
264
+ ...options,
265
+ dir: options.dir,
266
+ slug,
267
+ name: displayName(options.name ?? titleCase(slug)),
268
+ owners: [...new Set(options.owners.map(normalOwner))],
269
+ }
270
+ }