@wildo-ai/wildo-module-client 1.1.10 → 1.1.12
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/dist/esm/index.js.map +1 -1
- package/dist/esm/services/_http-client.js.map +1 -1
- package/dist/esm/services/_zod-issue-formatting.js.map +1 -1
- package/dist/esm/services/index.js.map +1 -1
- package/dist/esm/services/lockfile-repair.service.d.ts +51 -0
- package/dist/esm/services/lockfile-repair.service.d.ts.map +1 -1
- package/dist/esm/services/lockfile-repair.service.js +95 -4
- package/dist/esm/services/lockfile-repair.service.js.map +1 -1
- package/dist/esm/services/module-adopter.service.js.map +1 -1
- package/dist/esm/services/module-packager.service.d.ts +8 -8
- package/dist/esm/services/module-packager.service.js +8 -8
- package/dist/esm/services/module-packager.service.js.map +1 -1
- package/dist/esm/services/provider-materialization-hook.js.map +1 -1
- package/dist/esm/services/provider-sync-runner.d.ts +8 -9
- package/dist/esm/services/provider-sync-runner.d.ts.map +1 -1
- package/dist/esm/services/provider-sync-runner.js +6 -7
- package/dist/esm/services/provider-sync-runner.js.map +1 -1
- package/dist/esm/services/registry-companion-client.js.map +1 -1
- package/dist/esm/services/registry-lockfile.service.js.map +1 -1
- package/dist/esm/services/registry-server-client.d.ts +23 -1
- package/dist/esm/services/registry-server-client.d.ts.map +1 -1
- package/dist/esm/services/registry-server-client.js +62 -5
- package/dist/esm/services/registry-server-client.js.map +1 -1
- package/dist/esm/services/types.d.ts.map +1 -1
- package/dist/esm/services/types.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +5 -5
- package/src/__tests__/registry-lockfile.service.test.ts +3 -2
- package/src/__tests__/registry-server-client.test.ts +126 -3
- package/src/services/lockfile-repair.service.ts +132 -3
- package/src/services/module-packager.service.ts +8 -8
- package/src/services/provider-sync-runner.ts +8 -9
- package/src/services/registry-server-client.ts +74 -3
- package/dist/tsconfig.tsbuildinfo +0 -1
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,cAAc,YAAY,CAAC","sourcesContent":["/**\n * `@wildo-ai/wildo-module-client` — runtime services for the Wildo\n * module-registry workstream (KD-3).\n *\n * Phase 0.5 surface:\n * - `RegistryServerClient` — HTTP client for the registry server.\n * - `RegistryCompanionClient` — HTTP client for the dev companion.\n * - `RegistryLockfileService` — section-scoped `sections.modules`\n * reader/writer.\n * - `runProviderMaterializationHook` — post-mutation no-op hook\n * that delegates to `wildo config sync --domain config`.\n *\n * Phase 1+ adds `ModulePackagerService`, `ModuleAdopterService`,\n * `LockfileRepairService`, and the real (locked + atomic) lockfile\n * mutation surface.\n */\n\nexport * from './services';\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_http-client.js","sourceRoot":"","sources":["../../../../src/services/_http-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAEpH,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAElC;;;;GAIG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AAExD,MAAM,UAAU,OAAO,CAAC,IAAY,EAAE,IAAY;IAChD,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC;IAC5D,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,UAAU,EAAE,CAAC;AACnD,CAAC;AAQD,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,GAAW,EACX,OAA6B,E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ACzB,MAAM,IAAI,KAAK,CAAC,UAAU,CAAC;QAC7B,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IACF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AAC/B,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,GAAW,EACX,OAA6B,EAAE;IAE/B,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC9C,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CACb,GAAG,IAAI,CAAC,eAAe,IAAI,MAAM,sBAAsB,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,UAAU,QAAQ,GAAG,EAAE,CACjG,CAAC;IACJ,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Internal HTTP client utilities shared by `RegistryServerClient`\n * and `RegistryCompanionClient`.\n *\n * Both clients want the same primitives:\n * - `joinUrl(base, path)` — single-source-of-truth path joiner\n * that tolerates leading/trailing slashes;\n * - `fetchWithTimeout(url, init)` — one budget for a metadata\n * exchange; an abort becomes a typed `RegistryRequestTimeoutError`;\n * - `readJsonBody(...)` — reads that exchange's JSON body, typing a\n * body cut short by the same budget as a `READING_BODY` timeout;\n * - `fetchTransfer(url, init)` — an artifact download: a response\n * budget plus an idle budget between body chunks (#1763);\n * - `fetchJsonOk(...)` — convenience for liveness probes that\n * want a boolean answer.\n *\n * The leading underscore signals \"package-internal\" — these are\n * intentionally NOT re-exported from `services/index.ts`. Phase 2\n * services that need fancier HTTP (multipart upload, streaming\n * download) extend this file rather than copy the primitives.\n */\n\nimport { isAbortLikeError, RegistryRequestTimeoutError, RegistryTimeoutPhase } from '@wildo-ai/platform-config-lib';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/**\n * How long a DOWNLOAD may go without receiving a single byte (#1763). An idle budget, not a cap on the\n * whole body: a large artifact over a slow but moving link finishes, a stalled one fails. 30 s is the\n * order npm and cargo tolerate before calling a transfer stuck.\n */\nexport const REGISTRY_TRANSFER_IDLE_TIMEOUT_MS = 30_000;\n\nexport function joinUrl(base: string, path: string): string {\n const normalized = path.startsWith('/') ? path : `/${path}`;\n return `${base.replace(/\\/$/, '')}${normalized}`;\n}\n\nexport interface FetchWithTimeoutInit extends RequestInit {\n timeoutMs?: number;\n /** Used in the diagnostic timeout message (e.g. \"Registry\", \"Companion registry\"). */\n diagnosticLabel?: string;\n}\n\nexport async function fetchWithTimeout(\n url: string,\n init: FetchWithTimeoutInit = {},\n): Promise<Response> {\n const timeoutMs = init.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const label = init.diagnosticLabel ?? 'HTTP';\n const signal = AbortSignal.timeout(timeoutMs);\n // Strip the wrapper-only fields before forwarding to `fetch`. The\n // `_` names are conventional unused-binding markers.\n //\n // 6th-pass M1 — tsconfig premise (corrected): the wider repo's\n // `engine/tsconfig.common.json` currently sets both `noUnusedLocals`\n // and `noUnusedParameters` to `false`, so any unused binding (with\n // or without `_` prefix) compiles clean today. If either flag is\n // ever flipped to `true`, TypeScript's underscore-prefix convention\n // applies to parameters reliably and to destructured `let`/`const`\n // bindings depending on TS version + setting — so the `_` prefix\n // here is a defensive signal of \"intentional discard\" should that\n // happen. Today it's purely cosmetic.\n const { timeoutMs: _timeoutMs, diagnosticLabel: _diagnosticLabel, ...rest } = init;\n try {\n return await fetch(url, { ...rest, signal });\n } catch (err) {\n // Typed, so an `isRegistryError(err)` handler sees it (#1763). The budget spans the whole exchange,\n // which is right for a small metadata response; a body read the same signal aborts is translated by\n // the reader (see `readJsonBody`).\n if (isAbortLikeError(err)) throw new RegistryRequestTimeoutError(url, label, RegistryTimeoutPhase.AWAITING_RESPONSE, timeoutMs);\n throw err;\n }\n}\n\n/**\n * Read a small JSON body fetched through {@link fetchWithTimeout}. A read cut short by that request's\n * timeout is a TIMEOUT, never a malformed payload (it used to be reported as one).\n */\nexport async function readJsonBody(res: Response, url: string, label: string, timeoutMs: number | undefined): Promise<unknown> {\n try {\n return await res.json();\n } catch (err) {\n // The headers arrived; the body is what ran out of time (#1763 review).\n if (isAbortLikeError(err)) throw new RegistryRequestTimeoutError(url, label, RegistryTimeoutPhase.READING_BODY, timeoutMs ?? DEFAULT_TIMEOUT_MS);\n throw err;\n }\n}\n\nexport interface TransferInit extends FetchWithTimeoutInit {\n /** No-bytes budget for the body (default {@link REGISTRY_TRANSFER_IDLE_TIMEOUT_MS}). */\n idleTimeoutMs?: number;\n}\n\n/**\n * Fetch for a TRANSFER — an artifact download (#1763). Two budgets, because a metadata timeout cannot\n * be sized for a body of unknown length:\n * - `timeoutMs` bounds the wait for the RESPONSE (status + headers);\n * - `idleTimeoutMs` bounds the silence between body chunks, reset on every chunk.\n * Both aborts surface as `RegistryRequestTimeoutError`, with the phase that fired.\n */\nexport async function fetchTransfer(url: string, init: TransferInit = {}): Promise<{ response: Response; readAll: () => Promise<Uint8Array> }> {\n const timeoutMs = init.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const idleTimeoutMs = init.idleTimeoutMs ?? REGISTRY_TRANSFER_IDLE_TIMEOUT_MS;\n const label = init.diagnosticLabel ?? 'HTTP';\n const { timeoutMs: _t, idleTimeoutMs: _i, diagnosticLabel: _d, ...rest } = init;\n const controller = new AbortController();\n let phase = RegistryTimeoutPhase.AWAITING_RESPONSE;\n let timer = setTimeout(() => controller.abort(), timeoutMs);\n const timeoutError = () =>\n new RegistryRequestTimeoutError(url, label, phase, phase === RegistryTimeoutPhase.AWAITING_RESPONSE ? timeoutMs : idleTimeoutMs);\n let response: Response;\n try {\n response = await fetch(url, { ...rest, signal: controller.signal });\n } catch (err) {\n clearTimeout(timer);\n if (isAbortLikeError(err)) throw timeoutError();\n throw err;\n }\n clearTimeout(timer);\n const readAll = async (): Promise<Uint8Array> => {\n phase = RegistryTimeoutPhase.TRANSFER_STALLED;\n const chunks: Uint8Array[] = [];\n let total = 0;\n const reader = response.body?.getReader();\n if (!reader) return new Uint8Array(0);\n const arm = () => {\n clearTimeout(timer);\n timer = setTimeout(() => controller.abort(), idleTimeoutMs);\n };\n arm();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n total += value.byteLength;\n arm();\n }\n } catch (err) {\n if (isAbortLikeError(err) || controller.signal.aborted) throw timeoutError();\n throw err;\n } finally {\n clearTimeout(timer);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n };\n return { response, readAll };\n}\n\n/**\n * Throws on non-2xx; returns the Response otherwise.\n *\n * C-L2 (4th-pass review) waiver: this helper deliberately throws\n * bare `Error` and is NOT part of the typed `RegistryError`\n * vocabulary. It exists for liveness probes (`ping()`) that wrap\n * the call in their own try/catch and convert any thrown exception\n * to `false`. Future callers MUST do the same — if a caller wants\n * to surface a typed error to the user, they should not use\n * `fetchJsonOk` and should call `fetchWithTimeout` directly +\n * inspect `res.ok` themselves to throw the right\n * `RegistryUnexpectedStatusError` / `RegistryAuthRequiredError` /\n * etc. variant.\n *\n * @internal — internal lib helper, not re-exported from the\n * package root.\n */\nexport async function fetchJsonOk(\n url: string,\n init: FetchWithTimeoutInit = {},\n): Promise<Response> {\n const res = await fetchWithTimeout(url, init);\n if (!res.ok) {\n throw new Error(\n `${init.diagnosticLabel ?? 'HTTP'} request rejected (${res.status} ${res.statusText}) at ${url}`,\n );\n }\n return res;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"_http-client.js","sourceRoot":"","sources":["../../../src/services/_http-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAEpH,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAElC;;;;GAIG;AACH,MA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C,GAAG,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,OAAO;gBAAE,MAAM,YAAY,EAAE,CAAC;YAC7E,MAAM,GAAG,CAAC;QACZ,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;QACD,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;QACpC,IAAI,MAAM,GAAG,CAAC,CAAC;QACf,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YAC3B,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,UAAU,CAAC;QAC7B,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IACF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AAC/B,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,GAAW,EACX,OAA6B,EAAE;IAE/B,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC9C,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CACb,GAAG,IAAI,CAAC,eAAe,IAAI,MAAM,sBAAsB,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,UAAU,QAAQ,GAAG,EAAE,CACjG,CAAC;IACJ,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Internal HTTP client utilities shared by `RegistryServerClient`\n * and `RegistryCompanionClient`.\n *\n * Both clients want the same primitives:\n * - `joinUrl(base, path)` — single-source-of-truth path joiner\n * that tolerates leading/trailing slashes;\n * - `fetchWithTimeout(url, init)` — one budget for a metadata\n * exchange; an abort becomes a typed `RegistryRequestTimeoutError`;\n * - `readJsonBody(...)` — reads that exchange's JSON body, typing a\n * body cut short by the same budget as a `READING_BODY` timeout;\n * - `fetchTransfer(url, init)` — an artifact download: a response\n * budget plus an idle budget between body chunks (#1763);\n * - `fetchJsonOk(...)` — convenience for liveness probes that\n * want a boolean answer.\n *\n * The leading underscore signals \"package-internal\" — these are\n * intentionally NOT re-exported from `services/index.ts`. Phase 2\n * services that need fancier HTTP (multipart upload, streaming\n * download) extend this file rather than copy the primitives.\n */\n\nimport { isAbortLikeError, RegistryRequestTimeoutError, RegistryTimeoutPhase } from '@wildo-ai/platform-config-lib';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/**\n * How long a DOWNLOAD may go without receiving a single byte (#1763). An idle budget, not a cap on the\n * whole body: a large artifact over a slow but moving link finishes, a stalled one fails. 30 s is the\n * order npm and cargo tolerate before calling a transfer stuck.\n */\nexport const REGISTRY_TRANSFER_IDLE_TIMEOUT_MS = 30_000;\n\nexport function joinUrl(base: string, path: string): string {\n const normalized = path.startsWith('/') ? path : `/${path}`;\n return `${base.replace(/\\/$/, '')}${normalized}`;\n}\n\nexport interface FetchWithTimeoutInit extends RequestInit {\n timeoutMs?: number;\n /** Used in the diagnostic timeout message (e.g. \"Registry\", \"Companion registry\"). */\n diagnosticLabel?: string;\n}\n\nexport async function fetchWithTimeout(\n url: string,\n init: FetchWithTimeoutInit = {},\n): Promise<Response> {\n const timeoutMs = init.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const label = init.diagnosticLabel ?? 'HTTP';\n const signal = AbortSignal.timeout(timeoutMs);\n // Strip the wrapper-only fields before forwarding to `fetch`. The\n // `_` names are conventional unused-binding markers.\n //\n // 6th-pass M1 — tsconfig premise (corrected): the wider repo's\n // `engine/tsconfig.common.json` currently sets both `noUnusedLocals`\n // and `noUnusedParameters` to `false`, so any unused binding (with\n // or without `_` prefix) compiles clean today. If either flag is\n // ever flipped to `true`, TypeScript's underscore-prefix convention\n // applies to parameters reliably and to destructured `let`/`const`\n // bindings depending on TS version + setting — so the `_` prefix\n // here is a defensive signal of \"intentional discard\" should that\n // happen. Today it's purely cosmetic.\n const { timeoutMs: _timeoutMs, diagnosticLabel: _diagnosticLabel, ...rest } = init;\n try {\n return await fetch(url, { ...rest, signal });\n } catch (err) {\n // Typed, so an `isRegistryError(err)` handler sees it (#1763). The budget spans the whole exchange,\n // which is right for a small metadata response; a body read the same signal aborts is translated by\n // the reader (see `readJsonBody`).\n if (isAbortLikeError(err)) throw new RegistryRequestTimeoutError(url, label, RegistryTimeoutPhase.AWAITING_RESPONSE, timeoutMs);\n throw err;\n }\n}\n\n/**\n * Read a small JSON body fetched through {@link fetchWithTimeout}. A read cut short by that request's\n * timeout is a TIMEOUT, never a malformed payload (it used to be reported as one).\n */\nexport async function readJsonBody(res: Response, url: string, label: string, timeoutMs: number | undefined): Promise<unknown> {\n try {\n return await res.json();\n } catch (err) {\n // The headers arrived; the body is what ran out of time (#1763 review).\n if (isAbortLikeError(err)) throw new RegistryRequestTimeoutError(url, label, RegistryTimeoutPhase.READING_BODY, timeoutMs ?? DEFAULT_TIMEOUT_MS);\n throw err;\n }\n}\n\nexport interface TransferInit extends FetchWithTimeoutInit {\n /** No-bytes budget for the body (default {@link REGISTRY_TRANSFER_IDLE_TIMEOUT_MS}). */\n idleTimeoutMs?: number;\n}\n\n/**\n * Fetch for a TRANSFER — an artifact download (#1763). Two budgets, because a metadata timeout cannot\n * be sized for a body of unknown length:\n * - `timeoutMs` bounds the wait for the RESPONSE (status + headers);\n * - `idleTimeoutMs` bounds the silence between body chunks, reset on every chunk.\n * Both aborts surface as `RegistryRequestTimeoutError`, with the phase that fired.\n */\nexport async function fetchTransfer(url: string, init: TransferInit = {}): Promise<{ response: Response; readAll: () => Promise<Uint8Array> }> {\n const timeoutMs = init.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const idleTimeoutMs = init.idleTimeoutMs ?? REGISTRY_TRANSFER_IDLE_TIMEOUT_MS;\n const label = init.diagnosticLabel ?? 'HTTP';\n const { timeoutMs: _t, idleTimeoutMs: _i, diagnosticLabel: _d, ...rest } = init;\n const controller = new AbortController();\n let phase = RegistryTimeoutPhase.AWAITING_RESPONSE;\n let timer = setTimeout(() => controller.abort(), timeoutMs);\n const timeoutError = () =>\n new RegistryRequestTimeoutError(url, label, phase, phase === RegistryTimeoutPhase.AWAITING_RESPONSE ? timeoutMs : idleTimeoutMs);\n let response: Response;\n try {\n response = await fetch(url, { ...rest, signal: controller.signal });\n } catch (err) {\n clearTimeout(timer);\n if (isAbortLikeError(err)) throw timeoutError();\n throw err;\n }\n clearTimeout(timer);\n const readAll = async (): Promise<Uint8Array> => {\n phase = RegistryTimeoutPhase.TRANSFER_STALLED;\n const chunks: Uint8Array[] = [];\n let total = 0;\n const reader = response.body?.getReader();\n if (!reader) return new Uint8Array(0);\n const arm = () => {\n clearTimeout(timer);\n timer = setTimeout(() => controller.abort(), idleTimeoutMs);\n };\n arm();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n total += value.byteLength;\n arm();\n }\n } catch (err) {\n if (isAbortLikeError(err) || controller.signal.aborted) throw timeoutError();\n throw err;\n } finally {\n clearTimeout(timer);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n };\n return { response, readAll };\n}\n\n/**\n * Throws on non-2xx; returns the Response otherwise.\n *\n * C-L2 (4th-pass review) waiver: this helper deliberately throws\n * bare `Error` and is NOT part of the typed `RegistryError`\n * vocabulary. It exists for liveness probes (`ping()`) that wrap\n * the call in their own try/catch and convert any thrown exception\n * to `false`. Future callers MUST do the same — if a caller wants\n * to surface a typed error to the user, they should not use\n * `fetchJsonOk` and should call `fetchWithTimeout` directly +\n * inspect `res.ok` themselves to throw the right\n * `RegistryUnexpectedStatusError` / `RegistryAuthRequiredError` /\n * etc. variant.\n *\n * @internal — internal lib helper, not re-exported from the\n * package root.\n */\nexport async function fetchJsonOk(\n url: string,\n init: FetchWithTimeoutInit = {},\n): Promise<Response> {\n const res = await fetchWithTimeout(url, init);\n if (!res.ok) {\n throw new Error(\n `${init.diagnosticLabel ?? 'HTTP'} request rejected (${res.status} ${res.statusText}) at ${url}`,\n );\n }\n return res;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_zod-issue-formatting.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"_zod-issue-formatting.js","sourceRoot":"","sources":["../../../src/services/_zod-issue-formatting.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,0EAA0E;AAC1E,MAAM,qBAAqB,GAAG,QAAQ,CAAC;AAEvC,oEAAoE;AACpE,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAE7B;;;;;;;;GAQG;AACH,MAAM,UAAU,2BAA2B,CAAC,KAAe;IACzD,MAAM,QAAQ,GAAG,KAAK,CAAC,MAAM;SAC1B,KAAK,CAAC,CAAC,EAAE,kBAAkB,CAAC;SAC5B,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,qBAAqB,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IACxF,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,kBAAkB,CAAC;IACzD,IAAI,OAAO,GAAG,CAAC;QAAE,QAAQ,CAAC,IAAI,CAAC,KAAK,OAAO,QAAQ,CAAC,CAAC;IACrD,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import type { ZodError } from 'zod';\n\n/**\n * Package-internal mirror of `summarizeZodIssues` from `@wildo-ai/saas-models`,\n * which is the canonical authority every other Wildo surface delegates to.\n *\n * zod-issue-formatter-mirror: engine/saas-models/src/errors/zod-issue-formatting.shared.utils.ts\n *\n * Why a mirror rather than an import: this package declares exactly ONE\n * workspace dependency (`@wildo-ai/platform-config-lib`) plus a `zod` peer.\n * Importing `saas-models` would pull its decorator-bound schema tree into a\n * lean registry client to save a handful of lines — a bad trade. The boundary\n * is the reason for the duplication; keep the RENDERING identical, and mirror\n * any change to the canonical helper's path / root-label / overflow semantics\n * here.\n *\n * The marker above is not decoration — `pnpm check:zod-issue-formatter-mirror`\n * discovers this file by it and fails if the constants below drift from the\n * canonical source it names. If the dependency constraint that justifies this\n * mirror ever stops holding, delete the file and import the canonical formatter\n * rather than keeping a mirror nobody needs.\n *\n * Within this package this is the single source: `registry-server-client.ts`\n * and `lockfile-repair.service.ts` both call it instead of re-inlining the\n * `.slice(0, 5).map(...).join('; ')` chain.\n */\n\n/** Label for an issue whose `path` is empty — the value itself failed. */\nconst ROOT_ISSUE_PATH_LABEL = '<root>';\n\n/** Issue cap; a malformed payload can fail on hundreds of paths. */\nconst ISSUE_RENDER_LIMIT = 5;\n\n/**\n * Render a `ZodError` as one operator-readable line —\n * `path: message; path: message; …` — bounded at {@link ISSUE_RENDER_LIMIT}\n * with an explicit `(+N more)` so truncation is never silent.\n *\n * Used as the `detail` on `RegistryMalformedPayloadError` and on lockfile\n * repair findings. The raw `error.message` in Zod 4 is the JSON-stringified\n * issues array — verbose, multi-line, and unreadable in CLI / SIEM output.\n */\nexport function formatZodIssuesAsSingleLine(error: ZodError): string {\n const rendered = error.issues\n .slice(0, ISSUE_RENDER_LIMIT)\n .map((issue) => `${issue.path.join('.') || ROOT_ISSUE_PATH_LABEL}: ${issue.message}`);\n const omitted = error.issues.length - ISSUE_RENDER_LIMIT;\n if (omitted > 0) rendered.push(`(+${omitted} more)`);\n return rendered.join('; ');\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/services/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,0BAA0B,CAAC;AACzC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,wBAAwB,CAAC;AACvC,cAAc,iCAAiC,CAAC;AAChD,cAAc,2BAA2B,CAAC;AAC1C,cAAc,0BAA0B,CAAC;AACzC,cAAc,2BAA2B,CAAC","sourcesContent":["export * from './types';\nexport * from './registry-server-client';\nexport * from './registry-companion-client';\nexport * from './registry-lockfile.service';\nexport * from './provider-sync-runner';\nexport * from './provider-materialization-hook';\nexport * from './module-packager.service';\nexport * from './module-adopter.service';\nexport * from './lockfile-repair.service';\n"]}
|
|
@@ -15,6 +15,26 @@
|
|
|
15
15
|
* read path; this service only owns module diagnostics.
|
|
16
16
|
*/
|
|
17
17
|
import { type RegistryModulesLockEntry } from '@wildo-ai/platform-config-lib';
|
|
18
|
+
/**
|
|
19
|
+
* Why a provider module's install-script name cannot simply be written back into the application's
|
|
20
|
+
* `onlyBuiltDependencies` (#2809). Each is the application's own policy, which the install (#2801) also refuses to
|
|
21
|
+
* override, and pnpm reads it as follows (measured on 10.6.4 in #2801 and #2808, and again on 10.34.9 in #3014: a
|
|
22
|
+
* `package.json` list still replaces the workspace file's, and both lists together still refuse the install).
|
|
23
|
+
*
|
|
24
|
+
* A third member, `workspace-allow-list` (an allow-list kept in `pnpm-workspace.yaml`, which a `package.json` list would
|
|
25
|
+
* replace), was RETIRED by #2808: the install and the repair now write the workspace file, so that list is the one
|
|
26
|
+
* they extend.
|
|
27
|
+
*/
|
|
28
|
+
export declare enum ApplicationInstallScriptPolicy {
|
|
29
|
+
/** A `neverBuiltDependencies` list names the package, and pnpm refuses to install with both lists. */
|
|
30
|
+
NEVER_BUILT_LIST = "never-built-list",
|
|
31
|
+
/**
|
|
32
|
+
* The application declares an allow-list AND a `neverBuiltDependencies` list (in either file): pnpm (10.6.4 and 10.34.9) refuses to
|
|
33
|
+
* install at all (`ERR_PNPM_CONFIG_CONFLICT_BUILT_DEPENDENCIES`, measured in #2809's review), so writing a name changes
|
|
34
|
+
* nothing until the application keeps one of them.
|
|
35
|
+
*/
|
|
36
|
+
CONFLICTING_LISTS = "conflicting-lists"
|
|
37
|
+
}
|
|
18
38
|
export type LockfileRepairFinding = {
|
|
19
39
|
severity: 'error';
|
|
20
40
|
kind: 'envelope-malformed';
|
|
@@ -30,6 +50,37 @@ export type LockfileRepairFinding = {
|
|
|
30
50
|
kind: 'module-file-missing';
|
|
31
51
|
moduleId: string;
|
|
32
52
|
filePath: string;
|
|
53
|
+
} | {
|
|
54
|
+
/** A vendor pin the module's recorded wiring wrote (#2789) is gone from the application's overrides: restorable. */
|
|
55
|
+
severity: 'warn';
|
|
56
|
+
kind: 'vendor-pin-missing';
|
|
57
|
+
moduleId: string;
|
|
58
|
+
name: string;
|
|
59
|
+
version: string;
|
|
60
|
+
} | {
|
|
61
|
+
/** A recorded vendor pin the application moved since install: its decision, reported and never overwritten. */
|
|
62
|
+
severity: 'warn';
|
|
63
|
+
kind: 'vendor-pin-moved';
|
|
64
|
+
moduleId: string;
|
|
65
|
+
name: string;
|
|
66
|
+
version: string;
|
|
67
|
+
found: string;
|
|
68
|
+
} | {
|
|
69
|
+
/**
|
|
70
|
+
* An install-script name the module's recorded wiring wrote (#2801), not held by the application, that the
|
|
71
|
+
* application's allow-list no longer carries: restorable into `onlyBuiltDependencies` in `pnpm-workspace.yaml`.
|
|
72
|
+
*/
|
|
73
|
+
severity: 'warn';
|
|
74
|
+
kind: 'only-built-missing';
|
|
75
|
+
moduleId: string;
|
|
76
|
+
name: string;
|
|
77
|
+
} | {
|
|
78
|
+
/** A recorded install-script name the application's own policy does not allow, and `--fix` must not write: reported only. */
|
|
79
|
+
severity: 'warn';
|
|
80
|
+
kind: 'only-built-blocked';
|
|
81
|
+
moduleId: string;
|
|
82
|
+
name: string;
|
|
83
|
+
policy: ApplicationInstallScriptPolicy;
|
|
33
84
|
};
|
|
34
85
|
export interface LockfileRepairReport {
|
|
35
86
|
/** Absolute path the report covers. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lockfile-repair.service.d.ts","sourceRoot":"","sources":["../../../src/services/lockfile-repair.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAMH,OAAO,
|
|
1
|
+
{"version":3,"file":"lockfile-repair.service.d.ts","sourceRoot":"","sources":["../../../src/services/lockfile-repair.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAMH,OAAO,EAKL,KAAK,wBAAwB,EAE9B,MAAM,+BAA+B,CAAC;AAEvC;;;;;;;;;GASG;AACH,oBAAY,8BAA8B;IACxC,sGAAsG;IACtG,gBAAgB,qBAAqB;IACrC;;;;OAIG;IACH,iBAAiB,sBAAsB;CACxC;AAeD,MAAM,MAAM,qBAAqB,GAC7B;IACE,QAAQ,EAAE,OAAO,CAAC;IAClB,IAAI,EAAE,oBAAoB,CAAC;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GACD;IACE,QAAQ,EAAE,OAAO,CAAC;IAClB,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GACD;IACE,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,qBAAqB,CAAC;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB,GACD;IACE,oHAAoH;IACpH,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,oBAAoB,CAAC;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB,GACD;IACE,+GAA+G;IAC/G,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,kBAAkB,CAAC;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;CACf,GACD;IACE;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,oBAAoB,CAAC;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd,GACD;IACE,6HAA6H;IAC7H,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,oBAAoB,CAAC;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,8BAA8B,CAAC;CACxC,CAAC;AAEN,MAAM,WAAW,oBAAoB;IACnC,uCAAuC;IACvC,YAAY,EAAE,MAAM,CAAC;IACrB,4DAA4D;IAC5D,EAAE,EAAE,OAAO,CAAC;IACZ,QAAQ,EAAE,SAAS,qBAAqB,EAAE,CAAC;CAC5C;AA6ED,eAAO,MAAM,qBAAqB;IAChC,iDAAiD;iCAC/B,MAAM,KAAG,MAAM;IAIjC;;OAEG;iCACqB,MAAM,KAAG,OAAO,CAAC,oBAAoB,CAAC;IAkF9D;;OAEG;8CAES,MAAM,YACN,MAAM,SACT,wBAAwB,YACrB,qBAAqB,EAAE,KAChC,OAAO,CAAC,IAAI,CAAC;CAaR,CAAC"}
|
|
@@ -18,16 +18,38 @@ import { promises as fs } from 'node:fs';
|
|
|
18
18
|
import * as path from 'node:path';
|
|
19
19
|
import { z } from 'zod';
|
|
20
20
|
import { formatZodIssuesAsSingleLine } from './_zod-issue-formatting.js';
|
|
21
|
-
import { RegistryModulesLockSectionSchema, getWildoSaasLockPath, } from '@wildo-ai/platform-config-lib';
|
|
21
|
+
import { readApplicationPnpmSettings, RegistryModulesLockSectionSchema, getWildoSaasLockPath, withoutRetiredLockfileEnvelopeKeys, } from '@wildo-ai/platform-config-lib';
|
|
22
|
+
/**
|
|
23
|
+
* Why a provider module's install-script name cannot simply be written back into the application's
|
|
24
|
+
* `onlyBuiltDependencies` (#2809). Each is the application's own policy, which the install (#2801) also refuses to
|
|
25
|
+
* override, and pnpm reads it as follows (measured on 10.6.4 in #2801 and #2808, and again on 10.34.9 in #3014: a
|
|
26
|
+
* `package.json` list still replaces the workspace file's, and both lists together still refuse the install).
|
|
27
|
+
*
|
|
28
|
+
* A third member, `workspace-allow-list` (an allow-list kept in `pnpm-workspace.yaml`, which a `package.json` list would
|
|
29
|
+
* replace), was RETIRED by #2808: the install and the repair now write the workspace file, so that list is the one
|
|
30
|
+
* they extend.
|
|
31
|
+
*/
|
|
32
|
+
export var ApplicationInstallScriptPolicy;
|
|
33
|
+
(function (ApplicationInstallScriptPolicy) {
|
|
34
|
+
/** A `neverBuiltDependencies` list names the package, and pnpm refuses to install with both lists. */
|
|
35
|
+
ApplicationInstallScriptPolicy["NEVER_BUILT_LIST"] = "never-built-list";
|
|
36
|
+
/**
|
|
37
|
+
* The application declares an allow-list AND a `neverBuiltDependencies` list (in either file): pnpm (10.6.4 and 10.34.9) refuses to
|
|
38
|
+
* install at all (`ERR_PNPM_CONFIG_CONFLICT_BUILT_DEPENDENCIES`, measured in #2809's review), so writing a name changes
|
|
39
|
+
* nothing until the application keeps one of them.
|
|
40
|
+
*/
|
|
41
|
+
ApplicationInstallScriptPolicy["CONFLICTING_LISTS"] = "conflicting-lists";
|
|
42
|
+
})(ApplicationInstallScriptPolicy || (ApplicationInstallScriptPolicy = {}));
|
|
22
43
|
/**
|
|
23
44
|
* Permissive envelope schema used by repair only — it accepts any
|
|
24
45
|
* `sections.*` payload without delegating to per-section schemas
|
|
25
46
|
* so the repair flow can isolate "envelope is malformed" from
|
|
26
|
-
* "envelope is fine but modules section is malformed".
|
|
47
|
+
* "envelope is fine but modules section is malformed". Applied after
|
|
48
|
+
* `withoutRetiredLockfileEnvelopeKeys`, like every lockfile reader, so a
|
|
49
|
+
* file written before the envelope lost its `generatedAt` still parses.
|
|
27
50
|
*/
|
|
28
51
|
const RelaxedEnvelopeSchema = z.strictObject({
|
|
29
52
|
schemaVersion: z.literal(2),
|
|
30
|
-
generatedAt: z.iso.datetime({ offset: true }),
|
|
31
53
|
sections: z.record(z.string(), z.unknown()),
|
|
32
54
|
});
|
|
33
55
|
async function fileExists(absPath) {
|
|
@@ -39,6 +61,71 @@ async function fileExists(absPath) {
|
|
|
39
61
|
return false;
|
|
40
62
|
}
|
|
41
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* The application's effective pnpm settings (#2808), as pnpm 10 reads them: `pnpm-workspace.yaml`, or `package.json` →
|
|
66
|
+
* `pnpm` for a setting an older application still keeps there. A file the helper cannot read faithfully THROWS
|
|
67
|
+
* (`PnpmSettingsFormatError`, naming the line): reading it as empty would report every recorded pin as missing, and a
|
|
68
|
+
* `--fix` would then write into a file it cannot read.
|
|
69
|
+
*/
|
|
70
|
+
function readEffectivePnpmSettings(saasRoot) {
|
|
71
|
+
return readApplicationPnpmSettings(saasRoot);
|
|
72
|
+
}
|
|
73
|
+
function asRecord(value) {
|
|
74
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
75
|
+
}
|
|
76
|
+
function asNames(value) {
|
|
77
|
+
return Array.isArray(value) ? value.filter((name) => typeof name === 'string') : undefined;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Each install-script name a provider module's recorded wiring WROTE (#2801; a held name is the application's own), judged
|
|
81
|
+
* as pnpm 10 (10.6.4 through 10.34.9, #3014) will judge it against the application's EFFECTIVE policy (#2808: wherever pnpm reads it), with the same
|
|
82
|
+
* precedence the install uses (`onlyBuiltStates` in `wildo-cli`):
|
|
83
|
+
* - an allow-list AND a `neverBuiltDependencies` list → pnpm installs nothing, so a name the allow-list lacks is blocked
|
|
84
|
+
* by `CONFLICTING_LISTS` and never written;
|
|
85
|
+
* - an allow-list → a name it lacks is `only-built-missing`, restorable into `pnpm-workspace.yaml`;
|
|
86
|
+
* - otherwise a `neverBuiltDependencies` list → a name it lists is blocked by `NEVER_BUILT_LIST`; any other name's
|
|
87
|
+
* script runs, so nothing is reported;
|
|
88
|
+
* - otherwise no policy at all → pnpm runs no script, and the name is `only-built-missing`: restoring it writes the list
|
|
89
|
+
* the install wrote.
|
|
90
|
+
*/
|
|
91
|
+
function collectOnlyBuiltFindings(moduleId, entry, settings, findings) {
|
|
92
|
+
const wiring = entry.registration?.providerWiring;
|
|
93
|
+
const held = new Set(wiring?.heldOnlyBuiltDependencies ?? []);
|
|
94
|
+
const wrote = (wiring?.onlyBuiltDependencies ?? []).filter((name) => !held.has(name));
|
|
95
|
+
if (wrote.length === 0)
|
|
96
|
+
return;
|
|
97
|
+
const allowList = asNames(settings.onlyBuiltDependencies);
|
|
98
|
+
const never = asNames(settings.neverBuiltDependencies);
|
|
99
|
+
for (const name of wrote) {
|
|
100
|
+
if (allowList !== undefined && never !== undefined) {
|
|
101
|
+
if (!allowList.includes(name))
|
|
102
|
+
findings.push({ severity: 'warn', kind: 'only-built-blocked', moduleId, name, policy: ApplicationInstallScriptPolicy.CONFLICTING_LISTS });
|
|
103
|
+
}
|
|
104
|
+
else if (allowList !== undefined) {
|
|
105
|
+
if (!allowList.includes(name))
|
|
106
|
+
findings.push({ severity: 'warn', kind: 'only-built-missing', moduleId, name });
|
|
107
|
+
}
|
|
108
|
+
else if (never !== undefined) {
|
|
109
|
+
if (never.includes(name))
|
|
110
|
+
findings.push({ severity: 'warn', kind: 'only-built-blocked', moduleId, name, policy: ApplicationInstallScriptPolicy.NEVER_BUILT_LIST });
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
findings.push({ severity: 'warn', kind: 'only-built-missing', moduleId, name });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Each vendor pin a provider module's recorded wiring wrote (#2789), against the root overrides: missing (restorable by
|
|
119
|
+
* `--fix`), or moved by the application (reported only: a pin the application set is its own).
|
|
120
|
+
*/
|
|
121
|
+
function collectVendorPinFindings(moduleId, entry, overrides, findings) {
|
|
122
|
+
for (const [name, version] of Object.entries(entry.registration?.providerWiring?.vendorPins ?? {})) {
|
|
123
|
+
if (!Object.hasOwn(overrides, name))
|
|
124
|
+
findings.push({ severity: 'warn', kind: 'vendor-pin-missing', moduleId, name, version });
|
|
125
|
+
else if (overrides[name] !== version)
|
|
126
|
+
findings.push({ severity: 'warn', kind: 'vendor-pin-moved', moduleId, name, version, found: String(overrides[name]) });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
42
129
|
export const LockfileRepairService = {
|
|
43
130
|
/** Compute the lockfile path for a saas root. */
|
|
44
131
|
pathFor(saasRoot) {
|
|
@@ -86,7 +173,7 @@ export const LockfileRepairService = {
|
|
|
86
173
|
});
|
|
87
174
|
return { lockfilePath, ok: false, findings };
|
|
88
175
|
}
|
|
89
|
-
const envelopeParsed = RelaxedEnvelopeSchema.safeParse(parsedJson);
|
|
176
|
+
const envelopeParsed = RelaxedEnvelopeSchema.safeParse(withoutRetiredLockfileEnvelopeKeys(parsedJson));
|
|
90
177
|
if (!envelopeParsed.success) {
|
|
91
178
|
findings.push({
|
|
92
179
|
severity: 'error',
|
|
@@ -113,8 +200,12 @@ export const LockfileRepairService = {
|
|
|
113
200
|
return { lockfilePath, ok: false, findings };
|
|
114
201
|
}
|
|
115
202
|
const modules = parsed.data;
|
|
203
|
+
const pnpmSettings = readEffectivePnpmSettings(saasRoot);
|
|
204
|
+
const rootOverrides = asRecord(pnpmSettings.overrides);
|
|
116
205
|
for (const [moduleId, entry] of Object.entries(modules.installed)) {
|
|
117
206
|
await this.collectEntryFindings(saasRoot, moduleId, entry, findings);
|
|
207
|
+
collectVendorPinFindings(moduleId, entry, rootOverrides, findings);
|
|
208
|
+
collectOnlyBuiltFindings(moduleId, entry, pnpmSettings, findings);
|
|
118
209
|
}
|
|
119
210
|
const ok = findings.every((f) => f.severity !== 'error');
|
|
120
211
|
return { lockfilePath, ok, findings };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lockfile-repair.service.js","sourceRoot":"","sources":["../../../../src/services/lockfile-repair.service.ts"],"names":[],"mappings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AED,MAAM,EAAE,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC;QACzD,OAAO,EAAE,YAAY,EAAE,EAAE,EAAE,QAAQ,EAAE,CAAC;IACxC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,oBAAoB,CACxB,QAAgB,EAChB,QAAgB,EAChB,KAA+B,EAC/B,QAAiC;QAEjC,KAAK,MAAM,QAAQ,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YACnC,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;YAC7C,IAAI,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;gBAC7B,QAAQ,CAAC,IAAI,CAAC;oBACZ,QAAQ,EAAE,MAAM;oBAChB,IAAI,EAAE,qBAAqB;oBAC3B,QAAQ;oBACR,QAAQ;iBACT,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;CACO,CAAC;AAEX,qEAAqE;AACrE,kEAAkE;AAClE,mEAAmE","sourcesContent":["/**\n * `LockfileRepairService` — read-only lockfile diagnostics.\n *\n * Backs `wildo registry repair-lockfile`. Strict envelope and module-section\n * validation runs before file inspection. Malformed records, including invalid\n * artifact digests, require restoration from a trusted record; they are never\n * admitted into the automatic repair path. Valid records can report missing\n * source files, which the CLI can re-fetch at their recorded exact version.\n * This inspector does not mutate files.\n *\n * `i18n` validation is intentionally NOT performed here (KD-15 +\n * Review-pass-2 / MEDIUM-5): repair is the wrong place to\n * second-guess companion-owned section semantics. The shared\n * lockfile library STILL validates i18n on the companion-owned\n * read path; this service only owns module diagnostics.\n */\n\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { formatZodIssuesAsSingleLine } from './_zod-issue-formatting';\nimport {\n RegistryModulesLockSectionSchema,\n getWildoSaasLockPath,\n type RegistryModulesLockEntry,\n type RegistryModulesLockSection,\n} from '@wildo-ai/platform-config-lib';\n\n/**\n * Permissive envelope schema used by repair only — it accepts any\n * `sections.*` payload without delegating to per-section schemas\n * so the repair flow can isolate \"envelope is malformed\" from\n * \"envelope is fine but modules section is malformed\".\n */\nconst RelaxedEnvelopeSchema = z.strictObject({\n schemaVersion: z.literal(2),\n generatedAt: z.iso.datetime({ offset: true }),\n sections: z.record(z.string(), z.unknown()),\n});\n\nexport type LockfileRepairFinding =\n | {\n severity: 'error';\n kind: 'envelope-malformed';\n message: string;\n detail?: string;\n }\n | {\n severity: 'error';\n kind: 'modules-section-malformed';\n message: string;\n detail?: string;\n }\n | {\n severity: 'warn';\n kind: 'module-file-missing';\n moduleId: string;\n filePath: string;\n };\n\nexport interface LockfileRepairReport {\n /** Absolute path the report covers. */\n lockfilePath: string;\n /** True when no errors were produced (warnings allowed). */\n ok: boolean;\n findings: readonly LockfileRepairFinding[];\n}\n\nasync function fileExists(absPath: string): Promise<boolean> {\n try {\n await fs.access(absPath);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const LockfileRepairService = {\n /** Compute the lockfile path for a saas root. */\n pathFor(saasRoot: string): string {\n return getWildoSaasLockPath(saasRoot);\n },\n\n /**\n * Read the envelope + run every diagnostic. Read-only.\n */\n async inspect(saasRoot: string): Promise<LockfileRepairReport> {\n const lockfilePath = getWildoSaasLockPath(saasRoot);\n const findings: LockfileRepairFinding[] = [];\n\n // Read raw bytes ourselves so we can produce per-section\n // diagnostics: a malformed `modules` section under an\n // otherwise-valid envelope should report `modules-section-malformed`,\n // NOT `envelope-malformed` (the latter would tell the operator\n // to re-author the whole file when only one section is bad).\n let raw: string;\n try {\n raw = await fs.readFile(lockfilePath, 'utf8');\n } catch (err: unknown) {\n const errno = (err as NodeJS.ErrnoException)?.code;\n if (errno === 'ENOENT') {\n // Missing lockfile is \"ok\" from a repair POV.\n return { lockfilePath, ok: true, findings: [] };\n }\n findings.push({\n severity: 'error',\n kind: 'envelope-malformed',\n message: 'Failed to read lockfile bytes.',\n detail: err instanceof Error ? err.message : String(err),\n });\n return { lockfilePath, ok: false, findings };\n }\n\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(raw);\n } catch (err) {\n findings.push({\n severity: 'error',\n kind: 'envelope-malformed',\n message: 'Lockfile is not valid JSON.',\n detail: err instanceof Error ? err.message : String(err),\n });\n return { lockfilePath, ok: false, findings };\n }\n\n const envelopeParsed = RelaxedEnvelopeSchema.safeParse(parsedJson);\n if (!envelopeParsed.success) {\n findings.push({\n severity: 'error',\n kind: 'envelope-malformed',\n message: 'Top-level envelope failed to parse.',\n detail: formatZodIssuesAsSingleLine(envelopeParsed.error),\n });\n return { lockfilePath, ok: false, findings };\n }\n const envelope = envelopeParsed.data;\n\n const modulesPayload = envelope.sections.modules;\n if (modulesPayload === undefined) {\n // No modules section present — nothing to inspect.\n return { lockfilePath, ok: true, findings };\n }\n\n const parsed = RegistryModulesLockSectionSchema.safeParse(modulesPayload);\n if (!parsed.success) {\n findings.push({\n severity: 'error',\n kind: 'modules-section-malformed',\n message: '`sections.modules` failed schema validation. Restore the affected record from a trusted lockfile revision; automatic repair does not infer missing or invalid metadata.',\n detail: formatZodIssuesAsSingleLine(parsed.error),\n });\n return { lockfilePath, ok: false, findings };\n }\n const modules: RegistryModulesLockSection = parsed.data;\n\n for (const [moduleId, entry] of Object.entries(modules.installed)) {\n await this.collectEntryFindings(saasRoot, moduleId, entry, findings);\n }\n\n const ok = findings.every((f) => f.severity !== 'error');\n return { lockfilePath, ok, findings };\n },\n\n /**\n * Missing-file diagnostics for an entry already validated by the strict section schema.\n */\n async collectEntryFindings(\n saasRoot: string,\n moduleId: string,\n entry: RegistryModulesLockEntry,\n findings: LockfileRepairFinding[],\n ): Promise<void> {\n for (const filePath of entry.files) {\n const abs = path.resolve(saasRoot, filePath);\n if (!(await fileExists(abs))) {\n findings.push({\n severity: 'warn',\n kind: 'module-file-missing',\n moduleId,\n filePath,\n });\n }\n }\n },\n} as const;\n\n// L6 (third-pass review): re-export removed — barrel-discipline rule\n// says \"Never re-export except in the root `index.ts`.\" Consumers\n// import the symbol directly from `@wildo-ai/platform-config-lib`.\n"]}
|
|
1
|
+
{"version":3,"file":"lockfile-repair.service.js","sourceRoot":"","sources":["../../../src/services/lockfile-repair.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AACtE,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,EAChC,oBAAoB,EACpB,kCAAkC,GAGnC,MAAM,+BAA+B,CAAC;AAEvC;;;;;;;;;GASG;AACH,MAAM,CAAN,IAAY,8BASX;AATD,WAAY,8BAA8B;IACxC,sGAAsG;IACtG,uEAAqC,CAAA;IACrC;;;;OAIG;IACH,yEAAuC,CAAA;AACzC,CAAC,EATW,8BAA8B,KAA9B,8BAA8B,QASzC;AAED;;;;;;;GAOG;AACH,MAAM,qBAAqB,GAAG,CAAC,CAAC,YAAY,CAAC;IAC3C,aAAa,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;IAC3B,QAAQ,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;CAC5C,CAAC,CAAC;AAiEH,KAAK,UAAU,UAAU,CAAC,OAAe;IACvC,IAAI,CAAC;QACH,MAAM,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,SAAS,yBAAyB,CAAC,Q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E,EAAE,QAAQ,EAAE,CAAC;IACxC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,oBAAoB,CACxB,QAAgB,EAChB,QAAgB,EAChB,KAA+B,EAC/B,QAAiC;QAEjC,KAAK,MAAM,QAAQ,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YACnC,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;YAC7C,IAAI,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;gBAC7B,QAAQ,CAAC,IAAI,CAAC;oBACZ,QAAQ,EAAE,MAAM;oBAChB,IAAI,EAAE,qBAAqB;oBAC3B,QAAQ;oBACR,QAAQ;iBACT,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;CACO,CAAC;AAEX,qEAAqE;AACrE,kEAAkE;AAClE,mEAAmE","sourcesContent":["/**\n * `LockfileRepairService` — read-only lockfile diagnostics.\n *\n * Backs `wildo registry repair-lockfile`. Strict envelope and module-section\n * validation runs before file inspection. Malformed records, including invalid\n * artifact digests, require restoration from a trusted record; they are never\n * admitted into the automatic repair path. Valid records can report missing\n * source files, which the CLI can re-fetch at their recorded exact version.\n * This inspector does not mutate files.\n *\n * `i18n` validation is intentionally NOT performed here (KD-15 +\n * Review-pass-2 / MEDIUM-5): repair is the wrong place to\n * second-guess companion-owned section semantics. The shared\n * lockfile library STILL validates i18n on the companion-owned\n * read path; this service only owns module diagnostics.\n */\n\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport { z } from 'zod';\nimport { formatZodIssuesAsSingleLine } from './_zod-issue-formatting';\nimport {\n readApplicationPnpmSettings,\n RegistryModulesLockSectionSchema,\n getWildoSaasLockPath,\n withoutRetiredLockfileEnvelopeKeys,\n type RegistryModulesLockEntry,\n type RegistryModulesLockSection,\n} from '@wildo-ai/platform-config-lib';\n\n/**\n * Why a provider module's install-script name cannot simply be written back into the application's\n * `onlyBuiltDependencies` (#2809). Each is the application's own policy, which the install (#2801) also refuses to\n * override, and pnpm reads it as follows (measured on 10.6.4 in #2801 and #2808, and again on 10.34.9 in #3014: a\n * `package.json` list still replaces the workspace file's, and both lists together still refuse the install).\n *\n * A third member, `workspace-allow-list` (an allow-list kept in `pnpm-workspace.yaml`, which a `package.json` list would\n * replace), was RETIRED by #2808: the install and the repair now write the workspace file, so that list is the one\n * they extend.\n */\nexport enum ApplicationInstallScriptPolicy {\n /** A `neverBuiltDependencies` list names the package, and pnpm refuses to install with both lists. */\n NEVER_BUILT_LIST = 'never-built-list',\n /**\n * The application declares an allow-list AND a `neverBuiltDependencies` list (in either file): pnpm (10.6.4 and 10.34.9) refuses to\n * install at all (`ERR_PNPM_CONFIG_CONFLICT_BUILT_DEPENDENCIES`, measured in #2809's review), so writing a name changes\n * nothing until the application keeps one of them.\n */\n CONFLICTING_LISTS = 'conflicting-lists',\n}\n\n/**\n * Permissive envelope schema used by repair only — it accepts any\n * `sections.*` payload without delegating to per-section schemas\n * so the repair flow can isolate \"envelope is malformed\" from\n * \"envelope is fine but modules section is malformed\". Applied after\n * `withoutRetiredLockfileEnvelopeKeys`, like every lockfile reader, so a\n * file written before the envelope lost its `generatedAt` still parses.\n */\nconst RelaxedEnvelopeSchema = z.strictObject({\n schemaVersion: z.literal(2),\n sections: z.record(z.string(), z.unknown()),\n});\n\nexport type LockfileRepairFinding =\n | {\n severity: 'error';\n kind: 'envelope-malformed';\n message: string;\n detail?: string;\n }\n | {\n severity: 'error';\n kind: 'modules-section-malformed';\n message: string;\n detail?: string;\n }\n | {\n severity: 'warn';\n kind: 'module-file-missing';\n moduleId: string;\n filePath: string;\n }\n | {\n /** A vendor pin the module's recorded wiring wrote (#2789) is gone from the application's overrides: restorable. */\n severity: 'warn';\n kind: 'vendor-pin-missing';\n moduleId: string;\n name: string;\n version: string;\n }\n | {\n /** A recorded vendor pin the application moved since install: its decision, reported and never overwritten. */\n severity: 'warn';\n kind: 'vendor-pin-moved';\n moduleId: string;\n name: string;\n version: string;\n found: string;\n }\n | {\n /**\n * An install-script name the module's recorded wiring wrote (#2801), not held by the application, that the\n * application's allow-list no longer carries: restorable into `onlyBuiltDependencies` in `pnpm-workspace.yaml`.\n */\n severity: 'warn';\n kind: 'only-built-missing';\n moduleId: string;\n name: string;\n }\n | {\n /** A recorded install-script name the application's own policy does not allow, and `--fix` must not write: reported only. */\n severity: 'warn';\n kind: 'only-built-blocked';\n moduleId: string;\n name: string;\n policy: ApplicationInstallScriptPolicy;\n };\n\nexport interface LockfileRepairReport {\n /** Absolute path the report covers. */\n lockfilePath: string;\n /** True when no errors were produced (warnings allowed). */\n ok: boolean;\n findings: readonly LockfileRepairFinding[];\n}\n\nasync function fileExists(absPath: string): Promise<boolean> {\n try {\n await fs.access(absPath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * The application's effective pnpm settings (#2808), as pnpm 10 reads them: `pnpm-workspace.yaml`, or `package.json` →\n * `pnpm` for a setting an older application still keeps there. A file the helper cannot read faithfully THROWS\n * (`PnpmSettingsFormatError`, naming the line): reading it as empty would report every recorded pin as missing, and a\n * `--fix` would then write into a file it cannot read.\n */\nfunction readEffectivePnpmSettings(saasRoot: string): { overrides?: unknown; onlyBuiltDependencies?: unknown; neverBuiltDependencies?: unknown } {\n return readApplicationPnpmSettings(saasRoot);\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n}\n\nfunction asNames(value: unknown): string[] | undefined {\n return Array.isArray(value) ? value.filter((name): name is string => typeof name === 'string') : undefined;\n}\n\n/**\n * Each install-script name a provider module's recorded wiring WROTE (#2801; a held name is the application's own), judged\n * as pnpm 10 (10.6.4 through 10.34.9, #3014) will judge it against the application's EFFECTIVE policy (#2808: wherever pnpm reads it), with the same\n * precedence the install uses (`onlyBuiltStates` in `wildo-cli`):\n * - an allow-list AND a `neverBuiltDependencies` list → pnpm installs nothing, so a name the allow-list lacks is blocked\n * by `CONFLICTING_LISTS` and never written;\n * - an allow-list → a name it lacks is `only-built-missing`, restorable into `pnpm-workspace.yaml`;\n * - otherwise a `neverBuiltDependencies` list → a name it lists is blocked by `NEVER_BUILT_LIST`; any other name's\n * script runs, so nothing is reported;\n * - otherwise no policy at all → pnpm runs no script, and the name is `only-built-missing`: restoring it writes the list\n * the install wrote.\n */\nfunction collectOnlyBuiltFindings(\n moduleId: string,\n entry: RegistryModulesLockEntry,\n settings: { onlyBuiltDependencies?: unknown; neverBuiltDependencies?: unknown },\n findings: LockfileRepairFinding[],\n): void {\n const wiring = entry.registration?.providerWiring;\n const held = new Set(wiring?.heldOnlyBuiltDependencies ?? []);\n const wrote = (wiring?.onlyBuiltDependencies ?? []).filter((name) => !held.has(name));\n if (wrote.length === 0) return;\n const allowList = asNames(settings.onlyBuiltDependencies);\n const never = asNames(settings.neverBuiltDependencies);\n for (const name of wrote) {\n if (allowList !== undefined && never !== undefined) {\n if (!allowList.includes(name)) findings.push({ severity: 'warn', kind: 'only-built-blocked', moduleId, name, policy: ApplicationInstallScriptPolicy.CONFLICTING_LISTS });\n } else if (allowList !== undefined) {\n if (!allowList.includes(name)) findings.push({ severity: 'warn', kind: 'only-built-missing', moduleId, name });\n } else if (never !== undefined) {\n if (never.includes(name)) findings.push({ severity: 'warn', kind: 'only-built-blocked', moduleId, name, policy: ApplicationInstallScriptPolicy.NEVER_BUILT_LIST });\n } else {\n findings.push({ severity: 'warn', kind: 'only-built-missing', moduleId, name });\n }\n }\n}\n\n/**\n * Each vendor pin a provider module's recorded wiring wrote (#2789), against the root overrides: missing (restorable by\n * `--fix`), or moved by the application (reported only: a pin the application set is its own).\n */\nfunction collectVendorPinFindings(moduleId: string, entry: RegistryModulesLockEntry, overrides: Record<string, unknown>, findings: LockfileRepairFinding[]): void {\n for (const [name, version] of Object.entries(entry.registration?.providerWiring?.vendorPins ?? {})) {\n if (!Object.hasOwn(overrides, name)) findings.push({ severity: 'warn', kind: 'vendor-pin-missing', moduleId, name, version });\n else if (overrides[name] !== version) findings.push({ severity: 'warn', kind: 'vendor-pin-moved', moduleId, name, version, found: String(overrides[name]) });\n }\n}\n\nexport const LockfileRepairService = {\n /** Compute the lockfile path for a saas root. */\n pathFor(saasRoot: string): string {\n return getWildoSaasLockPath(saasRoot);\n },\n\n /**\n * Read the envelope + run every diagnostic. Read-only.\n */\n async inspect(saasRoot: string): Promise<LockfileRepairReport> {\n const lockfilePath = getWildoSaasLockPath(saasRoot);\n const findings: LockfileRepairFinding[] = [];\n\n // Read raw bytes ourselves so we can produce per-section\n // diagnostics: a malformed `modules` section under an\n // otherwise-valid envelope should report `modules-section-malformed`,\n // NOT `envelope-malformed` (the latter would tell the operator\n // to re-author the whole file when only one section is bad).\n let raw: string;\n try {\n raw = await fs.readFile(lockfilePath, 'utf8');\n } catch (err: unknown) {\n const errno = (err as NodeJS.ErrnoException)?.code;\n if (errno === 'ENOENT') {\n // Missing lockfile is \"ok\" from a repair POV.\n return { lockfilePath, ok: true, findings: [] };\n }\n findings.push({\n severity: 'error',\n kind: 'envelope-malformed',\n message: 'Failed to read lockfile bytes.',\n detail: err instanceof Error ? err.message : String(err),\n });\n return { lockfilePath, ok: false, findings };\n }\n\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(raw);\n } catch (err) {\n findings.push({\n severity: 'error',\n kind: 'envelope-malformed',\n message: 'Lockfile is not valid JSON.',\n detail: err instanceof Error ? err.message : String(err),\n });\n return { lockfilePath, ok: false, findings };\n }\n\n const envelopeParsed = RelaxedEnvelopeSchema.safeParse(withoutRetiredLockfileEnvelopeKeys(parsedJson));\n if (!envelopeParsed.success) {\n findings.push({\n severity: 'error',\n kind: 'envelope-malformed',\n message: 'Top-level envelope failed to parse.',\n detail: formatZodIssuesAsSingleLine(envelopeParsed.error),\n });\n return { lockfilePath, ok: false, findings };\n }\n const envelope = envelopeParsed.data;\n\n const modulesPayload = envelope.sections.modules;\n if (modulesPayload === undefined) {\n // No modules section present — nothing to inspect.\n return { lockfilePath, ok: true, findings };\n }\n\n const parsed = RegistryModulesLockSectionSchema.safeParse(modulesPayload);\n if (!parsed.success) {\n findings.push({\n severity: 'error',\n kind: 'modules-section-malformed',\n message: '`sections.modules` failed schema validation. Restore the affected record from a trusted lockfile revision; automatic repair does not infer missing or invalid metadata.',\n detail: formatZodIssuesAsSingleLine(parsed.error),\n });\n return { lockfilePath, ok: false, findings };\n }\n const modules: RegistryModulesLockSection = parsed.data;\n\n const pnpmSettings = readEffectivePnpmSettings(saasRoot);\n const rootOverrides = asRecord(pnpmSettings.overrides);\n for (const [moduleId, entry] of Object.entries(modules.installed)) {\n await this.collectEntryFindings(saasRoot, moduleId, entry, findings);\n collectVendorPinFindings(moduleId, entry, rootOverrides, findings);\n collectOnlyBuiltFindings(moduleId, entry, pnpmSettings, findings);\n }\n\n const ok = findings.every((f) => f.severity !== 'error');\n return { lockfilePath, ok, findings };\n },\n\n /**\n * Missing-file diagnostics for an entry already validated by the strict section schema.\n */\n async collectEntryFindings(\n saasRoot: string,\n moduleId: string,\n entry: RegistryModulesLockEntry,\n findings: LockfileRepairFinding[],\n ): Promise<void> {\n for (const filePath of entry.files) {\n const abs = path.resolve(saasRoot, filePath);\n if (!(await fileExists(abs))) {\n findings.push({\n severity: 'warn',\n kind: 'module-file-missing',\n moduleId,\n filePath,\n });\n }\n }\n },\n} as const;\n\n// L6 (third-pass review): re-export removed — barrel-discipline rule\n// says \"Never re-export except in the root `index.ts`.\" Consumers\n// import the symbol directly from `@wildo-ai/platform-config-lib`.\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module-adopter.service.js","sourceRoot":"","sources":["
|
|
1
|
+
{"version":3,"file":"module-adopter.service.js","sourceRoot":"","sources":["../../../src/services/module-adopter.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,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Q,EAAE,QAAQ,CAAC,EAAE;gBACrB,eAAe;gBACf,QAAQ;aACT,CAAC,CAAC;YACH,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;QACvC,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;IAC9B,CAAC;CACO,CAAC","sourcesContent":["/**\n * `ModuleAdopterService` — Phase 2 CLI-direct adoption flow.\n *\n * `wildo registry adopt` takes existing app code that fits the\n * Wildo module-artifact shape and prepares it for publication\n * (KD-14). Adoption is intentionally CLI-DIRECT (Review-pass-3 /\n * MEDIUM-G) — it only reads source slices and stages files. AST\n * mutations on the host app's source are NOT part of adopt; if a\n * future flow needs them, they go through the companion HTTP\n * surface like every other source-mutating verb.\n *\n * Service surface:\n * - `discoverModuleFiles(saasRoot, manifest)` — walks each\n * declared `boundaries.*` allow-list and returns the set of\n * files that exist on disk and are within the boundary.\n * - `adoptToStaging(saasRoot, manifest)` — clears + populates\n * `<saasRoot>/.wildo-saas/generated/modules-artifacts/<id>/`\n * with the manifest + every discovered file, then computes\n * the staging digest. Phase 6 plugs this into the publish\n * flow.\n */\n\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport { isModuleArtifactPathAllowed, MODULE_BOUNDARY_LAYERS, type ModuleManifest } from '@wildo-ai/platform-config-lib';\nimport { ModulePackagerService, type StagingPaths } from './module-packager.service';\n\nexport interface AdoptionPlan {\n /** Per-layer file list, relative to saas root. */\n files: readonly string[];\n /** Empty when every declared boundary contributed at least one file. */\n emptyBoundaries: readonly string[];\n}\n\nexport interface AdoptionResult {\n manifest: ModuleManifest;\n staging: StagingPaths;\n /** Files that were copied into the staging root. */\n staged: readonly string[];\n /** sha256 digest of the staged tree (matches `Sha256DigestSchema`). */\n digest: string;\n}\n\nasync function fileExists(absPath: string): Promise<boolean> {\n try {\n const stat = await fs.stat(absPath);\n return stat.isFile() || stat.isDirectory();\n } catch {\n return false;\n }\n}\n\nasync function walkBoundary(\n saasRoot: string,\n appRelative: string,\n): Promise<string[]> {\n const abs = path.resolve(saasRoot, appRelative);\n if (!(await fileExists(abs))) return [];\n const stat = await fs.stat(abs);\n if (stat.isFile()) return [appRelative];\n const out: string[] = [];\n const queue: string[] = [appRelative];\n while (queue.length > 0) {\n const cur = queue.shift()!;\n const entries = await fs.readdir(path.resolve(saasRoot, cur), { withFileTypes: true });\n for (const entry of entries) {\n const rel = path.join(cur, entry.name);\n // Skip what a module never ships, exactly as `wildo registry publish` does — otherwise the\n // packager (which refuses those paths) throws on a module's own `.env` or `node_modules`.\n if (!isModuleArtifactPathAllowed(rel.split(path.sep).join('/'))) continue;\n if (entry.isDirectory()) {\n queue.push(rel);\n } else if (entry.isFile()) {\n out.push(rel);\n }\n }\n }\n return out;\n}\n\nexport const ModuleAdopterService = {\n /**\n * Walk every declared `boundaries.*` allow-list and return the\n * files that actually exist on disk.\n */\n async discoverModuleFiles(\n saasRoot: string,\n manifest: ModuleManifest,\n ): Promise<AdoptionPlan> {\n const boundaries = manifest.boundaries;\n if (!boundaries) {\n return { files: [], emptyBoundaries: [] };\n }\n // Every layer the registry knows, not a hand-kept copy: a copy here missed `providers` (#2014).\n const layers = MODULE_BOUNDARY_LAYERS;\n const aggregate = new Set<string>();\n const empty: string[] = [];\n for (const layer of layers) {\n const allows = boundaries[layer];\n let layerCount = 0;\n for (const rel of allows) {\n const collected = await walkBoundary(saasRoot, rel);\n for (const file of collected) aggregate.add(file);\n layerCount += collected.length;\n }\n if (allows.length > 0 && layerCount === 0) empty.push(layer);\n }\n return {\n files: [...aggregate].sort(),\n emptyBoundaries: empty,\n };\n },\n\n /**\n * Stage the module from existing app source. Idempotent — calling\n * twice with the same source produces the same digest.\n */\n async adoptToStaging(\n saasRoot: string,\n manifest: ModuleManifest,\n ): Promise<AdoptionResult> {\n const plan = await this.discoverModuleFiles(saasRoot, manifest);\n const { staging, written } = await this.runAdoptionPlan(saasRoot, manifest, plan);\n const digest = await ModulePackagerService.computeStagingDigest(saasRoot, manifest.id);\n return { manifest, staging, staged: written, digest };\n },\n\n /**\n * Re-usable apply step: writes manifest + copies every file in\n * the plan. Exposed so Phase 6 publish can reuse it after a\n * separate staging-prep step.\n */\n async runAdoptionPlan(\n saasRoot: string,\n manifest: ModuleManifest,\n plan: AdoptionPlan,\n ): Promise<{ staging: StagingPaths; written: readonly string[] }> {\n const staging = await ModulePackagerService.stageFresh(saasRoot, manifest.id);\n await ModulePackagerService.writeManifest({ saasRoot, manifest });\n const written: string[] = [];\n for (const appRelativePath of plan.files) {\n const result = await ModulePackagerService.copyFile({\n saasRoot,\n moduleId: manifest.id,\n appRelativePath,\n manifest,\n });\n written.push(result.appRelativePath);\n }\n return { staging, written };\n },\n} as const;\n"]}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `ModulePackagerService` —
|
|
2
|
+
* `ModulePackagerService` — staging logic for module
|
|
3
3
|
* publishing.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
5
|
+
* Layout:
|
|
6
6
|
* - Published artifacts are zip archives staged under
|
|
7
7
|
* `<saasRoot>/.wildo-saas/generated/modules-artifacts/<module.id>/`.
|
|
8
8
|
* - The staged folder is the source of the artifact. It must
|
|
9
9
|
* include the `wildo.module.json` manifest, copied source
|
|
10
10
|
* files, and dependency declarations.
|
|
11
11
|
*
|
|
12
|
-
*
|
|
12
|
+
* This service ships the staging-folder primitives (path resolution,
|
|
13
13
|
* stage-fresh, copy-source-tree, write-manifest, compute-digest).
|
|
14
|
-
*
|
|
15
|
-
*
|
|
14
|
+
* `wildo registry publish` calls these and the zip step; install
|
|
15
|
+
* consumes the same digest.
|
|
16
16
|
*
|
|
17
17
|
* Hard contracts:
|
|
18
18
|
* - Staging is always a fresh tree per call (`stageFresh`
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* from a previous failed stage MUST NOT leak into the digest.
|
|
22
22
|
* - The staged tree is a CHILD of `<saasRoot>/.wildo-saas/`,
|
|
23
23
|
* never reaches outside `saasRoot`.
|
|
24
|
-
* - Boundary enforcement
|
|
24
|
+
* - Boundary enforcement lives in this service: the
|
|
25
25
|
* staging primitive rejects file paths that escape the
|
|
26
26
|
* declared `boundaries.<layer>` allow-list, so a publish
|
|
27
27
|
* can never claim app surface it doesn't own.
|
|
@@ -41,7 +41,7 @@ export interface StagingPaths {
|
|
|
41
41
|
export declare function getModuleStagingPaths(saasRoot: string, moduleId: string): StagingPaths;
|
|
42
42
|
/**
|
|
43
43
|
* Verify a candidate file path is contained inside one of the
|
|
44
|
-
* manifest's declared `boundaries
|
|
44
|
+
* manifest's declared `boundaries`. Returns the resolved
|
|
45
45
|
* absolute path on success; throws `RegistryBoundaryViolationError`
|
|
46
46
|
* otherwise.
|
|
47
47
|
*/
|
|
@@ -60,7 +60,7 @@ export declare const ModulePackagerService: {
|
|
|
60
60
|
/**
|
|
61
61
|
* Copy a single file from the app source into the staging tree.
|
|
62
62
|
* Path is verified against the manifest's declared boundaries
|
|
63
|
-
*
|
|
63
|
+
* — files outside `boundaries.*` are rejected with
|
|
64
64
|
* `RegistryBoundaryViolationError`. The relative path INSIDE the
|
|
65
65
|
* staging root mirrors the relative path inside the saas root,
|
|
66
66
|
* so callers don't need to translate paths between the two
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `ModulePackagerService` —
|
|
2
|
+
* `ModulePackagerService` — staging logic for module
|
|
3
3
|
* publishing.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
5
|
+
* Layout:
|
|
6
6
|
* - Published artifacts are zip archives staged under
|
|
7
7
|
* `<saasRoot>/.wildo-saas/generated/modules-artifacts/<module.id>/`.
|
|
8
8
|
* - The staged folder is the source of the artifact. It must
|
|
9
9
|
* include the `wildo.module.json` manifest, copied source
|
|
10
10
|
* files, and dependency declarations.
|
|
11
11
|
*
|
|
12
|
-
*
|
|
12
|
+
* This service ships the staging-folder primitives (path resolution,
|
|
13
13
|
* stage-fresh, copy-source-tree, write-manifest, compute-digest).
|
|
14
|
-
*
|
|
15
|
-
*
|
|
14
|
+
* `wildo registry publish` calls these and the zip step; install
|
|
15
|
+
* consumes the same digest.
|
|
16
16
|
*
|
|
17
17
|
* Hard contracts:
|
|
18
18
|
* - Staging is always a fresh tree per call (`stageFresh`
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* from a previous failed stage MUST NOT leak into the digest.
|
|
22
22
|
* - The staged tree is a CHILD of `<saasRoot>/.wildo-saas/`,
|
|
23
23
|
* never reaches outside `saasRoot`.
|
|
24
|
-
* - Boundary enforcement
|
|
24
|
+
* - Boundary enforcement lives in this service: the
|
|
25
25
|
* staging primitive rejects file paths that escape the
|
|
26
26
|
* declared `boundaries.<layer>` allow-list, so a publish
|
|
27
27
|
* can never claim app surface it doesn't own.
|
|
@@ -89,7 +89,7 @@ function isPathInside(child, parent) {
|
|
|
89
89
|
}
|
|
90
90
|
/**
|
|
91
91
|
* Verify a candidate file path is contained inside one of the
|
|
92
|
-
* manifest's declared `boundaries
|
|
92
|
+
* manifest's declared `boundaries`. Returns the resolved
|
|
93
93
|
* absolute path on success; throws `RegistryBoundaryViolationError`
|
|
94
94
|
* otherwise.
|
|
95
95
|
*/
|
|
@@ -131,7 +131,7 @@ export const ModulePackagerService = {
|
|
|
131
131
|
/**
|
|
132
132
|
* Copy a single file from the app source into the staging tree.
|
|
133
133
|
* Path is verified against the manifest's declared boundaries
|
|
134
|
-
*
|
|
134
|
+
* — files outside `boundaries.*` are rejected with
|
|
135
135
|
* `RegistryBoundaryViolationError`. The relative path INSIDE the
|
|
136
136
|
* staging root mirrors the relative path inside the saas root,
|
|
137
137
|
* so callers don't need to translate paths between the two
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module-packager.service.js","sourceRoot":"","sources":["../../../../src/services/module-packager.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,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logic for module\n * publishing.\n *\n * Per KD-8 / `module-registry-analysis.md`:\n * - Published artifacts are zip archives staged under\n * `<saasRoot>/.wildo-saas/generated/modules-artifacts/<module.id>/`.\n * - The staged folder is the source of the artifact. It must\n * include the `wildo.module.json` manifest, copied source\n * files, and dependency declarations.\n *\n * Phase 2 ships the staging-folder primitives (path resolution,\n * stage-fresh, copy-source-tree, write-manifest, compute-digest).\n * Phase 6 wires `wildo registry publish` to call these and the zip\n * step. Phase 5 install consumes the same digest.\n *\n * Hard contracts:\n * - Staging is always a fresh tree per call (`stageFresh`\n * removes the destination first). The artifact's content\n * digest is over-the-wire deterministic — leftover bytes\n * from a previous failed stage MUST NOT leak into the digest.\n * - The staged tree is a CHILD of `<saasRoot>/.wildo-saas/`,\n * never reaches outside `saasRoot`.\n * - Boundary enforcement (KD-12) lives in this service: the\n * staging primitive rejects file paths that escape the\n * declared `boundaries.<layer>` allow-list, so a publish\n * can never claim app surface it doesn't own.\n */\n\nimport { createHash } from 'node:crypto';\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport {\n flattenModuleBoundaries,\n isModuleArtifactPathAllowed,\n isModuleId,\n ModuleManifestSchema,\n RegistryBoundaryViolationError,\n type ModuleManifest,\n type ModuleManifestBoundaries,\n MODULE_MANIFEST_FILE_NAME as MANIFEST_FILE_NAME,\n} from '@wildo-ai/platform-config-lib';\n\nexport const MODULES_ARTIFACTS_RELATIVE_DIR = '.wildo-saas/generated/modules-artifacts';\n\nexport interface StagingPaths {\n /** Absolute path to the per-module staging root. */\n stagingRoot: string;\n /** Absolute path to the manifest file inside the staging root. */\n manifestPath: string;\n}\n\n/**\n * Resolve the per-module staging paths. Pure path arithmetic — no\n * fs side effects.\n */\nexport function getModuleStagingPaths(saasRoot: string, moduleId: string): StagingPaths {\n // The full `<scope>/<name>` shape, not merely \"contains a `/`\": `stageFresh` runs a recursive delete\n // on the path built here, and `a/../../../..` contained a slash.\n if (!isModuleId(moduleId)) {\n // C-L3 (4th-pass review): `TypeError` is Node's standard for\n // argument-shape violations. The typed `RegistryError` subclasses\n // model registry-runtime conditions (auth, integrity, version\n // not found); a malformed `moduleId` argument is a developer\n // contract violation that downstream `isRegistryError(err)`\n // handlers should NOT catch. `TypeError` keeps the error visible\n // and stops the typed-error vocabulary from absorbing pure\n // argument-validation concerns.\n throw new TypeError(\n `Module id \"${moduleId}\" must be in <scope>/<name> form (e.g. \"acme/billing\"), each half lowercase letters, digits, \".\", \"_\" or \"-\".`,\n );\n }\n const artifactsRoot = path.resolve(saasRoot, MODULES_ARTIFACTS_RELATIVE_DIR);\n const stagingRoot = path.resolve(artifactsRoot, moduleId);\n if (!isPathInside(stagingRoot, artifactsRoot) || stagingRoot === artifactsRoot) {\n throw new TypeError(`Module id \"${moduleId}\" resolves outside ${MODULES_ARTIFACTS_RELATIVE_DIR}.`);\n }\n return {\n stagingRoot,\n manifestPath: path.join(stagingRoot, MANIFEST_FILE_NAME),\n };\n}\n\n/**\n * Returns `true` iff `child` is the same path as `parent` or\n * a descendant of it. Both arguments are expected to be absolute,\n * already resolved (no `..` segments). Tail-`/` arithmetic prevents\n * the classic `/foo/barx` → `/foo/bar` false-positive.\n *\n * Extracted as a helper (5th-pass C-L2) so the boundary check below\n * and the future zip-slip / symlink-escape guards in this package\n * share one reading of the containment rule.\n *\n * 6th-pass C-L1 — root edge case: when `parent` is the filesystem\n * root (`/` on POSIX, `C:\\` on Windows), appending `path.sep` would\n * produce `//` or `C:\\\\` and `startsWith` would reject every child.\n * Treat the root as a special case: any absolute child path is\n * \"inside\" the root by definition. Vanishingly unlikely in practice\n * (containerized SaaS roots are not literally `/`) but the helper\n * is also reusable for zip-slip guards where the assumption is\n * weaker.\n */\nfunction isPathInside(child: string, parent: string): boolean {\n // Special-case the filesystem root: any absolute child is inside it.\n if (parent === path.sep || /^[a-zA-Z]:[\\\\/]?$/.test(parent)) {\n return path.isAbsolute(child);\n }\n const childWithSep = child + path.sep;\n const parentWithSep = parent + path.sep;\n return childWithSep.startsWith(parentWithSep);\n}\n\n/**\n * Verify a candidate file path is contained inside one of the\n * manifest's declared `boundaries` (KD-12). Returns the resolved\n * absolute path on success; throws `RegistryBoundaryViolationError`\n * otherwise.\n */\nexport function assertWithinBoundaries(\n saasRoot: string,\n moduleId: string,\n appRelativePath: string,\n boundaries: ModuleManifestBoundaries | undefined,\n): string {\n const absolute = path.resolve(saasRoot, appRelativePath);\n // Path must stay inside saasRoot (no `..` escapes), and be a path a module artifact may carry at\n // all — no dot-segment (`.env`, `.git`), no `node_modules` — whatever the boundaries say.\n if (!isPathInside(absolute, path.resolve(saasRoot)) || !isModuleArtifactPathAllowed(appRelativePath.split(path.sep).join('/'))) {\n throw new RegistryBoundaryViolationError(moduleId, appRelativePath);\n }\n // No declared boundary means the module may write NOWHERE. This used to return early and admit\n // every path in the application — the fail-open reading of an absent declaration.\n const allowed: readonly string[] = flattenModuleBoundaries(boundaries);\n // The candidate must be inside at least one declared boundary.\n const isInside = allowed.some((rel) => isPathInside(absolute, path.resolve(saasRoot, rel)));\n if (!isInside) {\n throw new RegistryBoundaryViolationError(moduleId, appRelativePath);\n }\n return absolute;\n}\n\nexport const ModulePackagerService = {\n /**\n * Compute the per-module staging paths.\n */\n paths(saasRoot: string, moduleId: string): StagingPaths {\n return getModuleStagingPaths(saasRoot, moduleId);\n },\n\n /**\n * Remove and recreate the staging root. The freshness guarantee\n * is critical for digest determinism — `stageFresh` is the only\n * way to enter the per-module staging root.\n */\n async stageFresh(saasRoot: string, moduleId: string): Promise<StagingPaths> {\n const paths = getModuleStagingPaths(saasRoot, moduleId);\n await fs.rm(paths.stagingRoot, { recursive: true, force: true });\n await fs.mkdir(paths.stagingRoot, { recursive: true });\n return paths;\n },\n\n /**\n * Copy a single file from the app source into the staging tree.\n * Path is verified against the manifest's declared boundaries\n * (KD-12) — files outside `boundaries.*` are rejected with\n * `RegistryBoundaryViolationError`. The relative path INSIDE the\n * staging root mirrors the relative path inside the saas root,\n * so callers don't need to translate paths between the two\n * trees.\n */\n async copyFile(args: {\n saasRoot: string;\n moduleId: string;\n appRelativePath: string;\n manifest: ModuleManifest;\n }): Promise<{ stagedAbsolute: string; appRelativePath: string }> {\n const { saasRoot, moduleId, appRelativePath, manifest } = args;\n const sourceAbsolute = assertWithinBoundaries(\n saasRoot,\n moduleId,\n appRelativePath,\n manifest.boundaries,\n );\n const { stagingRoot } = getModuleStagingPaths(saasRoot, moduleId);\n const destAbsolute = path.join(stagingRoot, appRelativePath);\n await fs.mkdir(path.dirname(destAbsolute), { recursive: true });\n await fs.copyFile(sourceAbsolute, destAbsolute);\n return { stagedAbsolute: destAbsolute, appRelativePath };\n },\n\n /**\n * Validate the manifest, then write `wildo.module.json` into the\n * staging root. Manifest authors who pass a typo-laden object\n * get a Zod parse error here, before any zip work.\n */\n async writeManifest(args: {\n saasRoot: string;\n manifest: ModuleManifest;\n }): Promise<{ manifestPath: string; manifest: ModuleManifest }> {\n const validated = ModuleManifestSchema.parse(args.manifest);\n const { manifestPath, stagingRoot } = getModuleStagingPaths(args.saasRoot, validated.id);\n await fs.mkdir(stagingRoot, { recursive: true });\n await fs.writeFile(manifestPath, JSON.stringify(validated, null, 2) + '\\n', 'utf8');\n return { manifestPath, manifest: validated };\n },\n\n /**\n * Compute the sha256 digest of every file in the staging tree, in\n * stable lexicographic path order. Returns the canonical\n * `sha256:<64-hex>` form.\n *\n * The digest is over-the-wire deterministic for the same set of\n * staged files because:\n * 1. File order is sorted lexicographically (no fs traversal\n * randomness leaks in).\n * 2. The path prefix is the relative-from-staging-root path\n * (no absolute-path noise).\n * 3. We append the file content bytes verbatim.\n */\n async computeStagingDigest(saasRoot: string, moduleId: string): Promise<string> {\n const { stagingRoot } = getModuleStagingPaths(saasRoot, moduleId);\n const files = await collectFilesRelative(stagingRoot, '');\n // Normalize separators to POSIX before sorting + hashing — the\n // digest must reproduce across platforms for the same staged\n // tree, so the bytes fed into the hash cannot depend on the\n // publisher's OS path-separator convention.\n const normalized = files.map((f) => f.split(path.sep).join(path.posix.sep));\n normalized.sort();\n const hash = createHash('sha256');\n for (const rel of normalized) {\n const abs = path.join(stagingRoot, rel.split(path.posix.sep).join(path.sep));\n hash.update(rel);\n hash.update('\\0');\n hash.update(await fs.readFile(abs));\n hash.update('\\0');\n }\n return `sha256:${hash.digest('hex')}`;\n },\n} as const;\n\nasync function collectFilesRelative(rootAbs: string, prefix: string): Promise<string[]> {\n const here = path.join(rootAbs, prefix);\n const entries = await fs.readdir(here, { withFileTypes: true });\n const out: string[] = [];\n for (const entry of entries) {\n const rel = path.join(prefix, entry.name);\n if (entry.isDirectory()) {\n out.push(...(await collectFilesRelative(rootAbs, rel)));\n } else if (entry.isFile()) {\n out.push(rel);\n }\n }\n return out;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"module-packager.service.js","sourceRoot":"","sources":["../../../src/services/module-packager.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EACL,uBAAuB,EACvB,2BAA2B,EAC3B,UAAU,EACV,oBAAoB,EACpB,8BAA8B,EAG9B,yBAAyB,IAAI,kBAAkB,GAChD,MAAM,+BAA+B,CAAC;AAEvC,MAAM,CAAC,MAAM,8BAA8B,GAAG,yCAAyC,CAAC;AASxF;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,QAAgB,EAAE,QAAgB;IACtE,qGAAqG;IACrG,iEAAiE;IACjE,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1B,6DAA6D;QAC7D,kEAAkE;QAClE,8DAA8D;QAC9D,6DAA6D;QAC7D,4DAA4D;QAC5D,iEAAiE;QACjE,2DAA2D;QAC3D,gCAAgC;QAChC,MAAM,IAAI,SAAS,CACjB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AO,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;IAChE,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QAC1C,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;YACxB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,oBAAoB,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;QAC1D,CAAC;aAAM,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;YAC1B,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAChB,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * `ModulePackagerService` — staging logic for module\n * publishing.\n *\n * Layout:\n * - Published artifacts are zip archives staged under\n * `<saasRoot>/.wildo-saas/generated/modules-artifacts/<module.id>/`.\n * - The staged folder is the source of the artifact. It must\n * include the `wildo.module.json` manifest, copied source\n * files, and dependency declarations.\n *\n * This service ships the staging-folder primitives (path resolution,\n * stage-fresh, copy-source-tree, write-manifest, compute-digest).\n * `wildo registry publish` calls these and the zip step; install\n * consumes the same digest.\n *\n * Hard contracts:\n * - Staging is always a fresh tree per call (`stageFresh`\n * removes the destination first). The artifact's content\n * digest is over-the-wire deterministic — leftover bytes\n * from a previous failed stage MUST NOT leak into the digest.\n * - The staged tree is a CHILD of `<saasRoot>/.wildo-saas/`,\n * never reaches outside `saasRoot`.\n * - Boundary enforcement lives in this service: the\n * staging primitive rejects file paths that escape the\n * declared `boundaries.<layer>` allow-list, so a publish\n * can never claim app surface it doesn't own.\n */\n\nimport { createHash } from 'node:crypto';\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport {\n flattenModuleBoundaries,\n isModuleArtifactPathAllowed,\n isModuleId,\n ModuleManifestSchema,\n RegistryBoundaryViolationError,\n type ModuleManifest,\n type ModuleManifestBoundaries,\n MODULE_MANIFEST_FILE_NAME as MANIFEST_FILE_NAME,\n} from '@wildo-ai/platform-config-lib';\n\nexport const MODULES_ARTIFACTS_RELATIVE_DIR = '.wildo-saas/generated/modules-artifacts';\n\nexport interface StagingPaths {\n /** Absolute path to the per-module staging root. */\n stagingRoot: string;\n /** Absolute path to the manifest file inside the staging root. */\n manifestPath: string;\n}\n\n/**\n * Resolve the per-module staging paths. Pure path arithmetic — no\n * fs side effects.\n */\nexport function getModuleStagingPaths(saasRoot: string, moduleId: string): StagingPaths {\n // The full `<scope>/<name>` shape, not merely \"contains a `/`\": `stageFresh` runs a recursive delete\n // on the path built here, and `a/../../../..` contained a slash.\n if (!isModuleId(moduleId)) {\n // C-L3 (4th-pass review): `TypeError` is Node's standard for\n // argument-shape violations. The typed `RegistryError` subclasses\n // model registry-runtime conditions (auth, integrity, version\n // not found); a malformed `moduleId` argument is a developer\n // contract violation that downstream `isRegistryError(err)`\n // handlers should NOT catch. `TypeError` keeps the error visible\n // and stops the typed-error vocabulary from absorbing pure\n // argument-validation concerns.\n throw new TypeError(\n `Module id \"${moduleId}\" must be in <scope>/<name> form (e.g. \"acme/billing\"), each half lowercase letters, digits, \".\", \"_\" or \"-\".`,\n );\n }\n const artifactsRoot = path.resolve(saasRoot, MODULES_ARTIFACTS_RELATIVE_DIR);\n const stagingRoot = path.resolve(artifactsRoot, moduleId);\n if (!isPathInside(stagingRoot, artifactsRoot) || stagingRoot === artifactsRoot) {\n throw new TypeError(`Module id \"${moduleId}\" resolves outside ${MODULES_ARTIFACTS_RELATIVE_DIR}.`);\n }\n return {\n stagingRoot,\n manifestPath: path.join(stagingRoot, MANIFEST_FILE_NAME),\n };\n}\n\n/**\n * Returns `true` iff `child` is the same path as `parent` or\n * a descendant of it. Both arguments are expected to be absolute,\n * already resolved (no `..` segments). Tail-`/` arithmetic prevents\n * the classic `/foo/barx` → `/foo/bar` false-positive.\n *\n * Extracted as a helper (5th-pass C-L2) so the boundary check below\n * and the future zip-slip / symlink-escape guards in this package\n * share one reading of the containment rule.\n *\n * 6th-pass C-L1 — root edge case: when `parent` is the filesystem\n * root (`/` on POSIX, `C:\\` on Windows), appending `path.sep` would\n * produce `//` or `C:\\\\` and `startsWith` would reject every child.\n * Treat the root as a special case: any absolute child path is\n * \"inside\" the root by definition. Vanishingly unlikely in practice\n * (containerized SaaS roots are not literally `/`) but the helper\n * is also reusable for zip-slip guards where the assumption is\n * weaker.\n */\nfunction isPathInside(child: string, parent: string): boolean {\n // Special-case the filesystem root: any absolute child is inside it.\n if (parent === path.sep || /^[a-zA-Z]:[\\\\/]?$/.test(parent)) {\n return path.isAbsolute(child);\n }\n const childWithSep = child + path.sep;\n const parentWithSep = parent + path.sep;\n return childWithSep.startsWith(parentWithSep);\n}\n\n/**\n * Verify a candidate file path is contained inside one of the\n * manifest's declared `boundaries`. Returns the resolved\n * absolute path on success; throws `RegistryBoundaryViolationError`\n * otherwise.\n */\nexport function assertWithinBoundaries(\n saasRoot: string,\n moduleId: string,\n appRelativePath: string,\n boundaries: ModuleManifestBoundaries | undefined,\n): string {\n const absolute = path.resolve(saasRoot, appRelativePath);\n // Path must stay inside saasRoot (no `..` escapes), and be a path a module artifact may carry at\n // all — no dot-segment (`.env`, `.git`), no `node_modules` — whatever the boundaries say.\n if (!isPathInside(absolute, path.resolve(saasRoot)) || !isModuleArtifactPathAllowed(appRelativePath.split(path.sep).join('/'))) {\n throw new RegistryBoundaryViolationError(moduleId, appRelativePath);\n }\n // No declared boundary means the module may write NOWHERE. This used to return early and admit\n // every path in the application — the fail-open reading of an absent declaration.\n const allowed: readonly string[] = flattenModuleBoundaries(boundaries);\n // The candidate must be inside at least one declared boundary.\n const isInside = allowed.some((rel) => isPathInside(absolute, path.resolve(saasRoot, rel)));\n if (!isInside) {\n throw new RegistryBoundaryViolationError(moduleId, appRelativePath);\n }\n return absolute;\n}\n\nexport const ModulePackagerService = {\n /**\n * Compute the per-module staging paths.\n */\n paths(saasRoot: string, moduleId: string): StagingPaths {\n return getModuleStagingPaths(saasRoot, moduleId);\n },\n\n /**\n * Remove and recreate the staging root. The freshness guarantee\n * is critical for digest determinism — `stageFresh` is the only\n * way to enter the per-module staging root.\n */\n async stageFresh(saasRoot: string, moduleId: string): Promise<StagingPaths> {\n const paths = getModuleStagingPaths(saasRoot, moduleId);\n await fs.rm(paths.stagingRoot, { recursive: true, force: true });\n await fs.mkdir(paths.stagingRoot, { recursive: true });\n return paths;\n },\n\n /**\n * Copy a single file from the app source into the staging tree.\n * Path is verified against the manifest's declared boundaries\n * — files outside `boundaries.*` are rejected with\n * `RegistryBoundaryViolationError`. The relative path INSIDE the\n * staging root mirrors the relative path inside the saas root,\n * so callers don't need to translate paths between the two\n * trees.\n */\n async copyFile(args: {\n saasRoot: string;\n moduleId: string;\n appRelativePath: string;\n manifest: ModuleManifest;\n }): Promise<{ stagedAbsolute: string; appRelativePath: string }> {\n const { saasRoot, moduleId, appRelativePath, manifest } = args;\n const sourceAbsolute = assertWithinBoundaries(\n saasRoot,\n moduleId,\n appRelativePath,\n manifest.boundaries,\n );\n const { stagingRoot } = getModuleStagingPaths(saasRoot, moduleId);\n const destAbsolute = path.join(stagingRoot, appRelativePath);\n await fs.mkdir(path.dirname(destAbsolute), { recursive: true });\n await fs.copyFile(sourceAbsolute, destAbsolute);\n return { stagedAbsolute: destAbsolute, appRelativePath };\n },\n\n /**\n * Validate the manifest, then write `wildo.module.json` into the\n * staging root. Manifest authors who pass a typo-laden object\n * get a Zod parse error here, before any zip work.\n */\n async writeManifest(args: {\n saasRoot: string;\n manifest: ModuleManifest;\n }): Promise<{ manifestPath: string; manifest: ModuleManifest }> {\n const validated = ModuleManifestSchema.parse(args.manifest);\n const { manifestPath, stagingRoot } = getModuleStagingPaths(args.saasRoot, validated.id);\n await fs.mkdir(stagingRoot, { recursive: true });\n await fs.writeFile(manifestPath, JSON.stringify(validated, null, 2) + '\\n', 'utf8');\n return { manifestPath, manifest: validated };\n },\n\n /**\n * Compute the sha256 digest of every file in the staging tree, in\n * stable lexicographic path order. Returns the canonical\n * `sha256:<64-hex>` form.\n *\n * The digest is over-the-wire deterministic for the same set of\n * staged files because:\n * 1. File order is sorted lexicographically (no fs traversal\n * randomness leaks in).\n * 2. The path prefix is the relative-from-staging-root path\n * (no absolute-path noise).\n * 3. We append the file content bytes verbatim.\n */\n async computeStagingDigest(saasRoot: string, moduleId: string): Promise<string> {\n const { stagingRoot } = getModuleStagingPaths(saasRoot, moduleId);\n const files = await collectFilesRelative(stagingRoot, '');\n // Normalize separators to POSIX before sorting + hashing — the\n // digest must reproduce across platforms for the same staged\n // tree, so the bytes fed into the hash cannot depend on the\n // publisher's OS path-separator convention.\n const normalized = files.map((f) => f.split(path.sep).join(path.posix.sep));\n normalized.sort();\n const hash = createHash('sha256');\n for (const rel of normalized) {\n const abs = path.join(stagingRoot, rel.split(path.posix.sep).join(path.sep));\n hash.update(rel);\n hash.update('\\0');\n hash.update(await fs.readFile(abs));\n hash.update('\\0');\n }\n return `sha256:${hash.digest('hex')}`;\n },\n} as const;\n\nasync function collectFilesRelative(rootAbs: string, prefix: string): Promise<string[]> {\n const here = path.join(rootAbs, prefix);\n const entries = await fs.readdir(here, { withFileTypes: true });\n const out: string[] = [];\n for (const entry of entries) {\n const rel = path.join(prefix, entry.name);\n if (entry.isDirectory()) {\n out.push(...(await collectFilesRelative(rootAbs, rel)));\n } else if (entry.isFile()) {\n out.push(rel);\n }\n }\n return out;\n}\n"]}
|