@orkestrel/test 0.0.36 → 0.0.38
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.
- package/README.md +13 -5
- package/dist/reporter/main.d.ts +5 -0
- package/dist/reporter/main.js +6 -0
- package/dist/reporter/main.js.map +1 -0
- package/dist/src/server/index.cjs +657 -12
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +583 -15
- package/dist/src/server/index.d.ts +583 -15
- package/dist/src/server/index.js +643 -15
- package/dist/src/server/index.js.map +1 -1
- package/package.json +16 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["request","requestHTTP"],"sources":["../../../src/server/constants.ts","../../../src/server/helpers.ts","../../../src/server/Loopback.ts","../../../src/server/factories.ts"],"sourcesContent":["/**\n * Caps the attempts `removeTree` makes before rethrowing a retryable removal error.\n */\nexport const REMOVE_TREE_MAX_ATTEMPTS = 10\n\n/**\n * Names the synchronous delay, in milliseconds, `removeTree` waits between attempts.\n */\nexport const REMOVE_TREE_RETRY_DELAY_MS = 100\n\n/**\n * Names the error codes `removeTree` retries; every other code rethrows immediately.\n */\nexport const REMOVE_TREE_RETRYABLE_CODES: readonly string[] = Object.freeze([\n\t'EBUSY',\n\t'ENOTEMPTY',\n\t'EPERM',\n])\n","import type { Stats } from 'node:fs'\nimport type { Socket } from 'node:net'\nimport type { ChooserRequest, WaitOptions } from '@src/core'\nimport type { FileChooser, Page } from 'playwright'\nimport type {\n\tChooserContext,\n\tInventoryOptions,\n\tScratchIdentity,\n\tScratchInterface,\n\tUpgradeOptions,\n\tUpgradeResult,\n} from './types.js'\nimport { Buffer } from 'node:buffer'\nimport { createHash } from 'node:crypto'\nimport {\n\tlstatSync,\n\tmkdirSync,\n\tmkdtempSync,\n\treaddirSync,\n\treadFileSync,\n\trealpathSync,\n\trmSync,\n\tstatSync,\n\tsymlinkSync,\n\twriteFileSync,\n} from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { request as requestHTTP } from 'node:http'\nimport { tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { isNumber, isObject, isString } from '@orkestrel/contract'\nimport { checkBounds, waitForDelay, waitForEvent } from '@src/core'\nimport {\n\tREMOVE_TREE_MAX_ATTEMPTS,\n\tREMOVE_TREE_RETRY_DELAY_MS,\n\tREMOVE_TREE_RETRYABLE_CODES,\n} from './constants.js'\n\n/**\n * Reads the lowercase hexadecimal SHA-256 digest of a captured file's bytes.\n *\n * @param path - The absolute screenshot path returned by the browser provider.\n * @throws Thrown when the path is relative or the file cannot be read.\n * @remarks Register a browser command that checks Vitest's file-access policy before calling this\n * helper. Only the digest crosses back to the browser; the file is read in Node.\n * @example\n * ```ts\n * const digest = await readCapture(written)\n * ```\n */\nexport async function readCapture(path: string): Promise<string> {\n\tif (!isAbsolute(path)) throw new Error(`Capture path must be absolute: ${path}`)\n\treturn createHash('sha256')\n\t\t.update(await readFile(path))\n\t\t.digest('hex')\n}\n\n/**\n * Resolves a target that stays below a root directory.\n *\n * @param root - The absolute root directory.\n * @param target - The relative or absolute target to resolve.\n * @returns The absolute target, or `undefined` when the target resolves outside the root.\n */\nexport function resolveContained(root: string, target: string): string | undefined {\n\tconst candidate = resolve(root, target)\n\tconst contained = relative(root, candidate)\n\t// `relative` answers with an absolute path where the target carries a root of its own — a second\n\t// drive letter or a UNC share on Windows — and that spelling names no ancestor, so the `..` tests\n\t// miss it and containment turns on `isAbsolute`.\n\tif (contained === '..' || contained.startsWith(`..${sep}`) || isAbsolute(contained)) {\n\t\treturn undefined\n\t}\n\treturn candidate\n}\n\n/**\n * Resolves a target that stays below a root directory, refusing a path outside it.\n *\n * @param root - The absolute root directory.\n * @param target - The relative or absolute target to resolve.\n * @returns The absolute target below the root.\n * @throws An `Error` reading `Path outside scratch directory: <target>` when the target resolves outside the\n * root.\n * @remarks This is {@link resolveContained} with the refusal every contained scratch operation makes\n * of a path outside the root, so the check and its one message are stated once. Read `resolveContained` where\n * a path outside the root is an answer rather than a refusal.\n *\n * @example\n * ```ts\n * import { requireContained } from '@orkestrel/test/server'\n *\n * requireContained('/scratch', 'nested/file.txt') // '/scratch/nested/file.txt'\n *\n * // Throws Error: Path outside scratch directory: ../escape.ts\n * requireContained('/scratch', '../escape.ts')\n * ```\n */\nexport function requireContained(root: string, target: string): string {\n\tconst candidate = resolveContained(root, target)\n\tif (candidate === undefined) throw new Error(`Path outside scratch directory: ${target}`)\n\treturn candidate\n}\n\n/**\n * Reads the identity of one allocated directory off a host status.\n *\n * @param status - The status read from the directory's path.\n * @returns The device, index node, and creation time that together name the allocation.\n *\n * @example\n * ```ts\n * import { statSync } from 'node:fs'\n * import { readIdentity } from '@orkestrel/test/server'\n *\n * const status = statSync('/scratch')\n *\n * readIdentity(status) // { birth: status.birthtimeMs, device: status.dev, inode: status.ino }\n * ```\n */\nexport function readIdentity(status: Stats): ScratchIdentity {\n\treturn { birth: status.birthtimeMs, device: status.dev, inode: status.ino }\n}\n\n/**\n * Reports whether a contained entry exists under a scratch directory without following its final link.\n *\n * @param root - The absolute scratch directory path.\n * @param target - The relative or absolute contained entry to inspect.\n * @returns True if the root directory and entry exist; false otherwise.\n * @throws Thrown when the target resolves outside the root, the root is a symbolic link or not a directory,\n * or the host refuses to inspect either path.\n * @remarks Checks containment before inspecting the root. Intermediate links are followed; a\n * dangling final link counts as present. The root's allocation identity is not checked.\n *\n * @example\n * ```ts\n * import { createScratch, hasScratchPath } from '@orkestrel/test/server'\n *\n * const scratch = createScratch({ files: { 'entry.txt': 'present' } })\n * try {\n * \thasScratchPath(scratch.path, 'entry.txt') // true\n * \thasScratchPath(scratch.path, 'missing.txt') // false\n * } finally {\n * \tscratch.destroy()\n * }\n * ```\n */\nexport function hasScratchPath(root: string, target: string): boolean {\n\tconst candidate = requireContained(root, target)\n\tconst rootStatus = lstatSync(root, { throwIfNoEntry: false })\n\tif (rootStatus === undefined) return false\n\tif (rootStatus.isSymbolicLink()) throw new Error('Scratch directory is a symbolic link')\n\tif (!rootStatus.isDirectory()) throw new Error('Scratch path is not a directory')\n\n\treturn lstatSync(candidate, { throwIfNoEntry: false }) !== undefined\n}\n\n/**\n * Reads the `code` an unknown thrown value carries.\n *\n * @param error - The thrown value to read.\n * @returns The string `code` the value carries, or `undefined` when it carries none.\n * @remarks The read is contained on its own terms: a value that is not an object, one carrying no\n * `code`, and one carrying a `code` that is not a string all answer `undefined`. A null-prototype\n * object is read the same way, because the key is tested with `in` rather than through\n * `hasOwnProperty`.\n *\n * @example\n * ```ts\n * import { readFileSync } from 'node:fs'\n * import { captureError } from '@orkestrel/test'\n * import { readErrorCode } from '@orkestrel/test/server'\n *\n * readErrorCode(captureError(() => readFileSync('/scratch/absent.txt', 'utf8'))) // 'ENOENT'\n * readErrorCode(new Error('refused')) // undefined\n * ```\n */\nexport function readErrorCode(error: unknown): string | undefined {\n\treturn isObject(error) && 'code' in error && isString(error.code) ? error.code : undefined\n}\n\n/**\n * Reports whether two directory identities name the same allocation.\n *\n * @param current - The identity read from the path.\n * @param allocation - The identity recorded when the directory was allocated.\n * @returns True if the device, the index node, and the creation time all match; false otherwise.\n * @remarks All three fields are compared because none of them alone identifies an allocation. A\n * device is shared by every directory on one filesystem, an index node is reused after its directory\n * is removed, and a creation time repeats within the host's timestamp resolution.\n *\n * @example\n * ```ts\n * import { statSync } from 'node:fs'\n * import { matchesIdentity, readIdentity } from '@orkestrel/test/server'\n *\n * const allocation = readIdentity(statSync('/scratch'))\n *\n * matchesIdentity(readIdentity(statSync('/scratch')), allocation) // true\n * matchesIdentity({ birth: 3, device: 1, inode: 9 }, { birth: 3, device: 1, inode: 2 }) // false\n * ```\n */\nexport function matchesIdentity(current: ScratchIdentity, allocation: ScratchIdentity): boolean {\n\treturn (\n\t\tcurrent.device === allocation.device &&\n\t\tcurrent.inode === allocation.inode &&\n\t\tcurrent.birth === allocation.birth\n\t)\n}\n\n/**\n * Reports whether a root-relative key matches an exclusion.\n *\n * @param key - The root-relative key to test.\n * @param exclusions - The normalized root-relative exclusion keys.\n * @returns True if an exclusion names the key or one of its ancestors; false otherwise.\n *\n * @example\n * ```ts\n * import { isExcluded } from '@orkestrel/test/server'\n *\n * isExcluded('src/index.ts', ['src']) // true\n * isExcluded('src-other/index.ts', ['src']) // false\n * ```\n */\nexport function isExcluded(key: string, exclusions: readonly string[]): boolean {\n\treturn exclusions.some((rule) => rule === '' || key === rule || key.startsWith(`${rule}/`))\n}\n\n/**\n * Creates a symbolic link with a directory-junction fallback for hosts that refuse symbolic links.\n *\n * @param path - The path where the link is created.\n * @param source - The destination path the link points at.\n * @throws The original link error when its code is not `EPERM`, or when the source names an\n * existing non-directory; otherwise, any error from inspecting the source or creating the junction.\n * @remarks Only `EPERM` from the first symbolic-link attempt triggers the fallback. The fallback\n * resolves the source against the link's directory. An existing non-directory rethrows the original\n * `EPERM`, while a directory or missing source is passed to a junction attempt. A missing source is\n * accepted to create a dangling junction. Where the host creates a junction, its stored value is the\n * resolved absolute path.\n *\n * @example\n * ```ts\n * import { readFileSync } from 'node:fs'\n * import { createLink } from '@orkestrel/test/server'\n *\n * // `/scratch/source` is a directory holding `file.txt`.\n * createLink('/scratch/linked', '/scratch/source')\n *\n * readFileSync('/scratch/linked/file.txt', 'utf8') // 'linked'\n * ```\n */\nexport function createLink(path: string, source: string): void {\n\ttry {\n\t\tsymlinkSync(source, path)\n\t} catch (error) {\n\t\tif (readErrorCode(error) !== 'EPERM') throw error\n\n\t\tconst resolved = resolve(dirname(path), source)\n\t\tconst status = statSync(resolved, { throwIfNoEntry: false })\n\t\tif (status !== undefined && !status.isDirectory()) throw error\n\t\tsymlinkSync(resolved, path, 'junction')\n\t}\n}\n\n/**\n * Removes a directory tree, retrying past a transient Windows handle-release race.\n *\n * @param path - The absolute directory to remove.\n * @throws The last removal error after {@link REMOVE_TREE_MAX_ATTEMPTS} attempts are exhausted,\n * or immediately for any error whose code is not in {@link REMOVE_TREE_RETRYABLE_CODES}.\n * @remarks On Windows, a directory that a recently exited process still holds as its current\n * working directory throws `EPERM` for a short interval after that process exits. Node's own\n * `rmSync` `maxRetries`/`retryDelay` options do not cover this error class on that host: probed\n * against a real held directory, they neither delay nor retry before rethrowing, so the retry\n * is implemented here with a synchronous sleep instead. Ten attempts 100ms apart bound the wait\n * at roughly one second. A hold that outlasts that second is {@link destroyScratch}'s case, which\n * retries every refusal inside a caller's budget rather than the codes named here.\n *\n * @example\n * ```ts\n * import { existsSync } from 'node:fs'\n * import { removeTree } from '@orkestrel/test/server'\n *\n * removeTree('/scratch/tree')\n *\n * existsSync('/scratch/tree') // false\n * ```\n */\nexport function removeTree(path: string): void {\n\tfor (const [index] of Array.from({ length: REMOVE_TREE_MAX_ATTEMPTS }).entries()) {\n\t\ttry {\n\t\t\trmSync(path, { force: true, recursive: true })\n\t\t\treturn\n\t\t} catch (error) {\n\t\t\tconst code = readErrorCode(error)\n\t\t\tif (\n\t\t\t\tcode === undefined ||\n\t\t\t\t!REMOVE_TREE_RETRYABLE_CODES.includes(code) ||\n\t\t\t\tindex + 1 >= REMOVE_TREE_MAX_ATTEMPTS\n\t\t\t) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, REMOVE_TREE_RETRY_DELAY_MS)\n\t\t}\n\t}\n}\n\n/**\n * Reads files from selected targets below a root directory.\n *\n * @param root - The root directory as a path or file URL.\n * @param targets - The files to read directly and directories to visit below the root.\n * @param options - Optional file extension and path exclusions.\n * @returns File contents keyed by sorted root-relative paths.\n * @throws When the root or a named target is a symbolic link, is not a supported entry, or resolves\n * outside the root.\n * @remarks A named file is included regardless of the extension filter. An absent extension filter\n * includes every walked file. An exclusion matches whole root-relative key segments and covers every\n * key below it, and it applies to a named target and a walked entry alike.\n */\nexport function readInventory(\n\troot: URL | string,\n\ttargets: readonly string[],\n\toptions?: InventoryOptions,\n): Readonly<Record<string, string>> {\n\tconst supplied = resolve(isString(root) ? root : fileURLToPath(root))\n\tconst rootStatus = lstatSync(supplied)\n\tif (rootStatus.isSymbolicLink()) throw new Error('Root is a symbolic link')\n\tif (!rootStatus.isDirectory()) throw new Error('Root is not a directory')\n\n\tconst base = realpathSync.native(supplied)\n\tif (targets.length === 0) return Object.fromEntries([])\n\n\tconst exclusions = (options?.exclude ?? []).map((rule) => {\n\t\tconst unprefixed = rule.startsWith('./') ? rule.slice(2) : rule\n\t\tconst collapsed = unprefixed.replace(/\\/+/g, '/')\n\t\tconst untrailed = collapsed.endsWith('/') ? collapsed.slice(0, -1) : collapsed\n\t\treturn untrailed === '.' ? '' : untrailed\n\t})\n\tconst pending: string[] = []\n\tconst queued = new Set<string>()\n\tconst contents = new Map<string, string>()\n\n\tfor (const target of targets) {\n\t\tconst candidate = resolveContained(base, target)\n\t\tif (candidate === undefined) {\n\t\t\tthrow new Error(`Target outside root: ${target}`)\n\t\t}\n\n\t\tconst status = lstatSync(candidate)\n\t\tif (status.isSymbolicLink()) throw new Error(`Target is a symbolic link: ${target}`)\n\t\tif (!status.isDirectory() && !status.isFile()) {\n\t\t\tthrow new Error(`Target is not a file or directory: ${target}`)\n\t\t}\n\n\t\tconst physical = realpathSync.native(candidate)\n\t\tconst resolved = resolveContained(base, relative(base, physical))\n\t\tif (resolved === undefined) {\n\t\t\tthrow new Error(`Target outside root: ${target}`)\n\t\t}\n\n\t\tconst key = relative(base, resolved).split(sep).join('/')\n\t\tif (isExcluded(key, exclusions)) continue\n\t\tif (status.isFile()) {\n\t\t\tcontents.set(key, readFileSync(physical, 'utf8'))\n\t\t\tcontinue\n\t\t}\n\t\tif (queued.has(physical)) continue\n\t\tqueued.add(physical)\n\t\tpending.push(physical)\n\t}\n\n\twhile (pending.length > 0) {\n\t\tconst directory = pending.pop()\n\t\tif (directory === undefined) continue\n\n\t\tfor (const entry of readdirSync(directory, { withFileTypes: true })) {\n\t\t\tconst path = resolve(directory, entry.name)\n\t\t\tconst status = lstatSync(path)\n\t\t\tif (status.isSymbolicLink()) continue\n\n\t\t\tconst key = relative(base, path).split(sep).join('/')\n\t\t\tif (isExcluded(key, exclusions)) continue\n\n\t\t\tif (status.isDirectory()) {\n\t\t\t\tconst physical = realpathSync.native(path)\n\t\t\t\tconst resolved = resolveContained(base, relative(base, physical))\n\t\t\t\t// Walk containment is unproven because POSIX CI skips links before `realpath`;\n\t\t\t\t// a host that resolves a walked directory outside `base` would drive this branch.\n\t\t\t\tif (resolved === undefined || queued.has(physical)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tqueued.add(physical)\n\t\t\t\tpending.push(physical)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\t!status.isFile() ||\n\t\t\t\t(options?.extensions !== undefined &&\n\t\t\t\t\t!options.extensions.some((extension) => entry.name.endsWith(extension)))\n\t\t\t) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcontents.set(key, readFileSync(path, 'utf8'))\n\t\t}\n\t}\n\n\treturn Object.fromEntries(\n\t\tArray.from(contents).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)),\n\t)\n}\n\n/**\n * Reports whether a process id names a live process.\n *\n * @param pid - The process id to read.\n * @returns True if a process holds that id at the moment of the call; false otherwise, including a\n * pid the host refuses.\n * @throws Nothing. Every host refusal reads as false.\n * @remarks This is an instantaneous observation rather than a claim of ownership. A host reuses a\n * process id after the process holding it exits, so a true answer says some process holds that id at the time of the check\n * and never says it is the process the caller started. Two host answers are worth knowing. A POSIX\n * host refuses signal `0` to a process another user owns with `EPERM`, and that refusal reads as\n * false here. A pid of `0` names the caller's own process group on POSIX and the system idle process\n * on Windows, so it reads as true on both without naming a process anyone started.\n *\n * A Linux zombie — a process that has exited and whose parent has not reaped it — still accepts\n * signal `0`, so its `/proc` status is read and a `Z` state reads as false.\n *\n * @example\n * ```ts\n * import { isRunning } from '@orkestrel/test/server'\n *\n * isRunning(process.pid) // true\n * isRunning(2 ** 31) // false\n * ```\n */\nexport function isRunning(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0)\n\t} catch {\n\t\treturn false\n\t}\n\tif (process.platform !== 'linux') return true\n\n\t// The zombie refinement is unproven on a host that carries no `/proc`; a Linux gate drives it.\n\ttry {\n\t\tconst status = readFileSync(`/proc/${String(pid)}/stat`, 'utf8')\n\t\tconst boundary = status.lastIndexOf(') ')\n\t\treturn boundary < 0 || status.slice(boundary + 2, boundary + 3) !== 'Z'\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Waits for a socket to close, accepting a peer reset as a forced close.\n *\n * @param socket - The socket to wait on. One that has already closed resolves without listening.\n * @param options - The time bounds and abort signal.\n * @returns A promise that resolves when the socket emits `close`.\n * @throws The socket's own error when its code is not `ECONNRESET`, the abort reason, or an `Error`\n * when a bound is invalid or the socket does not close within the budget.\n * @remarks Default budget: `1000` milliseconds. A reset is the peer forcing the connection down, and\n * the socket still emits `close` afterwards, so `ECONNRESET` is waited past rather than raised while\n * every other error ends the wait. The interval is validated for consistency with the wait family but\n * is not used, because this helper parks on the socket's events. Both listeners are removed on every\n * settlement, so a caller may wait on one socket repeatedly.\n *\n * @example\n * ```ts\n * import { connect, createServer } from 'node:net'\n * import { createLoopback, waitForSocketClose } from '@orkestrel/test/server'\n *\n * const loopback = await createLoopback(createServer((socket) => socket.end()))\n * const client = connect(loopback.port, '127.0.0.1')\n *\n * await waitForSocketClose(client, { budget: 1000 }) // undefined\n * client.destroyed // true\n *\n * await loopback.destroy()\n * ```\n */\nexport async function waitForSocketClose(socket: Socket, options?: WaitOptions): Promise<void> {\n\tconst budget = options?.budget ?? 1000\n\tconst interval = options?.interval ?? 10\n\tcheckBounds('Socket', budget, interval)\n\n\tconst signal = options?.signal\n\tsignal?.throwIfAborted()\n\tif (socket.closed) return\n\n\t// The resolvers are the listeners themselves, so the same references remove them afterwards.\n\tconst closed = Promise.withResolvers<boolean>()\n\tconst failed = Promise.withResolvers<NodeJS.ErrnoException>()\n\tconst expiry = Promise.withResolvers<never>()\n\tconst aborted = Promise.withResolvers<never>()\n\tconst subscription = new AbortController()\n\tsocket.on('close', closed.resolve)\n\tsocket.on('error', failed.resolve)\n\tsignal?.addEventListener('abort', () => aborted.reject(signal.reason), {\n\t\tonce: true,\n\t\tsignal: subscription.signal,\n\t})\n\tconst timer = setTimeout(() => {\n\t\texpiry.reject(new Error(`Socket did not close within ${budget}ms`))\n\t}, budget)\n\n\ttry {\n\t\tconst error = await Promise.race([\n\t\t\tclosed.promise.then(() => undefined),\n\t\t\tfailed.promise,\n\t\t\texpiry.promise,\n\t\t\taborted.promise,\n\t\t])\n\t\tif (error === undefined) return\n\t\tif (error.code !== 'ECONNRESET') throw error\n\t\tawait Promise.race([closed.promise, expiry.promise, aborted.promise])\n\t} finally {\n\t\tclearTimeout(timer)\n\t\tsubscription.abort()\n\t\tsocket.off('close', closed.resolve)\n\t\tsocket.off('error', failed.resolve)\n\t}\n}\n\n/**\n * Destroys a scratch directory, retrying until the host releases it.\n *\n * @param scratch - The scratch directory to destroy.\n * @param options - The time bounds and abort signal.\n * @returns A promise that resolves after `destroy()` returns without throwing.\n * @throws The abort reason, or an `Error` when a bound is invalid or the budget elapses. The\n * exhaustion error carries the last host refusal as its `cause`.\n * @remarks Default budget: `10000` milliseconds. Default interval: `25` milliseconds. A host holds a\n * directory for a short interval after the process that held it exits, and a recently stopped child's\n * working directory is the case this exists for, so removal is attempted until the host lets go\n * rather than exactly once. {@link ScratchInterface.destroy} stays synchronous and is unchanged; this\n * is the bounded retry around it. A directory nothing releases still fails, with the host's own\n * refusal as the `cause`.\n *\n * Every refusal is retried, deliberately, and that is wider than {@link removeTree}'s policy: that\n * one retries the codes {@link REMOVE_TREE_RETRYABLE_CODES} names and rethrows the rest at once.\n * The hold this waits out is not classifiable across hosts — Windows reports a working-directory\n * hold as `EPERM`, POSIX hosts and network filesystems report their own — so a code list here would\n * be a list of the hosts it had been run on. The residual is the cost of that: a fault no wait can\n * clear, such as a path removed from under the allocation or a permission the process never had,\n * spends the whole budget before it surfaces, and it surfaces wrapped in the exhaustion error with\n * the host's refusal as `cause` rather than by identity. Pass a shorter `budget` or a `signal`\n * wherever a caller must bound that cost.\n */\nexport async function destroyScratch(\n\tscratch: ScratchInterface,\n\toptions?: WaitOptions,\n): Promise<void> {\n\tconst budget = options?.budget ?? 10_000\n\tconst interval = options?.interval ?? 25\n\tcheckBounds('Scratch', budget, interval)\n\n\tconst start = performance.now()\n\twhile (true) {\n\t\toptions?.signal?.throwIfAborted()\n\t\ttry {\n\t\t\tscratch.destroy()\n\t\t\treturn\n\t\t} catch (error) {\n\t\t\tif (performance.now() - start >= budget) {\n\t\t\t\tthrow new Error(`Scratch directory was not destroyed within ${budget}ms`, {\n\t\t\t\t\tcause: error,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tawait waitForDelay(interval)\n\t}\n}\n\n/**\n * Reads the loop clock Node stamps on an armed timer, in whole milliseconds.\n *\n * @returns The reading since the loop's timer base, independent of `performance.now()`.\n * @throws Thrown when Node's `Timeout` carries no numeric `_idleStart` field.\n * @remarks Node refreshes libuv's clock when arming a timer and records it in the undocumented\n * `_idleStart` field. Compare these readings with each other, never with another clock.\n * @example\n * ```ts\n * const before = readLoopClock()\n * alignLoopClock()\n * readLoopClock() > before // true\n * ```\n */\nexport function readLoopClock(): number {\n\tconst timer = setTimeout(() => undefined, 1)\n\tclearTimeout(timer)\n\tconst stamp: unknown = Reflect.get(timer, '_idleStart')\n\tif (!isNumber(stamp)) throw new Error('the armed timer carries no numeric _idleStart stamp')\n\treturn stamp\n}\n\n/**\n * Spins synchronously past a loop-clock tick and an optional millisecond offset.\n *\n * @param offset - The milliseconds to spin after the tick. Default: `0`.\n * @remarks The spin holds the calling macrotask so libuv cannot refresh the clock through a yield.\n * An offset near 1 arms a subsequent timer late in a millisecond, exposing timer truncation.\n * @example\n * ```ts\n * alignLoopClock(0.9)\n * const started = performance.now()\n * await waitForDelay(10)\n * performance.now() - started >= 10 - TIMER_LEAD // true\n * ```\n */\nexport function alignLoopClock(offset = 0): void {\n\tconst tick = readLoopClock()\n\twhile (readLoopClock() === tick) {\n\t\t// A yield would let libuv refresh the clock outside this macrotask.\n\t}\n\tconst crossed = performance.now()\n\twhile (performance.now() - crossed < offset) {\n\t\t// Keep the offset within the same macrotask.\n\t}\n}\n\n/**\n * Drives a real client upgrade request against a loopback port and reports what the server did.\n *\n * @param port - The port the server listens on at `127.0.0.1`.\n * @param options - Optional request path, offered subprotocols, time bounds, and abort signal.\n * @returns A promise resolving to the server's answer: a claimed upgrade with the protocol it\n * selected, or a refusal with the status it answered.\n * @throws The client's own transport error, such as the `ECONNREFUSED` a closed port answers, the\n * abort reason, or an `Error` when a bound is invalid or the server does not answer within the\n * budget.\n * @remarks Default budget: `1000` milliseconds. The request carries `Connection: Upgrade` and\n * `Upgrade: websocket`, which is what makes a server's `upgrade` handler the one that answers it.\n * The `upgrade`, `response`, and `error` events are mutually exclusive in practice and the promise\n * settles on whichever arrives first, so a second event changes nothing. The client socket is\n * destroyed before every settlement, on the claimed path because an upgraded socket is detached from\n * the request and outlives it otherwise. The request is made with no agent, so no pooled connection\n * survives the call to keep a suite's event loop alive.\n *\n * A server that accepts the connection and answers nothing raises no transport error, so the budget\n * is what ends that call: the rejection names the port and path it was waiting on. The interval is\n * validated for consistency with the wait family but is not used, because this helper parks on the\n * request's events.\n *\n * A `101` is the claimed path's status on the wire and is deliberately not reported: `status` is the\n * refused arm's member, and a claimed upgrade produced no plain answer.\n * @example\n * ```ts\n * const answer = await requestUpgrade(loopback.port, { path: '/socket', protocols: ['chat'] })\n * // { claimed: true, protocol: 'chat' }\n * ```\n */\nexport async function requestUpgrade(\n\tport: number,\n\toptions?: UpgradeOptions,\n): Promise<UpgradeResult> {\n\tconst budget = options?.budget ?? 1000\n\tconst interval = options?.interval ?? 10\n\tcheckBounds('Upgrade', budget, interval)\n\n\tconst signal = options?.signal\n\tsignal?.throwIfAborted()\n\n\tconst path = options?.path ?? '/'\n\tconst target = `127.0.0.1:${port}${path}`\n\tconst headers: Record<string, string> = { connection: 'Upgrade', upgrade: 'websocket' }\n\tconst protocols = options?.protocols ?? []\n\tif (protocols.length > 0) headers['sec-websocket-protocol'] = protocols.join(', ')\n\n\tconst request = requestHTTP({ agent: false, headers, host: '127.0.0.1', path, port })\n\tconst settled = Promise.withResolvers<UpgradeResult>()\n\tconst expiry = Promise.withResolvers<never>()\n\tconst aborted = Promise.withResolvers<never>()\n\tconst subscription = new AbortController()\n\trequest.on('upgrade', (response, socket) => {\n\t\tconst protocol = response.headers['sec-websocket-protocol']\n\t\tsocket.destroy()\n\t\tsettled.resolve({ claimed: true, protocol })\n\t})\n\trequest.on('response', (response) => {\n\t\tconst status = response.statusCode\n\t\tresponse.destroy()\n\t\trequest.destroy()\n\t\t// A client response reaches this listener only after its status line is parsed, so the\n\t\t// refusal is unproven; the server-side `IncomingMessage` that shares this type carries no\n\t\t// status and would drive it.\n\t\tif (status === undefined) {\n\t\t\tsettled.reject(new Error(`Upgrade request to ${target} was answered without a status`))\n\t\t\treturn\n\t\t}\n\t\tsettled.resolve({ claimed: false, status })\n\t})\n\trequest.on('error', (error) => {\n\t\trequest.destroy()\n\t\tsettled.reject(error)\n\t})\n\tsignal?.addEventListener('abort', () => aborted.reject(signal.reason), {\n\t\tonce: true,\n\t\tsignal: subscription.signal,\n\t})\n\tconst timer = setTimeout(() => {\n\t\texpiry.reject(new Error(`Upgrade request to ${target} was not answered within ${budget}ms`))\n\t}, budget)\n\trequest.end()\n\n\ttry {\n\t\treturn await Promise.race([settled.promise, expiry.promise, aborted.promise])\n\t} finally {\n\t\tclearTimeout(timer)\n\t\tsubscription.abort()\n\t\trequest.destroy()\n\t}\n}\n\n/**\n * Checks whether this host links a directory, by creating one link and reading through it.\n *\n * @returns True if the created link reports as a symbolic link, resolves to a directory, and reaches\n * the destination's contents; false otherwise, including every host refusal.\n * @throws Nothing the attempt itself raises. Failing to allocate the probe directory, and failing to\n * remove it afterwards, both propagate.\n * @remarks `symlinkSync(source, target, 'junction')` creates a directory junction on Windows, which\n * needs no privilege, and Node ignores the type argument off Windows, so one call covers both hosts.\n * The answer is false on a filesystem carrying neither reparse points nor symbolic links. Every call\n * probes and cleans up after itself, so a host whose answer changes is read again rather than\n * remembered.\n *\n * @example\n * ```ts\n * import { supportsDirectoryLinks } from '@orkestrel/test/server'\n *\n * supportsDirectoryLinks() // true where the host creates a symbolic link or a junction\n * ```\n */\nexport function supportsDirectoryLinks(): boolean {\n\tconst directory = mkdtempSync(join(tmpdir(), 'orkestrel-test-directory-links-'))\n\ttry {\n\t\tconst source = join(directory, 'source')\n\t\tconst link = join(directory, 'link')\n\t\tmkdirSync(source)\n\t\twriteFileSync(join(source, 'marker.txt'), 'marked')\n\t\tsymlinkSync(source, link, 'junction')\n\t\treturn (\n\t\t\tlstatSync(link).isSymbolicLink() &&\n\t\t\tstatSync(link).isDirectory() &&\n\t\t\treadFileSync(join(link, 'marker.txt'), 'utf8') === 'marked'\n\t\t)\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tremoveTree(directory)\n\t}\n}\n\n/**\n * Checks whether this host links a file, by creating one link and reading the file through it.\n *\n * @returns True if the file's contents are readable through the link; false otherwise, including\n * every host refusal.\n * @throws Nothing the attempt itself raises. Failing to allocate the probe directory, and failing to\n * remove it afterwards, both propagate.\n * @remarks `symlinkSync(source, target, 'file')` needs the symbolic-link privilege, which Windows\n * grants under Developer Mode or administrator rights and refuses with `EPERM` otherwise, so the\n * answer is true on POSIX and on a privileged Windows host. Where it is false, no mechanism reaches a\n * file through a link and a proof that reads one back cannot run. This is a separate question from\n * {@link supportsDirectoryLinks}, which an unprivileged Windows host answers true through a junction\n * while answering this one false.\n */\nexport function supportsFileLinks(): boolean {\n\tconst directory = mkdtempSync(join(tmpdir(), 'orkestrel-test-file-links-'))\n\ttry {\n\t\tconst source = join(directory, 'source.txt')\n\t\tconst link = join(directory, 'link.txt')\n\t\twriteFileSync(source, 'linked')\n\t\tsymlinkSync(source, link, 'file')\n\t\treturn readFileSync(link, 'utf8') === 'linked'\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tremoveTree(directory)\n\t}\n}\n\n/**\n * Checks whether POSIX permission bits round-trip through this host's `chmod` and `stat`.\n *\n * @returns True if a directory created with mode `0o700` reports that mode back; false otherwise,\n * including every host refusal.\n * @throws Nothing the attempt itself raises. Failing to allocate the probe directory, and failing to\n * remove it afterwards, both propagate.\n * @remarks POSIX reports `mode & 0o777 === 0o700` and Windows reports `0o666` regardless, so the\n * answer is true on POSIX and false on Windows. Storing a bit is a narrower question than enforcing\n * it: a POSIX host running as uid `0` stores every bit faithfully and is exempt from the access check the\n * bits describe, so a caller that needs a permission to be enforced probes the refusal it needs\n * rather than reading this.\n *\n * @example\n * ```ts\n * import { supportsMode } from '@orkestrel/test/server'\n *\n * supportsMode() // true on a POSIX host, false on Windows\n * ```\n */\nexport function supportsMode(): boolean {\n\tconst directory = mkdtempSync(join(tmpdir(), 'orkestrel-test-mode-'))\n\ttry {\n\t\tconst path = join(directory, 'moded')\n\t\tmkdirSync(path, { mode: 0o700 })\n\t\treturn (statSync(path).mode & 0o777) === 0o700\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tremoveTree(directory)\n\t}\n}\n\n/**\n * Checks whether this host treats two names differing only by case as distinct files.\n *\n * @returns True if `A` and `a` hold the contents each was written with; false otherwise, including\n * every host refusal.\n * @throws Nothing the attempt itself raises. Failing to allocate the probe directory, and failing to\n * remove it afterwards, both propagate.\n * @remarks The names `A` and `a` differ by case and by nothing else, which is what makes the reading\n * an answer about case folding rather than an answer about two unrelated files. A case-folding volume\n * routes the second write onto the first entry, so reading the first back returns the second's\n * contents and the answer is false. The answer is true on a typical POSIX host and false on a\n * case-folding Windows or macOS volume.\n *\n * @example\n * ```ts\n * import { supportsCase } from '@orkestrel/test/server'\n *\n * supportsCase() // true on a case-sensitive volume, false on a case-folding one\n * ```\n */\nexport function supportsCase(): boolean {\n\tconst directory = mkdtempSync(join(tmpdir(), 'orkestrel-test-case-'))\n\ttry {\n\t\tconst upper = join(directory, 'A')\n\t\tconst lower = join(directory, 'a')\n\t\twriteFileSync(upper, 'upper')\n\t\twriteFileSync(lower, 'lower')\n\t\treturn readFileSync(upper, 'utf8') === 'upper' && readFileSync(lower, 'utf8') === 'lower'\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tremoveTree(directory)\n\t}\n}\n\n/**\n * Checks whether this host accepts a filename carrying a raw byte no UTF-8 decoder resolves.\n *\n * @returns True if a name ending in byte `0x80` is written and read back; false otherwise, including\n * every host refusal.\n * @throws Nothing the attempt itself raises. Failing to allocate the probe directory, and failing to\n * remove it afterwards, both propagate.\n * @remarks Byte `0x80` is an invalid UTF-8 lead byte. POSIX stores the name verbatim and Windows\n * rejects it with `ENOENT`, so the answer is true on POSIX and false on Windows. The path is passed\n * as a `Buffer` because the byte survives no string round trip.\n *\n * @example\n * ```ts\n * import { supportsBytes } from '@orkestrel/test/server'\n *\n * supportsBytes() // true on a POSIX host, false on Windows\n * ```\n */\nexport function supportsBytes(): boolean {\n\tconst directory = mkdtempSync(join(tmpdir(), 'orkestrel-test-bytes-'))\n\ttry {\n\t\tconst name = Buffer.concat([Buffer.from(`${directory}${sep}`), Buffer.from([0x80])])\n\t\twriteFileSync(name, 'raw')\n\t\treturn readFileSync(name, 'utf8') === 'raw'\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tremoveTree(directory)\n\t}\n}\n\n/**\n * Observes a native chooser before activating its input and supplies the verified chooser's fixture bytes.\n *\n * @param context - The real Playwright page and tester frame supplied by Vitest.\n * @param request - The resolved input selector, fixture selection, activation method, and wait budget.\n * @returns A promise resolving after the expected chooser receives the files and its observer is released.\n * @throws When activation fails, no chooser opens, another input opens it, the page closes, or fixture bytes are invalid.\n * @remarks Register this function as the `chooseFiles` command in the workspace's `configs/commands.ts`, the\n * module the root configuration passes to every browser project as `test.browser.commands`. It never falls\n * back to direct file assignment.\n * @example\n * ```ts\n * // configs/commands.ts\n * import { chooseFiles } from '@orkestrel/test/server'\n * import type { BrowserConfigOptions } from 'vitest/node'\n *\n * export const commands: Readonly<NonNullable<BrowserConfigOptions['commands']>> = Object.freeze({\n * \tchooseFiles,\n * })\n * ```\n */\nexport async function chooseFiles(context: ChooserContext, request: ChooserRequest): Promise<void> {\n\tconst budget = request.budget ?? 1000\n\tcheckBounds('File chooser', budget, 0)\n\tif (budget === 0) throw new Error('File chooser budget must be positive')\n\tconst files = request.files.map((file) => {\n\t\tif (file.bytes.some((byte) => !Number.isInteger(byte) || byte < 0 || byte > 255))\n\t\t\tthrow new Error('Fixture file bytes must be integers from 0 to 255')\n\t\treturn { name: file.name, mimeType: file.mime, buffer: Buffer.from(file.bytes) }\n\t})\n\tconst target = await context.iframe.locator(request.selector).elementHandle({ timeout: budget })\n\tif (target === null) throw new Error('Native file input disappeared before activation')\n\tconst controller = new AbortController()\n\ttry {\n\t\tif (\n\t\t\t!(await target.evaluate(\n\t\t\t\t(element) =>\n\t\t\t\t\telement.nodeName === 'INPUT' && element.getAttribute('type')?.toLowerCase() === 'file',\n\t\t\t))\n\t\t)\n\t\t\tthrow new Error('Resolved target is not a native file input')\n\t\tif (\n\t\t\trequest.keyboard &&\n\t\t\t!(await target.evaluate((element) => element === element.ownerDocument.activeElement))\n\t\t)\n\t\t\tthrow new Error('Native file input lost keyboard focus before activation')\n\t\tconst observed = waitForEvent<readonly [event: FileChooser | Page]>(\n\t\t\t(listener) => {\n\t\t\t\tcontext.page.on('filechooser', listener)\n\t\t\t\tcontext.page.on('close', listener)\n\t\t\t\treturn () => {\n\t\t\t\t\tcontext.page.off('filechooser', listener)\n\t\t\t\t\tcontext.page.off('close', listener)\n\t\t\t\t}\n\t\t\t},\n\t\t\t'native file chooser',\n\t\t\t{ budget, signal: controller.signal },\n\t\t)\n\t\tconst activated = request.keyboard\n\t\t\t? target.press('Enter', { timeout: budget })\n\t\t\t: target.click({ timeout: budget })\n\t\tconst joined = Promise.all([observed, activated])\n\t\t// The first failure or the joint success ends this wait; the observer is released next, and the\n\t\t// settled results then say whether a chooser opened even where activation failed.\n\t\tawait Promise.allSettled([joined])\n\t\tcontroller.abort()\n\t\tconst [result] = await Promise.allSettled([observed, activated])\n\t\tconst [event] = result.status === 'fulfilled' ? result.value : []\n\t\tconst chooser = event !== undefined && 'element' in event ? event : undefined\n\t\ttry {\n\t\t\t// Both promises have settled, so this rethrows the activation or observation failure by identity.\n\t\t\tawait joined\n\t\t\tif (chooser === undefined)\n\t\t\t\tthrow new Error('Page closed before the native file chooser opened')\n\t\t\tif (!(await chooser.element().evaluate((element, expected) => element === expected, target)))\n\t\t\t\tthrow new Error('Native file chooser belongs to a different input')\n\t\t\tawait chooser.setFiles(files, { timeout: budget })\n\t\t} finally {\n\t\t\tawait chooser?.element().dispose()\n\t\t}\n\t} finally {\n\t\tcontroller.abort()\n\t\tawait target.dispose()\n\t}\n}\n","import type { Server } from 'node:net'\nimport { isFunction } from '@orkestrel/contract'\n\n/** Owns the one shutdown promise behind a loopback projection. */\nexport class Loopback {\n\treadonly #server: Server\n\t#destruction: Promise<void> | undefined\n\n\tconstructor(server: Server) {\n\t\tthis.#server = server\n\t}\n\n\tdestroy(): Promise<void> {\n\t\tthis.#destruction ??= new Promise<void>((resolve, reject) => {\n\t\t\tif ('closeAllConnections' in this.#server && isFunction(this.#server.closeAllConnections)) {\n\t\t\t\tthis.#server.closeAllConnections()\n\t\t\t}\n\t\t\tthis.#server.close((error) => {\n\t\t\t\tif (error === undefined || ('code' in error && error.code === 'ERR_SERVER_NOT_RUNNING')) {\n\t\t\t\t\tresolve()\n\t\t\t\t} else {\n\t\t\t\t\treject(error)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t\treturn this.#destruction\n\t}\n}\n","import type { Server } from 'node:net'\nimport type {\n\tCookieJarInterface,\n\tLoopbackInterface,\n\tScratchInterface,\n\tScratchOptions,\n} from './types.js'\nimport { isNumber, isObject } from '@orkestrel/contract'\nimport { once } from 'node:events'\nimport {\n\tlstatSync,\n\tmkdirSync,\n\tmkdtempSync,\n\treadFileSync,\n\treaddirSync,\n\tstatSync,\n\twriteFileSync,\n} from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { dirname, resolve, sep } from 'node:path'\nimport {\n\tcreateLink,\n\thasScratchPath,\n\tmatchesIdentity,\n\treadIdentity,\n\tremoveTree,\n\trequireContained,\n} from './helpers.js'\nimport { Loopback } from './Loopback.js'\n\n/**\n * Allocates an owned temporary directory with contained file operations.\n *\n * @param options - Optional parent directory, name prefix, and initial files.\n * @returns The scratch directory and its file operations.\n * @throws When the parent is missing, a symbolic link, or not a directory; when the prefix contains\n * `/` or `\\`; or when allocation or seeding fails.\n * @remarks Default parent: the host temporary directory. Default prefix: `orkestrel-test-`. Seed\n * keys use root-relative paths.\n *\n * @example Own a temporary directory\n * ```ts\n * import { createScratch } from '@orkestrel/test/server'\n *\n * const scratch = createScratch({ prefix: 'guide-', files: { 'src/index.ts': 'export {}\\n' } })\n *\n * scratch.read('src/index.ts') // 'export {}\\n'\n * scratch.has('src') // true\n * scratch.read('src') // throws Error: Scratch path is a directory: src\n * scratch.read('missing.ts') // undefined\n * scratch.write('../escape.ts', '') // throws Error: Path outside scratch directory: ../escape.ts\n *\n * // `write` answers the contained path it wrote, the way `ensure` and `link` answer theirs, so the\n * // path goes straight to the code under test without joining it again.\n * scratch.write('src/notes.ts', 'export {}\\n') // `${scratch.path}/src/notes.ts`\n *\n * // `ensure` is how you get an empty directory, because every `write` creates a file.\n * scratch.ensure('empty')\n * scratch.names() // ['empty', 'src']\n * scratch.names('empty') // []\n *\n * // `parent` puts the allocation somewhere other than the host temporary directory.\n * const child = createScratch({ parent: scratch.path, prefix: 'child-' })\n * scratch.names().length // 3 — 'empty', 'src', and the child allocation\n * child.destroy()\n * scratch.names().length // 2 — the child removed itself and nothing else\n *\n * // `link` creates the symbolic link the threat model names, and `read` follows it. A directory\n * // source runs on a host that creates no symbolic link too; see \"Hosts that create no symbolic\n * // link\" for what such a host does with a file source.\n * const outside = createScratch({ prefix: 'outside-', files: { 'read.ts': 'export {}\\n' } })\n * scratch.link('gate', outside.path) // `${scratch.path}/gate` — the link's own path, not its destination\n * scratch.read('gate/read.ts') // 'export {}\\n' — read through the link, at its destination\n *\n * // A link pointing out of the allocation is resolved through, so a contained path acts outside it.\n * scratch.ensure('gate/made') // `${scratch.path}/gate/made` — the lexical path, not the destination\n * outside.names() // ['made', 'read.ts'] — the directory was made under `outside.path`\n * scratch.names('gate') // ['made', 'read.ts'] — the same entries, listed through the link\n *\n * // `link` acts at the final segment rather than through it, so `gate` is occupied.\n * scratch.link('gate', outside.path) // throws Error: EEXIST: file already exists\n *\n * // `has` reads the final segment without following it, and `read` follows it.\n * scratch.link('dangling', 'missing.ts')\n * scratch.has('dangling') // true — the link is there\n * scratch.read('dangling') // undefined — what it points at is not\n *\n * // `remove` takes one contained entry and acts at the final segment, so a link goes and whatever it\n * // pointed at stays. A missing target is a no-op.\n * scratch.remove('dangling')\n * scratch.has('dangling') // false\n * scratch.remove('missing.ts') // no throw — there was nothing there\n * scratch.remove('src') // the directory and everything under it\n * scratch.names() // ['empty', 'gate']\n *\n * scratch.destroy()\n * scratch.destroy() // no-op — destroy is idempotent\n * outside.has('made') // true — destroy unlinks `gate` and leaves what it pointed at\n * outside.destroy()\n * ```\n */\nexport function createScratch(options?: ScratchOptions): ScratchInterface {\n\tconst parent = resolve(options?.parent ?? tmpdir())\n\tconst parentStatus = lstatSync(parent, { throwIfNoEntry: false })\n\tif (parentStatus === undefined) throw new Error('Scratch parent does not exist')\n\tif (parentStatus.isSymbolicLink()) throw new Error('Scratch parent is a symbolic link')\n\tif (!parentStatus.isDirectory()) throw new Error('Scratch parent is not a directory')\n\n\tconst prefix = options?.prefix ?? 'orkestrel-test-'\n\tif (prefix.includes('/') || prefix.includes('\\\\')) {\n\t\tthrow new Error('Scratch prefix must be a name fragment')\n\t}\n\n\tconst path = mkdtempSync(`${parent}${sep}${prefix}`)\n\tconst allocation = readIdentity(statSync(path))\n\tconst unremovable = 'Scratch directory is not a removable target'\n\ttry {\n\t\tfor (const [target, text] of Object.entries(options?.files ?? {})) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tmkdirSync(dirname(candidate), { recursive: true })\n\t\t\twriteFileSync(candidate, text)\n\t\t}\n\t} catch (error) {\n\t\tremoveTree(path)\n\t\tthrow error\n\t}\n\n\treturn {\n\t\tpath,\n\t\twrite(target, text) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (!hasScratchPath(path, '.')) throw new Error('Scratch directory does not exist')\n\n\t\t\tmkdirSync(dirname(candidate), { recursive: true })\n\t\t\twriteFileSync(candidate, text)\n\t\t\treturn candidate\n\t\t},\n\t\tread(target) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (!hasScratchPath(path, target)) return undefined\n\t\t\tconst status = statSync(candidate, { throwIfNoEntry: false })\n\t\t\tif (status === undefined) return undefined\n\t\t\tif (status.isDirectory()) {\n\t\t\t\tthrow new Error(`Scratch path is a directory: ${target}`)\n\t\t\t}\n\t\t\treturn readFileSync(candidate, 'utf8')\n\t\t},\n\t\thas: hasScratchPath.bind(undefined, path),\n\t\tnames(target = '.') {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (!hasScratchPath(path, '.')) throw new Error('Scratch directory does not exist')\n\n\t\t\tconst status = statSync(candidate, { throwIfNoEntry: false })\n\t\t\tif (status === undefined) throw new Error(`Scratch path does not exist: ${target}`)\n\t\t\tif (!status.isDirectory()) throw new Error(`Scratch path is not a directory: ${target}`)\n\t\t\treturn readdirSync(candidate).sort()\n\t\t},\n\t\tensure(target) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (!hasScratchPath(path, '.')) throw new Error('Scratch directory does not exist')\n\n\t\t\tconst status = statSync(candidate, { throwIfNoEntry: false })\n\t\t\tif (status !== undefined && !status.isDirectory()) {\n\t\t\t\tthrow new Error(`Scratch path is not a directory: ${target}`)\n\t\t\t}\n\t\t\tif (status === undefined) mkdirSync(candidate, { recursive: true })\n\t\t\treturn candidate\n\t\t},\n\t\tlink(target, source) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (!hasScratchPath(path, '.')) throw new Error('Scratch directory does not exist')\n\n\t\t\tmkdirSync(dirname(candidate), { recursive: true })\n\t\t\tcreateLink(candidate, source)\n\t\t\treturn candidate\n\t\t},\n\t\tremove(target) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (candidate === path) throw new Error(`${unremovable}: ${target}`)\n\t\t\tif (!hasScratchPath(path, '.')) throw new Error('Scratch directory does not exist')\n\n\t\t\tconst status = lstatSync(candidate, { throwIfNoEntry: false })\n\t\t\tif (status !== undefined && matchesIdentity(readIdentity(status), allocation)) {\n\t\t\t\tthrow new Error(`${unremovable}: ${target}`)\n\t\t\t}\n\t\t\tremoveTree(candidate)\n\t\t},\n\t\tdestroy() {\n\t\t\tconst status = lstatSync(path, { throwIfNoEntry: false })\n\t\t\tif (status === undefined) return\n\t\t\tif (!matchesIdentity(readIdentity(status), allocation)) return\n\t\t\tremoveTree(path)\n\t\t},\n\t}\n}\n\n/**\n * Starts a server on an ephemeral IPv4 loopback port.\n *\n * @param server - The unstarted server to bind.\n * @returns The bound origin, assigned port, and asynchronous teardown.\n * @throws When the server cannot bind or reports an address without a numeric port.\n */\nexport async function createLoopback(server: Server): Promise<LoopbackInterface> {\n\tserver.listen(0, '127.0.0.1')\n\tawait once(server, 'listening')\n\n\tconst address = server.address()\n\tif (!isObject(address) || !('port' in address) || !isNumber(address.port)) {\n\t\tthrow new Error(`Loopback address must have a numeric port; found ${String(address)}`)\n\t}\n\n\tconst port = address.port\n\tconst loopback = new Loopback(server)\n\treturn {\n\t\turl: `http://127.0.0.1:${port}`,\n\t\tport,\n\t\tdestroy: loopback.destroy.bind(loopback),\n\t}\n}\n\n/**\n * Creates a cookie jar that records a real response's cookies and replays them as one header.\n *\n * @returns The rendered request header, and the members that read and capture cookies.\n * @remarks Selection is by name alone: no `Domain` or `Path` matching, no `Expires` or `Secure`\n * handling, and no persistence beyond the jar. That is what a test driving one origin over one path\n * needs, and a fixture needing a browser's cookie store needs a browser rather than this.\n */\nexport function createCookieJar(): CookieJarInterface {\n\tconst cookies = new Map<string, string>()\n\treturn {\n\t\tget header() {\n\t\t\tconst pairs = [...cookies].map(([name, value]) => `${name}=${value}`)\n\t\t\treturn pairs.length === 0 ? undefined : pairs.join('; ')\n\t\t},\n\t\tread(name) {\n\t\t\treturn cookies.get(name)\n\t\t},\n\t\tcapture(response) {\n\t\t\tconst fields = response.headers.getSetCookie()\n\t\t\tfor (const field of fields) {\n\t\t\t\tconst boundary = field.indexOf(';')\n\t\t\t\tconst pair = boundary < 0 ? field : field.slice(0, boundary)\n\t\t\t\tconst separator = pair.indexOf('=')\n\t\t\t\tif (separator < 1) continue\n\n\t\t\t\tconst name = pair.slice(0, separator)\n\t\t\t\t// An origin spells a deletion `Max-Age=0` in whatever case and spacing it likes, so the\n\t\t\t\t// attribute is matched rather than compared.\n\t\t\t\tif (/;\\s*max-age\\s*=\\s*0\\s*(?:;|$)/iu.test(field)) cookies.delete(name)\n\t\t\t\telse cookies.set(name, pair.slice(separator + 1))\n\t\t\t}\n\t\t\treturn fields\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAGA,IAAa,2BAA2B;;;;AAKxC,IAAa,6BAA6B;;;;AAK1C,IAAa,8BAAiD,OAAO,OAAO;CAC3E;CACA;CACA;AACD,CAAC;;;;;;;;;;;;;;ACkCD,eAAsB,YAAY,MAA+B;CAChE,IAAI,CAAC,WAAW,IAAI,GAAG,MAAM,IAAI,MAAM,kCAAkC,MAAM;CAC/E,OAAO,WAAW,QAAQ,CAAC,CACzB,OAAO,MAAM,SAAS,IAAI,CAAC,CAAC,CAC5B,OAAO,KAAK;AACf;;;;;;;;AASA,SAAgB,iBAAiB,MAAc,QAAoC;CAClF,MAAM,YAAY,QAAQ,MAAM,MAAM;CACtC,MAAM,Y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;AAUA,SAAgB,kBAAsC;CACrD,MAAM,0BAAU,IAAI,IAAoB;CACxC,OAAO;EACN,IAAI,SAAS;GACZ,MAAM,QAAQ,CAAC,GAAG,OAAO,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,GAAG,KAAK,GAAG,OAAO;GACpE,OAAO,MAAM,WAAW,IAAI,KAAA,IAAY,MAAM,KAAK,IAAI;EACxD;EACA,KAAK,MAAM;GACV,OAAO,QAAQ,IAAI,IAAI;EACxB;EACA,QAAQ,UAAU;GACjB,MAAM,SAAS,SAAS,QAAQ,aAAa;GAC7C,KAAK,MAAM,SAAS,QAAQ;IAC3B,MAAM,WAAW,MAAM,QAAQ,GAAG;IAClC,MAAM,OAAO,WAAW,IAAI,QAAQ,MAAM,MAAM,GAAG,QAAQ;IAC3D,MAAM,YAAY,KAAK,QAAQ,GAAG;IAClC,IAAI,YAAY,GAAG;IAEnB,MAAM,OAAO,KAAK,MAAM,GAAG,SAAS;IAGpC,IAAI,kCAAkC,KAAK,KAAK,GAAG,QAAQ,OAAO,IAAI;SACjE,QAAQ,IAAI,MAAM,KAAK,MAAM,YAAY,CAAC,CAAC;GACjD;GACA,OAAO;EACR;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["request","requestHTTP","performance"],"sources":["../../../src/server/constants.ts","../../../src/server/validators.ts","../../../src/server/helpers.ts","../../../src/server/Loopback.ts","../../../src/server/factories.ts","../../../src/server/reporters/ProgressReporter.ts"],"sourcesContent":["import type { ProgressRelation } from './types.js'\n\n/**\n * Caps the attempts `removeTree` makes before rethrowing a retryable removal error.\n */\nexport const REMOVE_TREE_MAX_ATTEMPTS = 10\n\n/**\n * Names the synchronous delay, in milliseconds, `removeTree` waits between attempts.\n */\nexport const REMOVE_TREE_RETRY_DELAY_MS = 100\n\n/**\n * Names the error codes `removeTree` retries; every other code rethrows immediately.\n */\nexport const REMOVE_TREE_RETRYABLE_CODES: readonly string[] = Object.freeze([\n\t'EBUSY',\n\t'ENOTEMPTY',\n\t'EPERM',\n])\n\n/**\n * Names the format version a progress file's `init` line carries; a reader refuses any other.\n */\nexport const PROGRESS_VERSION = 1\n\n/**\n * Caps the characters a progress error message keeps.\n */\nexport const PROGRESS_MESSAGE_LIMIT = 300\n\n/**\n * Names the label a rendered progress reading prints for each failure relation.\n */\nexport const PROGRESS_LABELS: Readonly<Record<ProgressRelation, string>> = Object.freeze({\n\tfirst: 'FIRST',\n\tbail: 'AFTER-BAIL',\n\tlater: 'FAILED',\n})\n","import type { Guard } from '@orkestrel/contract'\nimport type { ProgressError, ProgressEvent } from './types.js'\nimport { arrayOf, isNumber, isString, literalOf, recordOf, unionOf } from '@orkestrel/contract'\n\n/**\n * Checks whether a value is one error a progress line carries.\n *\n * @example\n * ```ts\n * import { isProgressError } from '@orkestrel/test/server'\n *\n * isProgressError({ message: 'Error: refused', location: 'tests/a.test.ts:4:9' }) // true\n * isProgressError({ location: 'tests/a.test.ts:4:9' }) // false\n * ```\n */\nexport const isProgressError: Guard<ProgressError> = recordOf(\n\t{ message: isString, location: isString },\n\t['location'],\n)\n\n/**\n * Checks whether a value is one line of a progress file.\n *\n * @example\n * ```ts\n * import { isProgressEvent } from '@orkestrel/test/server'\n *\n * isProgressEvent({ event: 'cancel', reason: 'test-failure', wall: 1, time: 2, pid: 3 }) // true\n * isProgressEvent({ event: 'cancel', reason: 'test-failure' }) // false\n * ```\n */\nexport const isProgressEvent: Guard<ProgressEvent> = unionOf(\n\trecordOf({\n\t\tevent: literalOf('init'),\n\t\tversion: isNumber,\n\t\twall: isNumber,\n\t\tbail: isNumber,\n\t\ttime: isNumber,\n\t\tpid: isNumber,\n\t}),\n\trecordOf({\n\t\tevent: literalOf('start'),\n\t\tspecifications: arrayOf(recordOf({ project: isString, module: isString })),\n\t\ttime: isNumber,\n\t\tpid: isNumber,\n\t}),\n\trecordOf({\n\t\tevent: literalOf('collected'),\n\t\tproject: isString,\n\t\tmodule: isString,\n\t\tplanned: isNumber,\n\t\terrors: arrayOf(isProgressError),\n\t\ttime: isNumber,\n\t\tpid: isNumber,\n\t}),\n\trecordOf({\n\t\tevent: literalOf('ready'),\n\t\tproject: isString,\n\t\tid: isString,\n\t\tname: isString,\n\t\ttime: isNumber,\n\t\tpid: isNumber,\n\t}),\n\trecordOf(\n\t\t{\n\t\t\tevent: literalOf('case'),\n\t\t\tproject: isString,\n\t\t\tmodule: isString,\n\t\t\tid: isString,\n\t\t\tname: isString,\n\t\t\tstate: literalOf('passed', 'failed', 'skipped', 'pending'),\n\t\t\tduration: isNumber,\n\t\t\tstart: isNumber,\n\t\t\terrors: arrayOf(isProgressError),\n\t\t\ttime: isNumber,\n\t\t\tpid: isNumber,\n\t\t},\n\t\t['duration', 'start', 'errors'],\n\t),\n\trecordOf({\n\t\tevent: literalOf('cancel'),\n\t\treason: isString,\n\t\twall: isNumber,\n\t\ttime: isNumber,\n\t\tpid: isNumber,\n\t}),\n\trecordOf({\n\t\tevent: literalOf('module'),\n\t\tproject: isString,\n\t\tmodule: isString,\n\t\tstate: literalOf('passed', 'failed', 'skipped', 'pending', 'queued'),\n\t\tduration: isNumber,\n\t\ttime: isNumber,\n\t\tpid: isNumber,\n\t}),\n\trecordOf({\n\t\tevent: literalOf('end'),\n\t\treason: literalOf('passed', 'interrupted', 'failed'),\n\t\toverhead: isNumber,\n\t\tunhandled: arrayOf(isProgressError),\n\t\ttime: isNumber,\n\t\tpid: isNumber,\n\t}),\n)\n","import type { BigIntStats } from 'node:fs'\nimport type { Socket } from 'node:net'\nimport type { ChooserRequest, WaitOptions } from '@src/core'\nimport type { FileChooser, Page } from 'playwright'\nimport type { SerializedError } from 'vitest/node'\nimport type {\n\tChooserContext,\n\tInventoryOptions,\n\tProgressError,\n\tProgressEvent,\n\tProgressFailure,\n\tProgressProject,\n\tProgressRun,\n\tScratchIdentity,\n\tScratchInterface,\n\tUpgradeOptions,\n\tUpgradeResult,\n} from './types.js'\nimport { Buffer } from 'node:buffer'\nimport { createHash } from 'node:crypto'\nimport {\n\tcloseSync,\n\tfstatSync,\n\tlstatSync,\n\tmkdirSync,\n\tmkdtempSync,\n\topenSync,\n\treaddirSync,\n\treadFileSync,\n\treadSync,\n\trealpathSync,\n\trmSync,\n\tstatSync,\n\tsymlinkSync,\n\twriteFileSync,\n} from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { request as requestHTTP } from 'node:http'\nimport { tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { stripVTControlCharacters } from 'node:util'\nimport { isNumber, isObject, isString } from '@orkestrel/contract'\nimport { checkBounds, decodeJSONLines, waitForDelay, waitForEvent } from '@src/core'\nimport {\n\tPROGRESS_LABELS,\n\tPROGRESS_MESSAGE_LIMIT,\n\tPROGRESS_VERSION,\n\tREMOVE_TREE_MAX_ATTEMPTS,\n\tREMOVE_TREE_RETRY_DELAY_MS,\n\tREMOVE_TREE_RETRYABLE_CODES,\n} from './constants.js'\nimport { isProgressEvent } from './validators.js'\n\n/**\n * Reads the lowercase hexadecimal SHA-256 digest of a captured file's bytes.\n *\n * @param path - The absolute screenshot path returned by the browser provider.\n * @throws Thrown when the path is relative or the file cannot be read.\n * @remarks Register a browser command that checks Vitest's file-access policy before calling this\n * helper. Only the digest crosses back to the browser; the file is read in Node.\n * @example\n * ```ts\n * const digest = await readCapture(written)\n * ```\n */\nexport async function readCapture(path: string): Promise<string> {\n\tif (!isAbsolute(path)) throw new Error(`Capture path must be absolute: ${path}`)\n\treturn createHash('sha256')\n\t\t.update(await readFile(path))\n\t\t.digest('hex')\n}\n\n/**\n * Resolves a target that stays below a root directory.\n *\n * @param root - The absolute root directory.\n * @param target - The relative or absolute target to resolve.\n * @returns The absolute target, or `undefined` when the target resolves outside the root.\n */\nexport function resolveContained(root: string, target: string): string | undefined {\n\tconst candidate = resolve(root, target)\n\tconst contained = relative(root, candidate)\n\t// `relative` answers with an absolute path where the target carries a root of its own — a second\n\t// drive letter or a UNC share on Windows — and that spelling names no ancestor, so the `..` tests\n\t// miss it and containment turns on `isAbsolute`.\n\tif (contained === '..' || contained.startsWith(`..${sep}`) || isAbsolute(contained)) {\n\t\treturn undefined\n\t}\n\treturn candidate\n}\n\n/**\n * Resolves a target that stays below a root directory, refusing a path outside it.\n *\n * @param root - The absolute root directory.\n * @param target - The relative or absolute target to resolve.\n * @returns The absolute target below the root.\n * @throws An `Error` reading `Path outside scratch directory: <target>` when the target resolves outside the\n * root.\n * @remarks This is {@link resolveContained} with the refusal every contained scratch operation makes\n * of a path outside the root, so the check and its one message are stated once. Read `resolveContained` where\n * a path outside the root is an answer rather than a refusal.\n *\n * @example\n * ```ts\n * import { requireContained } from '@orkestrel/test/server'\n *\n * requireContained('/scratch', 'nested/file.txt') // '/scratch/nested/file.txt'\n *\n * // Throws Error: Path outside scratch directory: ../escape.ts\n * requireContained('/scratch', '../escape.ts')\n * ```\n */\nexport function requireContained(root: string, target: string): string {\n\tconst candidate = resolveContained(root, target)\n\tif (candidate === undefined) throw new Error(`Path outside scratch directory: ${target}`)\n\treturn candidate\n}\n\n/**\n * Reads the identity of one allocated directory off a host status.\n *\n * @param status - The bigint status read from the directory's path with `{ bigint: true }`.\n * @returns The device, index node, and creation time in nanoseconds that together name the allocation.\n *\n * @example\n * ```ts\n * import { statSync } from 'node:fs'\n * import { readIdentity } from '@orkestrel/test/server'\n *\n * const status = statSync('/scratch', { bigint: true })\n *\n * readIdentity(status) // { birth: status.birthtimeNs, device: status.dev, inode: status.ino }\n * ```\n */\nexport function readIdentity(status: BigIntStats): ScratchIdentity {\n\treturn { birth: status.birthtimeNs, device: status.dev, inode: status.ino }\n}\n\n/**\n * Reports whether a contained entry exists under a scratch directory without following its final link.\n *\n * @param root - The absolute scratch directory path.\n * @param target - The relative or absolute contained entry to inspect.\n * @returns True if the root directory and entry exist; false otherwise.\n * @throws Thrown when the target resolves outside the root, the root is a symbolic link or not a directory,\n * or the host refuses to inspect either path.\n * @remarks Checks containment before inspecting the root. Intermediate links are followed; a\n * dangling final link counts as present. The root's allocation identity is not checked.\n *\n * @example\n * ```ts\n * import { createScratch, hasScratchPath } from '@orkestrel/test/server'\n *\n * const scratch = createScratch({ files: { 'entry.txt': 'present' } })\n * try {\n * \thasScratchPath(scratch.path, 'entry.txt') // true\n * \thasScratchPath(scratch.path, 'missing.txt') // false\n * } finally {\n * \tscratch.destroy()\n * }\n * ```\n */\nexport function hasScratchPath(root: string, target: string): boolean {\n\tconst candidate = requireContained(root, target)\n\tconst rootStatus = lstatSync(root, { throwIfNoEntry: false })\n\tif (rootStatus === undefined) return false\n\tif (rootStatus.isSymbolicLink()) throw new Error('Scratch directory is a symbolic link')\n\tif (!rootStatus.isDirectory()) throw new Error('Scratch path is not a directory')\n\n\treturn lstatSync(candidate, { throwIfNoEntry: false }) !== undefined\n}\n\n/**\n * Reads the `code` an unknown thrown value carries.\n *\n * @param error - The thrown value to read.\n * @returns The string `code` the value carries, or `undefined` when it carries none.\n * @remarks The read is contained on its own terms: a value that is not an object, one carrying no\n * `code`, and one carrying a `code` that is not a string all answer `undefined`. A null-prototype\n * object is read the same way, because the key is tested with `in` rather than through\n * `hasOwnProperty`.\n *\n * @example\n * ```ts\n * import { readFileSync } from 'node:fs'\n * import { captureError } from '@orkestrel/test'\n * import { readErrorCode } from '@orkestrel/test/server'\n *\n * readErrorCode(captureError(() => readFileSync('/scratch/absent.txt', 'utf8'))) // 'ENOENT'\n * readErrorCode(new Error('refused')) // undefined\n * ```\n */\nexport function readErrorCode(error: unknown): string | undefined {\n\treturn isObject(error) && 'code' in error && isString(error.code) ? error.code : undefined\n}\n\n/**\n * Reports whether two directory identities name the same allocation.\n *\n * @param current - The identity read from the path.\n * @param allocation - The identity recorded when the directory was allocated.\n * @returns True if the device, the index node, and the creation time all match; false otherwise.\n * @remarks All three fields are compared because none of them alone identifies an allocation. A\n * device is shared by every directory on one filesystem, an index node is reused after its directory\n * is removed, and a creation time repeats within the host's timestamp resolution.\n *\n * @example\n * ```ts\n * import { statSync } from 'node:fs'\n * import { matchesIdentity, readIdentity } from '@orkestrel/test/server'\n *\n * const allocation = readIdentity(statSync('/scratch', { bigint: true }))\n *\n * matchesIdentity(readIdentity(statSync('/scratch', { bigint: true })), allocation) // true\n * matchesIdentity({ birth: 3n, device: 1n, inode: 9n }, { birth: 3n, device: 1n, inode: 2n }) // false\n * ```\n */\nexport function matchesIdentity(current: ScratchIdentity, allocation: ScratchIdentity): boolean {\n\treturn (\n\t\tcurrent.device === allocation.device &&\n\t\tcurrent.inode === allocation.inode &&\n\t\tcurrent.birth === allocation.birth\n\t)\n}\n\n/**\n * Reports whether a root-relative key matches an exclusion.\n *\n * @param key - The root-relative key to test.\n * @param exclusions - The normalized root-relative exclusion keys.\n * @returns True if an exclusion names the key or one of its ancestors; false otherwise.\n *\n * @example\n * ```ts\n * import { isExcluded } from '@orkestrel/test/server'\n *\n * isExcluded('src/index.ts', ['src']) // true\n * isExcluded('src-other/index.ts', ['src']) // false\n * ```\n */\nexport function isExcluded(key: string, exclusions: readonly string[]): boolean {\n\treturn exclusions.some((rule) => rule === '' || key === rule || key.startsWith(`${rule}/`))\n}\n\n/**\n * Creates a symbolic link with a directory-junction fallback for hosts that refuse symbolic links.\n *\n * @param path - The path where the link is created.\n * @param source - The destination path the link points at.\n * @throws The original link error when its code is not `EPERM`, or when the source names an\n * existing non-directory; otherwise, any error from inspecting the source or creating the junction.\n * @remarks Only `EPERM` from the first symbolic-link attempt triggers the fallback. The fallback\n * resolves the source against the link's directory. An existing non-directory rethrows the original\n * `EPERM`, while a directory or missing source is passed to a junction attempt. A missing source is\n * accepted to create a dangling junction. Where the host creates a junction, its stored value is the\n * resolved absolute path.\n *\n * @example\n * ```ts\n * import { readFileSync } from 'node:fs'\n * import { createLink } from '@orkestrel/test/server'\n *\n * // `/scratch/source` is a directory holding `file.txt`.\n * createLink('/scratch/linked', '/scratch/source')\n *\n * readFileSync('/scratch/linked/file.txt', 'utf8') // 'linked'\n * ```\n */\nexport function createLink(path: string, source: string): void {\n\ttry {\n\t\tsymlinkSync(source, path)\n\t} catch (error) {\n\t\tif (readErrorCode(error) !== 'EPERM') throw error\n\n\t\tconst resolved = resolve(dirname(path), source)\n\t\tconst status = statSync(resolved, { throwIfNoEntry: false })\n\t\tif (status !== undefined && !status.isDirectory()) throw error\n\t\tsymlinkSync(resolved, path, 'junction')\n\t}\n}\n\n/**\n * Removes a directory tree, retrying past a transient Windows handle-release race.\n *\n * @param path - The absolute directory to remove.\n * @throws The last removal error after {@link REMOVE_TREE_MAX_ATTEMPTS} attempts are exhausted,\n * or immediately for any error whose code is not in {@link REMOVE_TREE_RETRYABLE_CODES}.\n * @remarks On Windows, a directory that a recently exited process still holds as its current\n * working directory throws `EPERM` for a short interval after that process exits. Node's own\n * `rmSync` `maxRetries`/`retryDelay` options do not cover this error class on that host: probed\n * against a real held directory, they neither delay nor retry before rethrowing, so the retry\n * is implemented here with a synchronous sleep instead. Ten attempts 100ms apart bound the wait\n * at roughly one second. A hold that outlasts that second is {@link destroyScratch}'s case, which\n * retries every refusal inside a caller's budget rather than the codes named here.\n *\n * @example\n * ```ts\n * import { existsSync } from 'node:fs'\n * import { removeTree } from '@orkestrel/test/server'\n *\n * removeTree('/scratch/tree')\n *\n * existsSync('/scratch/tree') // false\n * ```\n */\nexport function removeTree(path: string): void {\n\tfor (const [index] of Array.from({ length: REMOVE_TREE_MAX_ATTEMPTS }).entries()) {\n\t\ttry {\n\t\t\trmSync(path, { force: true, recursive: true })\n\t\t\treturn\n\t\t} catch (error) {\n\t\t\tconst code = readErrorCode(error)\n\t\t\tif (\n\t\t\t\tcode === undefined ||\n\t\t\t\t!REMOVE_TREE_RETRYABLE_CODES.includes(code) ||\n\t\t\t\tindex + 1 >= REMOVE_TREE_MAX_ATTEMPTS\n\t\t\t) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, REMOVE_TREE_RETRY_DELAY_MS)\n\t\t}\n\t}\n}\n\n/**\n * Reads files from selected targets below a root directory.\n *\n * @param root - The root directory as a path or file URL.\n * @param targets - The files to read directly and directories to visit below the root.\n * @param options - Optional file extension and path exclusions.\n * @returns File contents keyed by sorted root-relative paths.\n * @throws When the root or a named target is a symbolic link, is not a supported entry, or resolves\n * outside the root.\n * @remarks A named file is included regardless of the extension filter. An absent extension filter\n * includes every walked file. An exclusion matches whole root-relative key segments and covers every\n * key below it, and it applies to a named target and a walked entry alike.\n */\nexport function readInventory(\n\troot: URL | string,\n\ttargets: readonly string[],\n\toptions?: InventoryOptions,\n): Readonly<Record<string, string>> {\n\tconst supplied = resolve(isString(root) ? root : fileURLToPath(root))\n\tconst rootStatus = lstatSync(supplied)\n\tif (rootStatus.isSymbolicLink()) throw new Error('Root is a symbolic link')\n\tif (!rootStatus.isDirectory()) throw new Error('Root is not a directory')\n\n\tconst base = realpathSync.native(supplied)\n\tif (targets.length === 0) return Object.fromEntries([])\n\n\tconst exclusions = (options?.exclude ?? []).map((rule) => {\n\t\tconst unprefixed = rule.startsWith('./') ? rule.slice(2) : rule\n\t\tconst collapsed = unprefixed.replace(/\\/+/g, '/')\n\t\tconst untrailed = collapsed.endsWith('/') ? collapsed.slice(0, -1) : collapsed\n\t\treturn untrailed === '.' ? '' : untrailed\n\t})\n\tconst pending: string[] = []\n\tconst queued = new Set<string>()\n\tconst contents = new Map<string, string>()\n\n\tfor (const target of targets) {\n\t\tconst candidate = resolveContained(base, target)\n\t\tif (candidate === undefined) {\n\t\t\tthrow new Error(`Target outside root: ${target}`)\n\t\t}\n\n\t\tconst status = lstatSync(candidate)\n\t\tif (status.isSymbolicLink()) throw new Error(`Target is a symbolic link: ${target}`)\n\t\tif (!status.isDirectory() && !status.isFile()) {\n\t\t\tthrow new Error(`Target is not a file or directory: ${target}`)\n\t\t}\n\n\t\tconst physical = realpathSync.native(candidate)\n\t\tconst resolved = resolveContained(base, relative(base, physical))\n\t\tif (resolved === undefined) {\n\t\t\tthrow new Error(`Target outside root: ${target}`)\n\t\t}\n\n\t\tconst key = relative(base, resolved).split(sep).join('/')\n\t\tif (isExcluded(key, exclusions)) continue\n\t\tif (status.isFile()) {\n\t\t\tcontents.set(key, readFileSync(physical, 'utf8'))\n\t\t\tcontinue\n\t\t}\n\t\tif (queued.has(physical)) continue\n\t\tqueued.add(physical)\n\t\tpending.push(physical)\n\t}\n\n\twhile (pending.length > 0) {\n\t\tconst directory = pending.pop()\n\t\tif (directory === undefined) continue\n\n\t\tfor (const entry of readdirSync(directory, { withFileTypes: true })) {\n\t\t\tconst path = resolve(directory, entry.name)\n\t\t\tconst status = lstatSync(path)\n\t\t\tif (status.isSymbolicLink()) continue\n\n\t\t\tconst key = relative(base, path).split(sep).join('/')\n\t\t\tif (isExcluded(key, exclusions)) continue\n\n\t\t\tif (status.isDirectory()) {\n\t\t\t\tconst physical = realpathSync.native(path)\n\t\t\t\tconst resolved = resolveContained(base, relative(base, physical))\n\t\t\t\t// Walk containment is unproven because POSIX CI skips links before `realpath`;\n\t\t\t\t// a host that resolves a walked directory outside `base` would drive this branch.\n\t\t\t\tif (resolved === undefined || queued.has(physical)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tqueued.add(physical)\n\t\t\t\tpending.push(physical)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\t!status.isFile() ||\n\t\t\t\t(options?.extensions !== undefined &&\n\t\t\t\t\t!options.extensions.some((extension) => entry.name.endsWith(extension)))\n\t\t\t) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcontents.set(key, readFileSync(path, 'utf8'))\n\t\t}\n\t}\n\n\treturn Object.fromEntries(\n\t\tArray.from(contents).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)),\n\t)\n}\n\n/**\n * Reports whether a process id names a live process.\n *\n * @param pid - The process id to read.\n * @returns True if a process holds that id at the moment of the call; false otherwise, including a\n * pid the host refuses.\n * @throws Nothing. Every host refusal reads as false.\n * @remarks This is an instantaneous observation rather than a claim of ownership. A host reuses a\n * process id after the process holding it exits, so a true answer says some process holds that id at the time of the check\n * and never says it is the process the caller started. Two host answers are worth knowing. A POSIX\n * host refuses signal `0` to a process another user owns with `EPERM`, and that refusal reads as\n * false here. A pid of `0` names the caller's own process group on POSIX and the system idle process\n * on Windows, so it reads as true on both without naming a process anyone started.\n *\n * A Linux zombie — a process that has exited and whose parent has not reaped it — still accepts\n * signal `0`, so its `/proc` status is read and a `Z` state reads as false.\n *\n * @example\n * ```ts\n * import { isRunning } from '@orkestrel/test/server'\n *\n * isRunning(process.pid) // true\n * isRunning(2 ** 31) // false\n * ```\n */\nexport function isRunning(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0)\n\t} catch {\n\t\treturn false\n\t}\n\tif (process.platform !== 'linux') return true\n\n\t// The zombie refinement is unproven on a host that carries no `/proc`; a Linux gate drives it.\n\ttry {\n\t\tconst status = readFileSync(`/proc/${String(pid)}/stat`, 'utf8')\n\t\tconst boundary = status.lastIndexOf(') ')\n\t\treturn boundary < 0 || status.slice(boundary + 2, boundary + 3) !== 'Z'\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * Waits for a socket to close, accepting a peer reset as a forced close.\n *\n * @param socket - The socket to wait on. One that has already closed resolves without listening.\n * @param options - The time bounds and abort signal.\n * @returns A promise that resolves when the socket emits `close`.\n * @throws The socket's own error when its code is not `ECONNRESET`, the abort reason, or an `Error`\n * when a bound is invalid or the socket does not close within the budget.\n * @remarks Default budget: `1000` milliseconds. A reset is the peer forcing the connection down, and\n * the socket still emits `close` afterwards, so `ECONNRESET` is waited past rather than raised while\n * every other error ends the wait. The interval is validated for consistency with the wait family but\n * is not used, because this helper parks on the socket's events. Both listeners are removed on every\n * settlement, so a caller may wait on one socket repeatedly.\n *\n * @example\n * ```ts\n * import { connect, createServer } from 'node:net'\n * import { createLoopback, waitForSocketClose } from '@orkestrel/test/server'\n *\n * const loopback = await createLoopback(createServer((socket) => socket.end()))\n * const client = connect(loopback.port, '127.0.0.1')\n *\n * await waitForSocketClose(client, { budget: 1000 }) // undefined\n * client.destroyed // true\n *\n * await loopback.destroy()\n * ```\n */\nexport async function waitForSocketClose(socket: Socket, options?: WaitOptions): Promise<void> {\n\tconst budget = options?.budget ?? 1000\n\tconst interval = options?.interval ?? 10\n\tcheckBounds('Socket', budget, interval)\n\n\tconst signal = options?.signal\n\tsignal?.throwIfAborted()\n\tif (socket.closed) return\n\n\t// The resolvers are the listeners themselves, so the same references remove them afterwards.\n\tconst closed = Promise.withResolvers<boolean>()\n\tconst failed = Promise.withResolvers<NodeJS.ErrnoException>()\n\tconst expiry = Promise.withResolvers<never>()\n\tconst aborted = Promise.withResolvers<never>()\n\tconst subscription = new AbortController()\n\tsocket.on('close', closed.resolve)\n\tsocket.on('error', failed.resolve)\n\tsignal?.addEventListener('abort', () => aborted.reject(signal.reason), {\n\t\tonce: true,\n\t\tsignal: subscription.signal,\n\t})\n\tconst timer = setTimeout(() => {\n\t\texpiry.reject(new Error(`Socket did not close within ${budget}ms`))\n\t}, budget)\n\n\ttry {\n\t\tconst error = await Promise.race([\n\t\t\tclosed.promise.then(() => undefined),\n\t\t\tfailed.promise,\n\t\t\texpiry.promise,\n\t\t\taborted.promise,\n\t\t])\n\t\tif (error === undefined) return\n\t\tif (error.code !== 'ECONNRESET') throw error\n\t\tawait Promise.race([closed.promise, expiry.promise, aborted.promise])\n\t} finally {\n\t\tclearTimeout(timer)\n\t\tsubscription.abort()\n\t\tsocket.off('close', closed.resolve)\n\t\tsocket.off('error', failed.resolve)\n\t}\n}\n\n/**\n * Destroys a scratch directory, retrying until the host releases it.\n *\n * @param scratch - The scratch directory to destroy.\n * @param options - The time bounds and abort signal.\n * @returns A promise that resolves after `destroy()` returns without throwing.\n * @throws The abort reason, or an `Error` when a bound is invalid or the budget elapses. The\n * exhaustion error carries the last host refusal as its `cause`.\n * @remarks Default budget: `10000` milliseconds. Default interval: `25` milliseconds. A host holds a\n * directory for a short interval after the process that held it exits, and a recently stopped child's\n * working directory is the case this exists for, so removal is attempted until the host lets go\n * rather than exactly once. {@link ScratchInterface.destroy} stays synchronous and is unchanged; this\n * is the bounded retry around it. A directory nothing releases still fails, with the host's own\n * refusal as the `cause`.\n *\n * Every refusal is retried, deliberately, and that is wider than {@link removeTree}'s policy: that\n * one retries the codes {@link REMOVE_TREE_RETRYABLE_CODES} names and rethrows the rest at once.\n * The hold this waits out is not classifiable across hosts — Windows reports a working-directory\n * hold as `EPERM`, POSIX hosts and network filesystems report their own — so a code list here would\n * be a list of the hosts it had been run on. The residual is the cost of that: a fault no wait can\n * clear, such as a path removed from under the allocation or a permission the process never had,\n * spends the whole budget before it surfaces, and it surfaces wrapped in the exhaustion error with\n * the host's refusal as `cause` rather than by identity. Pass a shorter `budget` or a `signal`\n * wherever a caller must bound that cost.\n */\nexport async function destroyScratch(\n\tscratch: ScratchInterface,\n\toptions?: WaitOptions,\n): Promise<void> {\n\tconst budget = options?.budget ?? 10_000\n\tconst interval = options?.interval ?? 25\n\tcheckBounds('Scratch', budget, interval)\n\n\tconst start = performance.now()\n\twhile (true) {\n\t\toptions?.signal?.throwIfAborted()\n\t\ttry {\n\t\t\tscratch.destroy()\n\t\t\treturn\n\t\t} catch (error) {\n\t\t\tif (performance.now() - start >= budget) {\n\t\t\t\tthrow new Error(`Scratch directory was not destroyed within ${budget}ms`, {\n\t\t\t\t\tcause: error,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tawait waitForDelay(interval)\n\t}\n}\n\n/**\n * Reads the loop clock Node stamps on an armed timer, in whole milliseconds.\n *\n * @returns The reading since the loop's timer base, independent of `performance.now()`.\n * @throws Thrown when Node's `Timeout` carries no numeric `_idleStart` field.\n * @remarks Node refreshes libuv's clock when arming a timer and records it in the undocumented\n * `_idleStart` field. Compare these readings with each other, never with another clock.\n * @example\n * ```ts\n * const before = readLoopClock()\n * alignLoopClock()\n * readLoopClock() > before // true\n * ```\n */\nexport function readLoopClock(): number {\n\tconst timer = setTimeout(() => undefined, 1)\n\tclearTimeout(timer)\n\tconst stamp: unknown = Reflect.get(timer, '_idleStart')\n\tif (!isNumber(stamp)) throw new Error('the armed timer carries no numeric _idleStart stamp')\n\treturn stamp\n}\n\n/**\n * Spins synchronously past a loop-clock tick and an optional millisecond offset.\n *\n * @param offset - The milliseconds to spin after the tick. Default: `0`.\n * @remarks The spin holds the calling macrotask so libuv cannot refresh the clock through a yield.\n * An offset near 1 arms a subsequent timer late in a millisecond, exposing timer truncation.\n * @example\n * ```ts\n * alignLoopClock(0.9)\n * const started = performance.now()\n * await waitForDelay(10)\n * performance.now() - started >= 10 - TIMER_LEAD // true\n * ```\n */\nexport function alignLoopClock(offset = 0): void {\n\tconst tick = readLoopClock()\n\twhile (readLoopClock() === tick) {\n\t\t// A yield would let libuv refresh the clock outside this macrotask.\n\t}\n\tconst crossed = performance.now()\n\twhile (performance.now() - crossed < offset) {\n\t\t// Keep the offset within the same macrotask.\n\t}\n}\n\n/**\n * Drives a real client upgrade request against a loopback port and reports what the server did.\n *\n * @param port - The port the server listens on at `127.0.0.1`.\n * @param options - Optional request path, offered subprotocols, time bounds, and abort signal.\n * @returns A promise resolving to the server's answer: a claimed upgrade with the protocol it\n * selected, or a refusal with the status it answered.\n * @throws The client's own transport error, such as the `ECONNREFUSED` a closed port answers, the\n * abort reason, or an `Error` when a bound is invalid or the server does not answer within the\n * budget.\n * @remarks Default budget: `1000` milliseconds. The request carries `Connection: Upgrade` and\n * `Upgrade: websocket`, which is what makes a server's `upgrade` handler the one that answers it.\n * The `upgrade`, `response`, and `error` events are mutually exclusive in practice and the promise\n * settles on whichever arrives first, so a second event changes nothing. The client socket is\n * destroyed before every settlement, on the claimed path because an upgraded socket is detached from\n * the request and outlives it otherwise. The request is made with no agent, so no pooled connection\n * survives the call to keep a suite's event loop alive.\n *\n * A server that accepts the connection and answers nothing raises no transport error, so the budget\n * is what ends that call: the rejection names the port and path it was waiting on. The interval is\n * validated for consistency with the wait family but is not used, because this helper parks on the\n * request's events.\n *\n * A `101` is the claimed path's status on the wire and is deliberately not reported: `status` is the\n * refused arm's member, and a claimed upgrade produced no plain answer.\n * @example\n * ```ts\n * const answer = await requestUpgrade(loopback.port, { path: '/socket', protocols: ['chat'] })\n * // { claimed: true, protocol: 'chat' }\n * ```\n */\nexport async function requestUpgrade(\n\tport: number,\n\toptions?: UpgradeOptions,\n): Promise<UpgradeResult> {\n\tconst budget = options?.budget ?? 1000\n\tconst interval = options?.interval ?? 10\n\tcheckBounds('Upgrade', budget, interval)\n\n\tconst signal = options?.signal\n\tsignal?.throwIfAborted()\n\n\tconst path = options?.path ?? '/'\n\tconst target = `127.0.0.1:${port}${path}`\n\tconst headers: Record<string, string> = { connection: 'Upgrade', upgrade: 'websocket' }\n\tconst protocols = options?.protocols ?? []\n\tif (protocols.length > 0) headers['sec-websocket-protocol'] = protocols.join(', ')\n\n\tconst request = requestHTTP({ agent: false, headers, host: '127.0.0.1', path, port })\n\tconst settled = Promise.withResolvers<UpgradeResult>()\n\tconst expiry = Promise.withResolvers<never>()\n\tconst aborted = Promise.withResolvers<never>()\n\tconst subscription = new AbortController()\n\trequest.on('upgrade', (response, socket) => {\n\t\tconst protocol = response.headers['sec-websocket-protocol']\n\t\tsocket.destroy()\n\t\tsettled.resolve({ claimed: true, protocol })\n\t})\n\trequest.on('response', (response) => {\n\t\tconst status = response.statusCode\n\t\tresponse.destroy()\n\t\trequest.destroy()\n\t\t// A client response reaches this listener only after its status line is parsed, so the\n\t\t// refusal is unproven; the server-side `IncomingMessage` that shares this type carries no\n\t\t// status and would drive it.\n\t\tif (status === undefined) {\n\t\t\tsettled.reject(new Error(`Upgrade request to ${target} was answered without a status`))\n\t\t\treturn\n\t\t}\n\t\tsettled.resolve({ claimed: false, status })\n\t})\n\trequest.on('error', (error) => {\n\t\trequest.destroy()\n\t\tsettled.reject(error)\n\t})\n\tsignal?.addEventListener('abort', () => aborted.reject(signal.reason), {\n\t\tonce: true,\n\t\tsignal: subscription.signal,\n\t})\n\tconst timer = setTimeout(() => {\n\t\texpiry.reject(new Error(`Upgrade request to ${target} was not answered within ${budget}ms`))\n\t}, budget)\n\trequest.end()\n\n\ttry {\n\t\treturn await Promise.race([settled.promise, expiry.promise, aborted.promise])\n\t} finally {\n\t\tclearTimeout(timer)\n\t\tsubscription.abort()\n\t\trequest.destroy()\n\t}\n}\n\n/**\n * Checks whether this host links a directory, by creating one link and reading through it.\n *\n * @returns True if the created link reports as a symbolic link, resolves to a directory, and reaches\n * the destination's contents; false otherwise, including every host refusal.\n * @throws Nothing the attempt itself raises. Failing to allocate the probe directory, and failing to\n * remove it afterwards, both propagate.\n * @remarks `symlinkSync(source, target, 'junction')` creates a directory junction on Windows, which\n * needs no privilege, and Node ignores the type argument off Windows, so one call covers both hosts.\n * The answer is false on a filesystem carrying neither reparse points nor symbolic links. Every call\n * probes and cleans up after itself, so a host whose answer changes is read again rather than\n * remembered.\n *\n * @example\n * ```ts\n * import { supportsDirectoryLinks } from '@orkestrel/test/server'\n *\n * supportsDirectoryLinks() // true where the host creates a symbolic link or a junction\n * ```\n */\nexport function supportsDirectoryLinks(): boolean {\n\tconst directory = mkdtempSync(join(tmpdir(), 'orkestrel-test-directory-links-'))\n\ttry {\n\t\tconst source = join(directory, 'source')\n\t\tconst link = join(directory, 'link')\n\t\tmkdirSync(source)\n\t\twriteFileSync(join(source, 'marker.txt'), 'marked')\n\t\tsymlinkSync(source, link, 'junction')\n\t\treturn (\n\t\t\tlstatSync(link).isSymbolicLink() &&\n\t\t\tstatSync(link).isDirectory() &&\n\t\t\treadFileSync(join(link, 'marker.txt'), 'utf8') === 'marked'\n\t\t)\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tremoveTree(directory)\n\t}\n}\n\n/**\n * Checks whether this host links a file, by creating one link and reading the file through it.\n *\n * @returns True if the file's contents are readable through the link; false otherwise, including\n * every host refusal.\n * @throws Nothing the attempt itself raises. Failing to allocate the probe directory, and failing to\n * remove it afterwards, both propagate.\n * @remarks `symlinkSync(source, target, 'file')` needs the symbolic-link privilege, which Windows\n * grants under Developer Mode or administrator rights and refuses with `EPERM` otherwise, so the\n * answer is true on POSIX and on a privileged Windows host. Where it is false, no mechanism reaches a\n * file through a link and a proof that reads one back cannot run. This is a separate question from\n * {@link supportsDirectoryLinks}, which an unprivileged Windows host answers true through a junction\n * while answering this one false.\n */\nexport function supportsFileLinks(): boolean {\n\tconst directory = mkdtempSync(join(tmpdir(), 'orkestrel-test-file-links-'))\n\ttry {\n\t\tconst source = join(directory, 'source.txt')\n\t\tconst link = join(directory, 'link.txt')\n\t\twriteFileSync(source, 'linked')\n\t\tsymlinkSync(source, link, 'file')\n\t\treturn readFileSync(link, 'utf8') === 'linked'\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tremoveTree(directory)\n\t}\n}\n\n/**\n * Checks whether POSIX permission bits round-trip through this host's `chmod` and `stat`.\n *\n * @returns True if a directory created with mode `0o700` reports that mode back; false otherwise,\n * including every host refusal.\n * @throws Nothing the attempt itself raises. Failing to allocate the probe directory, and failing to\n * remove it afterwards, both propagate.\n * @remarks POSIX reports `mode & 0o777 === 0o700` and Windows reports `0o666` regardless, so the\n * answer is true on POSIX and false on Windows. Storing a bit is a narrower question than enforcing\n * it: a POSIX host running as uid `0` stores every bit faithfully and is exempt from the access check the\n * bits describe, so a caller that needs a permission to be enforced probes the refusal it needs\n * rather than reading this.\n *\n * @example\n * ```ts\n * import { supportsMode } from '@orkestrel/test/server'\n *\n * supportsMode() // true on a POSIX host, false on Windows\n * ```\n */\nexport function supportsMode(): boolean {\n\tconst directory = mkdtempSync(join(tmpdir(), 'orkestrel-test-mode-'))\n\ttry {\n\t\tconst path = join(directory, 'moded')\n\t\tmkdirSync(path, { mode: 0o700 })\n\t\treturn (statSync(path).mode & 0o777) === 0o700\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tremoveTree(directory)\n\t}\n}\n\n/**\n * Checks whether this host treats two names differing only by case as distinct files.\n *\n * @returns True if `A` and `a` hold the contents each was written with; false otherwise, including\n * every host refusal.\n * @throws Nothing the attempt itself raises. Failing to allocate the probe directory, and failing to\n * remove it afterwards, both propagate.\n * @remarks The names `A` and `a` differ by case and by nothing else, which is what makes the reading\n * an answer about case folding rather than an answer about two unrelated files. A case-folding volume\n * routes the second write onto the first entry, so reading the first back returns the second's\n * contents and the answer is false. The answer is true on a typical POSIX host and false on a\n * case-folding Windows or macOS volume.\n *\n * @example\n * ```ts\n * import { supportsCase } from '@orkestrel/test/server'\n *\n * supportsCase() // true on a case-sensitive volume, false on a case-folding one\n * ```\n */\nexport function supportsCase(): boolean {\n\tconst directory = mkdtempSync(join(tmpdir(), 'orkestrel-test-case-'))\n\ttry {\n\t\tconst upper = join(directory, 'A')\n\t\tconst lower = join(directory, 'a')\n\t\twriteFileSync(upper, 'upper')\n\t\twriteFileSync(lower, 'lower')\n\t\treturn readFileSync(upper, 'utf8') === 'upper' && readFileSync(lower, 'utf8') === 'lower'\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tremoveTree(directory)\n\t}\n}\n\n/**\n * Checks whether this host accepts a filename carrying a raw byte no UTF-8 decoder resolves.\n *\n * @returns True if a name ending in byte `0x80` is written and read back; false otherwise, including\n * every host refusal.\n * @throws Nothing the attempt itself raises. Failing to allocate the probe directory, and failing to\n * remove it afterwards, both propagate.\n * @remarks Byte `0x80` is an invalid UTF-8 lead byte. POSIX stores the name verbatim and Windows\n * rejects it with `ENOENT`, so the answer is true on POSIX and false on Windows. The path is passed\n * as a `Buffer` because the byte survives no string round trip.\n *\n * @example\n * ```ts\n * import { supportsBytes } from '@orkestrel/test/server'\n *\n * supportsBytes() // true on a POSIX host, false on Windows\n * ```\n */\nexport function supportsBytes(): boolean {\n\tconst directory = mkdtempSync(join(tmpdir(), 'orkestrel-test-bytes-'))\n\ttry {\n\t\tconst name = Buffer.concat([Buffer.from(`${directory}${sep}`), Buffer.from([0x80])])\n\t\twriteFileSync(name, 'raw')\n\t\treturn readFileSync(name, 'utf8') === 'raw'\n\t} catch {\n\t\treturn false\n\t} finally {\n\t\tremoveTree(directory)\n\t}\n}\n\n/**\n * Observes a native chooser before activating its input and supplies the verified chooser's fixture bytes.\n *\n * @param context - The real Playwright page and tester frame supplied by Vitest.\n * @param request - The resolved input selector, fixture selection, activation method, and wait budget.\n * @returns A promise resolving after the expected chooser receives the files and its observer is released.\n * @throws When activation fails, no chooser opens, another input opens it, the page closes, or fixture bytes are invalid.\n * @remarks Register this function as the `chooseFiles` command in the workspace's `configs/commands.ts`, the\n * module the root configuration passes to every browser project as `test.browser.commands`. It never falls\n * back to direct file assignment.\n * @example\n * ```ts\n * // configs/commands.ts\n * import { chooseFiles } from '@orkestrel/test/server'\n * import type { BrowserConfigOptions } from 'vitest/node'\n *\n * export const commands: Readonly<NonNullable<BrowserConfigOptions['commands']>> = Object.freeze({\n * \tchooseFiles,\n * })\n * ```\n */\nexport async function chooseFiles(context: ChooserContext, request: ChooserRequest): Promise<void> {\n\tconst budget = request.budget ?? 1000\n\tcheckBounds('File chooser', budget, 0)\n\tif (budget === 0) throw new Error('File chooser budget must be positive')\n\tconst files = request.files.map((file) => {\n\t\tif (file.bytes.some((byte) => !Number.isInteger(byte) || byte < 0 || byte > 255))\n\t\t\tthrow new Error('Fixture file bytes must be integers from 0 to 255')\n\t\treturn { name: file.name, mimeType: file.mime, buffer: Buffer.from(file.bytes) }\n\t})\n\tconst target = await context.iframe.locator(request.selector).elementHandle({ timeout: budget })\n\tif (target === null) throw new Error('Native file input disappeared before activation')\n\tconst controller = new AbortController()\n\ttry {\n\t\tif (\n\t\t\t!(await target.evaluate(\n\t\t\t\t(element) =>\n\t\t\t\t\telement.nodeName === 'INPUT' && element.getAttribute('type')?.toLowerCase() === 'file',\n\t\t\t))\n\t\t)\n\t\t\tthrow new Error('Resolved target is not a native file input')\n\t\tif (\n\t\t\trequest.keyboard &&\n\t\t\t!(await target.evaluate((element) => element === element.ownerDocument.activeElement))\n\t\t)\n\t\t\tthrow new Error('Native file input lost keyboard focus before activation')\n\t\tconst observed = waitForEvent<readonly [event: FileChooser | Page]>(\n\t\t\t(listener) => {\n\t\t\t\tcontext.page.on('filechooser', listener)\n\t\t\t\tcontext.page.on('close', listener)\n\t\t\t\treturn () => {\n\t\t\t\t\tcontext.page.off('filechooser', listener)\n\t\t\t\t\tcontext.page.off('close', listener)\n\t\t\t\t}\n\t\t\t},\n\t\t\t'native file chooser',\n\t\t\t{ budget, signal: controller.signal },\n\t\t)\n\t\tconst activated = request.keyboard\n\t\t\t? target.press('Enter', { timeout: budget })\n\t\t\t: target.click({ timeout: budget })\n\t\tconst joined = Promise.all([observed, activated])\n\t\t// The first failure or the joint success ends this wait; the observer is released next, and the\n\t\t// settled results then say whether a chooser opened even where activation failed.\n\t\tawait Promise.allSettled([joined])\n\t\tcontroller.abort()\n\t\tconst [result] = await Promise.allSettled([observed, activated])\n\t\tconst [event] = result.status === 'fulfilled' ? result.value : []\n\t\tconst chooser = event !== undefined && 'element' in event ? event : undefined\n\t\ttry {\n\t\t\t// Both promises have settled, so this rethrows the activation or observation failure by identity.\n\t\t\tawait joined\n\t\t\tif (chooser === undefined)\n\t\t\t\tthrow new Error('Page closed before the native file chooser opened')\n\t\t\tif (!(await chooser.element().evaluate((element, expected) => element === expected, target)))\n\t\t\t\tthrow new Error('Native file chooser belongs to a different input')\n\t\t\tawait chooser.setFiles(files, { timeout: budget })\n\t\t} finally {\n\t\t\tawait chooser?.element().dispose()\n\t\t}\n\t} finally {\n\t\tcontroller.abort()\n\t\tawait target.dispose()\n\t}\n}\n\n/**\n * Normalizes a module or stack-frame path to the form a progress line carries.\n *\n * @param file - The path Vitest reports, a Vite `/@fs/` path included.\n * @param root - The run's root directory.\n * @returns The path relative to the root with `/` separators, or the path unchanged when it resolves\n * outside the root.\n *\n * @example\n * ```ts\n * import { normalizeProgressPath } from '@orkestrel/test/server'\n *\n * normalizeProgressPath('/work/tests/a.test.ts', '/work') // 'tests/a.test.ts'\n * normalizeProgressPath('/elsewhere/b.ts', '/work') // '/elsewhere/b.ts'\n * ```\n */\nexport function normalizeProgressPath(file: string, root: string): string {\n\tconst path = relative(root, file.replace(/^\\/@fs\\//u, '')).replaceAll('\\\\', '/')\n\treturn path === '..' || path.startsWith('../') || isAbsolute(path) ? file : path\n}\n\n/**\n * Extracts the message line and location a progress line keeps from one Vitest error.\n *\n * @param error - The serialized error Vitest reports.\n * @param root - The run's root directory, which the location is relative to.\n * @returns The error's name and first message line, capped at `PROGRESS_MESSAGE_LIMIT` characters,\n * and the first stack frame outside `node_modules`, or the first frame when every frame sits there.\n *\n * @example\n * ```ts\n * import { extractProgressError } from '@orkestrel/test/server'\n *\n * extractProgressError(\n * \t{\n * \t\tname: 'AssertionError',\n * \t\tmessage: 'expected 1 to be 2\\nfull diff',\n * \t\tstacks: [{ method: '', file: '/work/tests/a.test.ts', line: 4, column: 9 }],\n * \t},\n * \t'/work',\n * )\n * // { message: 'AssertionError: expected 1 to be 2', location: 'tests/a.test.ts:4:9' }\n * ```\n */\nexport function extractProgressError(error: SerializedError, root: string): ProgressError {\n\tconst [line = ''] = stripVTControlCharacters(`${error.name ?? 'Error'}: ${error.message}`).split(\n\t\t/\\r?\\n/u,\n\t)\n\tconst message = line.slice(0, PROGRESS_MESSAGE_LIMIT)\n\tconst frame =\n\t\terror.stacks?.find((stack) => !stack.file.includes('node_modules')) ?? error.stacks?.[0]\n\treturn frame === undefined\n\t\t? { message }\n\t\t: {\n\t\t\t\tmessage,\n\t\t\t\tlocation: `${normalizeProgressPath(frame.file, root)}:${frame.line}:${frame.column}`,\n\t\t\t}\n}\n\n/**\n * Reports whether a collected case is one the run plans to report.\n *\n * @param test - A Vitest case, or any value carrying its `options.mode`.\n * @returns True if the case's mode is `run` or `only`; false for a case that `skip`, `todo`, or a\n * name filter removed.\n *\n * @example\n * ```ts\n * import { matchesPlannedCase } from '@orkestrel/test/server'\n *\n * matchesPlannedCase({ options: { mode: 'run' } }) // true\n * matchesPlannedCase({ options: { mode: 'skip' } }) // false\n * ```\n */\nexport function matchesPlannedCase(test: { readonly options: { readonly mode: string } }): boolean {\n\treturn test.options.mode === 'run' || test.options.mode === 'only'\n}\n\n/**\n * Reads the bytes a file holds when it is opened, leaving out every byte appended during the read.\n *\n * @param path - The file to read.\n * @returns The bytes up to the length the file had at open.\n * @throws Thrown when the host refuses to open, inspect, or read the file.\n *\n * @example\n * ```ts\n * import { writeFileSync } from 'node:fs'\n * import { readFileSnapshot } from '@orkestrel/test/server'\n *\n * writeFileSync('progress.jsonl', '{\"event\":\"init\"}\\n')\n * readFileSnapshot('progress.jsonl').length // 17\n * ```\n */\nexport function readFileSnapshot(path: string): Buffer {\n\tconst descriptor = openSync(path, 'r')\n\ttry {\n\t\tconst bytes = Buffer.alloc(fstatSync(descriptor).size)\n\t\treturn bytes.subarray(0, readSync(descriptor, bytes, 0, bytes.length, 0))\n\t} finally {\n\t\tcloseSync(descriptor)\n\t}\n}\n\n/**\n * Filters the progress lines of one event.\n *\n * @typeParam TName - The event to keep.\n * @param events - The lines to filter.\n * @param name - The event to keep.\n * @returns The matching lines in order.\n *\n * @example\n * ```ts\n * import { filterProgressEvents } from '@orkestrel/test/server'\n *\n * filterProgressEvents(\n * \t[\n * \t\t{ event: 'cancel', reason: 'test-failure', wall: 1, time: 2, pid: 3 },\n * \t\t{ event: 'ready', project: 'unit', id: 'a', name: 'adds', time: 3, pid: 3 },\n * \t],\n * \t'cancel',\n * ).length // 1\n * ```\n */\nexport function filterProgressEvents<TName extends ProgressEvent['event']>(\n\tevents: readonly ProgressEvent[],\n\tname: TName,\n): ReadonlyArray<Extract<ProgressEvent, { readonly event: TName }>> {\n\treturn events.filter(\n\t\t(event): event is Extract<ProgressEvent, { readonly event: TName }> => event.event === name,\n\t)\n}\n\n/**\n * Extracts the progress lines a text holds, skipping a partial last line.\n *\n * @param text - Progress file text, live or finished.\n * @returns Each complete line's event, in file order. The text after the last line feed is a line\n * the writer can still be appending, so it is never decoded.\n * @throws Thrown when a complete line is not valid JSON, is not a progress event, or is an `init`\n * line of another format version.\n *\n * @example\n * ```ts\n * import { extractProgressEvents } from '@orkestrel/test/server'\n *\n * extractProgressEvents(\n * \t'{\"event\":\"cancel\",\"reason\":\"test-failure\",\"wall\":1,\"time\":2,\"pid\":3}\\n{\"event\":\"ca',\n * ).length // 1\n * ```\n */\nexport function extractProgressEvents(text: string): readonly ProgressEvent[] {\n\treturn decodeJSONLines(text.slice(0, text.lastIndexOf('\\n') + 1)).map((value, index) => {\n\t\tif (!isProgressEvent(value)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Progress record ${index + 1} is not a progress event: ${JSON.stringify(value)?.slice(0, 200)}`,\n\t\t\t)\n\t\t}\n\t\tif (value.event === 'init' && value.version !== PROGRESS_VERSION) {\n\t\t\tthrow new Error(\n\t\t\t\t`Progress record ${index + 1} follows format version ${value.version}; this reader reads version ${PROGRESS_VERSION}`,\n\t\t\t)\n\t\t}\n\t\treturn value\n\t})\n}\n\n/**\n * Computes where the run one process wrote stands, from its last `init` line on.\n *\n * @param events - The lines one process wrote, in file order. Every line must carry the same `pid`;\n * lines of several processes read as one run and miscompute it, so pass a whole file to\n * `computeProgress`, which groups them first.\n * @param now - The wall-clock time of the reading, in milliseconds since the Unix epoch, which a\n * live run's elapsed time is measured to.\n * @returns The run, or `undefined` when no `init` line opens it.\n *\n * @example\n * ```ts\n * import { computeProgressRun } from '@orkestrel/test/server'\n *\n * computeProgressRun(\n * \t[{ event: 'init', version: 1, wall: 1_000, bail: 1, time: 0, pid: 7 }],\n * \t4_000,\n * )?.elapsed // 3000\n * ```\n */\nexport function computeProgressRun(\n\tevents: readonly ProgressEvent[],\n\tnow: number,\n): ProgressRun | undefined {\n\tconst begin = events.findLastIndex((event) => event.event === 'init')\n\tconst init = events[begin]\n\tif (init?.event !== 'init') return undefined\n\tconst own = events.slice(begin)\n\tconst specifications = filterProgressEvents(own, 'start').flatMap((start) => start.specifications)\n\tconst collections = filterProgressEvents(own, 'collected')\n\tconst cases = filterProgressEvents(own, 'case')\n\tconst cancel = filterProgressEvents(own, 'cancel').at(0)\n\tconst end = filterProgressEvents(own, 'end').at(0)\n\tconst clock = end?.time ?? now - init.wall + init.time\n\tconst names = [\n\t\t...new Set([\n\t\t\t...specifications.map((entry) => entry.project),\n\t\t\t...collections.map((entry) => entry.project),\n\t\t\t...cases.map((entry) => entry.project),\n\t\t]),\n\t]\n\tconst projects = names.map((name): ProgressProject => {\n\t\tconst results = cases.filter((entry) => entry.project === name)\n\t\tconst collected = collections.filter((entry) => entry.project === name)\n\t\treturn {\n\t\t\tname,\n\t\t\tplanned: collected.reduce((total, entry) => total + entry.planned, 0),\n\t\t\tdone: results.length,\n\t\t\tpassed: results.filter((entry) => entry.state === 'passed').length,\n\t\t\tfailed:\n\t\t\t\tresults.filter((entry) => entry.state === 'failed').length +\n\t\t\t\tcollected.filter((entry) => entry.errors.length > 0).length,\n\t\t\tskipped: results.filter((entry) => entry.state === 'skipped').length,\n\t\t\tmodules: specifications.filter((entry) => entry.project === name).length,\n\t\t\tcollected: collected.length,\n\t\t}\n\t})\n\tconst planned = projects.reduce((total, project) => total + project.planned, 0)\n\tconst exact =\n\t\tspecifications.length > 0 && projects.every((project) => project.collected >= project.modules)\n\tconst first = cases.at(0)\n\tconst span = first === undefined ? 0 : clock - (first.time - (first.duration ?? 0))\n\tconst rate = cases.length > 0 && span > 0 ? (cases.length / span) * 60_000 : undefined\n\tconst finished = new Set(cases.map((entry) => entry.id))\n\tconst position = cancel === undefined ? -1 : own.indexOf(cancel)\n\tconst trigger = own.find((event) => event.event === 'case' && event.state === 'failed')\n\tconst failures = own\n\t\t.flatMap((event, index) =>\n\t\t\t(event.event === 'case' && event.state === 'failed') ||\n\t\t\t(event.event === 'collected' && event.errors.length > 0)\n\t\t\t\t? [{ event, index }]\n\t\t\t\t: [],\n\t\t)\n\t\t.map(({ event, index }, order): ProgressFailure => {\n\t\t\t// A collection failure carries no timing, so only its order against the cancel decides.\n\t\t\tconst ended =\n\t\t\t\tevent.event === 'case'\n\t\t\t\t\t? (event.start ?? 0) + (event.duration ?? 0)\n\t\t\t\t\t: Number.NEGATIVE_INFINITY\n\t\t\treturn {\n\t\t\t\tproject: event.project,\n\t\t\t\tmodule: event.module,\n\t\t\t\tname: event.event === 'case' ? event.name : undefined,\n\t\t\t\ttime: event.time,\n\t\t\t\t// Vitest can write the cancel before the result of the failure that caused it, so the\n\t\t\t\t// failures up to the bail setting are causes whatever their order against the cancel. Only\n\t\t\t\t// a failed case can trigger a bail, so under a bail the first failed case is a cause even\n\t\t\t\t// when collection failures came before it.\n\t\t\t\trelation:\n\t\t\t\t\torder === 0\n\t\t\t\t\t\t? 'first'\n\t\t\t\t\t\t: order < init.bail ||\n\t\t\t\t\t\t\t (init.bail > 0 && event === trigger) ||\n\t\t\t\t\t\t\t cancel === undefined ||\n\t\t\t\t\t\t\t (index < position && ended <= cancel.wall)\n\t\t\t\t\t\t\t? 'later'\n\t\t\t\t\t\t\t: 'bail',\n\t\t\t\terror: event.errors?.at(0),\n\t\t\t}\n\t\t})\n\treturn {\n\t\tpid: init.pid,\n\t\twall: init.wall,\n\t\tstate: end?.reason ?? 'live',\n\t\tbail: init.bail,\n\t\telapsed: clock,\n\t\tdone: cases.length,\n\t\tplanned,\n\t\texact,\n\t\trate,\n\t\tremaining:\n\t\t\tend === undefined && exact && rate !== undefined\n\t\t\t\t? Math.max(0, ((planned - cases.length) / rate) * 60_000)\n\t\t\t\t: undefined,\n\t\tprojects,\n\t\trunning:\n\t\t\tend === undefined\n\t\t\t\t? filterProgressEvents(own, 'ready')\n\t\t\t\t\t\t.filter((ready) => !finished.has(ready.id))\n\t\t\t\t\t\t.map((ready) => ({\n\t\t\t\t\t\t\tproject: ready.project,\n\t\t\t\t\t\t\tname: ready.name,\n\t\t\t\t\t\t\tduration: Math.max(0, clock - ready.time),\n\t\t\t\t\t\t}))\n\t\t\t\t: [],\n\t\tcancel: cancel === undefined ? undefined : { reason: cancel.reason, time: cancel.time },\n\t\tfailures,\n\t\toverhead: end?.overhead,\n\t\tunhandled: end?.unhandled ?? [],\n\t}\n}\n\n/**\n * Computes where every run a progress file holds stands, one run per writing process.\n *\n * @param events - The file's lines, in file order, from any number of processes.\n * @param now - The wall-clock time of the reading, in milliseconds since the Unix epoch.\n * @returns One run per process id in first-seen order, each computed by `computeProgressRun` from\n * that process's lines alone. A process whose lines no `init` line opens contributes no run.\n *\n * @example\n * ```ts\n * import { computeProgress } from '@orkestrel/test/server'\n *\n * computeProgress(\n * \t[\n * \t\t{ event: 'init', version: 1, wall: 1_000, bail: 0, time: 0, pid: 7 },\n * \t\t{ event: 'init', version: 1, wall: 1_000, bail: 0, time: 0, pid: 8 },\n * \t],\n * \t4_000,\n * ).map((run) => [run.pid, run.elapsed]) // [[7, 3000], [8, 3000]]\n * ```\n */\nexport function computeProgress(\n\tevents: readonly ProgressEvent[],\n\tnow: number,\n): readonly ProgressRun[] {\n\treturn [...new Set(events.map((event) => event.pid))].flatMap((pid) => {\n\t\tconst run = computeProgressRun(\n\t\t\tevents.filter((event) => event.pid === pid),\n\t\t\tnow,\n\t\t)\n\t\treturn run === undefined ? [] : [run]\n\t})\n}\n\n/**\n * Reads where every run a progress file holds stands, live or finished.\n *\n * @param path - The progress file.\n * @param now - The wall-clock time of the reading. Default: `Date.now()`.\n * @returns One run per writing process.\n * @throws Thrown when the host refuses to read the file, or when a complete line is not a progress\n * event of this format version.\n * @remarks Reads the file once, up to its length at open, decodes complete lines only, holds no\n * timer, and writes nothing.\n *\n * @example\n * ```ts\n * import { readProgress } from '@orkestrel/test/server'\n *\n * const [run] = readProgress('tmp/runs/journey.progress.jsonl')\n * run?.state // 'live' while the run writes, then its end reason\n * ```\n */\nexport function readProgress(path: string, now: number = Date.now()): readonly ProgressRun[] {\n\treturn computeProgress(extractProgressEvents(readFileSnapshot(path).toString('utf8')), now)\n}\n\n/**\n * Renders a duration as whole minutes and seconds.\n *\n * @param milliseconds - The duration. A negative or non-finite duration renders as zero.\n * @returns The duration as `<minutes>m<seconds>s`, the seconds padded to two digits.\n *\n * @example\n * ```ts\n * import { renderDuration } from '@orkestrel/test/server'\n *\n * renderDuration(65_400) // '1m05s'\n * renderDuration(Number.NaN) // '0m00s'\n * ```\n */\nexport function renderDuration(milliseconds: number): string {\n\tconst seconds = Number.isFinite(milliseconds) ? Math.max(0, Math.floor(milliseconds / 1000)) : 0\n\treturn `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, '0')}s`\n}\n\n/**\n * Renders progress runs as the text a person reads mid-run.\n *\n * @param runs - The runs to render.\n * @returns One block per run: a summary line with done against planned cases, elapsed time, rate, and\n * estimate; a line per project; the running cases; the cancel; each failure labelled `FIRST`,\n * `AFTER-BAIL`, or `FAILED` under its module and case, or its module alone when the module failed to\n * collect, with its first message line and location; each unhandled error; and, after the end, the\n * reporter's overhead.\n *\n * @example\n * ```ts\n * import { readProgress, renderProgress } from '@orkestrel/test/server'\n *\n * renderProgress(readProgress('tmp/runs/journey.progress.jsonl'))\n * // 'run 37252 interrupted bail=1: 52/52 cases, elapsed 0m51s, rate 61.2/min, ETA -\\n…'\n * ```\n */\nexport function renderProgress(runs: readonly ProgressRun[]): string {\n\treturn runs\n\t\t.map((run) => {\n\t\t\tconst width = Math.max(0, ...run.projects.map((project) => project.name.length))\n\t\t\treturn [\n\t\t\t\t`run ${run.pid} ${run.state} ${run.bail === 0 ? 'full' : `bail=${run.bail}`}: ${run.done}/${run.planned}${run.exact ? '' : '+'} cases, elapsed ${renderDuration(run.elapsed)}, rate ${run.rate === undefined ? '-' : `${run.rate.toFixed(1)}/min`}, ETA ${run.remaining === undefined ? '-' : renderDuration(run.remaining)}`,\n\t\t\t\t...run.projects.map(\n\t\t\t\t\t(project) =>\n\t\t\t\t\t\t` ${project.name.padEnd(width)} ${project.done}/${project.planned} passed ${project.passed} failed ${project.failed} skipped ${project.skipped}${project.collected < project.modules ? ` (${project.collected}/${project.modules} modules collected)` : ''}`,\n\t\t\t\t),\n\t\t\t\t...run.running.map(\n\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t` running ${renderDuration(entry.duration)} [${entry.project}] ${entry.name}`,\n\t\t\t\t),\n\t\t\t\t...(run.cancel === undefined\n\t\t\t\t\t? []\n\t\t\t\t\t: [` cancelled (${run.cancel.reason}) at ${renderDuration(run.cancel.time)}`]),\n\t\t\t\t...[\n\t\t\t\t\t...run.failures.map((failure) => ({\n\t\t\t\t\t\theading: ` ${PROGRESS_LABELS[failure.relation]} ${renderDuration(failure.time)} [${failure.project}] ${failure.name === undefined ? failure.module : `${failure.module} > ${failure.name}`}`,\n\t\t\t\t\t\terror: failure.error,\n\t\t\t\t\t})),\n\t\t\t\t\t...run.unhandled.map((error) => ({ heading: ' UNHANDLED', error })),\n\t\t\t\t].flatMap(({ heading, error }) => [\n\t\t\t\t\theading,\n\t\t\t\t\t...(error === undefined\n\t\t\t\t\t\t? [' (no error recorded)']\n\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t` ${error.message}`,\n\t\t\t\t\t\t\t\t...(error.location === undefined ? [] : [` at ${error.location}`]),\n\t\t\t\t\t\t\t]),\n\t\t\t\t]),\n\t\t\t\t...(run.overhead === undefined ? [] : [` reporter overhead ${run.overhead} ms`]),\n\t\t\t].join('\\n')\n\t\t})\n\t\t.join('\\n')\n}\n","import type { Server } from 'node:net'\nimport { isFunction } from '@orkestrel/contract'\n\n/** Owns the one shutdown promise behind a loopback projection. */\nexport class Loopback {\n\treadonly #server: Server\n\t#destruction: Promise<void> | undefined\n\n\tconstructor(server: Server) {\n\t\tthis.#server = server\n\t}\n\n\tdestroy(): Promise<void> {\n\t\tthis.#destruction ??= new Promise<void>((resolve, reject) => {\n\t\t\tif ('closeAllConnections' in this.#server && isFunction(this.#server.closeAllConnections)) {\n\t\t\t\tthis.#server.closeAllConnections()\n\t\t\t}\n\t\t\tthis.#server.close((error) => {\n\t\t\t\tif (error === undefined || ('code' in error && error.code === 'ERR_SERVER_NOT_RUNNING')) {\n\t\t\t\t\tresolve()\n\t\t\t\t} else {\n\t\t\t\t\treject(error)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t\treturn this.#destruction\n\t}\n}\n","import type { Server } from 'node:net'\nimport type {\n\tCookieJarInterface,\n\tLoopbackInterface,\n\tScratchInterface,\n\tScratchOptions,\n} from './types.js'\nimport { isNumber, isObject } from '@orkestrel/contract'\nimport { once } from 'node:events'\nimport {\n\tlstatSync,\n\tmkdirSync,\n\tmkdtempSync,\n\treadFileSync,\n\treaddirSync,\n\tstatSync,\n\twriteFileSync,\n} from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { dirname, resolve, sep } from 'node:path'\nimport {\n\tcreateLink,\n\thasScratchPath,\n\tmatchesIdentity,\n\treadIdentity,\n\tremoveTree,\n\trequireContained,\n} from './helpers.js'\nimport { Loopback } from './Loopback.js'\n\n/**\n * Allocates an owned temporary directory with contained file operations.\n *\n * @param options - Optional parent directory, name prefix, and initial files.\n * @returns The scratch directory and its file operations.\n * @throws When the parent is missing, a symbolic link, or not a directory; when the prefix contains\n * `/` or `\\`; or when allocation or seeding fails.\n * @remarks Default parent: the host temporary directory. Default prefix: `orkestrel-test-`. Seed\n * keys use root-relative paths.\n *\n * @example Own a temporary directory\n * ```ts\n * import { createScratch } from '@orkestrel/test/server'\n *\n * const scratch = createScratch({ prefix: 'guide-', files: { 'src/index.ts': 'export {}\\n' } })\n *\n * scratch.read('src/index.ts') // 'export {}\\n'\n * scratch.has('src') // true\n * scratch.read('src') // throws Error: Scratch path is a directory: src\n * scratch.read('missing.ts') // undefined\n * scratch.write('../escape.ts', '') // throws Error: Path outside scratch directory: ../escape.ts\n *\n * // `write` answers the contained path it wrote, the way `ensure` and `link` answer theirs, so the\n * // path goes straight to the code under test without joining it again.\n * scratch.write('src/notes.ts', 'export {}\\n') // `${scratch.path}/src/notes.ts`\n *\n * // `ensure` is how you get an empty directory, because every `write` creates a file.\n * scratch.ensure('empty')\n * scratch.names() // ['empty', 'src']\n * scratch.names('empty') // []\n *\n * // `parent` puts the allocation somewhere other than the host temporary directory.\n * const child = createScratch({ parent: scratch.path, prefix: 'child-' })\n * scratch.names().length // 3 — 'empty', 'src', and the child allocation\n * child.destroy()\n * scratch.names().length // 2 — the child removed itself and nothing else\n *\n * // `link` creates the symbolic link the threat model names, and `read` follows it. A directory\n * // source runs on a host that creates no symbolic link too; see \"Hosts that create no symbolic\n * // link\" for what such a host does with a file source.\n * const outside = createScratch({ prefix: 'outside-', files: { 'read.ts': 'export {}\\n' } })\n * scratch.link('gate', outside.path) // `${scratch.path}/gate` — the link's own path, not its destination\n * scratch.read('gate/read.ts') // 'export {}\\n' — read through the link, at its destination\n *\n * // A link pointing out of the allocation is resolved through, so a contained path acts outside it.\n * scratch.ensure('gate/made') // `${scratch.path}/gate/made` — the lexical path, not the destination\n * outside.names() // ['made', 'read.ts'] — the directory was made under `outside.path`\n * scratch.names('gate') // ['made', 'read.ts'] — the same entries, listed through the link\n *\n * // `link` acts at the final segment rather than through it, so `gate` is occupied.\n * scratch.link('gate', outside.path) // throws Error: EEXIST: file already exists\n *\n * // `has` reads the final segment without following it, and `read` follows it.\n * scratch.link('dangling', 'missing.ts')\n * scratch.has('dangling') // true — the link is there\n * scratch.read('dangling') // undefined — what it points at is not\n *\n * // `remove` takes one contained entry and acts at the final segment, so a link goes and whatever it\n * // pointed at stays. A missing target is a no-op.\n * scratch.remove('dangling')\n * scratch.has('dangling') // false\n * scratch.remove('missing.ts') // no throw — there was nothing there\n * scratch.remove('src') // the directory and everything under it\n * scratch.names() // ['empty', 'gate']\n *\n * scratch.destroy()\n * scratch.destroy() // no-op — destroy is idempotent\n * outside.has('made') // true — destroy unlinks `gate` and leaves what it pointed at\n * outside.destroy()\n * ```\n */\nexport function createScratch(options?: ScratchOptions): ScratchInterface {\n\tconst parent = resolve(options?.parent ?? tmpdir())\n\tconst parentStatus = lstatSync(parent, { throwIfNoEntry: false })\n\tif (parentStatus === undefined) throw new Error('Scratch parent does not exist')\n\tif (parentStatus.isSymbolicLink()) throw new Error('Scratch parent is a symbolic link')\n\tif (!parentStatus.isDirectory()) throw new Error('Scratch parent is not a directory')\n\n\tconst prefix = options?.prefix ?? 'orkestrel-test-'\n\tif (prefix.includes('/') || prefix.includes('\\\\')) {\n\t\tthrow new Error('Scratch prefix must be a name fragment')\n\t}\n\n\tconst path = mkdtempSync(`${parent}${sep}${prefix}`)\n\tconst allocation = readIdentity(statSync(path, { bigint: true }))\n\tconst unremovable = 'Scratch directory is not a removable target'\n\ttry {\n\t\tfor (const [target, text] of Object.entries(options?.files ?? {})) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tmkdirSync(dirname(candidate), { recursive: true })\n\t\t\twriteFileSync(candidate, text)\n\t\t}\n\t} catch (error) {\n\t\tremoveTree(path)\n\t\tthrow error\n\t}\n\n\treturn {\n\t\tpath,\n\t\twrite(target, text) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (!hasScratchPath(path, '.')) throw new Error('Scratch directory does not exist')\n\n\t\t\tmkdirSync(dirname(candidate), { recursive: true })\n\t\t\twriteFileSync(candidate, text)\n\t\t\treturn candidate\n\t\t},\n\t\tread(target) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (!hasScratchPath(path, target)) return undefined\n\t\t\tconst status = statSync(candidate, { throwIfNoEntry: false })\n\t\t\tif (status === undefined) return undefined\n\t\t\tif (status.isDirectory()) {\n\t\t\t\tthrow new Error(`Scratch path is a directory: ${target}`)\n\t\t\t}\n\t\t\treturn readFileSync(candidate, 'utf8')\n\t\t},\n\t\thas: hasScratchPath.bind(undefined, path),\n\t\tnames(target = '.') {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (!hasScratchPath(path, '.')) throw new Error('Scratch directory does not exist')\n\n\t\t\tconst status = statSync(candidate, { throwIfNoEntry: false })\n\t\t\tif (status === undefined) throw new Error(`Scratch path does not exist: ${target}`)\n\t\t\tif (!status.isDirectory()) throw new Error(`Scratch path is not a directory: ${target}`)\n\t\t\treturn readdirSync(candidate).sort()\n\t\t},\n\t\tensure(target) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (!hasScratchPath(path, '.')) throw new Error('Scratch directory does not exist')\n\n\t\t\tconst status = statSync(candidate, { throwIfNoEntry: false })\n\t\t\tif (status !== undefined && !status.isDirectory()) {\n\t\t\t\tthrow new Error(`Scratch path is not a directory: ${target}`)\n\t\t\t}\n\t\t\tif (status === undefined) mkdirSync(candidate, { recursive: true })\n\t\t\treturn candidate\n\t\t},\n\t\tlink(target, source) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (!hasScratchPath(path, '.')) throw new Error('Scratch directory does not exist')\n\n\t\t\tmkdirSync(dirname(candidate), { recursive: true })\n\t\t\tcreateLink(candidate, source)\n\t\t\treturn candidate\n\t\t},\n\t\tremove(target) {\n\t\t\tconst candidate = requireContained(path, target)\n\t\t\tif (candidate === path) throw new Error(`${unremovable}: ${target}`)\n\t\t\tif (!hasScratchPath(path, '.')) throw new Error('Scratch directory does not exist')\n\n\t\t\tconst status = lstatSync(candidate, { bigint: true, throwIfNoEntry: false })\n\t\t\tif (status !== undefined && matchesIdentity(readIdentity(status), allocation)) {\n\t\t\t\tthrow new Error(`${unremovable}: ${target}`)\n\t\t\t}\n\t\t\tremoveTree(candidate)\n\t\t},\n\t\tdestroy() {\n\t\t\tconst status = lstatSync(path, { bigint: true, throwIfNoEntry: false })\n\t\t\tif (status === undefined) return\n\t\t\tif (!matchesIdentity(readIdentity(status), allocation)) return\n\t\t\tremoveTree(path)\n\t\t},\n\t}\n}\n\n/**\n * Starts a server on an ephemeral IPv4 loopback port.\n *\n * @param server - The unstarted server to bind.\n * @returns The bound origin, assigned port, and asynchronous teardown.\n * @throws When the server cannot bind or reports an address without a numeric port.\n */\nexport async function createLoopback(server: Server): Promise<LoopbackInterface> {\n\tserver.listen(0, '127.0.0.1')\n\tawait once(server, 'listening')\n\n\tconst address = server.address()\n\tif (!isObject(address) || !('port' in address) || !isNumber(address.port)) {\n\t\tthrow new Error(`Loopback address must have a numeric port; found ${String(address)}`)\n\t}\n\n\tconst port = address.port\n\tconst loopback = new Loopback(server)\n\treturn {\n\t\turl: `http://127.0.0.1:${port}`,\n\t\tport,\n\t\tdestroy: loopback.destroy.bind(loopback),\n\t}\n}\n\n/**\n * Creates a cookie jar that records a real response's cookies and replays them as one header.\n *\n * @returns The rendered request header, and the members that read and capture cookies.\n * @remarks Selection is by name alone: no `Domain` or `Path` matching, no `Expires` or `Secure`\n * handling, and no persistence beyond the jar. That is what a test driving one origin over one path\n * needs, and a fixture needing a browser's cookie store needs a browser rather than this.\n */\nexport function createCookieJar(): CookieJarInterface {\n\tconst cookies = new Map<string, string>()\n\treturn {\n\t\tget header() {\n\t\t\tconst pairs = [...cookies].map(([name, value]) => `${name}=${value}`)\n\t\t\treturn pairs.length === 0 ? undefined : pairs.join('; ')\n\t\t},\n\t\tread(name) {\n\t\t\treturn cookies.get(name)\n\t\t},\n\t\tcapture(response) {\n\t\t\tconst fields = response.headers.getSetCookie()\n\t\t\tfor (const field of fields) {\n\t\t\t\tconst boundary = field.indexOf(';')\n\t\t\t\tconst pair = boundary < 0 ? field : field.slice(0, boundary)\n\t\t\t\tconst separator = pair.indexOf('=')\n\t\t\t\tif (separator < 1) continue\n\n\t\t\t\tconst name = pair.slice(0, separator)\n\t\t\t\t// An origin spells a deletion `Max-Age=0` in whatever case and spacing it likes, so the\n\t\t\t\t// attribute is matched rather than compared.\n\t\t\t\tif (/;\\s*max-age\\s*=\\s*0\\s*(?:;|$)/iu.test(field)) cookies.delete(name)\n\t\t\t\telse cookies.set(name, pair.slice(separator + 1))\n\t\t\t}\n\t\t\treturn fields\n\t\t},\n\t}\n}\n","import type {\n\tReporter,\n\tSerializedError,\n\tTestCase,\n\tTestModule,\n\tTestRunEndReason,\n\tTestSpecification,\n\tVitest,\n} from 'vitest/node'\nimport type { ProgressError, ProgressEvent, ProgressStamp } from '../types.js'\nimport { appendFileSync, mkdirSync } from 'node:fs'\nimport { dirname, resolve } from 'node:path'\nimport { performance } from 'node:perf_hooks'\nimport { PROGRESS_VERSION } from '../constants.js'\nimport { extractProgressError, matchesPlannedCase, normalizeProgressPath } from '../helpers.js'\n\n/**\n * Appends one JSON line per Vitest run event to the file `--outputFile.progress` names, so a live\n * run's progress and each failure's first error can be read before the run ends.\n *\n * @example\n * ```ts\n * import { defineConfig } from 'vitest/config'\n * import { ProgressReporter } from '@orkestrel/test/server'\n *\n * export default defineConfig({\n * \ttest: {\n * \t\treporters: ['dot', new ProgressReporter()],\n * \t\toutputFile: { progress: 'tmp/runs/progress.jsonl' },\n * \t},\n * })\n * ```\n */\nexport class ProgressReporter implements Reporter {\n\treadonly #origin = performance.now()\n\treadonly #listener: (reason: string) => void\n\treadonly #planned = new WeakSet<TestCase>()\n\t#vitest: Vitest | undefined\n\t#path: string | undefined\n\t#overhead = 0\n\n\tconstructor() {\n\t\tthis.#listener = this.#cancel.bind(this)\n\t}\n\n\tonInit(vitest: Vitest): void {\n\t\tthis.#measure(() => {\n\t\t\tconst output = vitest.config.outputFile\n\t\t\tconst named = typeof output === 'object' ? output.progress : undefined\n\t\t\tif (named === undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'ProgressReporter writes no file: pass --outputFile.progress=<file>, or set outputFile: { progress: <file> } in the test config',\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.#vitest = vitest\n\t\t\tthis.#path = resolve(vitest.config.root, named)\n\t\t\tmkdirSync(dirname(this.#path), { recursive: true })\n\t\t\tthis.#write({\n\t\t\t\tevent: 'init',\n\t\t\t\tversion: PROGRESS_VERSION,\n\t\t\t\twall: Date.now(),\n\t\t\t\tbail: vitest.config.bail ?? 0,\n\t\t\t\t...this.#stamp(),\n\t\t\t})\n\t\t})\n\t}\n\n\t// Vitest clears its cancel listeners after `onTestRunStart`, so each run registers on its queued\n\t// modules; the listener set holds one copy of the bound listener.\n\tonTestModuleQueued(): void {\n\t\tthis.#vitest?.onCancel(this.#listener)\n\t}\n\n\tonTestRunStart(specifications: readonly TestSpecification[]): void {\n\t\tthis.#measure(() => {\n\t\t\tthis.#write({\n\t\t\t\tevent: 'start',\n\t\t\t\tspecifications: specifications.map((specification) => ({\n\t\t\t\t\tproject: specification.project.name,\n\t\t\t\t\tmodule: this.#relative(specification.moduleId),\n\t\t\t\t})),\n\t\t\t\t...this.#stamp(),\n\t\t\t})\n\t\t})\n\t}\n\n\tonTestModuleCollected(module: TestModule): void {\n\t\tthis.#measure(() => {\n\t\t\t// A name filter leaves its removed cases collected with mode `skip`, and Vitest still\n\t\t\t// readies and reports them, so only the cases planned here are ever written.\n\t\t\tconst planned = [...module.children.allTests()].filter((test) => matchesPlannedCase(test))\n\t\t\tfor (const test of planned) this.#planned.add(test)\n\t\t\tthis.#write({\n\t\t\t\tevent: 'collected',\n\t\t\t\tproject: module.project.name,\n\t\t\t\tmodule: this.#relative(module.moduleId),\n\t\t\t\tplanned: planned.length,\n\t\t\t\terrors: module.errors().map((error) => this.#error(error)),\n\t\t\t\t...this.#stamp(),\n\t\t\t})\n\t\t})\n\t}\n\n\tonTestCaseReady(test: TestCase): void {\n\t\tthis.#measure(() => {\n\t\t\tif (!this.#planned.has(test)) return\n\t\t\tthis.#write({\n\t\t\t\tevent: 'ready',\n\t\t\t\tproject: test.project.name,\n\t\t\t\tid: test.id,\n\t\t\t\tname: test.fullName,\n\t\t\t\t...this.#stamp(),\n\t\t\t})\n\t\t})\n\t}\n\n\tonTestCaseResult(test: TestCase): void {\n\t\tthis.#measure(() => {\n\t\t\t// A case a bail cuts off reports its result twice; the first report takes it off the plan.\n\t\t\tif (!this.#planned.delete(test)) return\n\t\t\tconst result = test.result()\n\t\t\tconst diagnostic = test.diagnostic()\n\t\t\tthis.#write({\n\t\t\t\tevent: 'case',\n\t\t\t\tproject: test.project.name,\n\t\t\t\tmodule: this.#relative(test.module.moduleId),\n\t\t\t\tid: test.id,\n\t\t\t\tname: test.fullName,\n\t\t\t\tstate: result.state,\n\t\t\t\t...(diagnostic === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { duration: Math.round(diagnostic.duration), start: Math.round(diagnostic.startTime) }),\n\t\t\t\t...(result.state === 'failed'\n\t\t\t\t\t? { errors: result.errors.map((error) => this.#error(error)) }\n\t\t\t\t\t: {}),\n\t\t\t\t...this.#stamp(),\n\t\t\t})\n\t\t})\n\t}\n\n\tonTestModuleEnd(module: TestModule): void {\n\t\tthis.#measure(() => {\n\t\t\tthis.#write({\n\t\t\t\tevent: 'module',\n\t\t\t\tproject: module.project.name,\n\t\t\t\tmodule: this.#relative(module.moduleId),\n\t\t\t\tstate: module.state(),\n\t\t\t\tduration: Math.round(module.diagnostic().duration),\n\t\t\t\t...this.#stamp(),\n\t\t\t})\n\t\t})\n\t}\n\n\t// The first parameter only holds the position Vitest passes the modules in.\n\tonTestRunEnd(\n\t\t_modules: readonly TestModule[],\n\t\tunhandled: readonly SerializedError[],\n\t\treason: TestRunEndReason,\n\t): void {\n\t\tconst errors = unhandled.map((error) => this.#error(error))\n\t\tthis.#write({\n\t\t\tevent: 'end',\n\t\t\treason,\n\t\t\toverhead: Math.round(this.#overhead * 100) / 100,\n\t\t\tunhandled: errors,\n\t\t\t...this.#stamp(),\n\t\t})\n\t}\n\n\t#cancel(reason: string): void {\n\t\tthis.#measure(() => {\n\t\t\tthis.#write({ event: 'cancel', reason, wall: Date.now(), ...this.#stamp() })\n\t\t})\n\t}\n\n\t#error(error: SerializedError): ProgressError {\n\t\treturn extractProgressError(error, this.#vitest?.config.root ?? process.cwd())\n\t}\n\n\t#relative(file: string): string {\n\t\treturn normalizeProgressPath(file, this.#vitest?.config.root ?? process.cwd())\n\t}\n\n\t#stamp(): ProgressStamp {\n\t\treturn { time: Math.round(performance.now() - this.#origin), pid: process.pid }\n\t}\n\n\t#measure(work: () => void): void {\n\t\tconst begin = performance.now()\n\t\ttry {\n\t\t\twork()\n\t\t} finally {\n\t\t\tthis.#overhead += performance.now() - begin\n\t\t}\n\t}\n\n\t#write(event: ProgressEvent): void {\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KAAK,MAAM,KAAK,YAAY,GAAG,IAAI;GAC7C,WAAW;GACX,GAAG,KAAK,OAAO;EAChB,CAAC;CACF;CAEA,QAAQ,QAAsB;EAC7B,KAAK,eAAe;GACnB,KAAK,OAAO;IAAE,OAAO;IAAU;IAAQ,MAAM,KAAK,IAAI;IAAG,GAAG,KAAK,OAAO;GAAE,CAAC;EAC5E,CAAC;CACF;CAEA,OAAO,OAAuC;EAC7C,OAAO,qBAAqB,OAAO,KAAK,SAAS,OAAO,QAAQ,QAAQ,IAAI,CAAC;CAC9E;CAEA,UAAU,MAAsB;EAC/B,OAAO,sBAAsB,MAAM,KAAK,SAAS,OAAO,QAAQ,QAAQ,IAAI,CAAC;CAC9E;CAEA,SAAwB;EACvB,OAAO;GAAE,MAAM,KAAK,MAAMA,cAAY,IAAI,IAAI,KAAK,OAAO;GAAG,KAAK,QAAQ;EAAI;CAC/E;CAEA,SAAS,MAAwB;EAChC,MAAM,QAAQA,cAAY,IAAI;EAC9B,IAAI;GACH,KAAK;EACN,UAAU;GACT,KAAK,aAAaA,cAAY,IAAI,IAAI;EACvC;CACD;CAEA,OAAO,OAA4B;EAClC,IAAI,KAAK,UAAU,KAAA,GAAW;EAC9B,eAAe,KAAK,OAAO,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG;CACxD;AACD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orkestrel/test",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.38",
|
|
4
4
|
"description": "The test helpers the Orkestrel fleet repeats — a call recorder, a real delay, JSON and async collectors, an owned scratch directory with a source-file walker, and a browser journey layer that drives real interfaces by role and accessible name. Part of the @orkestrel line.",
|
|
5
5
|
"keywords": [],
|
|
6
6
|
"homepage": "https://github.com/orkestrel/test#readme",
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
},
|
|
13
13
|
"files": [
|
|
14
14
|
"dist/src",
|
|
15
|
+
"dist/reporter",
|
|
15
16
|
"README.md"
|
|
16
17
|
],
|
|
17
18
|
"type": "module",
|
|
@@ -45,6 +46,12 @@
|
|
|
45
46
|
"default": "./dist/src/server/index.cjs"
|
|
46
47
|
}
|
|
47
48
|
},
|
|
49
|
+
"./reporter": {
|
|
50
|
+
"import": {
|
|
51
|
+
"types": "./dist/reporter/main.d.ts",
|
|
52
|
+
"default": "./dist/reporter/main.js"
|
|
53
|
+
}
|
|
54
|
+
},
|
|
48
55
|
"./package.json": "./package.json"
|
|
49
56
|
},
|
|
50
57
|
"publishConfig": {
|
|
@@ -58,12 +65,13 @@
|
|
|
58
65
|
"lint": "oxlint --config .oxlintrc.json --fix .",
|
|
59
66
|
"lint:check": "oxlint --config .oxlintrc.json --deny-warnings .",
|
|
60
67
|
"check": "tsc --noEmit --project tsconfig.json && npm run check:src",
|
|
61
|
-
"check:src": "npm run check:src:core && npm run check:src:browser && npm run check:src:server",
|
|
68
|
+
"check:src": "npm run check:src:core && npm run check:src:browser && npm run check:src:server && npm run check:src:reporter",
|
|
62
69
|
"check:src:core": "tsc --noEmit -p configs/src/tsconfig.core.json",
|
|
63
70
|
"check:src:browser": "tsc --noEmit -p configs/src/tsconfig.browser.json",
|
|
64
71
|
"check:src:server": "tsc --noEmit -p configs/src/tsconfig.server.json",
|
|
72
|
+
"check:src:reporter": "tsc --noEmit -p configs/src/tsconfig.reporter.json",
|
|
65
73
|
"test": "npm run test:src && npm run test:policy && npm run test:config && npm run test:setup && npm run test:setup:browser && npm run test:guides",
|
|
66
|
-
"test:src": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:core --project src:browser --project src:server",
|
|
74
|
+
"test:src": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:core --project src:browser --project src:server --project src:reporter",
|
|
67
75
|
"test:src:core": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:core",
|
|
68
76
|
"test:src:browser": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:browser",
|
|
69
77
|
"test:src:server": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:server",
|
|
@@ -72,16 +80,18 @@
|
|
|
72
80
|
"test:guides": "node --experimental-strip-types tests/guides.test.ts",
|
|
73
81
|
"test:probe": "vitest run --config vite.config.ts --no-cache --reporter=verbose --project probe",
|
|
74
82
|
"build": "npm run clean && npm run build:src",
|
|
75
|
-
"build:src": "npm run build:src:core && npm run build:src:browser && npm run build:src:server",
|
|
83
|
+
"build:src": "npm run build:src:core && npm run build:src:browser && npm run build:src:server && npm run build:src:reporter",
|
|
76
84
|
"build:src:core": "vite build --config configs/src/vite.core.config.ts && npm run copy dist/src/core/index.d.ts dist/src/core/index.d.cts",
|
|
77
85
|
"build:src:browser": "vite build --config configs/src/vite.browser.config.ts",
|
|
78
86
|
"build:src:server": "vite build --config configs/src/vite.server.config.ts && npm run copy dist/src/server/index.d.ts dist/src/server/index.d.cts",
|
|
87
|
+
"build:src:reporter": "vite build --config configs/src/vite.reporter.config.ts",
|
|
79
88
|
"prepack": "npm run build",
|
|
80
89
|
"prepublishOnly": "npm run format:check && npm run lint:check && npm run check && npm run build && npm test && npm run test:distribution -- --mode release",
|
|
81
90
|
"test:distribution": "vitest run --config vite.config.ts --no-cache --reporter=dot --project distribution",
|
|
82
91
|
"test:bench": "vitest bench --config vite.config.ts --no-cache --project \"probe (bench)\" --mode benchmark",
|
|
83
92
|
"test:setup": "vitest run --config vite.config.ts --no-cache --reporter=dot --project setup",
|
|
84
|
-
"test:setup:browser": "vitest run --config vite.config.ts --no-cache --reporter=dot --project setup:browser"
|
|
93
|
+
"test:setup:browser": "vitest run --config vite.config.ts --no-cache --reporter=dot --project setup:browser",
|
|
94
|
+
"test:src:reporter": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:reporter"
|
|
85
95
|
},
|
|
86
96
|
"dependencies": {
|
|
87
97
|
"@orkestrel/contract": "^0.0.23"
|
|
@@ -91,7 +101,7 @@
|
|
|
91
101
|
"@orkestrel/browser": "^0.0.33",
|
|
92
102
|
"@orkestrel/guide": "^0.0.31",
|
|
93
103
|
"@orkestrel/probe": "^0.0.30",
|
|
94
|
-
"@orkestrel/scaffold": "^0.0.
|
|
104
|
+
"@orkestrel/scaffold": "^0.0.134",
|
|
95
105
|
"@types/node": "^26.6.6",
|
|
96
106
|
"@vitest/browser-playwright": "^5.1.0",
|
|
97
107
|
"oxfmt": "^0.78.0",
|