@hublo/sentinel 1.7.0-alpha.30 → 1.7.0-alpha.31

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 (45) hide show
  1. package/README.md +2 -1
  2. package/dist/bin/sentinel.js +13 -7
  3. package/dist/{chunk-HYXFUUF5.js → chunk-2DUG6GVU.js} +3850 -2246
  4. package/dist/chunk-F5WISUN3.js +17 -0
  5. package/dist/chunk-F5WISUN3.js.map +1 -0
  6. package/dist/{chunk-2PRJJRJI.js → chunk-FZLUCPST.js} +1 -1
  7. package/dist/{chunk-YUZB4LRJ.js → chunk-KKHKRY7P.js} +6 -1
  8. package/dist/chunk-KKHKRY7P.js.map +1 -0
  9. package/dist/chunk-NE3IEJBN.js +59 -0
  10. package/dist/chunk-NE3IEJBN.js.map +1 -0
  11. package/dist/{chunk-SHF46ALB.js → chunk-NGLEGAEN.js} +1 -1
  12. package/dist/chunk-NGLEGAEN.js.map +1 -0
  13. package/dist/{chunk-LVY5NPOC.js → chunk-QMIJ4ZGJ.js} +2 -2
  14. package/dist/chunk-U7G2Y6YC.js +15 -0
  15. package/dist/chunk-U7G2Y6YC.js.map +1 -0
  16. package/dist/chunk-VWASE6NN.js +34 -0
  17. package/dist/chunk-VWASE6NN.js.map +1 -0
  18. package/dist/{chunk-APBEGLRI.js → chunk-XMAXE2Q2.js} +5 -2
  19. package/dist/chunk-XMAXE2Q2.js.map +1 -0
  20. package/dist/index.js +9 -5
  21. package/dist/roles/runtime-analysis/config.d.ts +97 -0
  22. package/dist/roles/runtime-analysis/config.js +10 -0
  23. package/dist/roles/runtime-analysis/config.js.map +1 -0
  24. package/dist/roles/runtime-analysis/gateway.d.ts +2 -0
  25. package/dist/roles/runtime-analysis/gateway.js +89 -0
  26. package/dist/roles/runtime-analysis/gateway.js.map +1 -0
  27. package/dist/roles/runtime-analysis/mock-api.d.ts +2 -0
  28. package/dist/roles/runtime-analysis/mock-api.js +43 -0
  29. package/dist/roles/runtime-analysis/mock-api.js.map +1 -0
  30. package/dist/roles/sql/config.js +1 -1
  31. package/dist/roles/static-analysis/config.js +1 -1
  32. package/dist/roles/test/setup/jest-parity.js +2 -2
  33. package/dist/roles/test/setup/workspace-entry.js +2 -2
  34. package/dist/{validate-4GMB32V7.js → validate-GTBRD2M4.js} +2 -2
  35. package/docs/runtime-analysis-adoption.md +198 -0
  36. package/docs/sql-adoption.md +18 -92
  37. package/docs/typescript-traces.md +2 -38
  38. package/package.json +10 -3
  39. package/runtime-analysis-deps/load.mjs +6 -0
  40. package/runtime-analysis-deps/package-lock.json +1766 -0
  41. package/runtime-analysis-deps/package.json +11 -0
  42. package/dist/chunk-APBEGLRI.js.map +0 -1
  43. package/dist/chunk-SHF46ALB.js.map +0 -1
  44. package/dist/chunk-YUZB4LRJ.js.map +0 -1
  45. /package/dist/{chunk-LVY5NPOC.js.map → chunk-QMIJ4ZGJ.js.map} +0 -0
