@sssb/tools 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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/bin/sssb.js +102 -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/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,262 @@
1
+ // @ts-check
2
+ // How `sssb doctor` asks Vitest what would actually run (ADR-0014 part 3), instead of reading the config: `vitest
3
+ // list --filesOnly` with each config that could run an app's tests (it loads the config and globs, and runs no
4
+ // globalSetup), then a full `vitest list` with only the configs that must list check names, each read back as JSON
5
+ // from a file (stdout carries Vite's warnings beside it). What a CI step adds on its command line is not here to see
6
+ // (doctor reports what its scripts add).
7
+ import { spawnSync } from 'node:child_process'
8
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'
9
+ import { createRequire } from 'node:module'
10
+ import { tmpdir } from 'node:os'
11
+ import path from 'node:path'
12
+ import { pathToFileURL } from 'node:url'
13
+ import { readJson } from '../app.js'
14
+ import { aliasRoutes, packageDirFrom } from './doctor-checks.js'
15
+
16
+ /** @typedef {import('./doctor-checks.js').SeamRoute} SeamRoute */
17
+
18
+ const EXTENSIONS = ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs']
19
+
20
+ /**
21
+ * The other config files doctor asks about: every `vitest*.config.*` beyond the one a bare `vitest` loads
22
+ * (`vitest.contract.config.ts`, `vitest.ci.config.ts`, `vitest-e2e.config.mjs`...), each of which a command can name
23
+ * with `--config`. Vite configs are left out (`vite.config.*` counts only where Vitest itself loads it, see
24
+ * bareConfigIn; `vite.demo.config.ts` is a build config Vitest loads only when a command names it).
25
+ */
26
+ const VITEST_CONFIG = new RegExp(`^vitest[\\w.-]*\\.config\\.(${EXTENSIONS.join('|')})$`)
27
+
28
+ /** @typedef {{ cwd: string, config: string | null }} VitestRun where and with which config Vitest is run (null: none, Vitest's defaults) */
29
+
30
+ /**
31
+ * The config a bare `vitest` run in `dir` loads from `dir` itself, as Vitest looks (vitest.config.<ext>, then
32
+ * vite.config.<ext>, extensions in Vitest's order): so a `vite.config.*` beside a `vitest.config.*` is never it. Null
33
+ * when `dir` holds neither.
34
+ * @param {string} dir
35
+ * @returns {string | null}
36
+ */
37
+ function bareConfigIn(dir) {
38
+ for (const stem of ['vitest', 'vite']) {
39
+ for (const ext of EXTENSIONS) {
40
+ const file = path.join(dir, `${stem}.config.${ext}`)
41
+ if (existsSync(file)) return file
42
+ }
43
+ }
44
+ return null
45
+ }
46
+
47
+ /**
48
+ * The config a bare `vitest` run in `dir` loads, found as Vitest finds it: walking up from `dir` to the filesystem root,
49
+ * the first directory with a bareConfigIn. Null when there is none (Vitest then runs on its defaults).
50
+ * @param {string} dir
51
+ * @returns {string | null}
52
+ */
53
+ export function vitestDefaultConfig(dir) {
54
+ for (let at = path.resolve(dir); ; at = path.dirname(at)) {
55
+ const found = bareConfigIn(at)
56
+ if (found !== null) return found
57
+ if (path.dirname(at) === at) return null
58
+ }
59
+ }
60
+
61
+ /** @param {VitestRun} run */
62
+ export const runKey = (run) => `${run.cwd}\0${run.config ?? ''}`
63
+
64
+ /**
65
+ * WHERE VITEST COULD RUN AN APP'S TESTS (ADR-0014 part 3), in two lists:
66
+ *
67
+ * - `bare`: the runs a bare `vitest` would make for the app, in the order doctor tries them for the MAIN unit run:
68
+ * from the workspace root with the config the root holds itself, when it holds one; then from the app's directory
69
+ * with the config Vitest finds walking up from there (the app's own, else the root's, else none at all: Vitest's
70
+ * defaults);
71
+ * - `configs`: every config file at the root and in the app, each run from its own directory: the one a bare
72
+ * `vitest` loads there (bareConfigIn), and every other `vitest*.config.*`.
73
+ *
74
+ * Doctor cannot know which of them CI runs; which ones hold the app to which checks is planFor's (doctor.js).
75
+ * @param {string} root
76
+ * @param {string} appDir
77
+ * @returns {{ bare: VitestRun[], configs: VitestRun[] }}
78
+ */
79
+ export function vitestRunsFor(root, appDir) {
80
+ /** @param {VitestRun[]} runs */
81
+ const unique = (runs) => runs.filter((run, i) => runs.findIndex((r) => runKey(r) === runKey(run)) === i)
82
+ const atRoot = bareConfigIn(root)
83
+ const bare = unique([
84
+ ...(atRoot === null ? [] : [{ cwd: root, config: atRoot }]),
85
+ { cwd: appDir, config: vitestDefaultConfig(appDir) },
86
+ ])
87
+ const dirs = path.resolve(appDir) === path.resolve(root) ? [root] : [root, appDir]
88
+ const configs = unique(
89
+ dirs.flatMap((dir) => {
90
+ const own = bareConfigIn(dir)
91
+ const named = readdirSync(dir)
92
+ .filter((name) => VITEST_CONFIG.test(name))
93
+ .sort()
94
+ .map((name) => path.join(dir, name))
95
+ return [...(own === null ? [] : [own]), ...named].map((config) => ({ cwd: dir, config }))
96
+ }),
97
+ )
98
+ return { bare, configs }
99
+ }
100
+
101
+ /**
102
+ * The `vitest` CLI the directory `cwd` would run (`pnpm exec vitest` there): the nearest installed package, walking
103
+ * up. Null when none is installed.
104
+ * @param {string} cwd
105
+ */
106
+ function vitestCli(cwd) {
107
+ const dir = packageDirFrom(cwd, 'vitest')
108
+ if (dir === null) return null
109
+ const bin = readJson(path.join(dir, 'package.json')).bin
110
+ const relative = typeof bin === 'string' ? bin : bin?.vitest
111
+ return typeof relative === 'string' ? path.join(dir, relative) : null
112
+ }
113
+
114
+ /** The environment variable that sets the limit on one `vitest list`, in seconds. */
115
+ const TIMEOUT_ENV = 'SSSB_DOCTOR_VITEST_TIMEOUT'
116
+
117
+ /** The limit on one `vitest list`, in whole milliseconds: `SSSB_DOCTOR_VITEST_TIMEOUT` seconds when set, else 120 s. */
118
+ function listTimeoutMs() {
119
+ const seconds = Number(process.env[TIMEOUT_ENV])
120
+ return Number.isFinite(seconds) && seconds > 0 ? Math.min(Math.ceil(seconds * 1000), 2 ** 31 - 1) : 120_000
121
+ }
122
+
123
+ /** The exit code the launcher gives when it stopped Vitest at the limit. */
124
+ const TIMED_OUT = 124
125
+
126
+ /**
127
+ * Runs Vitest (`process.argv` after the limit) in a process group of its own and, at the limit (ms), kills the whole
128
+ * group, so no pool worker of a listing that never finished outlives it (killing Vitest's own process leaves them
129
+ * running), then exits TIMED_OUT. Otherwise it exits with Vitest's code. Run with `node -e`, so it ships as this string.
130
+ */
131
+ const LAUNCHER = `
132
+ const { spawn } = require('node:child_process')
133
+ const [limit, ...args] = process.argv.slice(1)
134
+ const child = spawn(process.execPath, args, { stdio: 'inherit', detached: process.platform !== 'win32' })
135
+ const stop = () => {
136
+ try { process.kill(process.platform === 'win32' ? child.pid : -child.pid, 'SIGKILL') } catch {}
137
+ }
138
+ const timer = setTimeout(() => { stop(); process.exit(${TIMED_OUT}) }, Number(limit))
139
+ child.on('exit', (code) => { clearTimeout(timer); stop(); process.exit(code ?? 1) })
140
+ `
141
+
142
+ /** @typedef {{ name: string, file: string, projectName?: string }} ListedTest */
143
+ /** @typedef {{ file: string, projectName?: string }} ListedFile */
144
+
145
+ /**
146
+ * `vitest list --json=<file>`, with `--filesOnly` or not, from `run.cwd`, selecting `projects` (none: all). Returns
147
+ * what it listed, or the error Vitest stopped with (a test file that throws while it is collected stops the list,
148
+ * and Vitest then writes no JSON at all). A listing that runs past `timeoutMs` is killed, its workers with it, and
149
+ * reported as an error with `timedOut`, so nothing it waits on can hang doctor.
150
+ * @param {VitestRun} run
151
+ * @param {{ filesOnly?: boolean, projects?: readonly string[], timeoutMs?: number }} [options]
152
+ * @returns {{ ok: true, listed: ListedTest[] } | { ok: false, error: string, timedOut?: true }}
153
+ */
154
+ export function vitestList(run, { filesOnly = false, projects = [], timeoutMs = listTimeoutMs() } = {}) {
155
+ const cli = vitestCli(run.cwd)
156
+ if (cli === null) return { ok: false, error: `no vitest is installed for ${run.cwd}` }
157
+ const scratch = mkdtempSync(path.join(tmpdir(), 'sssb-doctor-'))
158
+ try {
159
+ const out = path.join(scratch, 'list.json')
160
+ const args = [cli, 'list', `--json=${out}`]
161
+ if (filesOnly) args.push('--filesOnly')
162
+ if (run.config) args.push('--config', run.config)
163
+ for (const project of projects) args.push('--project', project)
164
+ const result = spawnSync(process.execPath, ['-e', LAUNCHER, String(timeoutMs), ...args], {
165
+ cwd: run.cwd,
166
+ encoding: 'utf8',
167
+ env: { ...process.env, VITE_CONFIG_NATIVE_IGNORE_WARNING: 'true' },
168
+ maxBuffer: 64 * 1024 * 1024,
169
+ // The launcher's own limit, past Vitest's: should the launcher itself stall, this one still returns.
170
+ timeout: timeoutMs + 10_000,
171
+ killSignal: 'SIGKILL',
172
+ })
173
+ const output = `${result.stderr ?? ''}\n${result.stdout ?? ''}`
174
+ if (
175
+ result.status === TIMED_OUT ||
176
+ /** @type {NodeJS.ErrnoException | undefined} */ (result.error)?.code === 'ETIMEDOUT'
177
+ ) {
178
+ return {
179
+ ok: false,
180
+ timedOut: true,
181
+ error: `vitest list did not finish within ${timeoutMs / 1000}s, so doctor stopped it (${TIMEOUT_ENV} sets the limit, in seconds)`,
182
+ }
183
+ }
184
+ if (result.status === 0 && existsSync(out)) return { ok: true, listed: JSON.parse(readFileSync(out, 'utf8')) }
185
+ return { ok: false, error: vitestError(output, result.status) }
186
+ } finally {
187
+ rmSync(scratch, { recursive: true, force: true })
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Vitest's error line (`Error: ...`, `TypeError: ...`), without the source excerpt and stack below it; else the first
193
+ * line that says Error, else the last line. Vitest's section banners (`⎯⎯⎯ Collect Error ⎯⎯⎯`) are never picked.
194
+ * @param {string} output
195
+ * @param {number | null} status
196
+ */
197
+ function vitestError(output, status) {
198
+ const lines = output
199
+ .split('\n')
200
+ .map((line) => line.trim())
201
+ .filter((line) => line !== '' && !line.includes('⎯'))
202
+ const picked =
203
+ lines.find((line) => /^\w*Error\b.*:/.test(line)) ??
204
+ lines.find((line) => /\b\w*Error\b/.test(line)) ??
205
+ lines.at(-1)
206
+ return `vitest list exited ${status ?? 'by a signal'}${picked ? `: ${picked}` : ''}`
207
+ }
208
+
209
+ /**
210
+ * The names of the projects that run any test file inside `appDir`, from a `--filesOnly` listing.
211
+ * @param {readonly ListedFile[]} files
212
+ * @param {string} appDir
213
+ * @returns {string[]}
214
+ */
215
+ export function projectsRunning(files, appDir) {
216
+ const inside = path.resolve(appDir) + path.sep
217
+ return [
218
+ ...new Set(
219
+ files
220
+ .filter((entry) => path.resolve(entry.file).startsWith(inside))
221
+ .map((entry) => entry.projectName ?? ''),
222
+ ),
223
+ ]
224
+ }
225
+
226
+ /**
227
+ * Each project's aliases that would match an `@sssb/app-config` specifier, with where each sends it (aliasRoutes), as
228
+ * Vitest itself resolves the config (in-repo mode's alias check), through the Vitest the run directory installs. An
229
+ * empty list for a project without such an alias.
230
+ * @param {VitestRun} run
231
+ * @param {readonly string[]} projects
232
+ * @param {string} own the app's own seam directory (real path)
233
+ * @returns {Promise<Map<string, SeamRoute[]>>}
234
+ */
235
+ export async function seamAliases(run, projects, own) {
236
+ const vitestNode = createRequire(path.join(run.cwd, 'package.json')).resolve('vitest/node')
237
+ const { createVitest } = await import(pathToFileURL(vitestNode).href)
238
+ // Vite's notice about its future config loader is not doctor's to print (the `vitest list` children set it too).
239
+ process.env['VITE_CONFIG_NATIVE_IGNORE_WARNING'] ??= 'true'
240
+ const vitest = await createVitest(
241
+ 'test',
242
+ {
243
+ watch: false,
244
+ ...(run.config ? { config: run.config } : {}),
245
+ ...(projects.length ? { project: [...projects] } : {}),
246
+ },
247
+ {},
248
+ )
249
+ /** @type {Map<string, SeamRoute[]>} */
250
+ const aliases = new Map()
251
+ try {
252
+ for (const project of vitest.projects) {
253
+ // Vite hands every project its aliases as one array of { find, replacement }, the object form converted.
254
+ /** @type {{ find: string | RegExp, replacement: string }[]} */
255
+ const list = project.vite.config.resolve.alias
256
+ aliases.set(project.name, aliasRoutes(list, own))
257
+ }
258
+ } finally {
259
+ await vitest.close()
260
+ }
261
+ return aliases
262
+ }