@sssb/tools 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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/bin/sssb.js +102 -0
  3. package/package.json +89 -3
  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/check-demo-size.js +80 -0
  9. package/src/commands/check-doc-paths.js +48 -0
  10. package/src/commands/check-e2e.js +611 -0
  11. package/src/commands/check-fences.js +51 -0
  12. package/src/commands/check-real-env.js +165 -0
  13. package/src/commands/check-tmpdir-leak.js +78 -0
  14. package/src/commands/ci.js +350 -0
  15. package/src/commands/dev-tick.js +25 -0
  16. package/src/commands/doctor-checks.js +1276 -0
  17. package/src/commands/doctor-vitest.js +262 -0
  18. package/src/commands/doctor.js +954 -0
  19. package/src/commands/e2e-profile.js +94 -0
  20. package/src/commands/guide.js +108 -0
  21. package/src/commands/launch-json.js +55 -0
  22. package/src/commands/port.js +22 -0
  23. package/src/commands/serve-standalone.js +78 -0
  24. package/src/commands/tick.js +27 -0
  25. package/src/doc-paths.d.ts +106 -0
  26. package/src/doc-paths.js +328 -0
  27. package/src/framework-guard.js +35 -0
  28. package/src/kit.d.ts +43 -0
  29. package/src/kit.js +205 -0
  30. package/src/next.d.ts +16 -0
  31. package/src/next.js +55 -0
  32. package/src/ports.d.ts +72 -0
  33. package/src/ports.js +306 -0
  34. package/src/prune-mantine-css.js +171 -0
  35. package/src/testing/tmp-dir-marker.js +9 -0
  36. package/src/testing/tmp-dir-setup.d.ts +2 -0
  37. package/src/testing/tmp-dir-setup.js +9 -0
  38. package/src/testing/tmp-dir.d.ts +20 -0
  39. package/src/testing/tmp-dir.js +174 -0
  40. package/src/tick/dev-tick.js +128 -0
  41. package/src/tick/tick.js +315 -0
  42. package/src/tick/ticker-marker.d.ts +17 -0
  43. package/src/tick/ticker-marker.js +83 -0
  44. package/src/tick/ticker.d.ts +36 -0
  45. package/src/tick/ticker.js +142 -0
  46. package/src/vite.d.ts +38 -0
  47. package/src/vite.js +64 -0
  48. package/src/vitest.d.ts +21 -0
  49. package/src/vitest.js +55 -0
  50. package/tsconfig.base.json +33 -0
  51. package/README.md +0 -3