@@ -0,0 +1,97 @@
1
+ declare const METHODS: readonly ["GET", "POST", "PUT", "PATCH", "DELETE"];
2
+ type Method = (typeof METHODS)[number];
3
+ /** One entry of a front's `api` list, as written. */
4
+ interface ApiEntry {
5
+ method?: Method;
6
+ path: string;
7
+ status?: number;
8
+ /** The JSON answered, relative to the module. */
9
+ file: string;
10
+ }
11
+
12
+ /** The one interaction a screen's flow performs, timed for INP. */
13
+ type Interaction = {
14
+ click: string;
15
+ } | {
16
+ clickText: string;
17
+ } | {
18
+ type: {
19
+ selector: string;
20
+ text: string;
21
+ };
22
+ };
23
+ /** A screen measured: the route that renders it, the path opened, and what proves it opened. */
24
+ interface Screen {
25
+ id: string;
26
+ /** The route file, relative to `router.routes`: a change to what it loads measures it. */
27
+ route: string;
28
+ /** The path opened, starting with `/`. */
29
+ path: string;
30
+ /** Texts the screen shows once opened: each must be visible before the figures count. */
31
+ expectText: string[];
32
+ interact: Interaction;
33
+ /** Rows the screen must list once opened, by count or at least a minimum. */
34
+ rows?: {
35
+ selector: string;
36
+ count?: number;
37
+ min?: number;
38
+ };
39
+ /** An element that must be there once opened. */
40
+ expectSelector?: string;
41
+ /**
42
+ * This screen's own ready call, when it does not make the front's: console's institution screens
43
+ * and its client page share no BFF call. Checked like the front's, answered by the mocks with 200.
44
+ */
45
+ ready?: string;
46
+ }
47
+ /** What a front's config file passes to `defineRuntimeAnalysis`. */
48
+ interface RuntimeAnalysisInput {
49
+ /** The front's own directory, normally `import.meta.dirname`. */
50
+ root?: string;
51
+ /** The path the app is served under: the rest goes to the mocks. Or `mockPrefixes`, not both. */
52
+ basePath?: string;
53
+ /** The paths sent to the mocks, for an app served at the root. Or `basePath`, not both. */
54
+ mockPrefixes?: string[];
55
+ /** The app's health path, answered once it is up. */
56
+ health: string;
57
+ /** The call that tells the app is ready (a session): answered by the mocks, with 200. */
58
+ ready: string;
59
+ build: {
60
+ /** The build output, relative to the front. */
61
+ output: string;
62
+ /** The server the output starts with (`node <server>`, `HOST` and `PORT` set). */
63
+ server: string;
64
+ /** The build variables; `{origin}` is the gateway the build is served behind. */
65
+ env: Record<string, string>;
66
+ };
67
+ /** The answers of the calls the screens make. */
68
+ api: ApiEntry[];
69
+ router: {
70
+ /** The tsconfig the route imports are resolved with. */
71
+ tsconfig: string;
72
+ /** The app shell files every screen loads. */
73
+ shell: string[];
74
+ /** The file routes directory (TanStack Router), holding `__root.tsx`. */
75
+ routes: string;
76
+ };
77
+ screens: Screen[];
78
+ /**
79
+ * The translations folder, relative to the front, holding `<lang>/<namespace>.json`: a change
80
+ * to one measures the screens whose code names its namespace, not every screen.
81
+ */
82
+ translations?: string;
83
+ /**
84
+ * The browser's language, as the screens' expected texts are written (`fr-FR`): a front that
85
+ * picks its language from the browser otherwise renders the runner's. `en-US` when left out.
86
+ */
87
+ locale?: string;
88
+ }
89
+ /** The browser language when a config names none. */
90
+ declare const DEFAULT_LOCALE: string;
91
+ /** The config as sentinel reads it: what the module passed, marked as defined here. */
92
+ type RuntimeAnalysisConfig = RuntimeAnalysisInput & {
93
+ readonly defined: true;
94
+ };
95
+ declare function defineRuntimeAnalysis(input: RuntimeAnalysisInput): RuntimeAnalysisConfig;
96
+
97
+ export { DEFAULT_LOCALE, type Interaction, type RuntimeAnalysisConfig, type RuntimeAnalysisInput, type Screen, defineRuntimeAnalysis };
@@ -0,0 +1,10 @@
1
+ import {
2
+ DEFAULT_LOCALE,
3
+ defineRuntimeAnalysis
4
+ } from "../../chunk-U7G2Y6YC.js";
5
+ import "../../chunk-F5WISUN3.js";
6
+ export {
7
+ DEFAULT_LOCALE,
8
+ defineRuntimeAnalysis
9
+ };
10
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,89 @@
1
+ import {
2
+ loadRuntimeConfig
3
+ } from "../../chunk-VWASE6NN.js";
4
+ import "../../chunk-F5WISUN3.js";
5
+
6
+ // src/roles/runtime-analysis/serve/gateway-main.ts
7
+ import { resolve } from "node:path";
8
+ import { parseArgs } from "node:util";
9
+
10
+ // src/roles/runtime-analysis/serve/gateway.ts
11
+ import { appendFileSync, writeFileSync } from "node:fs";
12
+ import http from "node:http";
13
+ var under = (pathname, prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`);
14
+ function isAppPath(pathname, options) {
15
+ const base = (options.basePath ?? "").replace(/\/$/, "");
16
+ return options.mockPrefixes ? !options.mockPrefixes.some((prefix) => under(pathname, prefix)) : under(pathname, base);
17
+ }
18
+ function createGateway(options) {
19
+ writeFileSync(options.log, "");
20
+ const agent = new http.Agent({ keepAlive: true });
21
+ return http.createServer((request, response) => {
22
+ const startedAt = Date.now();
23
+ const { pathname } = new URL(request.url ?? "/", "http://gateway");
24
+ const toApp = isAppPath(pathname, options);
25
+ const port = toApp ? options.appPort : options.mockPort;
26
+ const log = (status, mock, error) => appendFileSync(
27
+ options.log,
28
+ `${JSON.stringify({ at: new Date(startedAt).toISOString(), method: request.method, path: request.url, to: toApp ? "app" : "mock", status, mock, ms: Date.now() - startedAt, ...error ? { error } : {} })}
29
+ `
30
+ );
31
+ const upstream = http.request(
32
+ {
33
+ hostname: "127.0.0.1",
34
+ port,
35
+ path: request.url,
36
+ method: request.method,
37
+ // What an ingress does: the upstream gets its own host, and the host the browser used in
38
+ // `x-forwarded-host`. A server that trusts only its public origin reads it there: console
39
+ // answered 500 ("Untrusted Console request origin") when it saw only the app's port.
40
+ headers: {
41
+ ...request.headers,
42
+ host: `127.0.0.1:${port}`,
43
+ "x-forwarded-host": request.headers["x-forwarded-host"] ?? request.headers.host ?? ""
44
+ },
45
+ agent
46
+ },
47
+ (answer) => {
48
+ response.writeHead(answer.statusCode ?? 502, answer.headers);
49
+ answer.pipe(response);
50
+ answer.on("end", () => log(answer.statusCode, answer.headers["x-cwv-mock"] ?? null));
51
+ }
52
+ );
53
+ upstream.on("error", (error) => {
54
+ log(502, null, error.code ?? String(error));
55
+ response.writeHead(502, { "content-type": "text/plain" });
56
+ response.end("upstream unreachable");
57
+ });
58
+ request.pipe(upstream);
59
+ });
60
+ }
61
+
62
+ // src/roles/runtime-analysis/serve/gateway-main.ts
63
+ var { values: args } = parseArgs({
64
+ options: Object.fromEntries(
65
+ ["module", "port", "app-port", "mock-port", "log"].map((key) => [
66
+ key,
67
+ { type: "string" }
68
+ ])
69
+ )
70
+ });
71
+ var loaded = await loadRuntimeConfig(resolve(String(args.module)));
72
+ if (!("config" in loaded)) {
73
+ console.error(`no runtime-analysis config in ${args.module}`);
74
+ process.exit(2);
75
+ }
76
+ createGateway({
77
+ ...loaded.config.basePath === void 0 ? {} : { basePath: loaded.config.basePath },
78
+ ...loaded.config.mockPrefixes === void 0 ? {} : { mockPrefixes: loaded.config.mockPrefixes },
79
+ appPort: Number(args["app-port"]),
80
+ mockPort: Number(args["mock-port"]),
81
+ log: resolve(String(args.log))
82
+ }).listen(
83
+ Number(args.port),
84
+ "127.0.0.1",
85
+ () => console.log(
86
+ `gateway on http://127.0.0.1:${args.port}, app ${args["app-port"]}, mocks ${args["mock-port"]}`
87
+ )
88
+ );
89
+ //# sourceMappingURL=gateway.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/roles/runtime-analysis/serve/gateway-main.ts","../../../src/roles/runtime-analysis/serve/gateway.ts"],"sourcesContent":["/**\n * The gateway as its own process: `node gateway.js --module <dir> --port 4101 --app-port 4111\n * --mock-port 4199 --log requests-base.jsonl`. The front's routing is read from its config.\n */\nimport { resolve } from 'node:path'\nimport { parseArgs } from 'node:util'\n\nimport { loadRuntimeConfig } from '../config/resolve.js'\n\nimport { createGateway } from './gateway.js'\n\nconst { values: args } = parseArgs({\n options: Object.fromEntries(\n ['module', 'port', 'app-port', 'mock-port', 'log'].map((key) => [\n key,\n { type: 'string' as const },\n ]),\n ),\n})\nconst loaded = await loadRuntimeConfig(resolve(String(args.module)))\nif (!('config' in loaded)) {\n console.error(`no runtime-analysis config in ${args.module}`)\n process.exit(2)\n}\ncreateGateway({\n ...(loaded.config.basePath === undefined ? {} : { basePath: loaded.config.basePath }),\n ...(loaded.config.mockPrefixes === undefined ? {} : { mockPrefixes: loaded.config.mockPrefixes }),\n appPort: Number(args['app-port']),\n mockPort: Number(args['mock-port']),\n log: resolve(String(args.log)),\n}).listen(Number(args.port), '127.0.0.1', () =>\n console.log(\n `gateway on http://127.0.0.1:${args.port}, app ${args['app-port']}, mocks ${args['mock-port']}`,\n ),\n)\n","/**\n * The gateway, one per build, like an environment's: the front's own paths go to that build's\n * server, every other path to the mock API. A plain proxy, no interception. Every request is logged\n * as one JSON line with its status and whether the mock API handled it, which is how a flow later\n * proves its screen was fed by the mocks and nothing else.\n *\n * Moved from the monorepo's harness (`engine/serve/gateway.mjs`, hublo/monorepo#23672), unchanged\n * in behaviour. It runs in its OWN process (`gateway-main.ts`): proxying from the process that runs\n * Lighthouse would delay the very responses being measured.\n */\nimport { appendFileSync, writeFileSync } from 'node:fs'\nimport http from 'node:http'\n\nexport interface GatewayOptions {\n /** The path the app is served under; the rest is mocked. Or `mockPrefixes`. */\n basePath?: string\n /** The paths mocked, for an app at the root; the rest goes to the app. */\n mockPrefixes?: string[]\n appPort: number\n mockPort: number\n /** The request log, one JSON line per request, emptied at start. */\n log: string\n}\n\nconst under = (pathname: string, prefix: string): boolean =>\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n\n/** Whether a request's path is the app's, by the front's base path or its mocked prefixes. */\nexport function isAppPath(\n pathname: string,\n options: Pick<GatewayOptions, 'basePath' | 'mockPrefixes'>,\n): boolean {\n const base = (options.basePath ?? '').replace(/\\/$/, '')\n return options.mockPrefixes\n ? !options.mockPrefixes.some((prefix) => under(pathname, prefix))\n : under(pathname, base)\n}\n\nexport function createGateway(options: GatewayOptions): http.Server {\n writeFileSync(options.log, '')\n const agent = new http.Agent({ keepAlive: true })\n return http.createServer((request, response) => {\n const startedAt = Date.now()\n const { pathname } = new URL(request.url ?? '/', 'http://gateway')\n const toApp = isAppPath(pathname, options)\n const port = toApp ? options.appPort : options.mockPort\n const log = (\n status: number | undefined,\n mock: string | string[] | null,\n error?: string,\n ): void =>\n appendFileSync(\n options.log,\n `${JSON.stringify({ at: new Date(startedAt).toISOString(), method: request.method, path: request.url, to: toApp ? 'app' : 'mock', status, mock, ms: Date.now() - startedAt, ...(error ? { error } : {}) })}\\n`,\n )\n const upstream = http.request(\n {\n hostname: '127.0.0.1',\n port,\n path: request.url,\n method: request.method,\n // What an ingress does: the upstream gets its own host, and the host the browser used in\n // `x-forwarded-host`. A server that trusts only its public origin reads it there: console\n // answered 500 (\"Untrusted Console request origin\") when it saw only the app's port.\n headers: {\n ...request.headers,\n host: `127.0.0.1:${port}`,\n 'x-forwarded-host': request.headers['x-forwarded-host'] ?? request.headers.host ?? '',\n },\n agent,\n },\n (answer) => {\n response.writeHead(answer.statusCode ?? 502, answer.headers)\n answer.pipe(response)\n answer.on('end', () => log(answer.statusCode, answer.headers['x-cwv-mock'] ?? null))\n },\n )\n upstream.on('error', (error: NodeJS.ErrnoException) => {\n log(502, null, error.code ?? String(error))\n response.writeHead(502, { 'content-type': 'text/plain' })\n response.end('upstream unreachable')\n })\n request.pipe(upstream)\n })\n}\n"],"mappings":"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","names":[]}
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,43 @@
1
+ import {
2
+ answer,
3
+ loadApi
4
+ } from "../../chunk-NE3IEJBN.js";
5
+ import {
6
+ loadRuntimeConfig
7
+ } from "../../chunk-VWASE6NN.js";
8
+ import "../../chunk-F5WISUN3.js";
9
+
10
+ // src/roles/runtime-analysis/serve/mock-api-main.ts
11
+ import { resolve } from "node:path";
12
+ import { parseArgs } from "node:util";
13
+
14
+ // src/roles/runtime-analysis/serve/mock-api.ts
15
+ import http from "node:http";
16
+ function createMockApi(api) {
17
+ return http.createServer((request, response) => {
18
+ request.resume();
19
+ const { status, body, mock } = answer(api, request.method ?? "GET", request.url ?? "/");
20
+ response.writeHead(status, {
21
+ "content-type": mock === "handled" ? "application/json" : "text/plain",
22
+ "x-cwv-mock": mock
23
+ });
24
+ response.end(body);
25
+ });
26
+ }
27
+
28
+ // src/roles/runtime-analysis/serve/mock-api-main.ts
29
+ var { values: args } = parseArgs({
30
+ options: { module: { type: "string" }, port: { type: "string" } }
31
+ });
32
+ var moduleDir = resolve(String(args.module));
33
+ var loaded = await loadRuntimeConfig(moduleDir);
34
+ if (!("config" in loaded)) {
35
+ console.error(`no runtime-analysis config in ${args.module}`);
36
+ process.exit(2);
37
+ }
38
+ createMockApi(loadApi(loaded.config.api, moduleDir)).listen(
39
+ Number(args.port),
40
+ "127.0.0.1",
41
+ () => console.log(`mock API on http://127.0.0.1:${args.port}`)
42
+ );
43
+ //# sourceMappingURL=mock-api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/roles/runtime-analysis/serve/mock-api-main.ts","../../../src/roles/runtime-analysis/serve/mock-api.ts"],"sourcesContent":["/** The mock API as its own process: `node mock-api.js --module <dir> --port 4199`. */\nimport { resolve } from 'node:path'\nimport { parseArgs } from 'node:util'\n\nimport { loadApi } from '../config/api.js'\nimport { loadRuntimeConfig } from '../config/resolve.js'\n\nimport { createMockApi } from './mock-api.js'\n\nconst { values: args } = parseArgs({\n options: { module: { type: 'string' }, port: { type: 'string' } },\n})\nconst moduleDir = resolve(String(args.module))\nconst loaded = await loadRuntimeConfig(moduleDir)\nif (!('config' in loaded)) {\n console.error(`no runtime-analysis config in ${args.module}`)\n process.exit(2)\n}\ncreateMockApi(loadApi(loaded.config.api, moduleDir)).listen(Number(args.port), '127.0.0.1', () =>\n console.log(`mock API on http://127.0.0.1:${args.port}`),\n)\n","/**\n * The mock API: answers a front's API calls from the `api` list of its config, nothing else. A\n * request no entry matches is answered 501, which fails the flow's \"no unhandled request\" proof.\n * Moved from the monorepo's harness (`engine/serve/mock-api.mjs`), unchanged in behaviour; its own\n * process (`mock-api-main.ts`), like the gateway.\n */\nimport http from 'node:http'\n\nimport { answer, type LoadedAnswer } from '../config/api.js'\n\nexport function createMockApi(api: readonly LoadedAnswer[]): http.Server {\n return http.createServer((request, response) => {\n // The body is not read: an entry answers by method and path only.\n request.resume()\n const { status, body, mock } = answer(api, request.method ?? 'GET', request.url ?? '/')\n response.writeHead(status, {\n 'content-type': mock === 'handled' ? 'application/json' : 'text/plain',\n 'x-cwv-mock': mock,\n })\n response.end(body)\n })\n}\n"],"mappings":";;;;;;;;;;AACA,SAAS,eAAe;AACxB,SAAS,iBAAiB;;;ACI1B,OAAO,UAAU;AAIV,SAAS,cAAc,KAA2C;AACvE,SAAO,KAAK,aAAa,CAAC,SAAS,aAAa;AAE9C,YAAQ,OAAO;AACf,UAAM,EAAE,QAAQ,MAAM,KAAK,IAAI,OAAO,KAAK,QAAQ,UAAU,OAAO,QAAQ,OAAO,GAAG;AACtF,aAAS,UAAU,QAAQ;AAAA,MACzB,gBAAgB,SAAS,YAAY,qBAAqB;AAAA,MAC1D,cAAc;AAAA,IAChB,CAAC;AACD,aAAS,IAAI,IAAI;AAAA,EACnB,CAAC;AACH;;;ADZA,IAAM,EAAE,QAAQ,KAAK,IAAI,UAAU;AAAA,EACjC,SAAS,EAAE,QAAQ,EAAE,MAAM,SAAS,GAAG,MAAM,EAAE,MAAM,SAAS,EAAE;AAClE,CAAC;AACD,IAAM,YAAY,QAAQ,OAAO,KAAK,MAAM,CAAC;AAC7C,IAAM,SAAS,MAAM,kBAAkB,SAAS;AAChD,IAAI,EAAE,YAAY,SAAS;AACzB,UAAQ,MAAM,iCAAiC,KAAK,MAAM,EAAE;AAC5D,UAAQ,KAAK,CAAC;AAChB;AACA,cAAc,QAAQ,OAAO,OAAO,KAAK,SAAS,CAAC,EAAE;AAAA,EAAO,OAAO,KAAK,IAAI;AAAA,EAAG;AAAA,EAAa,MAC1F,QAAQ,IAAI,gCAAgC,KAAK,IAAI,EAAE;AACzD;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  defineSql
3
- } from "../../chunk-SHF46ALB.js";
3
+ } from "../../chunk-NGLEGAEN.js";
4
4
  import "../../chunk-PXTU5MPW.js";
