@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,128 @@
1
+ // @ts-check
2
+ // What `pnpm dev` runs: the app's `next dev`, plus, only when asked, `pnpm tick` on a timer.
3
+ //
4
+ // DEV_TICK_SECONDS=30 pnpm dev # also tick the scheduler every 30 seconds
5
+ // pnpm dev # as before: nothing ticks it
6
+ //
7
+ // OFF BY DEFAULT, and not by oversight (docs/decision-log.md, "`pnpm tick`, and a dev ticker that is opt-in"). The
8
+ // showcase's Simulator controls the world clock in a demo and says when a digest fires; the e2e suites expect a
9
+ // scheduler that does nothing until a test asks; and hermetic dev does not do work nobody asked for. So the ticker is a
10
+ // variable you set, never a default, and the places that must stay quiet say so themselves:
11
+ //
12
+ // * Playwright starts the server with `pnpm dev` and blanks `DEV_TICK_SECONDS` for it (both apps' playwright
13
+ // configs), so a value in your shell never reaches a server Playwright starts;
14
+ // * Playwright ADOPTS a dev server already on its port when it is not on CI, so a ticking server you left running
15
+ // would be adopted: while a ticker runs it leaves a marker (ticker-marker.js) and both playwright configs
16
+ // refuse to load while one is live;
17
+ // * `E2E_BUILD` and `DEMO_MODE` are the build-time switches of the e2e build and the demo build. Those servers
18
+ // start from `sssb serve-standalone`, not from here, but a ticker asked for with either set is refused and
19
+ // said so, rather than trusted to be unreachable;
20
+ // * the file:// static demo has no server at all, so there is nothing to tick.
21
+ //
22
+ // This wraps `next dev`, it does not live inside the app: the app's source stays free of any reading of
23
+ // `process.env`, and nothing in the server changes. The ticking itself is ticker.js, which owns start, stop,
24
+ // the interval and its status and knows nothing of the environment: this file is the policy for `pnpm dev`.
25
+ import { spawn } from 'node:child_process'
26
+ import { foreignAppSlotProblem, portFor } from '../ports.js'
27
+ import { tickAppNames, tickSlot } from './tick.js'
28
+ import { createTicker, intervalProblem } from './ticker.js'
29
+ import { tickerMarkerPath } from './ticker-marker.js'
30
+
31
+ const DEV_TICK_VARIABLE = 'DEV_TICK_SECONDS'
32
+
33
+ /**
34
+ * What the environment asks of the ticker.
35
+ *
36
+ * @param {Record<string, string | undefined>} env
37
+ * @returns {{ mode: 'off' } | { mode: 'refused', reason: string } | { mode: 'on', seconds: number } | { mode: 'invalid', reason: string }}
38
+ */
39
+ export function resolveDevTick(env) {
40
+ const raw = env[DEV_TICK_VARIABLE]
41
+ if (raw === undefined || raw.trim() === '') return { mode: 'off' }
42
+ const seconds = Number(raw)
43
+ const problem = intervalProblem(seconds)
44
+ if (problem) {
45
+ return {
46
+ mode: 'invalid',
47
+ reason: `${DEV_TICK_VARIABLE} must be ${problem} (or unset, for no ticker), got "${raw}"`,
48
+ }
49
+ }
50
+ const blocker = ['E2E_BUILD', 'DEMO_MODE'].find((name) => env[name])
51
+ if (blocker) {
52
+ return {
53
+ mode: 'refused',
54
+ reason: `${DEV_TICK_VARIABLE} is ignored while ${blocker} is set: the ticker never runs under e2e or the demo`,
55
+ }
56
+ }
57
+ return { mode: 'on', seconds }
58
+ }
59
+
60
+ /**
61
+ * `sssb dev-tick <app> -- <command...>`
62
+ *
63
+ * @param {string[]} argv
64
+ * @param {import('../ports.d.ts').PortDeclaration} [declared] the port slot the app in the working directory declares
65
+ * @returns {{ app: string, command: string[] } | { error: string }}
66
+ */
67
+ export function parseDevArgs(argv, declared) {
68
+ const dash = argv.indexOf('--')
69
+ const app = argv[0]
70
+ if (dash !== 1 || argv.length < 3 || tickSlot(app, declared) === undefined) {
71
+ return {
72
+ error:
73
+ (dash === 1 && foreignAppSlotProblem(app, declared)) ||
74
+ `usage: sssb dev-tick <${tickAppNames(declared).join('|')}> -- <the dev server's command...>`,
75
+ }
76
+ }
77
+ return { app, command: argv.slice(dash + 1) }
78
+ }
79
+
80
+ /**
81
+ * @param {string[]} argv
82
+ * @param {import('../ports.d.ts').PortDeclaration} [declared] the port slot the app in the working directory declares
83
+ */
84
+ export async function main(argv, declared) {
85
+ const parsed = parseDevArgs(argv, declared)
86
+ if ('error' in parsed) {
87
+ console.error(parsed.error)
88
+ return 2
89
+ }
90
+ const wanted = resolveDevTick(process.env)
91
+ if (wanted.mode === 'invalid') {
92
+ // Before the server starts: a typo'd variable is a mistake to fix, not a ticker to quietly not have.
93
+ console.error(`dev: ${wanted.reason}`)
94
+ return 2
95
+ }
96
+ if (wanted.mode === 'refused') console.warn(`[tick] ${wanted.reason}`)
97
+
98
+ const child = spawn(parsed.command[0], parsed.command.slice(1), {
99
+ stdio: 'inherit',
100
+ shell: process.platform === 'win32',
101
+ })
102
+
103
+ // This process is now the pid a supervisor holds (it was `next` itself when the script was a bare `next dev`), so
104
+ // every signal that stopped the server has to reach it. A terminal's Ctrl-C reaches the child directly as well, so
105
+ // `next` sees SIGINT twice, which it tolerates (checked: SIGINT to the whole process group of `pnpm dev` with a real
106
+ // `next dev` exited 0, removed the marker and left no process behind).
107
+ for (const name of /** @type {const} */ (['SIGINT', 'SIGTERM', 'SIGHUP'])) process.on(name, () => child.kill(name))
108
+
109
+ const origin = `http://localhost:${portFor(/** @type {import('../ports.d.ts').PortDeclaration} */ (tickSlot(parsed.app, declared)))}`
110
+ const ticker = createTicker({ origin, markerFile: tickerMarkerPath() })
111
+ if (wanted.mode === 'on') {
112
+ console.log(
113
+ `[tick] ${DEV_TICK_VARIABLE}=${wanted.seconds}: ticking ${origin} every ${wanted.seconds}s (pnpm tick does it once)`,
114
+ )
115
+ ticker.start(wanted.seconds)
116
+ }
117
+
118
+ return await new Promise((resolve) => {
119
+ child.on('error', (error) => {
120
+ console.error(`dev: could not start ${parsed.command[0]}: ${error.message}`)
121
+ void ticker.stop().then(() => resolve(1))
122
+ })
123
+ child.on('exit', (code, signal) => {
124
+ const status = code ?? (signal ? 128 + (signal === 'SIGINT' ? 2 : signal === 'SIGTERM' ? 15 : 1) : 1)
125
+ void ticker.stop().then(() => resolve(status))
126
+ })
127
+ })
128
+ }
@@ -0,0 +1,317 @@
1
+ // @ts-check
2
+ // `sssb tick <app>` (an app's `pnpm tick`) — calls the running dev server's scheduled-tick route once and says what ran.
3
+ //
4
+ // In a deployment an external scheduler POSTs each app's `/api/webhooks/cron` (the `scheduled-tick` cutover row).
5
+ // In `pnpm dev` nothing does, so a due digest or a webhook retry sits there until somebody does it by hand. This is
6
+ // the by-hand, as one command; `sssb dev-tick` (dev-tick.js) is the same call on a timer, opt-in.
7
+ //
8
+ // What this is NOT: a way around the route's guard. The route is `withWebhookSecret(...)`, and this sends it the
9
+ // per-checkout dev secret (`<app>/.data/auth/webhook-secret`, the file the simulated server generates) in its header,
10
+ // exactly as an external caller would. It adds nothing to the server: no flag, no header beyond the credential every
11
+ // caller sends, no route. A server in real mode checks `WEBHOOK_SECRET` instead, never reads that file, and answers this 401.
12
+ //
13
+ // Run through the package script (`pnpm tick`, `pnpm tick:starter`): the working directory is then the app's, which is
14
+ // where the server keeps `.data` (`APP_DATA_DIR` overrides it, for both).
15
+ import { existsSync, readFileSync } from 'node:fs'
16
+ import path from 'node:path'
17
+ import { foreignAppSlotProblem, portFor } from '../ports.js'
18
+
19
+ /**
20
+ * The built-in apps that have a tick route. The key is the PORT key (a slot, not the app's name, so it survives a
21
+ * rename of the app). An app that declares a slot of its own (`"sssb": { "port": { "name": … } }`) ticks under that
22
+ * name, which `tickSlot` resolves from the declaration the command read.
23
+ */
24
+ const TICK_APPS = ['showcase', 'starter']
25
+
26
+ /**
27
+ * What an app name on a tick command line means: a built-in app, or the slot the app in the working directory
28
+ * declares under that name. Undefined when it is neither.
29
+ * @param {string} app
30
+ * @param {import('../ports.d.ts').PortDeclaration | undefined} [declared]
31
+ * @returns {import('../ports.d.ts').PortDeclaration | undefined}
32
+ */
33
+ export function tickSlot(app, declared) {
34
+ // Another app's built-in slot is no app of this one's when it declares a slot of its own (foreignAppSlotProblem).
35
+ if (TICK_APPS.includes(app)) {
36
+ return foreignAppSlotProblem(app, declared) === null
37
+ ? /** @type {import('../ports.d.ts').PortService} */ (app)
38
+ : undefined
39
+ }
40
+ return declared !== undefined && typeof declared === 'object' && declared.name === app ? declared : undefined
41
+ }
42
+
43
+ /**
44
+ * The names `tickSlot` accepts, for a usage message.
45
+ * @param {import('../ports.d.ts').PortDeclaration | undefined} [declared]
46
+ */
47
+ export function tickAppNames(declared) {
48
+ return typeof declared === 'object' ? [declared.name] : [...TICK_APPS]
49
+ }
50
+
51
+ export const TICK_PATH = '/api/webhooks/cron'
52
+
53
+ /** A cold `next dev` compiles the route on its first hit, so the default is generous. */
54
+ export const DEFAULT_TIMEOUT_SECONDS = 60
55
+
56
+ /** Bounds that keep `AbortSignal.timeout` meaningful: a value that rounds to 0 times out at once, a huge one throws. */
57
+ const MIN_TIMEOUT_SECONDS = 0.1
58
+ const MAX_TIMEOUT_SECONDS = 3600
59
+
60
+ const USAGE = `usage: pnpm tick [--url <origin>] [--timeout <seconds>] (sssb tick also takes --app <dir>)
61
+ (with no slot it ticks the app's own, the slot its package.json declares; or name one: sssb tick <${TICK_APPS.join('|')}, or the slot an app declares for itself> ...)
62
+
63
+ --url <origin> the dev server's origin, loopback only (default: this checkout's port for the app)
64
+ --timeout <seconds> give up on the request after this long, ${MIN_TIMEOUT_SECONDS} to ${MAX_TIMEOUT_SECONDS} (default ${DEFAULT_TIMEOUT_SECONDS})`
65
+
66
+ /** A failure with a message meant for the person at the terminal. `usage` marks a bad command line, not a bad tick. */
67
+ export class TickError extends Error {
68
+ /** @param {string} message @param {{ usage?: boolean }} [options] */
69
+ constructor(message, { usage = false } = {}) {
70
+ super(message)
71
+ this.name = 'TickError'
72
+ this.usage = usage
73
+ }
74
+ }
75
+
76
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
77
+
78
+ /**
79
+ * Loopback only. The secret is the dev secret and it is sent in the clear, so a URL that is not this machine is
80
+ * refused rather than trusted: there is no flag to point this at a real deployment, whose scheduler is not this.
81
+ *
82
+ * @param {string} value
83
+ * @returns {string} the origin, without a trailing slash
84
+ */
85
+ export function parseLoopbackOrigin(value) {
86
+ let url
87
+ try {
88
+ url = new URL(value)
89
+ } catch {
90
+ throw new TickError(`--url must be an origin like http://localhost:3000, got "${value}"`, { usage: true })
91
+ }
92
+ if (url.protocol !== 'http:' || !LOOPBACK_HOSTS.has(url.hostname)) {
93
+ throw new TickError(
94
+ `--url must be http on localhost, 127.0.0.1 or [::1] (the dev secret is sent in the clear), got "${value}"`,
95
+ { usage: true },
96
+ )
97
+ }
98
+ return url.origin
99
+ }
100
+
101
+ /**
102
+ * @param {string[]} argv the arguments after the script name
103
+ * @param {import('../ports.d.ts').PortDeclaration} [declared] the port slot the app in the working directory declares
104
+ * @returns {{ app: string, origin: string, timeoutMs: number }}
105
+ */
106
+ export function parseTickArgs(argv, declared) {
107
+ /** @type {string | undefined} */
108
+ let app
109
+ /** @type {string | undefined} */
110
+ let url
111
+ let timeoutSeconds = DEFAULT_TIMEOUT_SECONDS
112
+
113
+ for (let i = 0; i < argv.length; i++) {
114
+ const arg = argv[i]
115
+ const flag = arg.startsWith('--') ? arg.split('=', 1)[0] : null
116
+ if (flag === '--url' || flag === '--timeout') {
117
+ const inline = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : undefined
118
+ const value = inline ?? argv[++i]
119
+ if (value === undefined || value === '' || (inline === undefined && value.startsWith('--'))) {
120
+ throw new TickError(`${flag} needs a value`, { usage: true })
121
+ }
122
+ if (flag === '--url') {
123
+ url = value
124
+ } else {
125
+ const parsed = Number(value)
126
+ if (!Number.isFinite(parsed) || parsed < MIN_TIMEOUT_SECONDS || parsed > MAX_TIMEOUT_SECONDS) {
127
+ throw new TickError(
128
+ `--timeout must be between ${MIN_TIMEOUT_SECONDS} and ${MAX_TIMEOUT_SECONDS} seconds, got "${value}"`,
129
+ { usage: true },
130
+ )
131
+ }
132
+ timeoutSeconds = parsed
133
+ }
134
+ } else if (arg.startsWith('-')) {
135
+ throw new TickError(`unknown option "${arg}"`, { usage: true })
136
+ } else if (app === undefined) {
137
+ app = arg
138
+ } else {
139
+ throw new TickError(`unexpected argument "${arg}"`, { usage: true })
140
+ }
141
+ }
142
+
143
+ if (app === undefined) throw new TickError('which app? the first argument is the app', { usage: true })
144
+ const slot = tickSlot(app, declared)
145
+ if (slot === undefined) {
146
+ throw new TickError(
147
+ foreignAppSlotProblem(app, declared) ??
148
+ `unknown app "${app}" (known: ${tickAppNames(declared).join(', ')})`,
149
+ { usage: true },
150
+ )
151
+ }
152
+
153
+ let origin
154
+ if (url !== undefined) {
155
+ origin = parseLoopbackOrigin(url)
156
+ } else {
157
+ try {
158
+ origin = `http://localhost:${portFor(slot)}`
159
+ } catch (error) {
160
+ throw new TickError(error instanceof Error ? error.message : String(error), { usage: true })
161
+ }
162
+ }
163
+ return { app, origin, timeoutMs: Math.round(timeoutSeconds * 1000) }
164
+ }
165
+
166
+ /**
167
+ * Where the simulated server keeps its inbound-webhook secret: `dataDir('auth')` in the kit
168
+ * (`APP_DATA_DIR`, else `.data` under the app's working directory) plus `webhook-secret`.
169
+ *
170
+ * @param {Record<string, string | undefined>} [env]
171
+ * @param {string} [cwd]
172
+ */
173
+ export function secretFilePath(env = process.env, cwd = process.cwd()) {
174
+ return path.join(env.APP_DATA_DIR ?? path.join(cwd, '.data'), 'auth', 'webhook-secret')
175
+ }
176
+
177
+ /**
178
+ * @param {unknown} error
179
+ * @param {string} endpoint
180
+ */
181
+ function unreachable(error, endpoint) {
182
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause : error
183
+ const code = cause && typeof cause === 'object' && 'code' in cause ? String(cause.code) : null
184
+ if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
185
+ return new TickError(`no answer from ${endpoint} before the timeout`)
186
+ }
187
+ if (code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'UND_ERR_SOCKET') {
188
+ return new TickError(`could not reach ${endpoint} (${code}) — is the dev server running? (\`pnpm dev\`)`)
189
+ }
190
+ return new TickError(`request to ${endpoint} failed: ${error instanceof Error ? error.message : String(error)}`)
191
+ }
192
+
193
+ /**
194
+ * One tick. Resolves to the route's JSON body; rejects with a `TickError` for anything that is not a 2xx.
195
+ *
196
+ * The first request to a checkout's server is what creates its secret file, so with none on disk yet one request
197
+ * goes out with a throwaway secret (a 401, by design) to make the server write it, then the real one follows.
198
+ *
199
+ * `signal` ends a tick early (the dev ticker passes the one that stops it, so a tick in flight does not outlive the
200
+ * server it was for).
201
+ *
202
+ * @param {{ origin: string, timeoutMs: number, secretFile?: string, fetchImpl?: typeof fetch, signal?: AbortSignal }} options
203
+ * @returns {Promise<Record<string, unknown>>}
204
+ */
205
+ export async function tickOnce({ origin, timeoutMs, secretFile = secretFilePath(), fetchImpl = fetch, signal }) {
206
+ const endpoint = `${origin}${TICK_PATH}`
207
+ /** @param {string} secret */
208
+ const post = async (secret) => {
209
+ try {
210
+ return await fetchImpl(endpoint, {
211
+ method: 'POST',
212
+ // The webhook secret's own header (`@sssb/kit/service-auth/webhook`'s WEBHOOK_SECRET_HEADER), which a
213
+ // deployment's CloudFront passes through; it would replace `Authorization` with its own signature.
214
+ headers: { 'x-sssb-webhook-secret': secret },
215
+ signal: signal
216
+ ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)])
217
+ : AbortSignal.timeout(timeoutMs),
218
+ })
219
+ } catch (error) {
220
+ throw unreachable(error, endpoint)
221
+ }
222
+ }
223
+
224
+ if (!existsSync(secretFile)) {
225
+ const probe = await post('x')
226
+ await probe.body?.cancel()
227
+ if (!existsSync(secretFile)) {
228
+ throw new TickError(
229
+ `the server at ${origin} did not create a dev secret at ${secretFile}. Is it a simulated-mode dev server ` +
230
+ `(\`pnpm dev\`, not \`dev:real\`), and is this the app's own directory (APP_DATA_DIR unset or matching)?`,
231
+ )
232
+ }
233
+ }
234
+
235
+ /** @type {string} */
236
+ let secret
237
+ try {
238
+ secret = readFileSync(secretFile, 'utf8')
239
+ } catch (error) {
240
+ throw new TickError(
241
+ `could not read the dev secret at ${secretFile}: ${error instanceof Error ? error.message : String(error)}`,
242
+ )
243
+ }
244
+ const response = await post(secret)
245
+ const text = await response.text()
246
+ if (response.status === 401) {
247
+ throw new TickError(
248
+ `${endpoint} answered 401: the server did not accept the secret in ${secretFile}. A server in real mode checks ` +
249
+ `WEBHOOK_SECRET, not this file; a server started from another checkout or data dir has its own secret.`,
250
+ )
251
+ }
252
+ if (!response.ok) throw new TickError(`${endpoint} answered ${response.status}: ${text.slice(0, 300)}`)
253
+ try {
254
+ const body = JSON.parse(text)
255
+ if (body && typeof body === 'object' && !Array.isArray(body)) return body
256
+ } catch {
257
+ // fall through to the same message as a non-object body
258
+ }
259
+ throw new TickError(
260
+ `${endpoint} answered ${response.status} with a body that is not the tick's JSON: ${text.slice(0, 300)}`,
261
+ )
262
+ }
263
+
264
+ /** @param {unknown} value */
265
+ function count(value) {
266
+ return typeof value === 'number' ? value : 0
267
+ }
268
+
269
+ /**
270
+ * What a tick did, in one line. `failed` is a schedule whose spawn failed (the next tick retries it) and a delivery
271
+ * that failed or died: shown, but it is the tick reporting work that went wrong, not the tick failing.
272
+ *
273
+ * @param {Record<string, unknown>} body the route's JSON: `{ ok, spawned, failed, deliveries: { delivered, failed, dead } }`
274
+ */
275
+ export function summarizeTick(body) {
276
+ const deliveries =
277
+ body.deliveries && typeof body.deliveries === 'object'
278
+ ? /** @type {Record<string, unknown>} */ (body.deliveries)
279
+ : {}
280
+ return (
281
+ `ticked: ${count(body.spawned)} job(s) spawned from due schedules, ${count(body.failed)} schedule(s) failed; ` +
282
+ `webhook deliveries: ${count(deliveries.delivered)} delivered, ${count(deliveries.failed)} failed, ${count(deliveries.dead)} dead`
283
+ )
284
+ }
285
+
286
+ /**
287
+ * Whether a tick moved anything at all, for a caller that only wants to speak when something happened.
288
+ *
289
+ * @param {Record<string, unknown>} body
290
+ */
291
+ export function tickDidWork(body) {
292
+ const deliveries =
293
+ body.deliveries && typeof body.deliveries === 'object'
294
+ ? /** @type {Record<string, unknown>} */ (body.deliveries)
295
+ : {}
296
+ return [body.spawned, body.failed, deliveries.delivered, deliveries.failed, deliveries.dead].some(
297
+ (n) => count(n) > 0,
298
+ )
299
+ }
300
+
301
+ /**
302
+ * @param {string[]} argv
303
+ * @param {import('../ports.d.ts').PortDeclaration} [declared] the port slot the app in the working directory declares
304
+ */
305
+ export async function main(argv, declared) {
306
+ try {
307
+ const { origin, timeoutMs } = parseTickArgs(argv, declared)
308
+ const body = await tickOnce({ origin, timeoutMs })
309
+ console.log(summarizeTick(body))
310
+ return 0
311
+ } catch (error) {
312
+ if (!(error instanceof TickError)) throw error
313
+ console.error(`tick: ${error.message}`)
314
+ if (error.usage) console.error(USAGE)
315
+ return error.usage ? 2 : 1
316
+ }
317
+ }
@@ -0,0 +1,17 @@
1
+ /** Where a running dev ticker records itself: `<APP_DATA_DIR or ./.data>/dev-ticker.json`. */
2
+ export declare function tickerMarkerPath(env?: Record<string, string | undefined>, cwd?: string): string
3
+
4
+ /** Records a live ticker (this process's pid and its interval). */
5
+ export declare function writeTickerMarker(file: string, seconds: number): void
6
+
7
+ /** Removes the record, if this process wrote it: another ticker's marker is not ours to delete. */
8
+ export declare function removeTickerMarker(file: string): void
9
+
10
+ /** The live ticker a marker records, or null when there is none or its process is gone. */
11
+ export declare function liveTickerMarker(file: string): { pid: number; seconds: number; startedAt: string } | null
12
+
13
+ /**
14
+ * Throws while a dev ticker is live in this app's data directory: a Playwright config calls it so a ticking dev
15
+ * server is never adopted by an e2e run, whose scheduler must do nothing until a test asks.
16
+ */
17
+ export declare function assertNoLiveDevTicker(env?: Record<string, string | undefined>, cwd?: string): void
@@ -0,0 +1,83 @@
1
+ // @ts-check
2
+ // A marker file that says "a dev ticker is running against this app's data directory".
3
+ //
4
+ // Why it exists: Playwright's `reuseExistingServer` (everywhere but CI) ADOPTS a dev server already listening on the
5
+ // app's port. A developer who ran `DEV_TICK_SECONDS=30 pnpm dev` and then `pnpm test:e2e` in the same checkout would
6
+ // therefore run the suite against a server that spawns jobs and drains deliveries every 30 seconds, which is exactly
7
+ // what the suite expects not to happen. Blanking the variable for the server Playwright starts cannot reach a server it
8
+ // did not start, so the ticker leaves this marker, and both playwright configs refuse to run while one is live.
9
+ //
10
+ // Imported by playwright.config.ts, which Playwright compiles to CommonJS: no `import.meta`, no top-level await, nothing
11
+ // but `node:` imports here (the constraint @sssb/tools' ports module documents).
12
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
13
+ import path from 'node:path'
14
+
15
+ /**
16
+ * @param {Record<string, string | undefined>} [env]
17
+ * @param {string} [cwd]
18
+ */
19
+ export function tickerMarkerPath(env = process.env, cwd = process.cwd()) {
20
+ return path.join(env.APP_DATA_DIR ?? path.join(cwd, '.data'), 'dev-ticker.json')
21
+ }
22
+
23
+ /**
24
+ * @param {string} file
25
+ * @param {number} seconds
26
+ */
27
+ export function writeTickerMarker(file, seconds) {
28
+ mkdirSync(path.dirname(file), { recursive: true })
29
+ writeFileSync(file, JSON.stringify({ pid: process.pid, seconds, startedAt: new Date().toISOString() }))
30
+ }
31
+
32
+ /** @param {string} file */
33
+ export function removeTickerMarker(file) {
34
+ try {
35
+ const current = JSON.parse(readFileSync(file, 'utf8'))
36
+ // Only our own: a second wrapper's marker is not ours to delete.
37
+ if (current && current.pid === process.pid) rmSync(file, { force: true })
38
+ } catch {
39
+ // already gone, or never written
40
+ }
41
+ }
42
+
43
+ /**
44
+ * The live ticker's marker, or null. A marker whose process is gone (a wrapper that was SIGKILLed cannot clean up) is
45
+ * stale and ignored.
46
+ *
47
+ * @param {string} file
48
+ * @returns {{ pid: number, seconds: number, startedAt: string } | null}
49
+ */
50
+ export function liveTickerMarker(file) {
51
+ let marker
52
+ try {
53
+ marker = JSON.parse(readFileSync(file, 'utf8'))
54
+ } catch {
55
+ return null
56
+ }
57
+ if (!marker || !Number.isInteger(marker.pid)) return null
58
+ try {
59
+ process.kill(marker.pid, 0)
60
+ } catch (error) {
61
+ // ESRCH: no such process. EPERM means it exists and is someone else's: live.
62
+ if (!(error && typeof error === 'object' && 'code' in error && error.code === 'EPERM')) return null
63
+ }
64
+ return marker
65
+ }
66
+
67
+ /**
68
+ * For a playwright config: throw, at config load, while a dev ticker is running against this app's data directory.
69
+ *
70
+ * @param {Record<string, string | undefined>} [env]
71
+ * @param {string} [cwd]
72
+ */
73
+ export function assertNoLiveDevTicker(env = process.env, cwd = process.cwd()) {
74
+ const file = tickerMarkerPath(env, cwd)
75
+ const marker = liveTickerMarker(file)
76
+ if (marker) {
77
+ throw new Error(
78
+ `a dev ticker is running (pid ${marker.pid}, every ${marker.seconds}s; ${file}). The e2e suite expects a ` +
79
+ `scheduler that does nothing until a test asks, and Playwright would adopt that dev server. Stop it ` +
80
+ `(the \`DEV_TICK_SECONDS=… pnpm dev\` you left running) and run the suite again.`,
81
+ )
82
+ }
83
+ }
@@ -0,0 +1,36 @@
1
+ /** The dev ticker's bounds: a tick is a few queries, so under a second or over a day is a typo for another unit. */
2
+ export declare const MIN_INTERVAL_SECONDS: number
3
+ export declare const MAX_INTERVAL_SECONDS: number
4
+
5
+ /** What is wrong with an interval, or null: it must be a whole number of seconds within the bounds. */
6
+ export declare function intervalProblem(seconds: unknown): string | null
7
+
8
+ export interface TickerStatus {
9
+ running: boolean
10
+ seconds: number | null
11
+ ticks: number
12
+ lastTickAt: string | null
13
+ lastError: string | null
14
+ }
15
+
16
+ export interface Ticker {
17
+ /** Starts ticking every `seconds`, or does nothing if it already is (an interval change is a stop then a start). */
18
+ start(seconds: number): TickerStatus
19
+ /** Stops ticking and waits for a tick in flight to end. */
20
+ stop(): Promise<TickerStatus>
21
+ status(): TickerStatus
22
+ }
23
+
24
+ export interface TickerOptions {
25
+ /** The dev server's origin, loopback only. */
26
+ origin: string
27
+ /** Where a live ticker is recorded (see `@sssb/tools/ticker-marker`); none, none written. */
28
+ markerFile?: string
29
+ tick?: (options: { origin: string; timeoutMs: number; signal?: AbortSignal }) => Promise<Record<string, unknown>>
30
+ log?: (line: string) => void
31
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>
32
+ now?: () => Date
33
+ }
34
+
35
+ /** The dev ticker: one object that owns start, stop, the interval and whether it is running. */
36
+ export declare function createTicker(options: TickerOptions): Ticker