vouchington-tooling 0.62.0 → 0.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +147 -0
  2. package/dist/cli/commands/cloc.d.mts +7 -0
  3. package/dist/cli/commands/cloc.mjs +47 -0
  4. package/dist/cli/commands/storybook-browser-runner.d.mts +7 -0
  5. package/dist/cli/commands/storybook-browser-runner.mjs +29 -0
  6. package/dist/cli/index.mjs +4 -0
  7. package/dist/cli/parse-forwarded-commands.d.mts +6 -0
  8. package/dist/cli/parse-forwarded-commands.mjs +4 -0
  9. package/dist/cli/parse.d.mts +6 -0
  10. package/dist/cli/usage-text.d.mts +1 -1
  11. package/dist/cli/usage-text.mjs +18 -0
  12. package/dist/cloc/child-process.d.mts +3 -0
  13. package/dist/cloc/child-process.mjs +14 -0
  14. package/dist/cloc/classify.d.mts +8 -0
  15. package/dist/cloc/classify.mjs +20 -0
  16. package/dist/cloc/config-load.d.mts +7 -0
  17. package/dist/cloc/config-load.mjs +26 -0
  18. package/dist/cloc/config.d.mts +55 -0
  19. package/dist/cloc/config.mjs +109 -0
  20. package/dist/cloc/count.d.mts +9 -0
  21. package/dist/cloc/count.mjs +33 -0
  22. package/dist/cloc/index.d.mts +12 -0
  23. package/dist/cloc/index.mjs +7 -0
  24. package/dist/cloc/layout.test-helpers.d.mts +8 -0
  25. package/dist/cloc/layout.test-helpers.mjs +42 -0
  26. package/dist/cloc/paths.d.mts +7 -0
  27. package/dist/cloc/paths.mjs +29 -0
  28. package/dist/cloc/patterns.d.mts +10 -0
  29. package/dist/cloc/patterns.mjs +25 -0
  30. package/dist/cloc/rows.d.mts +13 -0
  31. package/dist/cloc/rows.mjs +42 -0
  32. package/dist/cloc/scc.d.mts +10 -0
  33. package/dist/cloc/scc.mjs +55 -0
  34. package/dist/cloc/tracked.d.mts +4 -0
  35. package/dist/cloc/tracked.mjs +40 -0
  36. package/dist/postgres-test-faults/fault-support.d.mts +11 -0
  37. package/dist/postgres-test-faults/fault-support.mjs +61 -0
  38. package/dist/postgres-test-faults/fault-types.d.mts +43 -0
  39. package/dist/postgres-test-faults/fault-types.mjs +1 -0
  40. package/dist/postgres-test-faults/index.d.mts +5 -0
  41. package/dist/postgres-test-faults/index.mjs +4 -0
  42. package/dist/postgres-test-faults/lock-observers.d.mts +20 -0
  43. package/dist/postgres-test-faults/lock-observers.mjs +14 -0
  44. package/dist/postgres-test-faults/lock-wait.d.mts +13 -0
  45. package/dist/postgres-test-faults/lock-wait.mjs +62 -0
  46. package/dist/postgres-test-faults/lock-waiter.d.mts +19 -0
  47. package/dist/postgres-test-faults/lock-waiter.mjs +95 -0
  48. package/dist/postgres-test-faults/observation-queue.d.mts +2 -0
  49. package/dist/postgres-test-faults/observation-queue.mjs +22 -0
  50. package/dist/postgres-test-faults/polling.d.mts +6 -0
  51. package/dist/postgres-test-faults/polling.mjs +33 -0
  52. package/dist/postgres-test-faults/pool-query-failure.d.mts +8 -0
  53. package/dist/postgres-test-faults/pool-query-failure.mjs +136 -0
  54. package/dist/postgres-test-faults/query-failure.d.mts +8 -0
  55. package/dist/postgres-test-faults/query-failure.mjs +108 -0
  56. package/dist/postgres-test-faults/test-cluster.test-helpers.d.mts +13 -0
  57. package/dist/postgres-test-faults/test-cluster.test-helpers.mjs +84 -0
  58. package/dist/provider-replay/abort-listeners.d.mts +4 -0
  59. package/dist/provider-replay/abort-listeners.mjs +19 -0
  60. package/dist/provider-replay/aws-replay-abort-signal.d.mts +5 -0
  61. package/dist/provider-replay/aws-replay-abort-signal.mjs +63 -0
  62. package/dist/provider-replay/aws-replay-request-handler.d.mts +38 -0
  63. package/dist/provider-replay/aws-replay-request-handler.mjs +66 -0
  64. package/dist/provider-replay/force-client-option.d.mts +6 -0
  65. package/dist/provider-replay/force-client-option.mjs +13 -0
  66. package/dist/provider-replay/index.d.mts +6 -0
  67. package/dist/provider-replay/index.mjs +6 -0
  68. package/dist/provider-replay/provider-replay.d.mts +32 -0
  69. package/dist/provider-replay/provider-replay.mjs +54 -0
  70. package/dist/provider-replay/recorded-response.d.mts +17 -0
  71. package/dist/provider-replay/recorded-response.mjs +42 -0
  72. package/dist/provider-replay/replay-response.d.mts +8 -0
  73. package/dist/provider-replay/replay-response.mjs +38 -0
  74. package/dist/storybook-browser-runner/args.d.mts +8 -0
  75. package/dist/storybook-browser-runner/args.mjs +52 -0
  76. package/dist/storybook-browser-runner/attempt-result.d.mts +41 -0
  77. package/dist/storybook-browser-runner/attempt-result.mjs +108 -0
  78. package/dist/storybook-browser-runner/bootstrap-telemetry.d.mts +35 -0
  79. package/dist/storybook-browser-runner/bootstrap-telemetry.mjs +138 -0
  80. package/dist/storybook-browser-runner/cache-plan.d.mts +22 -0
  81. package/dist/storybook-browser-runner/cache-plan.mjs +53 -0
  82. package/dist/storybook-browser-runner/diagnostics.d.mts +8 -0
  83. package/dist/storybook-browser-runner/diagnostics.mjs +29 -0
  84. package/dist/storybook-browser-runner/env.d.mts +2 -0
  85. package/dist/storybook-browser-runner/env.mjs +59 -0
  86. package/dist/storybook-browser-runner/fixtures.test-helpers.d.mts +49 -0
  87. package/dist/storybook-browser-runner/fixtures.test-helpers.mjs +95 -0
  88. package/dist/storybook-browser-runner/index.d.mts +15 -0
  89. package/dist/storybook-browser-runner/index.mjs +70 -0
  90. package/dist/storybook-browser-runner/observer-state.d.mts +22 -0
  91. package/dist/storybook-browser-runner/observer-state.mjs +21 -0
  92. package/dist/storybook-browser-runner/options.d.mts +18 -0
  93. package/dist/storybook-browser-runner/options.mjs +49 -0
  94. package/dist/storybook-browser-runner/output-observer.d.mts +37 -0
  95. package/dist/storybook-browser-runner/output-observer.mjs +130 -0
  96. package/dist/storybook-browser-runner/output-patterns.d.mts +14 -0
  97. package/dist/storybook-browser-runner/output-patterns.mjs +26 -0
  98. package/dist/storybook-browser-runner/quiet-output.d.mts +16 -0
  99. package/dist/storybook-browser-runner/quiet-output.mjs +79 -0
  100. package/dist/storybook-browser-runner/run-attempt.d.mts +14 -0
  101. package/dist/storybook-browser-runner/run-attempt.mjs +111 -0
  102. package/dist/storybook-browser-runner/runtime-metadata.d.mts +12 -0
  103. package/dist/storybook-browser-runner/runtime-metadata.mjs +50 -0
  104. package/dist/storybook-browser-runner/session-deps.d.mts +11 -0
  105. package/dist/storybook-browser-runner/session-deps.mjs +70 -0
  106. package/dist/storybook-browser-runner/types.d.mts +49 -0
  107. package/dist/storybook-browser-runner/types.mjs +1 -0
  108. package/dist/storybook-browser-runner/vite-detectors.d.mts +6 -0
  109. package/dist/storybook-browser-runner/vite-detectors.mjs +20 -0
  110. package/dist/storybook-browser-runner/watchdog.d.mts +23 -0
  111. package/dist/storybook-browser-runner/watchdog.mjs +55 -0
  112. package/package.json +27 -1
  113. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