5
5
  export {
6
6
  defineSql
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  defineStaticAnalysis
3
- } from "../../chunk-APBEGLRI.js";
3
+ } from "../../chunk-XMAXE2Q2.js";
4
4
  import "../../chunk-PXTU5MPW.js";
5
5
  export {
6
6
  defineStaticAnalysis
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  installWorkspaceSetup
3
- } from "../../../chunk-LVY5NPOC.js";
3
+ } from "../../../chunk-QMIJ4ZGJ.js";
4
4
  import {
5
5
  clearDeepMocks,
6
6
  resetDeepMocks
@@ -9,7 +9,7 @@ import {
9
9
  alreadyInstalled
10
10
  } from "../../../chunk-NUOQXAYR.js";
11
11
  import "../../../chunk-ELZHIN6E.js";
12
- import "../../../chunk-YUZB4LRJ.js";
12
+ import "../../../chunk-KKHKRY7P.js";
13
13
 
14
14
  // src/roles/test/setup/jest-parity.ts
15
15
  import { expect, vi } from "vitest";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  pinWorkspaceTimezone
3
- } from "../../../chunk-LVY5NPOC.js";
3
+ } from "../../../chunk-QMIJ4ZGJ.js";
4
4
  import "../../../chunk-ELZHIN6E.js";