@@ -0,0 +1,611 @@
1
+ // @ts-check
2
+ // `sssb check-e2e [--app <dir>] [--config <file>]...`: fails when an e2e spec reaches the framework other than through
3
+ // `@sssb/kit/testing/e2e` (ADR-0014 part 2).
4
+ //
5
+ // Playwright loads specs with Node. In an adopter's workspace the framework is TypeScript under node_modules, which
6
+ // Node will not strip, and its modules read the app's seam (`@sssb/app-config/*`), which Node cannot resolve the way a
7
+ // bundler does. So the one entry a spec may reach is `@sssb/kit/testing/e2e`, which ships compiled and seam-free. A
8
+ // lint ban on direct imports is not enough, because a spec reaches the kit indirectly too (the showcase's
9
+ // tickets-pagination spec imports the app's src/domain/tickets, which imported the kit's state machine). So this
10
+ // BUNDLES every file Playwright loads with esbuild (the app's tsconfig `paths` honoured, a metafile kept) and fails,
11
+ // naming file and kit file, for any kit file reached other than that entry.
12
+ //
13
+ // WHAT IS BUNDLED, WHAT STAYS EXTERNAL: Playwright transforms every file outside node_modules and leaves packages under
14
+ // it to Node. So a bare specifier is FOLLOWED when its real path is outside node_modules (the app's own files, its `@/`
15
+ // alias, a sibling workspace package and whatever that imports) or is framework source in any copy (its nearest named
16
+ // package.json is `@sssb/kit`'s), and the seam always; every other package stays external. A `require()` esbuild can
17
+ // see is followed like an import. A function made by `createRequire(...)` it cannot see through, so a followed file
18
+ // outside the kit that names `createRequire` in its code and, as a string literal in its code, an `@sssb/kit`
19
+ // specifier esbuild did not resolve (other than the entry and the kit's `package.json`) fails too; the file is read
20
+ // by the app's own TypeScript parser, so a comment is not code. A computed specifier stays out of reach of any static
21
+ // check.
22
+ //
23
+ // WHICH FILES: Playwright is asked. Each Playwright config of the app (`playwright.config.*`,
24
+ // `playwright.<name>.config.*` in its directory), plus each `--config <file>` given (repeatable, relative to the
25
+ // working directory, as `playwright test -c` takes one: for a config kept outside the app's directory), is listed by
26
+ // the app's own Playwright, from the app's directory: `playwright test --list --reporter=json --config <file>`, the
27
+ // report written to a file (`PLAYWRIGHT_JSON_OUTPUT_FILE`), since a spec's own output shares stdout. Listing loads the
28
+ // config and every file it matches as a run does (so a config that computes its `testDir` or `require`s, and every
29
+ // project's `testDir`, `testMatch` and `testIgnore`, count exactly as Playwright counts them), but starts no
30
+ // `webServer`, runs no global setup and needs no browser. The checked files are each config, the global setup and
31
+ // teardown the report names, and every file holding a listed test; a support module is checked through every spec
32
+ // that imports it. A config Playwright cannot list fails with Playwright's own error, and when that error names a kit
33
+ // file other than the allowed entry, the kit file is named too (a spec reaching the kit's TypeScript under
34
+ // node_modules, as in an adopter's workspace, stops the listing: Node will not load it). A config that lists no test
35
+ // fails as well. Where the report falls short: it names only the FIRST entry of a `globalSetup` or `globalTeardown`
36
+ // array (Playwright's public config holds one), and a matched file holding no test is not listed.
37
+ //
38
+ // THE ENTRY: whatever `@sssb/kit/testing/e2e` resolves to from the app. For an installed kit that is the compiled
39
+ // `dist/testing/e2e.js`, and only that file is allowed (in any copy of the kit a sibling package installs). In IN-REPO
40
+ // MODE (SSSB's own repository, where the apps' tsconfig `paths` send `@sssb/kit/*` to packages/kit/src) it is the
41
+ // entry's source, so the entry's own source closure, computed by bundling the entry alone, is allowed, and that
42
+ // closure must itself reach no `@sssb/app-config` module.
43
+ import { spawnSync } from 'node:child_process'
44
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync } from 'node:fs'
45
+ import { createRequire, isBuiltin } from 'node:module'
46
+ import { tmpdir } from 'node:os'
47
+ import path from 'node:path'
48
+ import { fileURLToPath } from 'node:url'
49
+ import { stripVTControlCharacters as plain } from 'node:util'
50
+ import * as esbuild from 'esbuild'
51
+ import { takeAppDir, takeOption, UsageError, workspaceRootOf } from '../app.js'
52
+ import { kitDirOf, resolveFromApp } from '../kit.js'
53
+ import { isInRepoKit, seamOfKit } from './doctor-checks.js'
54
+
55
+ const KIT = '@sssb/kit'
56
+ const ENTRY = `${KIT}/testing/e2e`
57
+ /** Kit specifiers beside `createRequire` that load no framework code. */
58
+ const NOT_FRAMEWORK = new Set([ENTRY, `${KIT}/package.json`])
59
+ const KEEP = /^@sssb\/(kit|app-config)(\/|$)/
60
+ const PROBE = 'sssbCheckE2eProbe'
61
+ const CONFIG = /^playwright(\.[\w-]+)?\.config\.(c|m)?[jt]s$/
62
+ const USAGE = 'usage: check-e2e [--app <dir>] [--config <file>]...'
63
+ /** Indents a detail line under a FAIL line. */
64
+ const DETAIL = '\n '
65
+
66
+ /** @param {string} child @param {string} parent */
67
+ const inside = (child, parent) => child === parent || child.startsWith(parent + path.sep)
68
+
69
+ /** @param {string} file */
70
+ const real = (file) => (existsSync(file) ? realpathSync(file) : path.resolve(file))
71
+
72
+ /** @param {string} file */
73
+ const underNodeModules = (file) => file.split(path.sep).includes('node_modules')
74
+
75
+ /** @type {Map<string, string | null>} each directory's nearest named package.json: its directory when `@sssb/kit` */
76
+ const kitRoots = new Map()
77
+
78
+ /**
79
+ * The root of the `@sssb/kit` copy `file` belongs to (its nearest named package.json is `@sssb/kit`'s, as
80
+ * `isFrameworkFile` decides), or null when it is not framework source.
81
+ * @param {string} file an absolute, real path
82
+ * @returns {string | null}
83
+ */
84
+ function kitRootOf(file) {
85
+ if (!path.isAbsolute(file)) return null
86
+ /** @type {string[]} */
87
+ const walked = []
88
+ /** @type {string | null} */
89
+ let found = null
90
+ for (let dir = path.dirname(file); ; dir = path.dirname(dir)) {
91
+ const cached = kitRoots.get(dir)
92
+ if (cached !== undefined) {
93
+ found = cached
94
+ break
95
+ }
96
+ walked.push(dir)
97
+ const manifest = path.join(dir, 'package.json')
98
+ let name
99
+ try {
100
+ name = existsSync(manifest) ? JSON.parse(readFileSync(manifest, 'utf8'))?.name : undefined
101
+ } catch {
102
+ name = undefined
103
+ }
104
+ if (typeof name === 'string') {
105
+ found = name === KIT ? dir : null
106
+ break
107
+ }
108
+ if (path.dirname(dir) === dir) break
109
+ }
110
+ for (const dir of walked) kitRoots.set(dir, found)
111
+ return found
112
+ }
113
+
114
+ /**
115
+ * Bundles one entry the way check-e2e reads it, and returns esbuild's metafile, or the error that stopped it.
116
+ * @param {{ appDir: string, entry: { file: string } | { contents: string } }} options
117
+ */
118
+ async function bundle({ appDir, entry }) {
119
+ const tsconfig = path.join(appDir, 'tsconfig.json')
120
+ try {
121
+ const result = await esbuild.build({
122
+ ...('file' in entry
123
+ ? { entryPoints: [entry.file] }
124
+ : { stdin: { contents: entry.contents, resolveDir: appDir, sourcefile: '<entry>', loader: 'ts' } }),
125
+ absWorkingDir: appDir,
126
+ bundle: true,
127
+ metafile: true,
128
+ write: false,
129
+ platform: 'node',
130
+ format: 'esm',
131
+ logLevel: 'silent',
132
+ ...(existsSync(tsconfig) ? { tsconfig } : {}),
133
+ loader: { '.css': 'empty', '.svg': 'empty', '.png': 'empty', '.jpg': 'empty', '.woff2': 'empty' },
134
+ plugins: [
135
+ {
136
+ name: 'sssb-check-e2e-external',
137
+ setup(build) {
138
+ // A bare specifier is followed when it lands outside node_modules or in framework source (as
139
+ // Playwright transforms it); every other package stays external, as Node would load it.
140
+ build.onResolve({ filter: /^[^./]/ }, async (args) => {
141
+ if (args.pluginData?.[PROBE] || KEEP.test(args.path)) return undefined
142
+ if (isBuiltin(args.path)) return { external: true }
143
+ const resolved = await build.resolve(args.path, {
144
+ kind: args.kind,
145
+ resolveDir: args.resolveDir,
146
+ importer: args.importer,
147
+ pluginData: { [PROBE]: true },
148
+ })
149
+ if (resolved.errors.length > 0 || resolved.external || !resolved.path)
150
+ return { external: true }
151
+ const target = real(resolved.path)
152
+ if (!underNodeModules(target) || kitRootOf(target) !== null) return { path: resolved.path }
153
+ return { path: args.path, external: true }
154
+ })
155
+ },
156
+ },
157
+ ],
158
+ })
159
+ return { ok: /** @type {const} */ (true), metafile: result.metafile }
160
+ } catch (error) {
161
+ const errors = /** @type {{ errors?: { text: string, location?: { file: string } | null }[] }} */ (error).errors
162
+ const first = errors?.[0]
163
+ return {
164
+ ok: /** @type {const} */ (false),
165
+ error: first
166
+ ? `${first.text}${first.location ? ` (${first.location.file})` : ''}`
167
+ : error instanceof Error
168
+ ? error.message
169
+ : String(error),
170
+ }
171
+ }
172
+ }
173
+
174
+ /**
175
+ * What check-e2e reads of Playwright's JSON report (`playwright test --list --reporter=json`): a suite names its file,
176
+ * relative to `config.rootDir`, and holds suites and specs; every path in `config` is absolute.
177
+ * @typedef {{ file?: string, suites?: ListedSuite[], specs?: { file?: string }[] }} ListedSuite
178
+ * @typedef {{
179
+ * config: { rootDir: string, globalSetup: string | null, globalTeardown: string | null,
180
+ * projects: { testDir: string }[] },
181
+ * suites: ListedSuite[], errors: { message?: string }[] }} ListReport
182
+ */
183
+
184
+ /**
185
+ * The app's own Playwright CLI, or why there is none.
186
+ * @param {string} app
187
+ * @returns {{ cli: string } | { error: string }}
188
+ */
189
+ function playwrightCliOf(app) {
190
+ try {
191
+ const manifest = resolveFromApp(
192
+ app,
193
+ '@playwright/test/package.json',
194
+ 'lists the files its Playwright configs load',
195
+ )
196
+ const bin = JSON.parse(readFileSync(manifest, 'utf8')).bin
197
+ const relative = typeof bin === 'string' ? bin : bin?.playwright
198
+ if (typeof relative !== 'string') return { error: `${manifest} names no \`playwright\` bin` }
199
+ return { cli: path.join(path.dirname(manifest), relative) }
200
+ } catch (error) {
201
+ return { error: error instanceof Error ? error.message : String(error) }
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Asks the app's own Playwright which files one config loads: lists it from the app's directory, the JSON report
207
+ * written to a temporary file.
208
+ * @param {string} cli
209
+ * @param {string} config absolute
210
+ * @param {string} app
211
+ * @returns {{ report: ListReport, status: number | null } | { error: string }}
212
+ */
213
+ function listConfig(cli, config, app) {
214
+ const out = mkdtempSync(path.join(tmpdir(), 'sssb-check-e2e-'))
215
+ try {
216
+ const json = path.join(out, 'list.json')
217
+ /** @type {NodeJS.ProcessEnv} */
218
+ const env = { ...process.env, PLAYWRIGHT_JSON_OUTPUT_FILE: json, FORCE_COLOR: '0' }
219
+ delete env['PLAYWRIGHT_JSON_OUTPUT_DIR']
220
+ delete env['PLAYWRIGHT_JSON_OUTPUT_NAME']
221
+ const child = spawnSync(process.execPath, [cli, 'test', '--list', '--reporter=json', '--config', config], {
222
+ cwd: app,
223
+ env,
224
+ encoding: 'utf8',
225
+ timeout: 120_000,
226
+ maxBuffer: 64 * 1024 * 1024,
227
+ })
228
+ if (existsSync(json)) return { report: JSON.parse(readFileSync(json, 'utf8')), status: child.status }
229
+ // A config that does not load stops Playwright before any reporter: its error is on stderr. Node may print a
230
+ // warning and the throwing source line first; the error itself is the line that names one.
231
+ const said = plain(`${child.stderr ?? ''}\n${child.stdout ?? ''}`)
232
+ .split('\n')
233
+ .map((line) => line.trim())
234
+ .filter((line) => line && !line.startsWith('at '))
235
+ const thrown = said.filter((line) => /^([\w$.]*Error|Uncaught)\b/.test(line))
236
+ const shown = (thrown.length > 0 ? thrown : said).slice(0, 3).join(' | ') || 'no output'
237
+ return { error: `(exit ${child.status ?? child.signal}): ${child.error ? child.error.message : shown}` }
238
+ } finally {
239
+ rmSync(out, { recursive: true, force: true })
240
+ }
241
+ }
242
+
243
+ /**
244
+ * The absolute paths `text` names as `file://` URLs or quoted absolute paths.
245
+ * @param {string} text
246
+ */
247
+ function pathsNamedIn(text) {
248
+ const found = new Set()
249
+ for (const [url] of text.matchAll(/file:\/\/[^\s"'`)]+/g)) {
250
+ try {
251
+ found.add(fileURLToPath(url))
252
+ } catch {
253
+ // not a file URL after all
254
+ }
255
+ }
256
+ for (const [, file] of text.matchAll(/["'`](\/[^"'`\s]+)["'`]/g)) if (file !== undefined) found.add(file)
257
+ return [...found]
258
+ }
259
+
260
+ /**
261
+ * The app's Playwright configs and every file Playwright says they load, as above. `extraConfigs` are `--config`
262
+ * files, already absolute. `problems` holds each config Playwright cannot list or that lists no test. `kitFile`, when
263
+ * given, says whether a path is a kit file a spec may not reach, and shows it: a listing error naming one says so.
264
+ * @param {string} appDir
265
+ * @param {string[]} [extraConfigs]
266
+ * @param {(file: string) => string | null} [kitFile]
267
+ * @returns {Promise<{ configs: string[], testDirs: string[], files: string[], problems: string[] }>}
268
+ */
269
+ export async function playwrightFiles(appDir, extraConfigs = [], kitFile = () => null) {
270
+ const app = real(appDir)
271
+ const discovered = readdirSync(app)
272
+ .filter((name) => CONFIG.test(name))
273
+ .map((name) => path.join(app, name))
274
+ const configs = [...new Set([...discovered, ...extraConfigs.map(real)])].sort()
275
+ /** @param {string} file */
276
+ const shown = (file) => path.relative(app, file) || '.'
277
+ if (configs.length === 0) return { configs, testDirs: [], files: [], problems: [] }
278
+ const files = new Set(configs)
279
+ /** @type {Set<string>} */
280
+ const testDirs = new Set()
281
+ /** @type {string[]} */
282
+ const problems = []
283
+ const playwright = playwrightCliOf(app)
284
+ if ('error' in playwright) {
285
+ problems.push(`Playwright cannot be run from the app to list its configs: ${playwright.error}`)
286
+ return { configs, testDirs: [], files: [...files].sort(), problems }
287
+ }
288
+ for (const config of configs) {
289
+ const listed = listConfig(playwright.cli, config, app)
290
+ if ('error' in listed) {
291
+ problems.push(`${shown(config)} could not be listed by Playwright ${listed.error}`)
292
+ continue
293
+ }
294
+ const { report, status } = listed
295
+ const searched = [...new Set(report.config.projects.map((project) => project.testDir))].sort()
296
+ const errors = [...new Set(report.errors.map((e) => plain(e.message ?? '').trim()).filter(Boolean))]
297
+ const onlyNoTests = errors.length > 0 && errors.every((message) => message === 'Error: No tests found')
298
+ if (errors.length > 0 && !onlyNoTests) {
299
+ const reached = [...new Set(errors.flatMap(pathsNamedIn).map(kitFile))].filter((f) => f !== null).sort()
300
+ problems.push(
301
+ `${shown(config)} could not be listed by Playwright (exit ${status}): ` +
302
+ errors.map((message) => message.split('\n')[0]).join(' | ') +
303
+ reached
304
+ .map((f) => `${DETAIL}a file Playwright loads reaches ${f}, other than through ${ENTRY}`)
305
+ .join(''),
306
+ )
307
+ continue
308
+ }
309
+ for (const dir of searched) testDirs.add(dir)
310
+ for (const script of [report.config.globalSetup, report.config.globalTeardown])
311
+ if (script) files.add(real(script))
312
+ /** @type {Set<string>} */
313
+ const specs = new Set()
314
+ /** @param {ListedSuite} suite */
315
+ const collect = (suite) => {
316
+ for (const file of [suite.file, ...(suite.specs ?? []).map((spec) => spec.file)])
317
+ if (file) specs.add(real(path.resolve(report.config.rootDir, file)))
318
+ for (const child of suite.suites ?? []) collect(child)
319
+ }
320
+ for (const suite of report.suites) collect(suite)
321
+ if (specs.size === 0) {
322
+ problems.push(
323
+ `${shown(config)} lists no test (under ${searched.map(shown).join(', ')}): Playwright would find no tests in it`,
324
+ )
325
+ }
326
+ for (const spec of specs) files.add(spec)
327
+ }
328
+ return { configs, testDirs: [...testDirs].sort(), files: [...files].sort(), problems }
329
+ }
330
+
331
+ /**
332
+ * The real path of each input of a metafile, by its key (keys are relative to the app; `<entry>` is the stdin one).
333
+ * @param {esbuild.Metafile} metafile
334
+ * @param {string} appDir
335
+ * @returns {Map<string, string>}
336
+ */
337
+ function realPaths(metafile, appDir) {
338
+ return new Map(
339
+ Object.keys(metafile.inputs).map((key) => [key, key.startsWith('<') ? key : real(path.resolve(appDir, key))]),
340
+ )
341
+ }
342
+
343
+ /**
344
+ * The shortest import chain from `from` to `to` in a metafile, as metafile keys.
345
+ * @param {esbuild.Metafile} metafile
346
+ * @param {string} from
347
+ * @param {string} to
348
+ */
349
+ function chain(metafile, from, to) {
350
+ /** @type {Map<string, string | null>} */
351
+ const previous = new Map([[from, null]])
352
+ const queue = [from]
353
+ while (queue.length > 0) {
354
+ const at = /** @type {string} */ (queue.shift())
355
+ if (at === to) break
356
+ for (const imported of metafile.inputs[at]?.imports ?? []) {
357
+ if (imported.external || previous.has(imported.path) || !(imported.path in metafile.inputs)) continue
358
+ previous.set(imported.path, at)
359
+ queue.push(imported.path)
360
+ }
361
+ }
362
+ /** @type {string[]} */
363
+ const steps = []
364
+ for (let at = /** @type {string | null | undefined} */ (to); at; at = previous.get(at)) steps.unshift(at)
365
+ return steps[0] === from ? steps : [to]
366
+ }
367
+
368
+ /** @type {Map<string, typeof import('typescript')>} the app's own TypeScript, by app */
369
+ const typescripts = new Map()
370
+
371
+ /**
372
+ * The `@sssb/kit` specifiers `file` writes as string literals in its CODE, when its code also names `createRequire`
373
+ * (none otherwise). Read by the app's own TypeScript parser, as doctor reads the app's tsconfig: comments are not code.
374
+ * @param {string} app
375
+ * @param {string} file
376
+ * @param {string} text
377
+ * @returns {string[]}
378
+ */
379
+ function kitLiteralsBesideCreateRequire(app, file, text) {
380
+ let ts = typescripts.get(app)
381
+ if (ts === undefined) {
382
+ const resolved = resolveFromApp(
383
+ app,
384
+ 'typescript',
385
+ 'sssb check-e2e reads the files that name `createRequire` with',
386
+ )
387
+ ts = /** @type {typeof import('typescript')} */ (createRequire(import.meta.url)(resolved))
388
+ typescripts.set(app, ts)
389
+ }
390
+ const ext = path.extname(file)
391
+ const kind =
392
+ ext === '.tsx'
393
+ ? ts.ScriptKind.TSX
394
+ : ext === '.jsx'
395
+ ? ts.ScriptKind.JSX
396
+ : /^\.[cm]?ts$/.test(ext)
397
+ ? ts.ScriptKind.TS
398
+ : ts.ScriptKind.JS
399
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false, kind)
400
+ let creates = false
401
+ /** @type {string[]} */
402
+ const literals = []
403
+ /** @param {import('typescript').Node} node */
404
+ const visit = (node) => {
405
+ if (ts.isIdentifier(node) && node.text === 'createRequire') creates = true
406
+ else if (
407
+ (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) &&
408
+ /^@sssb\/kit(\/|$)/.test(node.text)
409
+ )
410
+ literals.push(node.text)
411
+ ts.forEachChild(node, visit)
412
+ }
413
+ visit(source)
414
+ return creates ? literals : []
415
+ }
416
+
417
+ /**
418
+ * @typedef {{ file: string, error?: string, reached: { kitFile: string, via: string[] }[], count: number,
419
+ * unfollowed: string[], throughEntry: boolean }} SpecReach
420
+ * `reached`: the kit files outside the entry that the file enters the kit through (each with its import chain);
421
+ * `count`: every kit file outside the entry it reaches; `unfollowed`: a kit specifier named beside `createRequire`
422
+ * that esbuild could not follow; `throughEntry`: whether it reaches the allowed entry at all
423
+ */
424
+
425
+ /**
426
+ * What `sssb check-e2e` checks, without printing: the entry, what it allows, and each file's reach.
427
+ * @param {string} appDir
428
+ * @param {string[]} [extraConfigs] `--config` files, absolute
429
+ */
430
+ export async function e2eReach(appDir, extraConfigs = []) {
431
+ const app = realpathSync(appDir)
432
+ const root = realpathSync(workspaceRootOf(app))
433
+ const kitDir = kitDirOf(app)
434
+ const inRepo = isInRepoKit(kitDir, root)
435
+ /** @param {string} file */
436
+ const show = (file) => {
437
+ const kitRoot = kitRootOf(file)
438
+ if (kitRoot === null) return path.relative(app, file)
439
+ const within = path.relative(kitRoot, file)
440
+ return kitRoot === kitDir ? `${KIT}:${within}` : `${KIT}(${path.relative(app, kitRoot)}):${within}`
441
+ }
442
+
443
+ // The entry, alone: what it resolves to, its closure, and whether that closure touches the seam.
444
+ const alone = await bundle({ appDir: app, entry: { contents: `export * from '${ENTRY}'\n` } })
445
+ if (!alone.ok) throw new UsageError(`sssb check-e2e: ${ENTRY} does not bundle from ${app}: ${alone.error}`)
446
+ const entryReal = realPaths(alone.metafile, app)
447
+ const closure = [...entryReal.values()].filter((file) => inside(file, kitDir))
448
+ const entryKey = alone.metafile.inputs['<entry>']?.imports.find((i) => !i.external)?.path
449
+ const entryFile = entryKey === undefined ? undefined : entryReal.get(entryKey)
450
+ if (entryFile === undefined || !inside(entryFile, kitDir)) {
451
+ throw new UsageError(`sssb check-e2e: ${ENTRY} does not resolve into the @sssb/kit ${app} resolves (${kitDir})`)
452
+ }
453
+ /** @type {string[]} */
454
+ const entryProblems = []
455
+ const seams = [seamOfKit(kitDir), real(path.join(app, 'src', 'app-config'))].filter((s) => s !== null)
456
+ for (const [key, input] of Object.entries(alone.metafile.inputs)) {
457
+ for (const imported of input.imports) {
458
+ if (/^@sssb\/app-config(\/|$)/.test(imported.original ?? ''))
459
+ entryProblems.push(`${show(entryReal.get(key) ?? key)} imports ${imported.original}`)
460
+ }
461
+ const file = entryReal.get(key) ?? key
462
+ if (seams.some((seam) => inside(file, seam))) entryProblems.push(`${show(file)} is a seam module`)
463
+ }
464
+ // An installed kit's entry is compiled into one file: only that file is allowed. In-repo, its source closure. By
465
+ // the path within the kit, so the same file of another copy (a sibling package's own install) is allowed too.
466
+ const allowed = new Set((inRepo ? closure : [entryFile]).map((file) => path.relative(kitDir, file)))
467
+ if (!inRepo) {
468
+ for (const file of closure)
469
+ if (file !== entryFile) entryProblems.push(`the compiled entry reaches another kit file, ${show(file)}`)
470
+ }
471
+ /** @param {string} file */
472
+ const isKit = (file) => kitRootOf(file) !== null
473
+ /** @param {string} file */
474
+ const isAllowed = (file) => {
475
+ const kitRoot = kitRootOf(file)
476
+ return kitRoot !== null && allowed.has(path.relative(kitRoot, file))
477
+ }
478
+
479
+ const {
480
+ configs,
481
+ testDirs,
482
+ files,
483
+ problems: configProblems,
484
+ } = await playwrightFiles(app, extraConfigs, (file) =>
485
+ isKit(real(file)) && !isAllowed(real(file)) ? show(real(file)) : null,
486
+ )
487
+ /** @type {SpecReach[]} */
488
+ const reach = []
489
+ for (const file of files) {
490
+ const result = await bundle({ appDir: app, entry: { file } })
491
+ if (!result.ok) {
492
+ reach.push({
493
+ file: path.relative(app, file),
494
+ error: result.error,
495
+ reached: [],
496
+ count: 0,
497
+ unfollowed: [],
498
+ throughEntry: false,
499
+ })
500
+ continue
501
+ }
502
+ const realOf = realPaths(result.metafile, app)
503
+ const outside = new Set([...realOf].filter(([, f]) => isKit(f) && !isAllowed(f)).map(([key]) => key))
504
+ const fromKey = path.relative(app, file).split(path.sep).join('/')
505
+ const start = fromKey in result.metafile.inputs ? fromKey : (Object.keys(result.metafile.inputs)[0] ?? fromKey)
506
+ // Report where the file ENTERS the kit: an outside kit file imported by a file that is not part of the kit.
507
+ const entered = [...outside].filter((key) =>
508
+ Object.entries(result.metafile.inputs).some(
509
+ ([importer, input]) =>
510
+ !isKit(realOf.get(importer) ?? importer) &&
511
+ input.imports.some((i) => i.path === key && !i.external),
512
+ ),
513
+ )
514
+ // What esbuild cannot see: a kit specifier beside `createRequire` in a followed file outside the kit.
515
+ /** @type {string[]} */
516
+ const unfollowed = []
517
+ for (const [key, input] of Object.entries(result.metafile.inputs)) {
518
+ const source = realOf.get(key) ?? key
519
+ if (!path.isAbsolute(source) || isKit(source) || underNodeModules(source)) continue
520
+ const text = readFileSync(source, 'utf8')
521
+ if (!/\bcreateRequire\b/.test(text)) continue
522
+ const seen = new Set(input.imports.map((i) => i.original))
523
+ for (const specifier of kitLiteralsBesideCreateRequire(app, source, text)) {
524
+ if (!NOT_FRAMEWORK.has(specifier) && !seen.has(specifier))
525
+ unfollowed.push(`${show(source)} names '${specifier}' beside createRequire`)
526
+ }
527
+ }
528
+ reach.push({
529
+ file: path.relative(app, file),
530
+ reached: (entered.length ? entered : [...outside]).sort().map((key) => ({
531
+ kitFile: show(realOf.get(key) ?? key),
532
+ via: chain(result.metafile, start, key).map((k) => show(realOf.get(k) ?? k)),
533
+ })),
534
+ count: outside.size,
535
+ unfollowed: [...new Set(unfollowed)].sort(),
536
+ throughEntry: [...realOf.values()].some(isAllowed),
537
+ })
538
+ }
539
+ return {
540
+ app,
541
+ root,
542
+ kitDir,
543
+ inRepo,
544
+ entryFile: show(entryFile),
545
+ allowed: [...allowed].map((within) => `${KIT}:${within}`).sort(),
546
+ entryProblems,
547
+ configs: configs.map((c) => path.relative(app, c)),
548
+ testDirs: testDirs.map((d) => path.relative(app, d) || '.'),
549
+ configProblems,
550
+ reach,
551
+ }
552
+ }
553
+
554
+ /** @param {string[]} args */
555
+ export async function run(args) {
556
+ const appDir = takeAppDir(args)
557
+ /** @type {string[]} */
558
+ const extraConfigs = []
559
+ for (let config = takeOption(args, '--config'); config !== undefined; config = takeOption(args, '--config')) {
560
+ const file = path.resolve(config)
561
+ if (!existsSync(file)) throw new UsageError(`sssb check-e2e: --config ${config}: no such file`)
562
+ extraConfigs.push(file)
563
+ }
564
+ if (args.length > 0) throw new UsageError(`sssb check-e2e: unknown argument ${args[0]} (${USAGE})`)
565
+ const r = await e2eReach(appDir, extraConfigs)
566
+ if (r.configs.length === 0) {
567
+ console.log(`sssb check-e2e: ${path.relative(r.root, r.app)} has no Playwright config: nothing to check`)
568
+ return 0
569
+ }
570
+ console.log(
571
+ `sssb check-e2e: ${path.relative(r.root, r.app) || '.'}: ${r.reach.length} file(s) Playwright loads ` +
572
+ `(${r.configs.join(', ')}; under ${r.testDirs.join(', ') || 'no testDir'}); ${ENTRY} is ${r.entryFile}` +
573
+ (r.inRepo ? ` (in-repo mode: its source closure is allowed: ${r.allowed.join(', ')})` : ''),
574
+ )
575
+ let problems = 0
576
+ for (const problem of r.configProblems) {
577
+ problems++
578
+ console.log(`FAIL ${problem}`)
579
+ }
580
+ for (const problem of r.entryProblems) {
581
+ problems++
582
+ console.log(`FAIL ${ENTRY} is not seam-free: ${problem}`)
583
+ }
584
+ for (const spec of r.reach) {
585
+ if (spec.error !== undefined) {
586
+ problems++
587
+ console.log(`FAIL ${spec.file}: could not be bundled: ${spec.error}`)
588
+ continue
589
+ }
590
+ if (spec.count > 0) {
591
+ problems++
592
+ console.log(`FAIL ${spec.file} reaches ${spec.count} @sssb/kit file(s) other than ${ENTRY}:`)
593
+ for (const { kitFile, via } of spec.reached) console.log(` ${kitFile} (${via.join(' -> ')})`)
594
+ }
595
+ if (spec.unfollowed.length > 0) {
596
+ problems++
597
+ console.log(`FAIL ${spec.file} loads @sssb/kit where esbuild cannot follow:`)
598
+ for (const line of spec.unfollowed) console.log(` ${line}`)
599
+ }
600
+ if (spec.count === 0 && spec.unfollowed.length === 0)
601
+ console.log(`ok ${spec.file}${spec.throughEntry ? ` (reaches the kit through ${ENTRY})` : ''}`)
602
+ }
603
+ const reaching = r.reach.some((spec) => spec.count > 0 || spec.unfollowed.length > 0)
604
+ console.log(
605
+ problems === 0
606
+ ? `sssb check-e2e: ok, no file reaches @sssb/kit other than through ${ENTRY}`
607
+ : `sssb check-e2e: ${problems} problem(s)` +
608
+ (reaching ? `: a spec may reach the kit only through ${ENTRY}, which Node can load` : ''),
609
+ )
610
+ return problems === 0 ? 0 : 1
611
+ }
@@ -0,0 +1,51 @@
1
+ // @ts-check
2
+ // `sssb check-fences`: the lint fences as the app's real config composes them (ADR-0014 part 3). An adopter's
3
+ // eslint.config.mjs composes `@sssb/eslint-plugin`'s preset with blocks of its own, and nothing inside a rule can see
4
+ // what a later block did to it. The probes and the comparison are the plugin's (`@sssb/eslint-plugin/check-fences`):
5
+ // every source file's effective config against the preset's, probe files linted through the app's config, each
6
+ // lint-exceptions.mjs entry (the named file exempt, a sibling not), and every fence finding in the app's own files,
7
+ // at any severity, suppressed by a directive or switched off by an inline config (ESLint reads the directives). This command
8
+ // resolves the plugin, and through it ESLint, from the app's own directory, as every tool here resolves what the app
9
+ // installed; @sssb/tools depends on neither.
10
+ import { existsSync } from 'node:fs'
11
+ import { createRequire } from 'node:module'
12
+ import path from 'node:path'
13
+ import { pathToFileURL } from 'node:url'
14
+ import { takeAppDir, UsageError } from '../app.js'
15
+
16
+ // The plugin's directory, WALKED up from the app's `node_modules` chain, never `require.resolve`d: Node's resolver falls
17
+ // back to NODE_PATH, and `pnpm exec` sets it to the workspace's hoisted `.pnpm/node_modules`, where an app that
18
+ // installs no plugin would find another package's (the same reason src/kit.js walks for @sssb/kit).
19
+ /** @param {string} appDir */
20
+ function pluginDirOf(appDir) {
21
+ for (let dir = appDir; ; dir = path.dirname(dir)) {
22
+ const candidate = path.join(dir, 'node_modules', '@sssb', 'eslint-plugin')
23
+ if (existsSync(path.join(candidate, 'package.json'))) return candidate
24
+ if (path.dirname(dir) === dir) return undefined
25
+ }
26
+ }
27
+
28
+ /** @param {string[]} args */
29
+ export async function run(args) {
30
+ const appDir = takeAppDir(args)
31
+ if (args.length > 0) throw new UsageError('usage: sssb check-fences [--app <dir>]')
32
+ const pluginDir = pluginDirOf(appDir)
33
+ if (!pluginDir) {
34
+ throw new UsageError(
35
+ `sssb check-fences: ${appDir} does not resolve @sssb/eslint-plugin. Add it to the app's devDependencies ` +
36
+ 'and compose its preset in the eslint.config.mjs that lints the app.',
37
+ )
38
+ }
39
+ // The package names itself: a self-reference through its own `exports`.
40
+ const entry = createRequire(path.join(pluginDir, 'package.json')).resolve('@sssb/eslint-plugin/check-fences')
41
+ /** @type {{ checkFences: (o: { appDir: string }) => Promise<{ problems: string[], files: number, probes: number }> }} */
42
+ const { checkFences } = await import(pathToFileURL(entry).href)
43
+ const { problems, files, probes } = await checkFences({ appDir })
44
+ if (problems.length === 0) {
45
+ console.log(`sssb check-fences: every fence holds (${files} source files compared, ${probes} probes)`)
46
+ return 0
47
+ }
48
+ console.error(`sssb check-fences: ${problems.length} problem(s) in ${appDir}:`)
49
+ for (const problem of problems) console.error(` ${problem}`)
50
+ return 1
51
+ }