@@ -0,0 +1,63 @@
1
+ function assertAwsAbortSignal(source) {
2
+ if (typeof source !== 'object' || !('aborted' in source) || typeof source.aborted !== 'boolean')
3
+ throw new TypeError('Invalid AWS request abort signal');
4
+ }
5
+ /** Smithy accepts native, cross-realm EventTarget, and legacy onabort signals. */
6
+ export function observeAwsReplayAbort(source) {
7
+ if (source == null)
8
+ return { signal: undefined, detach: () => { } };
9
+ if (source instanceof AbortSignal)
10
+ return { signal: source, detach: () => { } };
11
+ assertAwsAbortSignal(source);
12
+ const controller = new AbortController();
13
+ const abort = () => controller.abort(source.reason);
14
+ if (source.aborted) {
15
+ abort();
16
+ return { signal: controller.signal, detach: () => { } };
17
+ }
18
+ let detach;
19
+ if (typeof source.addEventListener === 'function' &&
20
+ typeof source.removeEventListener === 'function') {
21
+ source.addEventListener('abort', abort, { once: true });
22
+ detach = () => source.removeEventListener('abort', abort);
23
+ }
24
+ else if ('onabort' in source) {
25
+ detach = observeLegacyAbort(source, abort);
26
+ }
27
+ else
28
+ throw new TypeError('AWS request abort signal has no notification API');
29
+ // Cancellation can race with installing the observer.
30
+ if (source.aborted)
31
+ abort();
32
+ return { signal: controller.signal, detach };
33
+ }
34
+ const legacyObservers = new WeakMap();
35
+ function legacyState(source) {
36
+ const existing = legacyObservers.get(source);
37
+ if (existing && source.onabort === existing.listener)
38
+ return existing;
39
+ const previous = source.onabort;
40
+ const callbacks = new Set();
41
+ const listener = (event) => {
42
+ for (const callback of callbacks)
43
+ callback();
44
+ previous?.call(source, event);
45
+ };
46
+ const state = { callbacks, previous, listener };
47
+ legacyObservers.set(source, state);
48
+ source.onabort = listener;
49
+ return state;
50
+ }
51
+ function observeLegacyAbort(source, abort) {
52
+ const observed = legacyState(source);
53
+ observed.callbacks.add(abort);
54
+ return () => {
55
+ observed.callbacks.delete(abort);
56
+ if (observed.callbacks.size > 0)
57
+ return;
58
+ if (source.onabort === observed.listener)
59
+ source.onabort = observed.previous;
60
+ if (legacyObservers.get(source) === observed)
61
+ legacyObservers.delete(source);
62
+ };
63
+ }
@@ -0,0 +1,38 @@
1
+ import { Readable } from 'node:stream';
2
+ import type { ProviderReplay } from './provider-replay.mts';
3
+ /** The parts of smithy's `HttpRequest` this handler reads. */
4
+ type AwsReplayHttpRequest = {
5
+ method: string;
6
+ protocol: string;
7
+ hostname: string;
8
+ port?: number;
9
+ path: string;
10
+ query?: Record<string, string | string[] | null>;
11
+ headers: Record<string, string>;
12
+ body?: RequestInit['body'];
13
+ };
14
+ type AwsReplayHandlerOptions = {
15
+ abortSignal?: unknown;
16
+ };
17
+ /** Smithy treats any object with a `handle` function as an `HttpHandler`. */
18
+ export type AwsReplayRequestHandler = {
19
+ handle: (request: AwsReplayHttpRequest, options?: AwsReplayHandlerOptions) => Promise<{
20
+ response: {
21
+ statusCode: number;
22
+ reason: string;
23
+ headers: Record<string, string>;
24
+ body: Readable;
25
+ };
26
+ }>;
27
+ destroy: () => void;
28
+ updateHttpClientConfig: () => void;
29
+ httpHandlerConfigs: () => Record<string, never>;
30
+ };
31
+ export declare function createAwsReplayRequestHandler(replay: ProviderReplay): AwsReplayRequestHandler;
32
+ /**
33
+ * Subclasses an AWS SDK client so every instance sends through the replay, whatever
34
+ * `requestHandler` production code configured. Use it inside a `vi.mock` of the SDK package for a
35
+ * client that production builds itself, so the test never edits production code.
36
+ */
37
+ export declare function replayAwsClient<Client extends abstract new (config: never) => object>(Constructor: Client, replay: ProviderReplay): Client;
38
+ export {};
@@ -0,0 +1,66 @@
1
+ import { Readable } from 'node:stream';
2
+ import { observeAwsReplayAbort } from "./aws-replay-abort-signal.mjs";
3
+ import { forceClientOption } from "./force-client-option.mjs";
4
+ export function createAwsReplayRequestHandler(replay) {
5
+ return {
6
+ async handle(request, options) {
7
+ const origin = new URL(`${request.protocol}//${request.hostname}`);
8
+ if (request.port)
9
+ origin.port = String(request.port);
10
+ const query = serializeAwsReplayQuery(request.query ?? {});
11
+ const url = `${origin.origin}${request.path}${query ? `?${query}` : ''}`;
12
+ const { signal, detach } = observeAwsReplayAbort(options?.abortSignal);
13
+ try {
14
+ const response = await replay.sendHttpRequest(url, {
15
+ method: request.method,
16
+ headers: request.headers,
17
+ body: request.body ?? null,
18
+ duplex: 'half',
19
+ signal: signal ?? null,
20
+ });
21
+ const body = response.body ? Readable.fromWeb(response.body) : Readable.from([]);
22
+ if (response.body)
23
+ body.once('close', detach);
24
+ else
25
+ detach();
26
+ return {
27
+ response: {
28
+ statusCode: response.status,
29
+ reason: response.statusText,
30
+ headers: Object.fromEntries(response.headers.entries()),
31
+ body,
32
+ },
33
+ };
34
+ }
35
+ catch (err) {
36
+ detach();
37
+ throw err;
38
+ }
39
+ },
40
+ destroy: () => { },
41
+ updateHttpClientConfig: () => { },
42
+ httpHandlerConfigs: () => ({}),
43
+ };
44
+ }
45
+ /** Smithy's wire query order and RFC3986 escaping, including bare null keys. */
46
+ function serializeAwsReplayQuery(query) {
47
+ const escape = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
48
+ return Object.keys(query)
49
+ .toSorted()
50
+ .flatMap((name) => {
51
+ const key = escape(name);
52
+ const value = query[name];
53
+ if (value == null)
54
+ return key;
55
+ return [value].flat().map((part) => `${key}=${escape(part)}`);
56
+ })
57
+ .join('&');
58
+ }
59
+ /**
60
+ * Subclasses an AWS SDK client so every instance sends through the replay, whatever
61
+ * `requestHandler` production code configured. Use it inside a `vi.mock` of the SDK package for a
62
+ * client that production builds itself, so the test never edits production code.
63
+ */
64
+ export function replayAwsClient(Constructor, replay) {
65
+ return forceClientOption(Constructor, 'requestHandler', createAwsReplayRequestHandler(replay));
66
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Subclasses an SDK client constructor so every instance is built with `options[name] = value`,
3
+ * whatever the caller configured for that option. The options object is the first constructor
4
+ * argument; any further arguments are forwarded untouched.
5
+ */
6
+ export declare function forceClientOption<Client extends abstract new (...args: never[]) => object>(Constructor: Client, name: string, value: unknown): Client;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Subclasses an SDK client constructor so every instance is built with `options[name] = value`,
3
+ * whatever the caller configured for that option. The options object is the first constructor
4
+ * argument; any further arguments are forwarded untouched.
5
+ */
6
+ export function forceClientOption(Constructor, name, value) {
7
+ class ForcedOptionClient extends Constructor {
8
+ constructor(options, ...rest) {
9
+ super({ ...options, [name]: value }, ...rest);
10
+ }
11
+ }
12
+ return ForcedOptionClient;
13
+ }
@@ -0,0 +1,6 @@
1
+ export { onAbort, readUntilAborted } from './abort-listeners.mts';
2
+ export { observeAwsReplayAbort } from './aws-replay-abort-signal.mts';
3
+ export { createAwsReplayRequestHandler, replayAwsClient, type AwsReplayRequestHandler, } from './aws-replay-request-handler.mts';
4
+ export { createProviderReplay, replayClient, type ProviderReplay, type ReplayedRequest, } from './provider-replay.mts';
5
+ export { loadRecordedResponse, parseRecordedResponse, type LoadRecordedResponseOptions, type RecordedResponse, } from './recorded-response.mts';
6
+ export { toReplayResponse } from './replay-response.mts';
@@ -0,0 +1,6 @@
1
+ export { onAbort, readUntilAborted } from "./abort-listeners.mjs";
2
+ export { observeAwsReplayAbort } from "./aws-replay-abort-signal.mjs";
3
+ export { createAwsReplayRequestHandler, replayAwsClient, } from "./aws-replay-request-handler.mjs";
4
+ export { createProviderReplay, replayClient, } from "./provider-replay.mjs";
5
+ export { loadRecordedResponse, parseRecordedResponse, } from "./recorded-response.mjs";
6
+ export { toReplayResponse } from "./replay-response.mjs";
@@ -0,0 +1,32 @@
1
+ import type { RecordedResponse } from './recorded-response.mts';
2
+ /** What the code under test sent. Header names are lower-cased. */
3
+ export type ReplayedRequest = {
4
+ method: string;
5
+ url: string;
6
+ headers: Record<string, string>;
7
+ body: Buffer | undefined;
8
+ json: <T = unknown>() => T;
9
+ };
10
+ export type ProviderReplay = {
11
+ /** Pass this as the SDK's `fetch` option. It answers each request with the next queued response. */
12
+ fetch: typeof fetch;
13
+ /** Raw HTTP transport: preserve serialized URL bytes instead of fetch URL normalization. */
14
+ sendHttpRequest: (url: string, init?: RequestInit) => Promise<Response>;
15
+ /** Every request the SDK sent, in order. */
16
+ requests: ReplayedRequest[];
17
+ /** Queue responses; the SDK receives them in request order. */
18
+ respondWith: (...responses: RecordedResponse[]) => void;
19
+ /** Fail when a queued response was never requested, so a skipped call cannot pass silently. */
20
+ assertDrained: () => void;
21
+ /** Forget the queue and the captured requests, for a client shared across the tests of a file. */
22
+ reset: () => void;
23
+ };
24
+ export declare function createProviderReplay(options?: {
25
+ chunkBytes?: number;
26
+ }): ProviderReplay;
27
+ /**
28
+ * Subclasses an SDK client so every instance sends through the replay, whatever `fetch` production
29
+ * code configured. Use it inside a `vi.mock` of the SDK package for a client that production builds
30
+ * itself, so the test never edits production code.
31
+ */
32
+ export declare function replayClient<Client extends abstract new (...args: never[]) => object>(Constructor: Client, replay: ProviderReplay): Client;
@@ -0,0 +1,54 @@
1
+ import { readUntilAborted } from "./abort-listeners.mjs";
2
+ import { forceClientOption } from "./force-client-option.mjs";
3
+ import { toReplayResponse } from "./replay-response.mjs";
4
+ export function createProviderReplay(options = {}) {
5
+ const requests = [];
6
+ const queue = [];
7
+ // `new Request(...)` applies fetch semantics to the SDK's arguments: the effective URL, method,
8
+ // and headers (a form body brings its own `content-type`), the body bytes, and an abort signal
9
+ // that follows `init.signal`.
10
+ const replayRequest = async (request, url = request.url, headers = request.headers) => {
11
+ const { signal } = request;
12
+ signal.throwIfAborted();
13
+ // Reserve the request's position and its response before awaiting the body, so concurrent
14
+ // calls keep the order in which they started.
15
+ const sent = {
16
+ method: request.method,
17
+ url,
18
+ headers: Object.fromEntries(headers.entries()),
19
+ body: undefined,
20
+ json: () => JSON.parse(sent.body?.toString('utf8') ?? 'null'),
21
+ };
22
+ requests.push(sent);
23
+ const next = queue.shift();
24
+ if (!next) {
25
+ throw new Error(`Provider replay has no recorded response for request ${requests.length}: ${sent.method} ${sent.url}`);
26
+ }
27
+ const bytes = await readUntilAborted(request, signal);
28
+ sent.body = bytes.length === 0 ? undefined : bytes;
29
+ return toReplayResponse(next, options.chunkBytes, signal);
30
+ };
31
+ return {
32
+ fetch: async (input, init) => replayRequest(new Request(input, init)),
33
+ sendHttpRequest: async (url, init) => replayRequest(new Request(url, init), url, new Headers(init?.headers)),
34
+ requests,
35
+ respondWith: (...responses) => void queue.push(...responses),
36
+ assertDrained: () => {
37
+ if (queue.length > 0) {
38
+ throw new Error(`Provider replay left ${queue.length} recorded response(s) unrequested`);
39
+ }
40
+ },
41
+ reset: () => {
42
+ requests.length = 0;
43
+ queue.length = 0;
44
+ },
45
+ };
46
+ }
47
+ /**
48
+ * Subclasses an SDK client so every instance sends through the replay, whatever `fetch` production
49
+ * code configured. Use it inside a `vi.mock` of the SDK package for a client that production builds
50
+ * itself, so the test never edits production code.
51
+ */
52
+ export function replayClient(Constructor, replay) {
53
+ return forceClientOption(Constructor, 'fetch', replay.fetch);
54
+ }
@@ -0,0 +1,17 @@
1
+ /** A provider response as it arrived on the wire: status, headers and the raw body bytes. */
2
+ export type RecordedResponse = {
3
+ status: number;
4
+ statusText: string;
5
+ headers: Array<[name: string, value: string]>;
6
+ body: Buffer;
7
+ };
8
+ export type LoadRecordedResponseOptions = {
9
+ /** Directory (path or `file:` URL) that holds the raw `.http` fixtures. */
10
+ fixtureRoot: string | URL;
11
+ /** Literal tokens swapped in the whole file, for ids a test must keep unique. */
12
+ replace?: Record<string, string>;
13
+ };
14
+ /** Loads the raw `.http` fixture `<fixtureRoot>/<name>` and parses it. */
15
+ export declare function loadRecordedResponse(name: string, options: LoadRecordedResponseOptions): RecordedResponse;
16
+ /** Parses raw HTTP response text: a status line, headers, a blank line, then the body bytes. */
17
+ export declare function parseRecordedResponse(raw: Buffer): RecordedResponse;
@@ -0,0 +1,42 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ /** Headers describing the original transfer framing; the replay serves the decoded body instead. */
5
+ const FRAMING_HEADERS = new Set([
6
+ 'connection',
7
+ 'content-encoding',
8
+ 'content-length',
9
+ 'keep-alive',
10
+ 'transfer-encoding',
11
+ ]);
12
+ /** Loads the raw `.http` fixture `<fixtureRoot>/<name>` and parses it. */
13
+ export function loadRecordedResponse(name, options) {
14
+ const { fixtureRoot } = options;
15
+ const root = typeof fixtureRoot === 'string' ? fixtureRoot : fileURLToPath(fixtureRoot);
16
+ let raw = readFileSync(resolve(root, name)).toString('latin1');
17
+ for (const [token, value] of Object.entries(options.replace ?? {})) {
18
+ raw = raw.replaceAll(token, value);
19
+ }
20
+ return parseRecordedResponse(Buffer.from(raw, 'latin1'));
21
+ }
22
+ /** Parses raw HTTP response text: a status line, headers, a blank line, then the body bytes. */
23
+ export function parseRecordedResponse(raw) {
24
+ const crlf = raw.indexOf('\r\n\r\n');
25
+ const lf = raw.indexOf('\n\n');
26
+ const useCrlf = crlf !== -1 && (lf === -1 || crlf < lf);
27
+ const headEnd = useCrlf ? crlf : lf;
28
+ const head = headEnd === -1 ? raw : raw.subarray(0, headEnd);
29
+ const body = headEnd === -1 ? Buffer.alloc(0) : raw.subarray(headEnd + (useCrlf ? 4 : 2));
30
+ const [statusLine = '', ...headerLines] = head.toString('latin1').split(/\r?\n/);
31
+ const status = /^HTTP\/\S+ (\d{3})(?: (.*))?$/.exec(statusLine);
32
+ if (!status)
33
+ throw new Error(`Recorded response has no HTTP status line: ${statusLine}`);
34
+ const headers = headerLines.flatMap((line) => {
35
+ const colon = line.indexOf(':');
36
+ const name = line.slice(0, colon).trim().toLowerCase();
37
+ if (colon < 1 || FRAMING_HEADERS.has(name))
38
+ return [];
39
+ return [[name, line.slice(colon + 1).trim()]];
40
+ });
41
+ return { status: Number(status[1]), statusText: status[2] ?? '', headers, body };
42
+ }
@@ -0,0 +1,8 @@
1
+ import type { RecordedResponse } from './recorded-response.mts';
2
+ /**
3
+ * Builds the `Response` an SDK reads. The body streams in `chunkBytes` pieces (default: one), so a
4
+ * small value proves the consumer does not depend on events arriving aligned to chunk boundaries.
5
+ * When the request's `signal` aborts while the body is being read, the stream errors with the
6
+ * signal's reason, as a real transport does.
7
+ */
8
+ export declare function toReplayResponse(recorded: RecordedResponse, chunkBytes?: number, signal?: AbortSignal | null): Response;
@@ -0,0 +1,38 @@
1
+ import { onAbort } from "./abort-listeners.mjs";
2
+ /**
3
+ * Builds the `Response` an SDK reads. The body streams in `chunkBytes` pieces (default: one), so a
4
+ * small value proves the consumer does not depend on events arriving aligned to chunk boundaries.
5
+ * When the request's `signal` aborts while the body is being read, the stream errors with the
6
+ * signal's reason, as a real transport does.
7
+ */
8
+ export function toReplayResponse(recorded, chunkBytes, signal) {
9
+ const size = chunkBytes ?? Math.max(recorded.body.length, 1);
10
+ if (!Number.isSafeInteger(size) || size < 1) {
11
+ throw new RangeError(`chunkBytes must be a positive integer, received ${chunkBytes}`);
12
+ }
13
+ let offset = 0;
14
+ let detach;
15
+ const body = recorded.body.length === 0
16
+ ? null
17
+ : new ReadableStream({
18
+ start(controller) {
19
+ detach = onAbort(signal, () => controller.error(signal?.reason));
20
+ },
21
+ pull(controller) {
22
+ if (signal?.aborted)
23
+ return controller.error(signal.reason);
24
+ if (offset >= recorded.body.length) {
25
+ detach();
26
+ return controller.close();
27
+ }
28
+ controller.enqueue(recorded.body.subarray(offset, offset + size));
29
+ offset += size;
30
+ },
31
+ cancel: detach,
32
+ });
33
+ return new Response(body, {
34
+ status: recorded.status,
35
+ statusText: recorded.statusText,
36
+ headers: recorded.headers,
37
+ });
38
+ }
@@ -0,0 +1,8 @@
1
+ import type { StorybookBrowserProject } from './types.mts';
2
+ export type ParsedStorybookBrowserRunnerArgs = StorybookBrowserProject;
3
+ /**
4
+ * Parses the `storybook-browser-runner` flags. Arguments after `--` replace the default argv
5
+ * (`exec vitest run --project <name>`), so they may begin with a dash. Flag values that begin
6
+ * with a dash use the `--flag=value` form. Throws an Error naming the first problem.
7
+ */
8
+ export declare function parseStorybookBrowserRunnerArgs(argv: readonly string[]): ParsedStorybookBrowserRunnerArgs;
@@ -0,0 +1,52 @@
1
+ import { parseArgs } from 'node:util';
2
+ function required(raw, flag) {
3
+ if (raw.length === 0 || raw.startsWith('-'))
4
+ throw new Error(`${flag} requires a value`);
5
+ return raw;
6
+ }
7
+ /**
8
+ * Parses the `storybook-browser-runner` flags. Arguments after `--` replace the default argv
9
+ * (`exec vitest run --project <name>`), so they may begin with a dash. Flag values that begin
10
+ * with a dash use the `--flag=value` form. Throws an Error naming the first problem.
11
+ */
12
+ export function parseStorybookBrowserRunnerArgs(argv) {
13
+ const { positionals, values } = parseArgs({
14
+ allowPositionals: true,
15
+ args: [...argv],
16
+ options: {
17
+ command: { type: 'string' },
18
+ 'completion-file': { type: 'string' },
19
+ 'coverage-arg': { type: 'string', multiple: true },
20
+ 'env-prefix': { type: 'string' },
21
+ 'optimize-deps-config': { type: 'string' },
22
+ 'progress-prefix': { type: 'string' },
23
+ project: { type: 'string' },
24
+ 'result-file': { type: 'string', multiple: true },
25
+ },
26
+ strict: true,
27
+ });
28
+ if (values.project === undefined)
29
+ throw new Error('--project <name> is required');
30
+ const optional = (flag) => {
31
+ const raw = values[flag];
32
+ return raw === undefined ? undefined : required(raw, `--${flag}`);
33
+ };
34
+ const project = { projectName: required(values.project, '--project') };
35
+ const assign = (key, value) => {
36
+ if (value !== undefined)
37
+ project[key] = value;
38
+ };
39
+ assign('command', optional('command'));
40
+ assign('completionFile', optional('completion-file'));
41
+ assign('envPrefix', optional('env-prefix'));
42
+ assign('optimizeDepsConfigPath', optional('optimize-deps-config'));
43
+ assign('progressPrefix', optional('progress-prefix'));
44
+ if (values['coverage-arg'])
45
+ project.coverageArgs = values['coverage-arg'];
46
+ if (values['result-file']) {
47
+ project.resultFiles = values['result-file'].map((file) => required(file, '--result-file'));
48
+ }
49
+ if (positionals.length > 0)
50
+ project.args = positionals;
51
+ return project;
52
+ }
@@ -0,0 +1,41 @@
1
+ import type { BrowserSessionResult } from '../browser-session-runner/index.mts';
2
+ import type { StorybookBrowserBootstrapSnapshot } from './bootstrap-telemetry.mts';
3
+ import type { OutputObserverSnapshot } from './observer-state.mts';
4
+ import type { WatchdogOutcome } from './watchdog.mts';
5
+ export type AttemptResult = {
6
+ bootstrap: StorybookBrowserBootstrapSnapshot;
7
+ budgetExpired: boolean;
8
+ code: number;
9
+ durationMs: number;
10
+ exitCode: number | null;
11
+ firstTestOutputAtMs: number | null;
12
+ hung: boolean;
13
+ isStall: boolean;
14
+ lastOutputAgeMs: number;
15
+ newOptimizeDeps: string[];
16
+ optimizerReadyAtMs: number | null;
17
+ optimizerReloadFromNewDeps: boolean;
18
+ resultFileDetectedAtMs: number | null;
19
+ retryable: boolean;
20
+ runnerMissing: boolean;
21
+ semanticProgress: boolean;
22
+ semanticStall: boolean;
23
+ signal: NodeJS.Signals | null;
24
+ viteFetchFailure: boolean;
25
+ viteReady: boolean;
26
+ };
27
+ export type AttemptFacts = {
28
+ bootstrap: StorybookBrowserBootstrapSnapshot;
29
+ finishedAt: number;
30
+ observed: OutputObserverSnapshot;
31
+ outcome: WatchdogOutcome;
32
+ spawnFailed: boolean;
33
+ startedAt: number;
34
+ };
35
+ /** Maps the session exit plus the observed output to the attempt result and its retry rule. */
36
+ export declare function buildAttemptResult(session: Pick<BrowserSessionResult, 'exit' | 'reason'>, facts: AttemptFacts): AttemptResult;
37
+ /** The command could not be started: failed, never retryable. */
38
+ export declare function failedSpawnAttempt(bootstrap: StorybookBrowserBootstrapSnapshot, startedAt: number, lastOutputAt: number, now: number): AttemptResult;
39
+ /** The session budget ran out before the session produced a result. */
40
+ export declare function expiredAttempt(bootstrap: StorybookBrowserBootstrapSnapshot, startedAt: number, now: number): AttemptResult;
41
+ export declare function formatAttemptResult(attempt: number, result: AttemptResult): string;
@@ -0,0 +1,108 @@
1
+ const relativeTo = (startedAt, at) => (at == null ? null : at - startedAt);
2
+ /** Maps the session exit plus the observed output to the attempt result and its retry rule. */
3
+ export function buildAttemptResult(session, facts) {
4
+ const { bootstrap, finishedAt, observed, outcome, spawnFailed, startedAt } = facts;
5
+ const optimizerReloadFromNewDeps = observed.sawNewOptimizeDeps && observed.sawOptimizerReload;
6
+ const runnerMissing = observed.sawAddonVitestSetupFile &&
7
+ observed.sawRunnerMissingMessage &&
8
+ !observed.storybookBrowserOutputSeen;
9
+ const connectionTimeout = observed.browserSessionConnectionTimedOut && !observed.semanticProgressSeen;
10
+ const budgetExpired = session.reason === 'deadline';
11
+ const killedByWatchdog = outcome.stalled ||
12
+ outcome.hung ||
13
+ outcome.semanticStall ||
14
+ budgetExpired ||
15
+ session.reason === 'parent-signal';
16
+ return {
17
+ bootstrap,
18
+ budgetExpired,
19
+ code: spawnFailed || killedByWatchdog ? 1 : (session.exit.code ?? 1),
20
+ durationMs: finishedAt - startedAt,
21
+ exitCode: spawnFailed ? 1 : session.exit.code,
22
+ firstTestOutputAtMs: relativeTo(startedAt, observed.firstTestOutputAt),
23
+ hung: outcome.hung || connectionTimeout,
24
+ isStall: outcome.stalled,
25
+ lastOutputAgeMs: finishedAt - observed.lastOutputAt,
26
+ newOptimizeDeps: observed.newOptimizeDeps,
27
+ optimizerReadyAtMs: relativeTo(startedAt, observed.optimizerReadyAt),
28
+ optimizerReloadFromNewDeps,
29
+ resultFileDetectedAtMs: relativeTo(startedAt, outcome.resultFileDetectedAt),
30
+ retryable: !spawnFailed &&
31
+ !budgetExpired &&
32
+ session.reason !== 'parent-signal' &&
33
+ !outcome.semanticStall &&
34
+ !optimizerReloadFromNewDeps &&
35
+ (observed.retryableViteFailure ||
36
+ runnerMissing ||
37
+ (!observed.semanticProgressSeen && (outcome.stalled || outcome.hung || connectionTimeout))),
38
+ runnerMissing,
39
+ semanticProgress: observed.semanticProgressSeen,
40
+ semanticStall: outcome.semanticStall,
41
+ signal: session.exit.signal,
42
+ viteFetchFailure: observed.retryableViteFailure,
43
+ viteReady: observed.startupComplete,
44
+ };
45
+ }
46
+ const baseResult = (bootstrap) => ({
47
+ bootstrap,
48
+ budgetExpired: false,
49
+ code: 1,
50
+ durationMs: 0,
51
+ exitCode: null,
52
+ firstTestOutputAtMs: null,
53
+ hung: false,
54
+ isStall: false,
55
+ lastOutputAgeMs: 0,
56
+ newOptimizeDeps: [],
57
+ optimizerReadyAtMs: null,
58
+ optimizerReloadFromNewDeps: false,
59
+ resultFileDetectedAtMs: null,
60
+ retryable: false,
61
+ runnerMissing: false,
62
+ semanticProgress: false,
63
+ semanticStall: false,
64
+ signal: null,
65
+ viteFetchFailure: false,
66
+ viteReady: false,
67
+ });
68
+ /** The command could not be started: failed, never retryable. */
69
+ export function failedSpawnAttempt(bootstrap, startedAt, lastOutputAt, now) {
70
+ return {
71
+ ...baseResult(bootstrap),
72
+ durationMs: now - startedAt,
73
+ exitCode: 1,
74
+ lastOutputAgeMs: now - lastOutputAt,
75
+ };
76
+ }
77
+ /** The session budget ran out before the session produced a result. */
78
+ export function expiredAttempt(bootstrap, startedAt, now) {
79
+ return { ...baseResult(bootstrap), budgetExpired: true, durationMs: now - startedAt };
80
+ }
81
+ export function formatAttemptResult(attempt, result) {
82
+ return `${[
83
+ `[storybook-browser] attempt=${attempt} finished in ${result.durationMs}ms`,
84
+ `code=${result.exitCode ?? 'null'}`,
85
+ `signal=${result.signal ?? 'null'}`,
86
+ `resolvedCode=${result.code}`,
87
+ `retryable=${String(result.retryable)}`,
88
+ `stall=${String(result.isStall)}`,
89
+ `hang=${String(result.hung)}`,
90
+ `runnerMissing=${String(result.runnerMissing)}`,
91
+ `budgetExpired=${String(result.budgetExpired)}`,
92
+ `semanticProgress=${String(result.semanticProgress)}`,
93
+ `semanticStall=${String(result.semanticStall)}`,
94
+ `viteReady=${String(result.viteReady)}`,
95
+ `optimizerReadyAtMs=${result.optimizerReadyAtMs ?? 'none'}`,
96
+ `firstTestOutputAtMs=${result.firstTestOutputAtMs ?? 'none'}`,
97
+ `lastOutputAgeMs=${result.lastOutputAgeMs}`,
98
+ `resultFileAtMs=${result.resultFileDetectedAtMs ?? 'none'}`,
99
+ `bootstrapStage=${result.bootstrap.terminalStage}`,
100
+ `bootstrapTimeline=${JSON.stringify(result.bootstrap.timeline)}`,
101
+ `orchestratorDisconnectCount=${result.bootstrap.orchestratorDisconnectCount}`,
102
+ `requestFailureCount=${result.bootstrap.requestFailureCount}`,
103
+ `requestFailureSamples=${JSON.stringify(result.bootstrap.requestFailureSamples)}`,
104
+ `viteFetchFailure=${String(result.viteFetchFailure)}`,
105
+ `optimizerReloadFromNewDeps=${String(result.optimizerReloadFromNewDeps)}`,
106
+ `newOptimizeDeps=${result.newOptimizeDeps.join(',') || 'none'}`,
107
+ ].join('; ')}\n`;
108
+ }
@@ -0,0 +1,35 @@
1
+ type OutputStream = 'stderr' | 'stdout';
2
+ export type StorybookBrowserBootstrapMilestone = 'context-ready' | 'navigation-requested' | 'orchestrator-connected' | 'page-ready' | 'provider-started' | 'semantic-progress';
3
+ type StorybookBrowserBootstrapTerminalStage = 'context-to-page' | 'handshake-after-websocket' | 'launch-or-context' | 'navigation-to-websocket' | 'no-provider-evidence' | 'page-to-navigation' | 'semantic-progress';
4
+ export interface StorybookBrowserBootstrapSnapshot {
5
+ orchestratorDisconnectCount: number;
6
+ requestFailureCount: number;
7
+ requestFailureSamples: string[];
8
+ terminalStage: StorybookBrowserBootstrapTerminalStage;
9
+ timeline: Array<{
10
+ atMs: number;
11
+ milestone: StorybookBrowserBootstrapMilestone;
12
+ }>;
13
+ }
14
+ interface ConsumedOutput {
15
+ hasNonDiagnosticOutput: boolean;
16
+ output: string;
17
+ }
18
+ export declare class StorybookBrowserBootstrapTelemetry {
19
+ private readonly lineBuffers;
20
+ private readonly milestones;
21
+ private readonly requestFailureSamples;
22
+ private readonly timeline;
23
+ private playwrightBrowserLineCount;
24
+ private orchestratorDisconnectCount;
25
+ private requestFailureCount;
26
+ consume(stream: OutputStream, chunk: string | Buffer, atMs: number): ConsumedOutput;
27
+ flush(stream: OutputStream, atMs: number): ConsumedOutput;
28
+ recordSemanticProgress(atMs: number): void;
29
+ snapshot(): StorybookBrowserBootstrapSnapshot;
30
+ private consumeLines;
31
+ private observeLine;
32
+ private filterLine;
33
+ private recordMilestone;
34
+ }
35
+ export {};