5
- import "../../../chunk-YUZB4LRJ.js";
5
+ import "../../../chunk-KKHKRY7P.js";
6
6
 
7
7
  // src/roles/test/setup/workspace-entry.ts
8
8
  await pinWorkspaceTimezone();
@@ -7,12 +7,12 @@ import {
7
7
  readTestAdoption,
8
8
  resolveVitest,
9
9
  suiteOf
10
- } from "./chunk-2PRJJRJI.js";
10
+ } from "./chunk-FZLUCPST.js";
11
11
  import "./chunk-ZFG6P27V.js";
12
12
  import "./chunk-O7REVMOC.js";
13
13
  import "./chunk-H4HAFJFZ.js";
14
14
  import "./chunk-QXFCZON7.js";
15
- import "./chunk-YUZB4LRJ.js";
15
+ import "./chunk-KKHKRY7P.js";
16
16
 
17
17
  // src/roles/test/validate.ts
18
18
  import { execFileSync } from "node:child_process";
@@ -0,0 +1,198 @@
1
+ # Runtime analysis adoption cheat sheet
2
+
3
+ `--runtime-analysis` measures the Core Web Vitals (LCP, CLS, INP) of a pull request on a React front's real builds. It builds the front twice, at the merge base and at the head, and serves both on the machine behind a gateway, with every API call answered from JSON files. It then measures the screens the diff can change in a real Chrome and fails the pull request only for a breach the pull request **creates**.
4
+
5
+ It is on demand: a measure costs minutes and a build, so `sentinel --run` never sweeps it, and a bare `--init` never adopts it. It runs only when you name it.
6
+
7
+ Scope: React fronts on TanStack Router file routes. A Next.js or Svelte front is reported as out of scope, not measured.
8
+
9
+ ## Adopt a front in two steps
10
+
11
+ ```bash
12
+ cd apps/front/<front>
13
+ # 1. write the front's config and the `runtime-analysis` script
14
+ npx --yes @hublo/sentinel@<exact version> --init --runtime-analysis
15
+ # 2. fill runtime-analysis.config.mjs with the front's screens, mocks and build, then check it
16
+ pnpm exec sentinel --inspect --runtime-analysis
17
+ ```
18
+
19
+ `--init` writes `runtime-analysis.config.mjs` with every key and what it means. A re-init never rewrites it, because its screens and mocks are the front's own. `--inspect` checks it before anything is built, and names each problem by its field.
20
+
21
+ ## The config, key by key
22
+
23
+ ```js
24
+ // runtime-analysis.config.mjs, at the front's root
25
+ import { defineRuntimeAnalysis } from '@hublo/sentinel/runtime-analysis'
26
+
27
+ export default defineRuntimeAnalysis({
28
+ root: import.meta.dirname,
29
+ basePath: '/admin',
30
+ health: '/admin/api/health',
31
+ ready: '/bff-admin/session',
32
+ build: {
33
+ output: '.output',
34
+ server: 'server/index.mjs',
35
+ env: { VITE_API_URL: '{origin}/bff-admin' },
36
+ },
37
+ api: [{ path: '/bff-admin/session', file: 'runtime-analysis/api/session.json' }],
38
+ router: { tsconfig: 'tsconfig.app.json', shell: ['src/router.tsx'], routes: 'src/routes' },
39
+ translations: 'src/assets/locales',
40
+ locale: 'fr-FR',
41
+ screens: [
42
+ {
43
+ id: 'contract-types',
44
+ route: 'contract-types/index.tsx',
45
+ path: '/admin/contract-types',
46
+ expectText: ['Types de contrat'],
47
+ interact: { click: 'main button' },
48
+ },
49
+ ],
50
+ })
51
+ ```
52
+
53
+ Every path is relative to the front.
54
+
55
+ | Key | What it is |
56
+ | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
57
+ | `basePath` or `mockPrefixes` | Where the app is served. Under `basePath`, the app gets that path and the mocks get the rest. At the root, `mockPrefixes` lists the paths sent to the mocks. Give one, not both. |
58
+ | `health` | The app's health path, polled until the server is up. |
59
+ | `ready` | The call that tells the app is ready, usually the session. A mock in `api` must answer it with 200. |
60
+ | `build.output`, `build.server` | The build output, and the server it starts with (`node <server>`, with `HOST` and `PORT` set). |
61
+ | `build.env` | The build variables. `{origin}` is replaced by the gateway the build is served behind: point every API there, never at a real one. Use placeholders, never a secret. |
62
+ | `api` | One entry per call the screens make: `path`, `file`, optional `method` (GET by default) and `status` (200). |
63
+ | `router` | `tsconfig` resolves the route imports, `shell` lists the files every screen loads, and `routes` is the file routes folder holding `__root.tsx`. |
64
+ | `translations` | Optional. The folder holding `<lang>/<namespace>.json`. A change to one namespace measures only the screens whose code names it. |
65
+ | `locale` | Optional, `en-US` by default. The browser's language, matching how `expectText` is written. |
66
+ | `screens` | What is measured. `route` is relative to `router.routes`, `path` is what is opened, `expectText` lists what must be visible before a figure counts, and `interact` is the one interaction timed for INP (`click`, `clickText` or `type`). Optional: `rows` (a count or a minimum of rows, never both), `expectSelector`, and `ready`, the screen's own ready call when it does not make the front's (console's client page shares no BFF call with its institution screens), checked the same way. |
67
+
68
+ A mocked list is written once, not copied out by hand:
69
+
70
+ ```json
71
+ {
72
+ "$repeat": 25,
73
+ "item": { "id": "cwv-{n}", "name": "Type {nn}", "kind": { "$cycle": ["CDI", "CDD"] } }
74
+ }
75
+ ```
76
+
77
+ That is 25 items. `{n}` is the item's number from 1, `{nn}` the same on two digits, and `$cycle` takes its values in turn.
78
+
79
+ ## A front whose server keeps its session
80
+
81
+ host-admin and career read their session through an HTTP call, so `api/session.json` answers it. A front that reads its session in its SERVER (console: better-auth, Redis, a signed cookie) needs two more files, found by name next to its mocks. Neither is a key of the config, and a front without them is measured as before.
82
+
83
+ ```
84
+ runtime-analysis/
85
+ ├── server.env the variables its server reads: test values only
86
+ ├── session.json its test session, as data
87
+ └── api/ its mocks, as for any front
88
+ ```
89
+
90
+ `server.env` is `KEY=VALUE` per line. `{origin}` is the gateway of the side being served, and `{host}` the same without the scheme, for a server that only trusts `https` origins and compares the host:
91
+
92
+ ```
93
+ DEPLOY_ENV=cwv
94
+ BFF_BACKOFFICE_BASE_URL={origin}
95
+ CONSOLE_TRUSTED_ORIGINS=https://{host}
96
+ CACHE_REDIS_URL=redis://127.0.0.1:6379
97
+ ```
98
+
99
+ `session.json` is what the server's store holds for one session, and the cookies the browser sends back. The secret that signs the cookie is a test value in `server.env`, the token is fixed and the expiry far away, so the cookie is a constant written once:
100
+
101
+ ```json
102
+ {
103
+ "store": {
104
+ "url": "redis://127.0.0.1:6379",
105
+ "entries": [{ "key": "console-cwv:cwv-token", "value": { "session": {}, "user": {} } }]
106
+ },
107
+ "cookies": [{ "name": "__Secure-console.session_token", "value": "cwv-token.<signature>" }]
108
+ }
109
+ ```
110
+
111
+ Sentinel writes `store.entries` to the store before the servers start, and sets the cookies on every screen. It never starts the store: in CI it is a service of the workflow, on a machine whatever runs it there (in the monorepo, `pnpm redis:start`).
112
+
113
+ ## Run it on your machine
114
+
115
+ ```bash
116
+ pnpm run runtime-analysis # sentinel --run --runtime-analysis
117
+ ```
118
+
119
+ With no phase, it builds the front once and measures it against itself, base against head on the same build. It judges the result and writes the comment to `runtime-analysis-report/runtime-analysis.md`. Every ❌ in that run is the machine's own noise, which makes it the way to check a new screen before a pull request relies on it.
120
+
121
+ It needs a real Google Chrome: the macOS or Linux install, or `CHROME_PATH`.
122
+
123
+ ## In CI: one command, in phases
124
+
125
+ A CI splits the measure over parallel jobs: one build job per front, then one measure job per front and screen. Each phase is the same command with its name after `--`:
126
+
127
+ | Phase | Where it runs | What it does |
128
+ | --------------------------------------------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
129
+ | `detect --base SHA --head SHA` (or `--all`) | in each affected front | Finds which of the front's screens the diff can change. Writes `runtime-analysis-report/detect.json` and prints `screens=a,b`. Fails on an invalid config. |
130
+ | `verdict --pending --detect DIR [--affected FILE]` | once | Writes the first comment, before any build: building, nothing to measure, or an invalid config. |
131
+ | `env --origin URL` | in the build job | Prints the front's build variables as shell exports, `{origin}` replaced. |
132
+ | `measure --screens a,b --base-build DIR --head-build DIR` | per front and screen | Serves both builds behind their gateways and measures. Writes the evidence to `--out`. |
133
+ | `verdict --evidence DIR --detect DIR` | once, at the end | Judges every measure job's evidence. Writes the comment, `verdict.json` and the budget, and exits 1 on a breach. |
134
+
135
+ Options of the final `verdict`:
136
+
137
+ - `--base` and `--head` print the commits.
138
+ - `--run-url` links the run's artifacts.
139
+ - `--jobs` and `--run` take the run's jobs and its creation time, read from the GitHub API, for the time of each phase.
140
+ - `--affected FILE` takes the projects the pull request affects (a JSON array or one per line), for the line saying none of them is a frontend.
141
+ - `--state closed|merged --report-url URL` adds a `notice.md` when the measure fails on a pull request closed meanwhile: GitHub notifies nobody of an edited comment, so the notice is posted as a new one.
142
+
143
+ sentinel never calls nx or the GitHub API. Which fronts a pull request affects, their builds and the posting of the comment stay the workflow's.
144
+
145
+ ## The browser packages: installed only where a measure runs
146
+
147
+ Lighthouse, Puppeteer and Playwright are not dependencies of sentinel, so a module that installs sentinel does not carry them. sentinel ships their manifest and lockfile in `runtime-analysis-deps/`. The `measure` phase installs them with `npm ci` into sentinel's cache, outside the repository: the workspace, its lockfile and its node_modules never change.
148
+
149
+ | Where | |
150
+ | -------------------------- | ------------------------------------------------------------------------------------------------- |
151
+ | The cache | `~/.cache/sentinel/runtime-analysis/<lockfile hash>`, or the folder named by `SENTINEL_CACHE_DIR` |
152
+ | First measure of a version | about 11 s and 213 MB, from the npm registry |
153
+ | Next measures | nothing to install |
154
+
155
+ In CI, set `SENTINEL_CACHE_DIR` to a folder and cache it with `actions/cache`, with the sentinel version as the key, so each version downloads once.
156
+
157
+ ## Reading the comment
158
+
159
+ The title says what happened: ✅ nothing degraded, ❌ a degradation with its metric and screen, ❌ flows not proven, or ❌ a measure that did not complete. Under it come the detection (what was measured and why), then one row per screen with each metric from base to head.
160
+
161
+ **What blocks, and only that:** a metric within Google's "good" threshold at the base (LCP 2500 ms, CLS 0.1, INP 200 ms) and over it at the head, by more than this run's noise. The noise is the base measured against itself in the same run, per round (the p90 of the gaps). These are reported without blocking:
162
+
163
+ - a breach already at the base;
164
+ - a breach within the noise;
165
+ - a move above the noise that stays within the threshold;
166
+ - TBT, which has no threshold of its own.
167
+
168
+ **Every figure is proven first.** Each flow must show:
169
+
170
+ - the screen opened, with its texts;
171
+ - every call answered by a mock;
172
+ - an LCP element that is neither a placeholder nor the login form;
173
+ - a second reading of the browser's own entries that agrees with Lighthouse.
174
+
175
+ A flow that fails a proof fails its screen. Its figure is not judged.
176
+
177
+ The folded sections hold the proof of every flow, the medians and the noise, the builds and settings, the time of each phase, and every flow's values.
178
+
179
+ The comment is sized to the 65,536 characters GitHub keeps of a comment: past that, GitHub cuts it mid-sentence. The headline, the detection and the verdict table always stay. Only the last folded sections drop out, and the comment names them. The full comment is then written beside it, to `runtime-analysis-report/runtime-analysis.full.md`.
180
+
181
+ ## Troubleshooting
182
+
183
+ | What you see | What it means |
184
+ | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
185
+ | `runtime-analysis.config.mjs is not valid`, with fields | Fix each named field; `--inspect --runtime-analysis` checks it in seconds. |
186
+ | `no Google Chrome found` | Install Chrome or set `CHROME_PATH`. |
187
+ | `could not install the measure's browser packages … ENOTFOUND on …` | The npm registry was unreachable. In CI, cache `SENTINEL_CACHE_DIR`. |
188
+ | A screen ❌ with `ready 200 (mocked)` failed | The `ready` call has no mock answering 200. |
189
+ | A screen ❌ with `no unhandled request` failed | The screen calls a path no `api` entry answers: add the entry. |
190
+ | `could not write the session to redis://…` | The store `session.json` names is not running. Start it (`pnpm redis:start`, or the workflow's service) and run again. |
191
+ | `this PR changes none of its screens` | The diff reaches none of the screen's route chain, its shell, its translations or the workspace's build inputs. A change the bundler erases (a type, a comment) does not count. |
192
+
193
+ ## What the role will not do
194
+
195
+ - Measure a real environment: both builds are served on the runner, with mocks, so only the code changes between base and head.
196
+ - Measure a screen that is not in the config: a screen is measured only once it is declared with its proofs.
197
+ - Block on a breach the base already had: that is reported, not blamed on the pull request.
198
+ - Follow a flat dot-notation layout (`posts.tsx` over `posts.$id.tsx`): a screen's layouts are `<dir>/route.tsx` or `<dir>.tsx`, one per folder level. A change to such a layout alone does not mark the screen. None of the measured fronts uses them.