@ethisyscore/vite-plugin 1.16.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/contract-a/schema-validator.ts","../src/contract-a/emit.ts","../src/contract-b/rewrite-imports.ts","../src/contract-b/worker-bundle.ts","../src/platform-react/page-bundles.ts","../src/platform-react/test-helpers.ts","../src/iframeSandboxPlugin.ts","../src/index.ts"],"names":["KNOWN_PRIMITIVES","KNOWN_OPERATORS","KNOWN_RULE_KINDS","SduiNode","ReactiveRule","normalize","isAbsolute","resolve","readManifest","existsSync","readFileSync","sep","assertHostOriginRelativePath","slash","createHash","ID_REGEX","path","mkdirSync","dirname","writeFileSync","IframeSandboxPageDeclaration","AssetDigest","assertSafeRelativePath","safeMountId"],"mappings":";;;;;;;;AAgDA,IAAM,mBAAA,GAAsB,IAAI,GAAA,CAAYA,yBAAgB,CAAA;AAC5D,IAAM,kBAAA,GAAqB,IAAI,GAAA,CAAYC,wBAAe,CAAA;AAC1D,IAAM,mBAAA,GAAsB,IAAI,GAAA,CAAYC,yBAAgB,CAAA;AAO5D,SAAS,cAAc,IAAA,EAA8C;AACnE,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACrB,IAAA,OAAO,EAAA;AAAA,EACT;AACA,EAAA,OAAO,GAAA,GAAM,IAAA,CACV,GAAA,CAAI,CAAC,GAAA,KAAQ;AACZ,IAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,IAAA,OAAO,EAAE,OAAA,CAAQ,IAAA,EAAM,IAAI,CAAA,CAAE,OAAA,CAAQ,OAAO,IAAI,CAAA;AAAA,EAClD,CAAC,CAAA,CACA,IAAA,CAAK,GAAG,CAAA;AACb;AAOA,SAAS,eAAA,CACP,KACA,KAAA,EACoB;AAEpB,EAAA,IAAI,KAAA,CAAM,IAAA,KAAS,eAAA,IAAmB,KAAA,CAAM,SAAS,oBA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A,IAGA,UAAU,EAAA,EAAI;AACZ,MAAA,MAAM,YAAA,GAAeK,OAAM,EAAE,CAAA;AAC7B,MAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA;AAAA,QACpB,CAAC,MAAMA,MAAAA,CAAMN,YAAAA,CAAQ,SAAS,CAAA,CAAE,UAAU,CAAC,CAAA,KAAM;AAAA,OACnD;AACA,MAAA,IAAI,KAAA,EAAO;AACT,QAAA,OAAO,EAAA;AAAA,MACT;AAAA,IACF,CAAA;AAAA;AAAA,IAGA,KAAK,EAAA,EAAI;AACP,MAAA,MAAM,YAAA,GAAeM,OAAM,EAAE,CAAA;AAC7B,MAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA;AAAA,QACpB,CAAC,MAAMA,MAAAA,CAAMN,YAAAA,CAAQ,SAAS,CAAA,CAAE,UAAU,CAAC,CAAA,KAAM;AAAA,OACnD;AACA,MAAA,IAAI,KAAA,EAAO;AACT,QAAA,OAAO,aAAa,KAAK,CAAA;AAAA,MAC3B;AAAA,IACF;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import {\n SduiNode,\n ReactiveRule,\n KNOWN_PRIMITIVES,\n KNOWN_OPERATORS,\n KNOWN_RULE_KINDS,\n} from \"@ethisyscore/protocol\";\n\n/**\n * Minimal structural shape of a Zod parse issue. Declared locally so the\n * vite-plugin package does not need a direct `zod` peer/runtime dependency —\n * the protocol package owns Zod, we just consume parse results.\n */\ninterface ZodLikeIssue {\n readonly code: string;\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n}\n\n/**\n * A single, structured validation failure surfaced by the Contract A\n * schema validators. Carries enough context for a build-time error\n * to be actionable without the plugin author opening the host runtime.\n */\nexport interface ValidationFailure {\n /** Absolute path of the source file whose JSON failed validation. */\n filePath: string;\n /**\n * JSON-pointer (RFC 6901) into the failing JSON document, pointing at\n * the offending node. Empty string when the offender is the root.\n */\n pointer: string;\n /** The offending operator / primitive / rule-kind name, if extractable. */\n offender?: string;\n /** Human-readable message suitable for surfacing at the build CLI. */\n message: string;\n}\n\n/**\n * Result of a validation call. Discriminated on `ok` so callers can branch\n * narrowly without juggling exception flow for expected outcomes.\n */\nexport type ValidationResult =\n | { ok: true }\n | { ok: false; failures: ValidationFailure[] };\n\n// ── Internal: Zod issue → ValidationFailure ─────────────────────\n\nconst KNOWN_PRIMITIVE_SET = new Set<string>(KNOWN_PRIMITIVES);\nconst KNOWN_OPERATOR_SET = new Set<string>(KNOWN_OPERATORS);\nconst KNOWN_RULE_KIND_SET = new Set<string>(KNOWN_RULE_KINDS);\n\n/**\n * Convert a Zod path array into a JSON Pointer (RFC 6901) string.\n *\n * Numeric segments stay as array indices, string segments are escaped per RFC.\n */\nfunction toJsonPointer(path: ReadonlyArray<string | number>): string {\n if (path.length === 0) {\n return \"\";\n }\n return \"/\" + path\n .map((seg) => {\n const s = String(seg);\n return s.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n })\n .join(\"/\");\n}\n\n/**\n * Walks the original JSON value and the Zod path to extract a likely offender\n * string. For unknown SDUI primitives the offender is the rejected `type`\n * value; for unknown JsonLogic operators the offender is the offending key.\n */\nfunction extractOffender(\n doc: unknown,\n issue: ZodLikeIssue,\n): string | undefined {\n // 1. enum mismatch — the offender is the input value\n if (issue.code === \"invalid_value\" || issue.code === \"invalid_enum_value\") {\n const received = (issue as unknown as { received?: unknown }).received;\n if (typeof received === \"string\") {\n return received;\n }\n }\n\n // 2. invalid_union (the operator object), or refine refusal — walk to the path\n // and look for an object whose only key is unknown.\n let cur: unknown = doc;\n for (const seg of issue.path) {\n if (cur === null || cur === undefined) {\n break;\n }\n cur = (cur as Record<string | number, unknown>)[seg as string | number];\n }\n if (cur && typeof cur === \"object\" && !Array.isArray(cur)) {\n const keys = Object.keys(cur as object);\n if (keys.length === 1 && !KNOWN_OPERATOR_SET.has(keys[0])) {\n return keys[0];\n }\n }\n\n // 3. Fall back to last path segment (e.g. an unknown rule-kind)\n if (issue.path.length > 0) {\n const last = issue.path[issue.path.length - 1];\n if (typeof last === \"string\" && !KNOWN_RULE_KIND_SET.has(last) && !KNOWN_PRIMITIVE_SET.has(last)) {\n return last;\n }\n }\n\n return undefined;\n}\n\n/**\n * Convert a Zod parse failure into structured {@link ValidationFailure}s.\n *\n * One Zod issue → one failure, preserving order. The original JSON `doc`\n * is walked in tandem with each issue's path so the offender name (an\n * unknown primitive, operator, or rule-kind) can be lifted into the\n * failure record.\n */\nfunction zodIssuesToFailures(\n doc: unknown,\n issues: readonly ZodLikeIssue[],\n filePath: string,\n): ValidationFailure[] {\n return issues.map((issue) => {\n const pointer = toJsonPointer(issue.path);\n const offender = extractOffender(doc, issue);\n const offenderSuffix = offender ? ` (offender: '${offender}')` : \"\";\n return {\n filePath,\n pointer,\n offender,\n message: `${filePath}${pointer ? ` at ${pointer}` : \"\"}: ${issue.message}${offenderSuffix}`,\n };\n });\n}\n\n/**\n * Validate a single declarative SDUI resource against the protocol's\n * {@link SduiNode} Zod schema. The recursive schema rejects unknown\n * primitives and unknown JsonLogic operators at any depth of the tree.\n *\n * `filePath` is propagated into every emitted failure so the build CLI\n * can point the author at the exact file on disk.\n */\nexport function validateDeclarativeResource(\n doc: unknown,\n uri: string,\n filePath: string,\n): ValidationResult {\n const parsed = SduiNode.safeParse(doc);\n if (parsed.success) {\n return { ok: true };\n }\n const failures = zodIssuesToFailures(doc, parsed.error.issues, filePath);\n // Tag the URI onto every message so the build CLI shows which resource failed.\n return {\n ok: false,\n failures: failures.map((f) => ({\n ...f,\n message: `[resource ${uri}] ${f.message}`,\n })),\n };\n}\n\n/**\n * Validate a single {@link ReactiveRule} against the protocol's curated\n * JsonLogic operator subset. Used for top-level reactivity declarations\n * declared on the manifest itself (i.e. not embedded under a `bindings`\n * key on a SDUI node — those are covered by {@link validateDeclarativeResource}).\n */\nexport function validateReactiveRule(\n rule: unknown,\n filePath: string,\n): ValidationResult {\n const parsed = ReactiveRule.safeParse(rule);\n if (parsed.success) {\n return { ok: true };\n }\n return {\n ok: false,\n failures: zodIssuesToFailures(rule, parsed.error.issues, filePath),\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize } from \"node:path\";\nimport type { Plugin } from \"vite\";\n\nimport {\n validateDeclarativeResource,\n validateReactiveRule,\n type ValidationFailure,\n} from \"./schema-validator\";\n\n// ── Manifest shapes (subset) ───────────────────────────────────\n\n/**\n * Reference from the plugin manifest to an SDUI resource JSON file.\n *\n * Wave 0 convention: the manifest declares each declarative resource with\n * a stable `uri` plus a `file` path (relative to the manifest's directory)\n * pointing at the JSON document the host will serve. The static-file\n * convention lets the Vite plugin validate the tree at build time without\n * having to execute plugin runtime code.\n */\nexport interface ManifestResourceRef {\n uri: string;\n /**\n * Relative path (POSIX or platform-native) to the SDUI JSON document.\n * Must not be absolute, must not contain `..` traversal segments.\n */\n file?: string;\n}\n\n/**\n * Top-level manifest reactivity-rule declaration. Each entry pairs an\n * author-supplied identifier with a {@link import(\"@ethisyscore/protocol\").ReactiveRule}.\n *\n * Reactivity declared inline on SDUI nodes (the `bindings` property) is\n * validated by the SDUI-tree pass; this surface covers the rarer case of\n * a manifest-level rule that applies cross-resource.\n */\nexport interface ManifestReactiveRuleRef {\n id: string;\n rule: unknown;\n}\n\n/**\n * The subset of the plugin manifest the Contract A Vite plugin pass cares\n * about. The full manifest is intentionally a superset — the plugin\n * tolerates additional fields it has not been taught yet so manifests\n * built against a newer schema still load.\n */\nexport interface ContractAManifest {\n resources?: ManifestResourceRef[];\n reactiveRules?: ManifestReactiveRuleRef[];\n [key: string]: unknown;\n}\n\n// ── Options ────────────────────────────────────────────────────\n\n/**\n * Author-facing options for the Contract A Vite plugin pass.\n *\n * `root` defaults to Vite's resolved root at `configResolved` time, so the\n * common case requires no configuration. `manifestPath` defaults to the\n * `feature.manifest.json` convention emitted by the host-rendered\n * scaffolding template; pass an absolute or relative path to override.\n */\nexport interface ContractAPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json` colocated with the Vite root.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted SDUI assets. Defaults to `sdui/`. The plugin\n * always emits an `${prefix}sdui-manifest.json` index alongside the\n * validated resource JSON.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────\n\n/** Slug-encode a resource URI into a filesystem-safe asset filename. */\nfunction slugForUri(uri: string): string {\n return uri.replace(/[^a-zA-Z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n}\n\n/** Reject path traversal and absolute paths in author-supplied references. */\nfunction assertSafeRelativePath(value: string, label: string): void {\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-contract-a] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-contract-a] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n/**\n * Render a {@link ValidationFailure} list into the multi-line build-failure\n * message Vite will surface to the author.\n */\nfunction formatFailures(failures: ValidationFailure[]): string {\n const lines = failures.map((f, i) => ` ${i + 1}. ${f.message}`);\n return [\n `[@ethisyscore/vite-plugin] Contract A schema validation failed:`,\n ...lines,\n ].join(\"\\n\");\n}\n\n// ── Plugin ─────────────────────────────────────────────────────\n\ninterface EmittedResource {\n uri: string;\n fileName: string;\n}\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore Contract A\n * (`renderMode: host-rendered`) plugins.\n *\n * Reads `feature.manifest.json` (or `extension.manifest.json` via\n * `manifestPath`), validates each declared SDUI resource against the\n * protocol's `SduiNode` Zod schema, validates each manifest-level\n * reactivity rule against `ReactiveRule`, and emits the validated JSON\n * into the Rollup bundle under the configured output prefix. Validation\n * failures abort the build with a multi-line structured error that names\n * the offending operator/primitive and the source file path + JSON\n * pointer so the author can land on the offending node immediately.\n *\n * Worker-bundle emission for `renderMode: remote-runtime` is deferred to\n * Wave 1's E7.S1b — this pass deliberately does nothing for non-Contract-A\n * manifests.\n */\nexport function ethisysContractAPlugin(\n options: ContractAPluginOptions = {},\n): Plugin {\n const outputPrefix = (options.outputPrefix ?? \"sdui/\").replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let validatedResources: EmittedResource[] = [];\n // Plugin-internal cache so generateBundle can re-emit without re-reading + re-parsing.\n const resourcePayloads = new Map<string, string>();\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): ContractAManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as ContractAManifest;\n } catch (e) {\n throw new Error(\n `[@ethisyscore/vite-plugin] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n function validate(): void {\n validatedResources = [];\n resourcePayloads.clear();\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n\n const failures: ValidationFailure[] = [];\n\n // ── Resources ───────────────────────────────────────────────\n for (const ref of manifest.resources ?? []) {\n if (!ref.file) {\n // A resource without a `file` field is a dynamic / runtime-rendered\n // resource. The Vite plugin can't introspect those at build time;\n // skip them.\n continue;\n }\n assertSafeRelativePath(ref.file, \"Resource file path\");\n\n const filePath = resolve(resolvedRoot, ref.file);\n if (!existsSync(filePath)) {\n failures.push({\n filePath,\n pointer: \"\",\n message:\n `[resource ${ref.uri}] file \"${ref.file}\" referenced by the manifest does not exist on disk (resolved: ${filePath}).`,\n });\n continue;\n }\n\n const rawJson = readFileSync(filePath, \"utf-8\");\n let doc: unknown;\n try {\n doc = JSON.parse(rawJson);\n } catch (e) {\n failures.push({\n filePath,\n pointer: \"\",\n message: `[resource ${ref.uri}] failed to parse JSON: ${(e as Error).message}`,\n });\n continue;\n }\n\n const result = validateDeclarativeResource(doc, ref.uri, filePath);\n if (!result.ok) {\n failures.push(...result.failures);\n continue;\n }\n\n // Serialise canonically (validated input → emitted payload) so the\n // host always sees a byte-stable artefact regardless of source whitespace.\n const fileName = `${outputPrefix}${slugForUri(ref.uri)}.json`;\n const payload = JSON.stringify(doc);\n resourcePayloads.set(fileName, payload);\n validatedResources.push({ uri: ref.uri, fileName });\n }\n\n // ── Manifest-level reactive rules ────────────────────────────\n for (const ruleRef of manifest.reactiveRules ?? []) {\n const result = validateReactiveRule(ruleRef.rule, manifestAbsPath);\n if (!result.ok) {\n failures.push(\n ...result.failures.map((f) => ({\n ...f,\n message: `[reactiveRule ${ruleRef.id}] ${f.message}`,\n })),\n );\n }\n }\n\n if (failures.length > 0) {\n throw new Error(formatFailures(failures));\n }\n }\n\n return {\n name: \"ethisys-contract-a\",\n enforce: \"pre\",\n\n configResolved(config) {\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing a resource JSON.\n validate();\n },\n\n generateBundle() {\n if (validatedResources.length === 0) {\n return;\n }\n\n // Emit each validated resource as a static asset.\n for (const { fileName } of validatedResources) {\n const source = resourcePayloads.get(fileName);\n if (source === undefined) {\n continue;\n }\n this.emitFile({ type: \"asset\", fileName, source });\n }\n\n // Emit a compact index so the host can list contracts without\n // walking the bundle. `name` is stable per build; `resources` is\n // sorted by URI for deterministic output.\n const sorted = [...validatedResources].sort((a, b) =>\n a.uri.localeCompare(b.uri),\n );\n const index = {\n version: 1,\n resources: sorted.map(({ uri, fileName }) => ({ uri, file: fileName })),\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}sdui-manifest.json`,\n source: JSON.stringify(index),\n });\n },\n };\n}\n","// ── Contract B safe-import rewriter ────────────────────────────────\n//\n// Static ES `import` statements with bare specifiers are unresolvable inside\n// a Contract B worker realm: the worker has no `<script type=\"importmap\">`\n// surface (workers don't host scripts) and the spec's `WorkerOptions.importMap`\n// is still proposal-stage in 2026-05. The bootstrap script\n// (`WorkerBootstrapScriptProvider.cs` in the API repo) composes a frozen\n// `IMPORT_MAP` per worker and exposes a synchronous-wrapper-free helper at\n// `globalThis.__ethisysSafeImport(spec) -> Promise<Module>`.\n//\n// The build-time complement to that runtime surface lives here: every static\n// `import` whose specifier is on the closed Contract B allowlist is rewritten\n// into a top-level `await` against `__ethisysSafeImport`. Module workers\n// support top-level await; the host loads the plugin bundle via dynamic\n// `import(moduleUrl)` which awaits the bundle's top-level evaluation, so the\n// `mod.activate(port)` call site sees a fully-initialised module.\n//\n// Specifiers outside the allowlist would not survive `Rollup.external` (which\n// the Contract B config already enforces), so this rewriter never observes\n// them in practice. It still guards against the case defensively — a future\n// `external` widening should not silently emit bare specifiers the worker\n// realm cannot resolve.\n\nconst STATIC_IMPORT_RE = /^([ \\t]*)import[ \\t]+(.*?)[ \\t]*;?[ \\t]*$/gm;\n\n/**\n * Rewrite static ES `import` statements whose specifier is a bare allowlist\n * entry into a top-level `await globalThis.__ethisysSafeImport(...)` form.\n *\n * Non-bare specifiers (relative paths, http(s) URLs, data:/blob:/javascript:\n * schemes) are passed through untouched. Dynamic `import()` calls are passed\n * through untouched. Bare specifiers outside `allowlist` are passed through\n * untouched — the surrounding `external` config is the gate; this function\n * only rewrites what the build pipeline contract guarantees.\n */\nexport function rewriteSafeImports(\n code: string,\n allowlist: readonly string[],\n): string {\n const allowSet = new Set(allowlist);\n\n return code.replace(STATIC_IMPORT_RE, (match, indent: string, body: string) => {\n const rewrite = tryRewriteImport(body, allowSet);\n return rewrite === null ? match : `${indent}${rewrite}`;\n });\n}\n\nfunction convertNamedBindings(namedClause: string): string {\n // `{ A, B as Local, C }` -> `A, B: Local, C` (object-destructuring rename form)\n const inner = namedClause.slice(1, -1).trim();\n if (inner.length === 0) {\n return \"\";\n }\n const parts = inner.split(\",\").map((p) => p.trim()).filter((p) => p.length > 0);\n const converted = parts.map((part) => {\n const asMatch = part.match(/^(\\w[\\w$]*)\\s+as\\s+(\\w[\\w$]*)$/);\n return asMatch === null ? part : `${asMatch[1]}: ${asMatch[2]}`;\n });\n return converted.join(\", \");\n}\n\nfunction tryRewriteImport(body: string, allowSet: ReadonlySet<string>): string | null {\n // Side-effect: `\"Button\"` or `'Button'`\n const sideEffect = body.match(/^[\"']([^\"']+)[\"']$/);\n if (sideEffect !== null) {\n const spec = sideEffect[1];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Default + named: `React, { useState, useEffect as fx } from \"react\"`\n const defaultPlusNamed = body.match(\n /^(\\w[\\w$]*)\\s*,\\s*(\\{[^}]*\\})\\s+from\\s+[\"']([^\"']+)[\"']$/,\n );\n if (defaultPlusNamed !== null) {\n const defaultLocal = defaultPlusNamed[1];\n const namedClause = defaultPlusNamed[2];\n const spec = defaultPlusNamed[3];\n if (!allowSet.has(spec)) {\n return null;\n }\n const bindings = convertNamedBindings(namedClause);\n const inner = bindings.length === 0\n ? `default: ${defaultLocal}`\n : `default: ${defaultLocal}, ${bindings}`;\n return `const { ${inner} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Default-only: `Foo from \"Button\"`\n const defaultOnly = body.match(/^(\\w[\\w$]*)\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (defaultOnly !== null) {\n const local = defaultOnly[1];\n const spec = defaultOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `const { default: ${local} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Named only: `{ A, B as Local } from \"react\"`\n const namedOnly = body.match(/^(\\{[^}]*\\})\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (namedOnly !== null) {\n const namedClause = namedOnly[1];\n const spec = namedOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n const bindings = convertNamedBindings(namedClause);\n return `const { ${bindings} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Namespace: `* as N from \"react\"`\n const namespaceOnly = body.match(/^\\*\\s+as\\s+(\\w[\\w$]*)\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (namespaceOnly !== null) {\n const local = namespaceOnly[1];\n const spec = namespaceOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `const ${local} = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n return null;\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize, sep } from \"node:path\";\nimport { rewriteSafeImports } from \"./rewrite-imports\";\nimport type { Plugin } from \"vite\";\n\n// ── Frozen import-map allowlist (E4.S4) ────────────────────────────\n//\n// The Contract B worker realm can ONLY import these bare specifiers. The\n// runtime side (`WorkerBootstrapScriptProvider` in the API repo) enforces the\n// same allowlist by composing a frozen `IMPORT_MAP` at handshake time. The two\n// lists MUST agree — drift is caught by the `import-map-allowlist matches\n// extension-runtime CONTRACT_B_PRIMITIVES` test in `contract-b.test.ts`,\n// which imports `CONTRACT_B_PRIMITIVES` from the sibling extension-runtime\n// package and diffs it against {@link CONTRACT_B_SEMANTIC_PRIMITIVES} below.\n//\n// Plugin-supplied bare specifiers outside this list fail the build with a\n// structured error so authors get a build-time signal instead of a runtime\n// `import-map-violation` from the worker bootstrap.\n\n/**\n * Contract B semantic primitive vocabulary (the closed v1 set authored in\n * `sdk/extension-runtime/src/host/worker/component-registry.ts`). The names\n * mirror the registry exactly; a drift between the two breaks the cross-repo\n * agreement that E4.S4 locks in.\n */\nexport const CONTRACT_B_SEMANTIC_PRIMITIVES = [\n \"Button\",\n \"DataTable\",\n \"Form\",\n \"EntityPicker\",\n \"CommandBar\",\n \"Drawer\",\n \"Modal\",\n \"CanvasSurface\",\n \"WebGLSurface\",\n // Phase 1 additions (per Contract B + PlatformReact plan §Q6, frequency\n // survey of coreconnect-web Timesheets feature). Card / Tabs / Select /\n // Alert close the four most-common gaps in the v1 primitive set:\n // - Card: universal layout container, ~20 imports across surveyed pages.\n // - Tabs: settings / configuration surfaces (6 tabs in TimesheetSettings).\n // - Select: filter + form input, ~10 imports; Form's text input doesn't\n // cover dropdowns.\n // - Alert: lock/unlock warnings, validation banners, non-modal system\n // messages; Card doesn't carry severity semantics.\n \"Card\",\n \"Tabs\",\n \"Select\",\n \"Alert\",\n] as const;\n\n/**\n * Non-component import-map entries — the runtime libraries the worker is\n * permitted to resolve via bare specifiers. Authoring constraint: the plugin's\n * single ESM bundle (Contract B emits exactly one — see `worker-bundle.ts`)\n * can `import x from \"react\"` or `import { ... } from \"@ethisyscore/extension-runtime\"`\n * and nothing else off-bundle.\n */\nexport const CONTRACT_B_RUNTIME_IMPORTS = [\n \"react\",\n \"@ethisyscore/extension-runtime\",\n] as const;\n\n/**\n * Full allowlist of bare specifiers a Contract B plugin bundle may import.\n * Frozen at module load so plugins can't mutate it via a transitive dep.\n */\nexport const CONTRACT_B_IMPORT_MAP_ALLOWLIST: readonly string[] = Object.freeze([\n ...CONTRACT_B_RUNTIME_IMPORTS,\n ...CONTRACT_B_SEMANTIC_PRIMITIVES,\n]);\n\nconst ALLOWLIST_SET: ReadonlySet<string> = new Set(CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * The subset of a Contract B (`renderMode: remote-runtime`) plugin manifest\n * that this Vite pass consumes. Manifests are tolerated as a superset — extra\n * fields are ignored so newer-schema manifests still load.\n */\nexport interface ContractBManifest {\n renderMode?: string;\n /**\n * Worker bundle declaration. Required when `renderMode === \"remote-runtime\"`.\n * The `entry` is a relative path (POSIX or platform-native) from the\n * manifest's directory to the plugin's TypeScript/JavaScript entrypoint.\n *\n * Absolute paths, path-traversal, and non-host-origin URLs are rejected at\n * build time — Contract B requires the worker bundle to be a host-origin\n * asset (the import-map enforcement in E4.S4 builds on this guarantee).\n */\n worker?: {\n entry?: string;\n };\n [key: string]: unknown;\n}\n\n/**\n * Author-facing options for the Contract B Vite pass.\n */\nexport interface ContractBPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json`.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted worker assets and the worker-bundle manifest.\n * Defaults to `worker/`.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\n/** Reject path traversal, absolute paths, and remote URLs in author refs. */\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n // Remote URLs (any scheme + `://`) are forbidden — Contract B bundles must\n // be host-origin assets so the worker bootstrap's frozen import map can\n // enforce origin restrictions deterministically.\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n // Reject `data:` / `blob:` (no `//`) too — also non-host-origin.\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n/** Normalise Windows backslashes for the Rollup input table. */\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore Contract B\n * (`renderMode: remote-runtime`) plugins.\n *\n * Behaviour:\n * - For `renderMode: \"remote-runtime\"`: declares a single ESM worker entry as\n * the Rollup input table. The output is forced to `format: \"es\"` and\n * `inlineDynamicImports: true` so a Contract B plugin always ships as ONE\n * bundled module — no chunk splitting, no shared chunks, no async imports\n * spread across multiple files. This is the precondition for E4.S4's\n * frozen import map.\n * - For any other `renderMode` (including `host-rendered` and `undefined`):\n * the pass is a no-op. The Wave 0 Contract A path (`ethisysContractAPlugin`)\n * continues to apply without interference. Composition is expected — the\n * recommended template registers both plugins so a manifest can switch\n * render modes without changing its Vite config.\n *\n * The pass also emits a `worker/worker-bundle.json` companion asset listing\n * the bundled entry so the host (or downstream packaging) can inspect what\n * the build produced without re-parsing the bundle.\n *\n * Origin enforcement on the import map (path-pinned host origin, no `data:` /\n * `blob:` imports) is the responsibility of E4.S4 (worker bootstrap) — this\n * pass only blocks remote/absolute paths at the manifest layer so a malformed\n * manifest fails fast.\n */\nexport function ethisysContractBPlugin(\n options: ContractBPluginOptions = {},\n): Plugin {\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n const outputPrefix = (options.outputPrefix ?? \"worker/\")\n .replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let workerEntryAbs: string | null = null;\n let workerEntryRel: string | null = null;\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): ContractBManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as ContractBManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-contract-b] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n /**\n * Validate the manifest and resolve the worker entry's absolute path.\n * Idempotent — repeated invocations return cached state.\n */\n function validate(): void {\n workerEntryAbs = null;\n workerEntryRel = null;\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n if (manifest.renderMode !== \"remote-runtime\") {\n // Non-Contract-B manifests are not our concern.\n return;\n }\n const entry = manifest.worker?.entry;\n if (typeof entry !== \"string\" || entry.length === 0) {\n throw new Error(\n `[ethisys-contract-b] manifest declares renderMode='remote-runtime' but no worker.entry. ` +\n `Set \"worker\": { \"entry\": \"src/worker.ts\" } (relative path).`,\n );\n }\n assertHostOriginRelativePath(entry, \"Worker entry\");\n\n const absPath = resolve(resolvedRoot, entry);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-contract-b] Worker entry file \"${entry}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n workerEntryAbs = absPath;\n workerEntryRel = entry;\n }\n\n return {\n name: \"ethisys-contract-b\",\n // `pre` ordering: validation should fire before user-supplied plugins.\n enforce: \"pre\",\n\n configResolved(config) {\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n },\n\n /**\n * Declares the Rollup input table and locks the output to a single ESM\n * module. Only fires when the manifest opts in (`renderMode: remote-runtime`).\n */\n config(_config, { command }) {\n if (command !== \"build\") {\n return;\n }\n // `config` runs before `buildStart`, so we validate here too — the user\n // needs the structured error at the same lifecycle gate that fails.\n validate();\n\n if (workerEntryAbs === null) {\n return; // Non-Contract-B manifest: no-op.\n }\n\n // The allowlist runtime libraries (`react`, `@ethisyscore/extension-runtime`)\n // and the semantic primitive names are NOT bundled — they're host-served\n // and resolved by the frozen import map at worker bootstrap time. Mark\n // them as `external` so Rollup leaves the bare specifiers intact in the\n // emitted bundle (which is what `generateBundle` then inspects).\n const externalSpecifiers = new Set<string>(CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n\n return {\n build: {\n rollupOptions: {\n input: { worker: slash(workerEntryAbs) },\n external: (id: string): boolean => externalSpecifiers.has(id),\n // CRITICAL: single-file output for the worker bundle. The\n // E4.S4 frozen import map presumes ONE module entry per plugin —\n // chunk splitting or dynamic-import shards would defeat it.\n output: {\n format: \"es\",\n inlineDynamicImports: true,\n entryFileNames: `${outputPrefix}[name].js`,\n chunkFileNames: `${outputPrefix}[name]-[hash].js`,\n assetFileNames: `${outputPrefix}[name][extname]`,\n },\n },\n },\n };\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing the manifest.\n validate();\n },\n\n /**\n * Reject `data:` / `blob:` / `javascript:` URL specifiers at resolve time.\n *\n * Rollup normally externalises unknown URL schemes silently, which would\n * mean a malicious `import(\"data:text/javascript,...\")` survives the\n * build untouched and only fails at runtime (where the bootstrap script's\n * `safeImport` would catch it). We want build-time failure too — the\n * import-map contract is enforced at BOTH ends.\n */\n resolveId(source) {\n if (workerEntryAbs === null) {\n return null;\n }\n if (/^(data|blob|javascript):/i.test(source)) {\n const scheme = source.split(\":\", 1)[0];\n this.error(\n `[ethisys-contract-b] Contract B bundle imports forbidden URL scheme '${scheme}:' ` +\n `(specifier: \"${source.slice(0, 80)}${source.length > 80 ? \"...\" : \"\"}\"). ` +\n `The worker realm rejects ${scheme}: imports at runtime; the build rejects them too.`,\n );\n }\n return null;\n },\n\n /**\n * Rewrite the emitted worker chunk's static bare-specifier imports into\n * top-level `await globalThis.__ethisysSafeImport(...)` calls. This is\n * the build-time complement to the worker bootstrap's frozen IMPORT_MAP\n * (defined in CoreConnect-Api's WorkerBootstrapScriptProvider.cs). The\n * worker realm has no `<script type=\"importmap\">` surface, so static\n * bare specifiers reach the browser's native ES loader as\n * `Failed to resolve module specifier` errors at module load time.\n *\n * Returns `null` (no transform) when the manifest is not Contract B —\n * the Contract A path's emitted chunks are left untouched.\n */\n renderChunk(code: string, chunk: { type: string; fileName: string }): { code: string } | null {\n if (workerEntryAbs === null) {\n return null;\n }\n if (chunk.type !== \"chunk\") {\n return null;\n }\n const rewritten = rewriteSafeImports(code, CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n if (rewritten === code) {\n return null;\n }\n return { code: rewritten };\n },\n\n /**\n * Inspect the emitted bundle for out-of-allowlist bare specifiers and emit\n * the per-bundle `worker-bundle.import-map.json` manifest.\n *\n * Because we marked allowlist specifiers as `external` in `config`, any\n * other bare specifier that the plugin tried to import would have failed\n * Rollup's resolver upstream — but we re-check the surviving `chunk.imports`\n * here as belt-and-braces in case a future Rollup or Vite change relaxes\n * the resolver path. Defence in depth at the build layer matches the\n * defence in depth at the runtime layer (E4.S3 bootstrap).\n */\n generateBundle(_outputOptions, bundle) {\n if (workerEntryAbs === null || workerEntryRel === null) {\n return;\n }\n\n const importedSpecifiers = new Set<string>();\n const violations: string[] = [];\n\n for (const [, chunk] of Object.entries(bundle)) {\n if (chunk.type !== \"chunk\") {\n continue;\n }\n // Both static imports (`chunk.imports`) and dynamic imports\n // (`chunk.dynamicImports`) are surveyed. `inlineDynamicImports: true`\n // collapses dynamic-imported chunks INTO the host chunk, but the\n // specifiers themselves still surface here for externalised IDs.\n const candidates: string[] = [\n ...(chunk.imports ?? []),\n ...(chunk.dynamicImports ?? []),\n ];\n for (const spec of candidates) {\n // Relative / absolute paths are emitted bundle artefacts — not\n // bare specifiers, not subject to the import-map. Skip them.\n if (spec.startsWith(\".\") || spec.startsWith(\"/\") || isAbsolute(spec)) {\n continue;\n }\n // URL-scheme specifiers should have been caught in `resolveId`,\n // but a relaxed-resolver path could let one through. Reject here too.\n if (/^[a-z][a-z0-9+.-]*:/i.test(spec)) {\n violations.push(spec);\n continue;\n }\n if (!ALLOWLIST_SET.has(spec)) {\n violations.push(spec);\n continue;\n }\n importedSpecifiers.add(spec);\n }\n }\n\n if (violations.length > 0) {\n // Sort + de-dupe for deterministic error message ordering.\n const unique = [...new Set(violations)].sort();\n this.error(\n `[ethisys-contract-b] Worker bundle imports specifier(s) outside the frozen import-map ` +\n `allowlist: ${unique.map(s => `\"${s}\"`).join(\", \")}. ` +\n `Allowed bare specifiers: ${CONTRACT_B_IMPORT_MAP_ALLOWLIST.map(s => `\"${s}\"`).join(\", \")}.`,\n );\n }\n\n // Sort the resolved entries so the emitted manifest is deterministic\n // across builds — content-hashable downstream without spurious churn.\n const resolvedEntries = [...importedSpecifiers].sort();\n\n const workerBundleManifest = {\n version: 1,\n renderMode: \"remote-runtime\",\n worker: { entry: workerEntryRel },\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}worker-bundle.json`,\n source: JSON.stringify(workerBundleManifest),\n });\n\n // The import-map manifest — the host fetches this at extension activation\n // time to auto-derive the frozen `IMPORT_MAP` the worker bootstrap\n // composes. Values are `null` to signal \"host fills in canonical URL at\n // serve time\" — the manifest is the SDK's authoritative list of which\n // entries the bundle declares it consumes, not a URL table.\n const importMapManifest = {\n version: 1,\n // Authoring contract: the bundle's bare-specifier surface area, in\n // sorted order, restricted to the frozen allowlist.\n imports: Object.fromEntries(resolvedEntries.map(spec => [spec, null])),\n // Mirror the canonical allowlist so consumers diffing manifests\n // across plugin versions can see the contract the build verified\n // against without re-reading SDK source.\n allowlist: [...CONTRACT_B_IMPORT_MAP_ALLOWLIST],\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}worker-bundle.import-map.json`,\n source: JSON.stringify(importMapManifest),\n });\n },\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize, sep } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport type { Plugin } from \"vite\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * A single PlatformReact page declaration extracted from\n * `ui.platformReactPages[]` in the manifest. Aligns with the typed interface\n * defined in `ethisyscore-protocol` RFC 0003.\n *\n * - `id` is the host-side page identifier and the basename of the emitted\n * bundle (e.g. `id: \"dashboard\"` → `platform-react/dashboard.js`).\n * - `moduleSpecifier` is a host-origin relative path to the page module — the\n * plugin author's source entry that Rollup bundles.\n * - `exportName` is the named export Rollup keeps live in the bundle. The host\n * loader reads `bundle[exportName]` at mount time.\n * - `title` is an optional display label for the host's surface chrome.\n */\nexport interface PlatformReactPageDeclaration {\n id?: string;\n moduleSpecifier?: string;\n exportName?: string;\n title?: string;\n [key: string]: unknown;\n}\n\n/**\n * The subset of a manifest this pass consumes. Manifests are tolerated as a\n * superset — extra fields are ignored so newer-schema manifests still load.\n */\nexport interface PlatformReactManifest {\n type?: string;\n ui?: {\n platformReactPages?: PlatformReactPageDeclaration[];\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\n/**\n * Author-facing options for the PlatformReact Vite pass.\n */\nexport interface PlatformReactPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json`.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted page assets and the companion manifest.\n * Defaults to `platform-react/`.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nconst ID_REGEX = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i;\n\n/** Reject path traversal, absolute paths, and remote URLs in author refs. */\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n/** Normalise Windows backslashes for the Rollup input table. */\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\ninterface ResolvedPage {\n id: string;\n exportName: string;\n title: string | null;\n moduleSpecifierRel: string;\n moduleSpecifierAbs: string;\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore PlatformReact pages\n * (RFC 0003: the high-trust, host-extension tier). For each entry under\n * `ui.platformReactPages[]` in the manifest, registers a Rollup input that\n * emits an ESM bundle the host loads via `import()` at surface mount time.\n *\n * Behaviour:\n * - For each declared page: registers `{ \"platform-react/<id>\": <moduleSpecifier> }`\n * in Rollup's input table. Output is forced to `format: \"es\"` and\n * `inlineDynamicImports: true` so each page ships as ONE bundled module.\n * - Emits a `platform-react/platform-react-pages.json` companion asset listing\n * the declared pages so the host (and the `.ccpkg` packaging step) can\n * inspect what the build produced.\n * - When `ui.platformReactPages` is absent or empty: the pass is a no-op.\n * Composition is expected — the recommended template registers this pass\n * alongside Contract A / Contract B so a single Vite config covers every\n * render mode.\n *\n * Origin enforcement of the bundle URL at runtime is the host's responsibility\n * (see `PlatformReactSurfaceMount.tsx` in `coreconnect-web`). This pass only\n * blocks remote/absolute paths at the manifest layer so a malformed manifest\n * fails fast.\n */\nexport function ethisysPlatformReactPlugin(\n options: PlatformReactPluginOptions = {},\n): Plugin {\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n const outputPrefix = (options.outputPrefix ?? \"platform-react/\")\n .replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let pages: ResolvedPage[] = [];\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n // Vite hasn't called configResolved yet (or this plugin is being driven\n // outside Vite — e.g. a unit test that only invokes the validation\n // helper). Fall back to the explicit option then cwd. configResolved\n // will overwrite this with the correct Vite-resolved root when it\n // fires, before validate() is called for real.\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): PlatformReactManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as PlatformReactManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-platform-react] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n /**\n * Validate the manifest and resolve each page's absolute source path.\n * Idempotent — repeated invocations rebuild from a fresh manifest read.\n */\n function validate(): void {\n pages = [];\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n const declared = manifest.ui?.platformReactPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n return;\n }\n\n const seenIds = new Set<string>();\n\n for (let i = 0; i < declared.length; i++) {\n const decl = declared[i];\n const where = `ui.platformReactPages[${i}]`;\n\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id is required (non-empty string).`,\n );\n }\n if (!ID_REGEX.test(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id \"${decl.id}\" must match [a-z0-9_-]+ (URL-safe; case-insensitive).`,\n );\n }\n if (seenIds.has(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] Duplicate page id \"${decl.id}\".`,\n );\n }\n seenIds.add(decl.id);\n\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier is required (non-empty relative path).`,\n );\n }\n assertHostOriginRelativePath(decl.moduleSpecifier, `${where}.moduleSpecifier`);\n\n const absPath = resolve(resolvedRoot, decl.moduleSpecifier);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier \"${decl.moduleSpecifier}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n\n const exportName =\n typeof decl.exportName === \"string\" && decl.exportName.length > 0\n ? decl.exportName\n : \"default\";\n\n pages.push({\n id: decl.id,\n exportName,\n title: typeof decl.title === \"string\" && decl.title.length > 0 ? decl.title : null,\n moduleSpecifierRel: decl.moduleSpecifier,\n moduleSpecifierAbs: absPath,\n });\n }\n }\n\n let isBuild = false;\n\n return {\n name: \"ethisys-platform-react\",\n // `pre` ordering: validation should fire before user-supplied plugins.\n enforce: \"pre\",\n\n /**\n * Force ESM single-module output per page. Output options don't depend on\n * the resolved root, so they're safe to declare here — `config()` runs\n * before `configResolved()`. The Rollup input table is added later in\n * `configResolved()` once Vite has populated `resolvedRoot` correctly.\n */\n config(_config, { command }) {\n if (command !== \"build\") {\n return;\n }\n return {\n build: {\n rollupOptions: {\n // CRITICAL: single-file ESM output per page. The host loads each\n // page via `import(url)` at mount time and reads the declared\n // `exportName` from the resulting module namespace. Chunk-split\n // output would break that contract because the host has no\n // import-map surface to resolve sibling chunks.\n output: {\n format: \"es\",\n inlineDynamicImports: true,\n entryFileNames: `${outputPrefix}[name].js`,\n chunkFileNames: `${outputPrefix}[name]-[hash].js`,\n assetFileNames: `${outputPrefix}[name][extname]`,\n },\n // Auto-externalise the host-ui-externals specifier so the host's\n // module-registry rewriter resolves it to the live `@coreconnect/gogo-ui`\n // instance at runtime — Tier T remotes never ship their own Gogo copy.\n external: [\"@ethisyscore/host-ui-externals\"],\n },\n },\n };\n },\n\n /**\n * Resolve the actual root Vite is using (which may differ from\n * `process.cwd()`), validate the manifest against it, and mutate the\n * resolved config's Rollup input table so each declared page becomes a\n * build entry. Mutation in `configResolved` is the standard Vite-plugin\n * pattern for input contributions that depend on the resolved root —\n * `config()` runs too early to know the real value.\n */\n configResolved(config) {\n isBuild = config.command === \"build\";\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n if (!isBuild) {\n return;\n }\n\n validate();\n if (pages.length === 0) {\n return;\n }\n\n const input: Record<string, string> = {};\n for (const page of pages) {\n // Input key = bare page id. The `outputPrefix` is applied by\n // `entryFileNames` so the final output is `<outputPrefix><id>.js`.\n input[page.id] = slash(page.moduleSpecifierAbs);\n }\n\n // Merge into Vite's resolved rollupOptions.input. The existing value\n // may be undefined, a single entry path, an array of entries, or an\n // already-keyed object — handle all four shapes so coexistence with\n // other Vite plugins (Contract A / Contract B passes that declare\n // their own entries) is non-destructive.\n //\n // Vite's `ResolvedConfig.build` is typed `readonly` in its public\n // declarations. The runtime object is mutable — Vite plugins that\n // need to contribute Rollup inputs from `configResolved` (which\n // requires the resolved root) widely follow this mutation pattern.\n // Cast through a writable view to bypass the type-level readonly\n // check; runtime semantics are unchanged.\n const writable = config as unknown as {\n build?: {\n rollupOptions?: {\n input?: Record<string, string> | string | string[];\n };\n };\n };\n writable.build ??= {};\n writable.build.rollupOptions ??= {};\n const rollupOptions = writable.build.rollupOptions;\n const existing = rollupOptions.input;\n if (existing && typeof existing === \"object\" && !Array.isArray(existing)) {\n rollupOptions.input = { ...(existing as Record<string, string>), ...input };\n } else if (typeof existing === \"string\") {\n rollupOptions.input = { _entry: existing, ...input };\n } else if (Array.isArray(existing)) {\n const indexed: Record<string, string> = {};\n existing.forEach((entry, idx) => {\n indexed[`_entry${idx}`] = entry;\n });\n rollupOptions.input = { ...indexed, ...input };\n } else {\n rollupOptions.input = input;\n }\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing the manifest. resolvedRoot is already set by\n // configResolved at this point.\n validate();\n },\n\n /**\n * Emit the companion `platform-react-pages.json` listing every declared\n * page. The `.ccpkg` packaging step (and the host's runtime loader) read\n * this file to discover which page modules ship in the bundle without\n * having to re-parse the manifest.\n */\n generateBundle(_options, bundle) {\n if (pages.length === 0) {\n return;\n }\n\n // ── Per-asset SHA-256 digest map (WI 4858 sub-plan 3) ──────────\n // Hash EVERY emitted chunk (not just entries) so the host's verified\n // loader can check each asset against the manifest's `assetDigests`\n // before evaluation. The build forces `inlineDynamicImports: true`\n // (see `config()`), collapsing each page to a single chunk; if that is\n // ever relaxed, every emitted chunk URL MUST still be routed through the\n // host's `verifyAndLoadPlatformReactBundle` with this full map.\n const digests: Array<{ path: string; sha256: string }> = [];\n for (const chunk of Object.values(bundle ?? {})) {\n if ((chunk as { type?: string }).type !== \"chunk\") {\n continue;\n }\n // Rollup `OutputChunk` exposes `code` (string) + `fileName`. Cast\n // through unknown because the union narrows on `type`.\n const code = (chunk as unknown as { code: string }).code;\n const fileName = (chunk as unknown as { fileName: string }).fileName;\n const hash = createHash(\"sha256\").update(code, \"utf8\").digest(\"hex\");\n digests.push({ path: fileName, sha256: hash });\n }\n\n const summary = {\n pages: pages.map((p) => ({\n id: p.id,\n exportName: p.exportName,\n title: p.title,\n bundlePath: `${outputPrefix}${p.id}.js`,\n source: p.moduleSpecifierRel,\n })),\n };\n\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}platform-react-pages.json`,\n source: JSON.stringify(summary, null, 2),\n });\n\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}platform-react-digest-map.json`,\n source: JSON.stringify({ digests }, null, 2),\n });\n },\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize } from \"node:path\";\nimport type {\n PlatformReactManifest,\n PlatformReactPageDeclaration,\n} from \"./page-bundles\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * A fully-validated PlatformReact page declaration. All fields are guaranteed\n * present (no `undefined`), `exportName` is defaulted to `\"default\"`, and the\n * `moduleSpecifier` is guaranteed to exist on disk when `verifyOnDisk: true`\n * was passed to {@link parsePlatformReactPages}.\n */\nexport interface ResolvedPlatformReactPage {\n id: string;\n moduleSpecifier: string;\n exportName: string;\n title: string | null;\n}\n\n/**\n * Options for {@link parsePlatformReactPages}.\n */\nexport interface ParsePlatformReactPagesOptions {\n /**\n * Root directory the manifest path and the page module specifiers are\n * resolved against. Defaults to `process.cwd()`.\n */\n root?: string;\n /**\n * When `true`, every declared `moduleSpecifier` must exist on disk (relative\n * to {@link root}). The default is `false` so the helper can be used to\n * snapshot-test a manifest without checking-out the page source files.\n */\n verifyOnDisk?: boolean;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nconst ID_REGEX = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i;\n\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n// ── Public API ─────────────────────────────────────────────────────\n\n/**\n * Parse + validate `ui.platformReactPages[]` declarations from a manifest\n * file. Designed for plugin authors writing Vitest tests against their own\n * manifest — the helper applies the same shape and uniqueness rules the\n * build-time Vite pass enforces, so a passing unit test gives the same\n * guarantee a green build would.\n *\n * Returns an empty array when the manifest does not exist OR does not\n * declare `ui.platformReactPages` OR declares it as an empty array.\n *\n * Throws on any malformed declaration. The thrown message matches the\n * build-time error so a failing test reads identically to a failing build.\n *\n * @example\n * ```ts\n * import { parsePlatformReactPages } from \"@ethisyscore/vite-plugin\";\n *\n * test(\"manifest declares dashboard and admin pages\", () => {\n * const pages = parsePlatformReactPages(\"./feature.manifest.json\");\n * expect(pages).toEqual([\n * { id: \"dashboard\", moduleSpecifier: \"src/pages/Dashboard.tsx\", exportName: \"default\", title: \"Dashboard\" },\n * { id: \"admin\", moduleSpecifier: \"src/pages/Admin.tsx\", exportName: \"AdminPage\", title: null },\n * ]);\n * });\n * ```\n */\nexport function parsePlatformReactPages(\n manifestPath: string,\n options: ParsePlatformReactPagesOptions = {},\n): ResolvedPlatformReactPage[] {\n const root = options.root ?? process.cwd();\n const verifyOnDisk = options.verifyOnDisk ?? false;\n const manifestAbsPath = isAbsolute(manifestPath)\n ? manifestPath\n : resolve(root, manifestPath);\n\n if (!existsSync(manifestAbsPath)) {\n return [];\n }\n\n let manifest: PlatformReactManifest;\n try {\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n manifest = JSON.parse(raw) as PlatformReactManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-platform-react] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n\n const declared = manifest.ui?.platformReactPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n return [];\n }\n\n const result: ResolvedPlatformReactPage[] = [];\n const seenIds = new Set<string>();\n\n for (let i = 0; i < declared.length; i++) {\n const decl: PlatformReactPageDeclaration = declared[i];\n const where = `ui.platformReactPages[${i}]`;\n\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id is required (non-empty string).`,\n );\n }\n if (!ID_REGEX.test(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id \"${decl.id}\" must match [a-z0-9_-]+ (URL-safe; case-insensitive).`,\n );\n }\n if (seenIds.has(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] Duplicate page id \"${decl.id}\".`,\n );\n }\n seenIds.add(decl.id);\n\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier is required (non-empty relative path).`,\n );\n }\n assertHostOriginRelativePath(decl.moduleSpecifier, `${where}.moduleSpecifier`);\n\n if (verifyOnDisk) {\n const absPath = resolve(root, decl.moduleSpecifier);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier \"${decl.moduleSpecifier}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n }\n\n result.push({\n id: decl.id,\n moduleSpecifier: decl.moduleSpecifier,\n exportName:\n typeof decl.exportName === \"string\" && decl.exportName.length > 0\n ? decl.exportName\n : \"default\",\n title:\n typeof decl.title === \"string\" && decl.title.length > 0\n ? decl.title\n : null,\n });\n }\n\n return result;\n}\n\n","import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve, sep } from \"node:path\";\nimport type { Plugin } from \"vite\";\n// Tier U manifest + integrity shapes are owned by the protocol SSOT (sub-plan 01 D1).\n// Consume them — do NOT re-declare a local copy.\nimport { AssetDigest, IframeSandboxPageDeclaration } from \"@ethisyscore/protocol\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/** One emitted artifact from a per-page Vite sub-build. */\nexport type IframeBuildOutputItem =\n | { type: \"chunk\"; fileName: string; code: string }\n | { type: \"asset\"; fileName: string; source: string | Uint8Array };\n\nexport interface IframeBuildResult {\n output: IframeBuildOutputItem[];\n}\n\n/** A single page handed to the (injectable) builder. */\nexport interface IframeBuildContext {\n id: string;\n title: string;\n entryPath: string;\n root: string;\n /** Per-page output directory (`<outputDir>/<id>`). */\n outDir: string;\n}\n\n/** Injectable per-page builder. Defaults to a real Vite library build. */\nexport type IframeViteBuild = (page: IframeBuildContext) => Promise<IframeBuildResult>;\n\nexport interface IframeSandboxPluginOptions {\n /** Root the manifest + entry paths resolve against. Defaults to Vite's resolved root / cwd. */\n root?: string;\n /** Manifest path (relative to `root`). Default `feature.manifest.json`. */\n manifestPath?: string;\n /** Output directory for per-page bundles + the digest map. Default `dist/iframe-sandbox`. */\n outputDir?: string;\n /** Inline manifest object (test injection). When omitted, the manifest is read from disk. */\n manifest?: unknown;\n /** Injectable per-page builder (test injection). When omitted, a real Vite build runs. */\n build?: IframeViteBuild;\n /** Injectable file writer (test injection). When omitted, writes via `fs` (creating dirs). */\n writeFile?: (path: string, contents: string) => void;\n}\n\nexport interface IframeSandboxBuildSummary {\n digests: Array<{ path: string; sha256: string }>;\n digestMapPath: string | null;\n}\n\nconst DEFAULT_MANIFEST = \"feature.manifest.json\";\nconst DEFAULT_OUTPUT_DIR = \"dist/iframe-sandbox\";\nconst DIGEST_MAP_FILENAME = \"iframe-sandbox-digest-map.json\";\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\nfunction defaultWriteFile(path: string, contents: string): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, contents);\n}\n\n/** Real per-page build via Vite's programmatic API. `vite` is an optional peer dep. */\nconst defaultBuild: IframeViteBuild = async (page) => {\n const { build } = await import(\"vite\");\n const result = await build({\n root: page.root,\n logLevel: \"warn\",\n build: {\n outDir: page.outDir,\n emptyOutDir: true,\n rollupOptions: {\n input: resolve(page.root, page.entryPath),\n },\n },\n });\n // `build()` returns RollupOutput | RollupOutput[] | RollupWatcher; the\n // library build (no watch) yields a single RollupOutput.\n const out = Array.isArray(result) ? result[0] : result;\n return { output: (out as unknown as IframeBuildResult).output };\n};\n\nfunction digestOf(item: IframeBuildOutputItem): string {\n const bytes = item.type === \"chunk\" ? item.code : item.source;\n return createHash(\"sha256\").update(bytes as string | Uint8Array).digest(\"hex\");\n}\n\nfunction readManifest(options: IframeSandboxPluginOptions, root: string): unknown {\n if (options.manifest !== undefined) {\n return options.manifest;\n }\n const rel = options.manifestPath ?? DEFAULT_MANIFEST;\n const abs = isAbsolute(rel) ? rel : resolve(root, rel);\n if (!existsSync(abs)) {\n return null;\n }\n const raw = readFileSync(abs, \"utf8\");\n try {\n return JSON.parse(raw);\n } catch (e) {\n throw new Error(`[ethisys-iframe-sandbox] Failed to parse manifest at \"${abs}\": ${(e as Error).message}`);\n }\n}\n\n// ── Orchestration (exposed for unit testing) ───────────────────────\n\n/**\n * Build each `ui.iframeSandboxPages[]` declaration as its own Vite app bundle and\n * emit a per-asset SHA-256 digest map in the SAME shape `ethisysPlatformReactPlugin`\n * produces (`{ digests: [{ path, sha256 }] }`). Tier U surfaces are independent\n * cross-origin apps, so each page is a separate sub-build under `<outputDir>/<id>/`;\n * every emitted artifact is hashed (and validated against the protocol `AssetDigest`\n * schema) so the edge integrity endpoint (sub-plan 5, Task 6) can verify served bytes.\n *\n * No-op when no pages are declared. Page shape is validated by the protocol\n * `IframeSandboxPageDeclaration` schema (a malformed entry rejects the build).\n */\nexport async function buildIframeSandboxPages(\n options: IframeSandboxPluginOptions = {},\n): Promise<IframeSandboxBuildSummary> {\n const root = options.root ?? process.cwd();\n const manifest = readManifest(options, root);\n\n const declared = (manifest as { ui?: { iframeSandboxPages?: unknown[] } } | null)?.ui?.iframeSandboxPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n return { digests: [], digestMapPath: null };\n }\n\n // Validate every page against the protocol schema (SSOT) before building.\n const pages = declared.map((raw, i) => {\n try {\n return IframeSandboxPageDeclaration.parse(raw);\n } catch (e) {\n throw new Error(\n `[ethisys-iframe-sandbox] ui.iframeSandboxPages[${i}] is invalid: ${(e as Error).message}`,\n );\n }\n });\n\n const seen = new Set<string>();\n for (const p of pages) {\n if (seen.has(p.id)) {\n throw new Error(`[ethisys-iframe-sandbox] Duplicate iframe-sandbox page id \"${p.id}\".`);\n }\n seen.add(p.id);\n }\n\n const build = options.build ?? defaultBuild;\n const write = options.writeFile ?? defaultWriteFile;\n const outputDir = options.outputDir ?? DEFAULT_OUTPUT_DIR;\n const outDirAbs = isAbsolute(outputDir) ? outputDir : resolve(root, outputDir);\n\n const digests: Array<{ path: string; sha256: string }> = [];\n for (const page of pages) {\n const result = await build({\n id: page.id,\n title: page.title,\n entryPath: page.entryPath,\n root,\n outDir: resolve(outDirAbs, page.id),\n });\n for (const item of result.output) {\n const entry = { path: `${page.id}/${item.fileName}`, sha256: digestOf(item) };\n // The integrity entry conforms to the protocol AssetDigest contract.\n AssetDigest.parse(entry);\n digests.push(entry);\n }\n }\n\n const digestMapPath = resolve(outDirAbs, DIGEST_MAP_FILENAME);\n write(slash(digestMapPath), JSON.stringify({ digests }, null, 2));\n return { digests, digestMapPath };\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Tier U (iframe-sandbox) Vite build pass (WI 4858 sub-plan 5). Mirrors\n * `ethisysPlatformReactPlugin`: keyed off `ui.iframeSandboxPages[]` and a no-op\n * when absent, so a single Vite config can compose every render-mode pass.\n *\n * Unlike Tier T (ESM modules in the parent build), each Tier U page is an\n * independent cross-origin app — so the pass runs a separate Vite sub-build per\n * page in `closeBundle` and emits the integrity digest map the host verifies.\n */\nexport function ethisysIframeSandboxPlugin(options: IframeSandboxPluginOptions = {}): Plugin {\n let resolvedRoot = options.root;\n\n return {\n name: \"ethisys-iframe-sandbox\",\n enforce: \"pre\",\n\n configResolved(config) {\n if (!options.root) {\n resolvedRoot = config.root;\n }\n },\n\n async closeBundle() {\n await buildIframeSandboxPages({ ...options, root: options.root ?? resolvedRoot });\n },\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { isAbsolute, normalize, resolve, sep } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\n\n// ── Contract A (Wave 0): SDUI schema validation + emission ─────────\n//\n// Re-exports the Contract A pass so consumers can compose it alongside the\n// legacy manifest HTML-entry plugin (or use it on its own for host-rendered\n// plugins that ship no HTML at all).\nexport {\n ethisysContractAPlugin,\n type ContractAPluginOptions,\n type ContractAManifest,\n type ManifestResourceRef,\n type ManifestReactiveRuleRef,\n} from \"./contract-a/emit\";\nexport {\n validateDeclarativeResource,\n validateReactiveRule,\n type ValidationResult,\n type ValidationFailure,\n} from \"./contract-a/schema-validator\";\n\n// ── Contract B (Wave 1): Worker-bundle emission ────────────────────\n//\n// Re-export the Contract B pass so consumers can compose it alongside the\n// Contract A schema-validation pass. The two passes are non-interfering:\n// each pass keys off `renderMode` and exits early when the manifest is not\n// addressed to it. The recommended scaffold registers both plugins so a\n// manifest can switch render modes without changing its Vite config.\nexport {\n ethisysContractBPlugin,\n type ContractBPluginOptions,\n type ContractBManifest,\n CONTRACT_B_SEMANTIC_PRIMITIVES,\n CONTRACT_B_RUNTIME_IMPORTS,\n CONTRACT_B_IMPORT_MAP_ALLOWLIST,\n} from \"./contract-b/worker-bundle\";\n\n// ── PlatformReact pages (RFC 0003) ─────────────────────────────────\n//\n// Build pass for the high-trust host-extension tier. Reads\n// `ui.platformReactPages[]` from the manifest and emits one ESM bundle per\n// page. The host loads each bundle at surface mount time via `import(url)`\n// against the same-origin asset endpoint.\nexport {\n ethisysPlatformReactPlugin,\n type PlatformReactPluginOptions,\n type PlatformReactManifest,\n type PlatformReactPageDeclaration,\n} from \"./platform-react/page-bundles\";\n\n// Test-time helper for plugin authors who want to snapshot-test their\n// manifest's PlatformReact page declarations without spinning a Vite build.\n// Applies the same shape + uniqueness rules the build-time pass enforces.\nexport {\n parsePlatformReactPages,\n type ResolvedPlatformReactPage,\n type ParsePlatformReactPagesOptions,\n} from \"./platform-react/test-helpers\";\n\n// ── Tier U: iframe-sandbox pages (WI 4858 sub-plan 5) ──────────────\n//\n// Build pass for the cross-origin sandboxed tier. Reads `ui.iframeSandboxPages[]`\n// (typed by the protocol `IframeSandboxPageDeclaration`), runs one Vite sub-build\n// per page, and emits the per-asset SHA-256 digest map the edge integrity endpoint\n// verifies. No-op when no iframe-sandbox pages are declared.\nexport {\n ethisysIframeSandboxPlugin,\n buildIframeSandboxPages,\n type IframeSandboxPluginOptions,\n type IframeSandboxBuildSummary,\n type IframeViteBuild,\n type IframeBuildContext,\n type IframeBuildResult,\n type IframeBuildOutputItem,\n} from \"./iframeSandboxPlugin\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\ninterface ManifestEntry {\n id?: string;\n entrypoint: string;\n source?: string;\n title?: string;\n template?: string;\n type?: string;\n route?: string;\n}\n\ninterface Manifest {\n ui?: {\n pages?: ManifestEntry[];\n surfaces?: ManifestEntry[];\n };\n}\n\nexport interface EthisysPluginOptions {\n /**\n * Path to the manifest file, relative to Vite's root directory.\n * @default \"../extension.manifest.json\"\n */\n manifestPath?: string;\n\n /**\n * ID of the mount element in the generated HTML.\n * React plugins use \"root\", Vue plugins use \"app\".\n * @default \"root\"\n */\n mountId?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\n/** Normalize Windows backslashes to forward slashes for Vite/Rollup compatibility. */\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\n/** Escape HTML special characters to prevent XSS via manifest fields (e.g., title). */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/** Validates a manifest path is relative with no traversal (cross-platform). */\nfunction assertSafeRelativePath(value: string, label: string): void {\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-manifest] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.includes(\"..\")) {\n throw new Error(\n `[ethisys-manifest] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Vite plugin that reads `extension.manifest.json` (or a custom manifest path)\n * and auto-generates HTML entry points for all pages and surfaces that declare\n * a `source` field. No physical HTML files are required.\n *\n * Pages without a `source` field share the main entry point (SPA mode).\n * Surfaces (dialogs, panels) each get their own HTML shell.\n */\nexport function ethisysManifestPlugin(\n options: EthisysPluginOptions = {},\n): Plugin {\n const manifestRelPath = options.manifestPath ?? \"../extension.manifest.json\";\n const mountId = options.mountId ?? \"root\";\n let entries: ManifestEntry[] = [];\n let rootDir: string;\n let manifestAbsPath: string;\n // Cache generated HTML Promises to avoid stampede on concurrent requests (PERF-5)\n const htmlCache = new Map<string, Promise<string>>();\n\n // ── HTML generation ──────────────────────────────────────────────\n\n function generateHtml(entry: ManifestEntry): string {\n // Enterprise escape hatch: custom HTML template\n if (entry.template) {\n assertSafeRelativePath(entry.template, \"Template path\");\n\n const templatePath = resolve(rootDir, entry.template);\n if (existsSync(templatePath)) {\n let html = readFileSync(templatePath, \"utf-8\");\n\n // Validate template has a mount point (flexible — accepts any element/quoting)\n const safeMountId = escapeHtml(mountId);\n const mountPattern = new RegExp(`id=[\"']${safeMountId}[\"']`);\n if (!mountPattern.test(html)) {\n throw new Error(\n `[ethisys-manifest] Custom template \"${entry.template}\" must contain an element with id=\"${mountId}\".`,\n );\n }\n\n html = html.replaceAll(\"{{SOURCE}}\", escapeHtml(entry.source!));\n return html;\n }\n }\n\n // Default minimal HTML shell.\n // Uses relative src (no leading /) so Vite's transformIndexHtml resolves\n // it against config.base correctly for CDN/subdirectory deployments.\n const safeTitle = escapeHtml(entry.title ?? \"Plugin\");\n const safeSource = escapeHtml(entry.source!);\n const safeMountId = escapeHtml(mountId);\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${safeTitle}</title>\n </head>\n <body>\n <div id=\"${safeMountId}\"></div>\n <script type=\"module\" src=\"${safeSource}\"></script>\n </body>\n</html>`;\n }\n\n // ── Manifest parsing ─────────────────────────────────────────────\n\n function readManifest(): ManifestEntry[] {\n if (!existsSync(manifestAbsPath)) {\n return [];\n }\n\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n let manifest: Manifest;\n try {\n manifest = JSON.parse(raw) as Manifest;\n } catch {\n throw new Error(\n `[ethisys-manifest] Failed to parse manifest at \"${manifestAbsPath}\".`,\n );\n }\n\n const result: ManifestEntry[] = [];\n\n // Collect entries with a source field (pages + surfaces)\n for (const page of manifest.ui?.pages ?? []) {\n if (page.source) {\n result.push(page);\n }\n }\n for (const surface of manifest.ui?.surfaces ?? []) {\n if (surface.source) {\n result.push(surface);\n }\n }\n\n return result;\n }\n\n // ── Validation ───────────────────────────────────────────────────\n\n function validateEntries(): void {\n // Multiple routes can share the same entrypoint (SPA mode).\n // But each entrypoint can only have ONE source file.\n const entrypointSources = new Map<string, string>();\n\n for (const entry of entries) {\n const source = entry.source!;\n\n // Validate no path traversal or absolute paths (cross-platform)\n assertSafeRelativePath(source, \"Source path\");\n\n // Validate source file exists on disk\n const sourcePath = resolve(rootDir, source);\n if (!existsSync(sourcePath)) {\n throw new Error(\n `[ethisys-manifest] Source file \"${source}\" for entry \"${entry.entrypoint}\" does not exist.`,\n );\n }\n\n // Validate entrypoint → source uniqueness\n const existingSource = entrypointSources.get(entry.entrypoint);\n if (existingSource && existingSource !== source) {\n throw new Error(\n `[ethisys-manifest] Conflicting sources for entrypoint \"${entry.entrypoint}\": ` +\n `\"${existingSource}\" and \"${source}\". ` +\n `Only one source file can be mapped to a single entrypoint.`,\n );\n }\n entrypointSources.set(entry.entrypoint, source);\n }\n }\n\n // ── Vite Plugin Hooks ────────────────────────────────────────────\n\n return {\n name: \"ethisys-manifest\",\n enforce: \"pre\",\n\n config(config, { command }) {\n rootDir = config.root ?? process.cwd();\n manifestAbsPath = resolve(rootDir, manifestRelPath);\n entries = readManifest();\n\n if (entries.length === 0) {\n return;\n }\n\n validateEntries();\n\n // Inject Rollup inputs for build mode.\n // ALL entries are virtual — including index.html.\n if (command === \"build\") {\n const input: Record<string, string> = {};\n const seen = new Set<string>();\n\n for (const entry of entries) {\n if (seen.has(entry.entrypoint)) {\n continue;\n }\n seen.add(entry.entrypoint);\n\n const name = entry.entrypoint.replace(/\\.html$/, \"\");\n input[name] = slash(resolve(rootDir, entry.entrypoint));\n }\n\n return {\n build: {\n rollupOptions: {\n input,\n },\n },\n };\n }\n },\n\n // Dev server: intercept HTML requests and serve virtual HTML.\n // Pre-middleware — runs before Vite's built-in handlers.\n // Safe because we only respond to .html requests and SPA navigation;\n // module requests (/@vite/client, /@react-refresh, .ts/.tsx/.css files)\n // don't match our conditions and pass through to Vite's transform middleware.\n configureServer(server: ViteDevServer) {\n server.watcher.add(manifestAbsPath);\n\n server.middlewares.use(async (req, res, next) => {\n try {\n const url = req.url?.split(\"?\")[0] ?? \"\";\n const acceptsHtml = req.headers.accept?.includes(\"text/html\");\n\n // 1. Explicit .html or root requests → match against entry points\n if (url.endsWith(\".html\") || url === \"/\" || url === \"/index.html\") {\n const filename =\n url === \"/\" || url === \"/index.html\"\n ? \"index.html\"\n : url.slice(1);\n\n const entry = entries.find((e) => e.entrypoint === filename);\n if (entry) {\n // Cache the Promise to prevent stampede on concurrent requests (PERF-5)\n const cacheKey = `entry:${filename}`;\n if (!htmlCache.has(cacheKey)) {\n const rawHtml = generateHtml(entry);\n htmlCache.set(cacheKey, server.transformIndexHtml(url, rawHtml));\n }\n const html = await htmlCache.get(cacheKey)!;\n res.setHeader(\"Content-Type\", \"text/html\");\n res.statusCode = 200;\n res.end(html);\n return;\n }\n }\n\n // 2. SPA fallback: non-file navigation requests (e.g., /books/catalog\n // refreshed in the browser) → serve index.html for client-side routing.\n // Only triggers for requests that explicitly Accept text/html (browser\n // navigation), not module/asset requests which use Accept: */*.\n if (acceptsHtml && !url.includes(\".\")) {\n const mainEntry = entries.find(\n (e) => e.entrypoint === \"index.html\",\n );\n if (mainEntry) {\n // SPA uses entrypoint as cache key (not url) to avoid unbounded cache growth\n const cacheKey = \"spa:index.html\";\n if (!htmlCache.has(cacheKey)) {\n const rawHtml = generateHtml(mainEntry);\n htmlCache.set(cacheKey, server.transformIndexHtml(\"/\", rawHtml));\n }\n const html = await htmlCache.get(cacheKey)!;\n res.setHeader(\"Content-Type\", \"text/html\");\n res.statusCode = 200;\n res.end(html);\n return;\n }\n }\n\n next();\n } catch (err) {\n next(err);\n }\n });\n },\n\n // Watch manifest for changes during dev — reload entries on edit.\n // Entire handler is wrapped in try/catch so JSON syntax errors in the\n // manifest don't crash the dev server (common during active editing).\n handleHotUpdate({ file, server }) {\n if (slash(file) === slash(manifestAbsPath)) {\n try {\n entries = readManifest();\n validateEntries();\n // Invalidate HTML cache on manifest change (PERF-5)\n htmlCache.clear();\n } catch (e) {\n server.config.logger.error(String(e));\n return [];\n }\n\n server.config.logger.info(\n \"[ethisys-manifest] Manifest changed — reloading entries\",\n );\n server.hot.send({ type: \"full-reload\" });\n return [];\n }\n },\n\n // Build: resolve virtual HTML module IDs (no physical files exist on disk)\n resolveId(id) {\n const normalizedId = slash(id);\n const match = entries.find(\n (e) => slash(resolve(rootDir, e.entrypoint)) === normalizedId,\n );\n if (match) {\n return id;\n }\n },\n\n // Build: provide virtual HTML content for Rollup\n load(id) {\n const normalizedId = slash(id);\n const match = entries.find(\n (e) => slash(resolve(rootDir, e.entrypoint)) === normalizedId,\n );\n if (match) {\n return generateHtml(match);\n }\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/contract-a/schema-validator.ts","../src/contract-a/emit.ts","../src/contract-b/rewrite-imports.ts","../src/contract-b/worker-bundle.ts","../src/platform-react/page-bundles.ts","../src/platform-react/test-helpers.ts","../src/platform-react/build-pages.ts","../src/iframeSandboxPlugin.ts","../src/index.ts"],"names":["KNOWN_PRIMITIVES","KNOWN_OPERATORS","KNOWN_RULE_KINDS","SduiNode","ReactiveRule","normalize","isAbsolute","resolve","readManifest","existsSync","readFileSync","sep","assertHostOriginRelativePath","slash","createHash","ID_REGEX","path","mkdirSync","dirname","writeFileSync","rmSync","DIGEST_MAP_FILENAME","def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E,CAAA;AAC7B,MAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA;AAAA,QACpB,CAAC,MAAMA,MAAAA,CAAMN,YAAAA,CAAQ,SAAS,CAAA,CAAE,UAAU,CAAC,CAAA,KAAM;AAAA,OACnD;AACA,MAAA,IAAI,KAAA,EAAO;AACT,QAAA,OAAO,EAAA;AAAA,MACT;AAAA,IACF,CAAA;AAAA;AAAA,IAGA,KAAK,EAAA,EAAI;AACP,MAAA,MAAM,YAAA,GAAeM,OAAM,EAAE,CAAA;AAC7B,MAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA;AAAA,QACpB,CAAC,MAAMA,MAAAA,CAAMN,YAAAA,CAAQ,SAAS,CAAA,CAAE,UAAU,CAAC,CAAA,KAAM;AAAA,OACnD;AACA,MAAA,IAAI,KAAA,EAAO;AACT,QAAA,OAAO,aAAa,KAAK,CAAA;AAAA,MAC3B;AAAA,IACF;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import {\n SduiNode,\n ReactiveRule,\n KNOWN_PRIMITIVES,\n KNOWN_OPERATORS,\n KNOWN_RULE_KINDS,\n} from \"@ethisyscore/protocol\";\n\n/**\n * Minimal structural shape of a Zod parse issue. Declared locally so the\n * vite-plugin package does not need a direct `zod` peer/runtime dependency —\n * the protocol package owns Zod, we just consume parse results.\n */\ninterface ZodLikeIssue {\n readonly code: string;\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n}\n\n/**\n * A single, structured validation failure surfaced by the Contract A\n * schema validators. Carries enough context for a build-time error\n * to be actionable without the plugin author opening the host runtime.\n */\nexport interface ValidationFailure {\n /** Absolute path of the source file whose JSON failed validation. */\n filePath: string;\n /**\n * JSON-pointer (RFC 6901) into the failing JSON document, pointing at\n * the offending node. Empty string when the offender is the root.\n */\n pointer: string;\n /** The offending operator / primitive / rule-kind name, if extractable. */\n offender?: string;\n /** Human-readable message suitable for surfacing at the build CLI. */\n message: string;\n}\n\n/**\n * Result of a validation call. Discriminated on `ok` so callers can branch\n * narrowly without juggling exception flow for expected outcomes.\n */\nexport type ValidationResult =\n | { ok: true }\n | { ok: false; failures: ValidationFailure[] };\n\n// ── Internal: Zod issue → ValidationFailure ─────────────────────\n\nconst KNOWN_PRIMITIVE_SET = new Set<string>(KNOWN_PRIMITIVES);\nconst KNOWN_OPERATOR_SET = new Set<string>(KNOWN_OPERATORS);\nconst KNOWN_RULE_KIND_SET = new Set<string>(KNOWN_RULE_KINDS);\n\n/**\n * Convert a Zod path array into a JSON Pointer (RFC 6901) string.\n *\n * Numeric segments stay as array indices, string segments are escaped per RFC.\n */\nfunction toJsonPointer(path: ReadonlyArray<string | number>): string {\n if (path.length === 0) {\n return \"\";\n }\n return \"/\" + path\n .map((seg) => {\n const s = String(seg);\n return s.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n })\n .join(\"/\");\n}\n\n/**\n * Walks the original JSON value and the Zod path to extract a likely offender\n * string. For unknown SDUI primitives the offender is the rejected `type`\n * value; for unknown JsonLogic operators the offender is the offending key.\n */\nfunction extractOffender(\n doc: unknown,\n issue: ZodLikeIssue,\n): string | undefined {\n // 1. enum mismatch — the offender is the input value\n if (issue.code === \"invalid_value\" || issue.code === \"invalid_enum_value\") {\n const received = (issue as unknown as { received?: unknown }).received;\n if (typeof received === \"string\") {\n return received;\n }\n }\n\n // 2. invalid_union (the operator object), or refine refusal — walk to the path\n // and look for an object whose only key is unknown.\n let cur: unknown = doc;\n for (const seg of issue.path) {\n if (cur === null || cur === undefined) {\n break;\n }\n cur = (cur as Record<string | number, unknown>)[seg as string | number];\n }\n if (cur && typeof cur === \"object\" && !Array.isArray(cur)) {\n const keys = Object.keys(cur as object);\n if (keys.length === 1 && !KNOWN_OPERATOR_SET.has(keys[0])) {\n return keys[0];\n }\n }\n\n // 3. Fall back to last path segment (e.g. an unknown rule-kind)\n if (issue.path.length > 0) {\n const last = issue.path[issue.path.length - 1];\n if (typeof last === \"string\" && !KNOWN_RULE_KIND_SET.has(last) && !KNOWN_PRIMITIVE_SET.has(last)) {\n return last;\n }\n }\n\n return undefined;\n}\n\n/**\n * Convert a Zod parse failure into structured {@link ValidationFailure}s.\n *\n * One Zod issue → one failure, preserving order. The original JSON `doc`\n * is walked in tandem with each issue's path so the offender name (an\n * unknown primitive, operator, or rule-kind) can be lifted into the\n * failure record.\n */\nfunction zodIssuesToFailures(\n doc: unknown,\n issues: readonly ZodLikeIssue[],\n filePath: string,\n): ValidationFailure[] {\n return issues.map((issue) => {\n const pointer = toJsonPointer(issue.path);\n const offender = extractOffender(doc, issue);\n const offenderSuffix = offender ? ` (offender: '${offender}')` : \"\";\n return {\n filePath,\n pointer,\n offender,\n message: `${filePath}${pointer ? ` at ${pointer}` : \"\"}: ${issue.message}${offenderSuffix}`,\n };\n });\n}\n\n/**\n * Validate a single declarative SDUI resource against the protocol's\n * {@link SduiNode} Zod schema. The recursive schema rejects unknown\n * primitives and unknown JsonLogic operators at any depth of the tree.\n *\n * `filePath` is propagated into every emitted failure so the build CLI\n * can point the author at the exact file on disk.\n */\nexport function validateDeclarativeResource(\n doc: unknown,\n uri: string,\n filePath: string,\n): ValidationResult {\n const parsed = SduiNode.safeParse(doc);\n if (parsed.success) {\n return { ok: true };\n }\n const failures = zodIssuesToFailures(doc, parsed.error.issues, filePath);\n // Tag the URI onto every message so the build CLI shows which resource failed.\n return {\n ok: false,\n failures: failures.map((f) => ({\n ...f,\n message: `[resource ${uri}] ${f.message}`,\n })),\n };\n}\n\n/**\n * Validate a single {@link ReactiveRule} against the protocol's curated\n * JsonLogic operator subset. Used for top-level reactivity declarations\n * declared on the manifest itself (i.e. not embedded under a `bindings`\n * key on a SDUI node — those are covered by {@link validateDeclarativeResource}).\n */\nexport function validateReactiveRule(\n rule: unknown,\n filePath: string,\n): ValidationResult {\n const parsed = ReactiveRule.safeParse(rule);\n if (parsed.success) {\n return { ok: true };\n }\n return {\n ok: false,\n failures: zodIssuesToFailures(rule, parsed.error.issues, filePath),\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize } from \"node:path\";\nimport type { Plugin } from \"vite\";\n\nimport {\n validateDeclarativeResource,\n validateReactiveRule,\n type ValidationFailure,\n} from \"./schema-validator\";\n\n// ── Manifest shapes (subset) ───────────────────────────────────\n\n/**\n * Reference from the plugin manifest to an SDUI resource JSON file.\n *\n * Wave 0 convention: the manifest declares each declarative resource with\n * a stable `uri` plus a `file` path (relative to the manifest's directory)\n * pointing at the JSON document the host will serve. The static-file\n * convention lets the Vite plugin validate the tree at build time without\n * having to execute plugin runtime code.\n */\nexport interface ManifestResourceRef {\n uri: string;\n /**\n * Relative path (POSIX or platform-native) to the SDUI JSON document.\n * Must not be absolute, must not contain `..` traversal segments.\n */\n file?: string;\n}\n\n/**\n * Top-level manifest reactivity-rule declaration. Each entry pairs an\n * author-supplied identifier with a {@link import(\"@ethisyscore/protocol\").ReactiveRule}.\n *\n * Reactivity declared inline on SDUI nodes (the `bindings` property) is\n * validated by the SDUI-tree pass; this surface covers the rarer case of\n * a manifest-level rule that applies cross-resource.\n */\nexport interface ManifestReactiveRuleRef {\n id: string;\n rule: unknown;\n}\n\n/**\n * The subset of the plugin manifest the Contract A Vite plugin pass cares\n * about. The full manifest is intentionally a superset — the plugin\n * tolerates additional fields it has not been taught yet so manifests\n * built against a newer schema still load.\n */\nexport interface ContractAManifest {\n resources?: ManifestResourceRef[];\n reactiveRules?: ManifestReactiveRuleRef[];\n [key: string]: unknown;\n}\n\n// ── Options ────────────────────────────────────────────────────\n\n/**\n * Author-facing options for the Contract A Vite plugin pass.\n *\n * `root` defaults to Vite's resolved root at `configResolved` time, so the\n * common case requires no configuration. `manifestPath` defaults to the\n * `feature.manifest.json` convention emitted by the host-rendered\n * scaffolding template; pass an absolute or relative path to override.\n */\nexport interface ContractAPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json` colocated with the Vite root.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted SDUI assets. Defaults to `sdui/`. The plugin\n * always emits an `${prefix}sdui-manifest.json` index alongside the\n * validated resource JSON.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────\n\n/** Slug-encode a resource URI into a filesystem-safe asset filename. */\nfunction slugForUri(uri: string): string {\n return uri.replace(/[^a-zA-Z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n}\n\n/** Reject path traversal and absolute paths in author-supplied references. */\nfunction assertSafeRelativePath(value: string, label: string): void {\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-contract-a] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-contract-a] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n/**\n * Render a {@link ValidationFailure} list into the multi-line build-failure\n * message Vite will surface to the author.\n */\nfunction formatFailures(failures: ValidationFailure[]): string {\n const lines = failures.map((f, i) => ` ${i + 1}. ${f.message}`);\n return [\n `[@ethisyscore/vite-plugin] Contract A schema validation failed:`,\n ...lines,\n ].join(\"\\n\");\n}\n\n// ── Plugin ─────────────────────────────────────────────────────\n\ninterface EmittedResource {\n uri: string;\n fileName: string;\n}\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore Contract A\n * (`renderMode: host-rendered`) plugins.\n *\n * Reads `feature.manifest.json` (or `extension.manifest.json` via\n * `manifestPath`), validates each declared SDUI resource against the\n * protocol's `SduiNode` Zod schema, validates each manifest-level\n * reactivity rule against `ReactiveRule`, and emits the validated JSON\n * into the Rollup bundle under the configured output prefix. Validation\n * failures abort the build with a multi-line structured error that names\n * the offending operator/primitive and the source file path + JSON\n * pointer so the author can land on the offending node immediately.\n *\n * Worker-bundle emission for `renderMode: remote-runtime` is deferred to\n * Wave 1's E7.S1b — this pass deliberately does nothing for non-Contract-A\n * manifests.\n */\nexport function ethisysContractAPlugin(\n options: ContractAPluginOptions = {},\n): Plugin {\n const outputPrefix = (options.outputPrefix ?? \"sdui/\").replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let validatedResources: EmittedResource[] = [];\n // Plugin-internal cache so generateBundle can re-emit without re-reading + re-parsing.\n const resourcePayloads = new Map<string, string>();\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): ContractAManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as ContractAManifest;\n } catch (e) {\n throw new Error(\n `[@ethisyscore/vite-plugin] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n function validate(): void {\n validatedResources = [];\n resourcePayloads.clear();\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n\n const failures: ValidationFailure[] = [];\n\n // ── Resources ───────────────────────────────────────────────\n for (const ref of manifest.resources ?? []) {\n if (!ref.file) {\n // A resource without a `file` field is a dynamic / runtime-rendered\n // resource. The Vite plugin can't introspect those at build time;\n // skip them.\n continue;\n }\n assertSafeRelativePath(ref.file, \"Resource file path\");\n\n const filePath = resolve(resolvedRoot, ref.file);\n if (!existsSync(filePath)) {\n failures.push({\n filePath,\n pointer: \"\",\n message:\n `[resource ${ref.uri}] file \"${ref.file}\" referenced by the manifest does not exist on disk (resolved: ${filePath}).`,\n });\n continue;\n }\n\n const rawJson = readFileSync(filePath, \"utf-8\");\n let doc: unknown;\n try {\n doc = JSON.parse(rawJson);\n } catch (e) {\n failures.push({\n filePath,\n pointer: \"\",\n message: `[resource ${ref.uri}] failed to parse JSON: ${(e as Error).message}`,\n });\n continue;\n }\n\n const result = validateDeclarativeResource(doc, ref.uri, filePath);\n if (!result.ok) {\n failures.push(...result.failures);\n continue;\n }\n\n // Serialise canonically (validated input → emitted payload) so the\n // host always sees a byte-stable artefact regardless of source whitespace.\n const fileName = `${outputPrefix}${slugForUri(ref.uri)}.json`;\n const payload = JSON.stringify(doc);\n resourcePayloads.set(fileName, payload);\n validatedResources.push({ uri: ref.uri, fileName });\n }\n\n // ── Manifest-level reactive rules ────────────────────────────\n for (const ruleRef of manifest.reactiveRules ?? []) {\n const result = validateReactiveRule(ruleRef.rule, manifestAbsPath);\n if (!result.ok) {\n failures.push(\n ...result.failures.map((f) => ({\n ...f,\n message: `[reactiveRule ${ruleRef.id}] ${f.message}`,\n })),\n );\n }\n }\n\n if (failures.length > 0) {\n throw new Error(formatFailures(failures));\n }\n }\n\n return {\n name: \"ethisys-contract-a\",\n enforce: \"pre\",\n\n configResolved(config) {\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing a resource JSON.\n validate();\n },\n\n generateBundle() {\n if (validatedResources.length === 0) {\n return;\n }\n\n // Emit each validated resource as a static asset.\n for (const { fileName } of validatedResources) {\n const source = resourcePayloads.get(fileName);\n if (source === undefined) {\n continue;\n }\n this.emitFile({ type: \"asset\", fileName, source });\n }\n\n // Emit a compact index so the host can list contracts without\n // walking the bundle. `name` is stable per build; `resources` is\n // sorted by URI for deterministic output.\n const sorted = [...validatedResources].sort((a, b) =>\n a.uri.localeCompare(b.uri),\n );\n const index = {\n version: 1,\n resources: sorted.map(({ uri, fileName }) => ({ uri, file: fileName })),\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}sdui-manifest.json`,\n source: JSON.stringify(index),\n });\n },\n };\n}\n","// ── Contract B safe-import rewriter ────────────────────────────────\n//\n// Static ES `import` statements with bare specifiers are unresolvable inside\n// a Contract B worker realm: the worker has no `<script type=\"importmap\">`\n// surface (workers don't host scripts) and the spec's `WorkerOptions.importMap`\n// is still proposal-stage in 2026-05. The bootstrap script\n// (`WorkerBootstrapScriptProvider.cs` in the API repo) composes a frozen\n// `IMPORT_MAP` per worker and exposes a synchronous-wrapper-free helper at\n// `globalThis.__ethisysSafeImport(spec) -> Promise<Module>`.\n//\n// The build-time complement to that runtime surface lives here: every static\n// `import` whose specifier is on the closed Contract B allowlist is rewritten\n// into a top-level `await` against `__ethisysSafeImport`. Module workers\n// support top-level await; the host loads the plugin bundle via dynamic\n// `import(moduleUrl)` which awaits the bundle's top-level evaluation, so the\n// `mod.activate(port)` call site sees a fully-initialised module.\n//\n// Specifiers outside the allowlist would not survive `Rollup.external` (which\n// the Contract B config already enforces), so this rewriter never observes\n// them in practice. It still guards against the case defensively — a future\n// `external` widening should not silently emit bare specifiers the worker\n// realm cannot resolve.\n\nconst STATIC_IMPORT_RE = /^([ \\t]*)import[ \\t]+(.*?)[ \\t]*;?[ \\t]*$/gm;\n\n/**\n * Rewrite static ES `import` statements whose specifier is a bare allowlist\n * entry into a top-level `await globalThis.__ethisysSafeImport(...)` form.\n *\n * Non-bare specifiers (relative paths, http(s) URLs, data:/blob:/javascript:\n * schemes) are passed through untouched. Dynamic `import()` calls are passed\n * through untouched. Bare specifiers outside `allowlist` are passed through\n * untouched — the surrounding `external` config is the gate; this function\n * only rewrites what the build pipeline contract guarantees.\n */\nexport function rewriteSafeImports(\n code: string,\n allowlist: readonly string[],\n): string {\n const allowSet = new Set(allowlist);\n\n return code.replace(STATIC_IMPORT_RE, (match, indent: string, body: string) => {\n const rewrite = tryRewriteImport(body, allowSet);\n return rewrite === null ? match : `${indent}${rewrite}`;\n });\n}\n\nfunction convertNamedBindings(namedClause: string): string {\n // `{ A, B as Local, C }` -> `A, B: Local, C` (object-destructuring rename form)\n const inner = namedClause.slice(1, -1).trim();\n if (inner.length === 0) {\n return \"\";\n }\n const parts = inner.split(\",\").map((p) => p.trim()).filter((p) => p.length > 0);\n const converted = parts.map((part) => {\n const asMatch = part.match(/^(\\w[\\w$]*)\\s+as\\s+(\\w[\\w$]*)$/);\n return asMatch === null ? part : `${asMatch[1]}: ${asMatch[2]}`;\n });\n return converted.join(\", \");\n}\n\nfunction tryRewriteImport(body: string, allowSet: ReadonlySet<string>): string | null {\n // Side-effect: `\"Button\"` or `'Button'`\n const sideEffect = body.match(/^[\"']([^\"']+)[\"']$/);\n if (sideEffect !== null) {\n const spec = sideEffect[1];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Default + named: `React, { useState, useEffect as fx } from \"react\"`\n const defaultPlusNamed = body.match(\n /^(\\w[\\w$]*)\\s*,\\s*(\\{[^}]*\\})\\s+from\\s+[\"']([^\"']+)[\"']$/,\n );\n if (defaultPlusNamed !== null) {\n const defaultLocal = defaultPlusNamed[1];\n const namedClause = defaultPlusNamed[2];\n const spec = defaultPlusNamed[3];\n if (!allowSet.has(spec)) {\n return null;\n }\n const bindings = convertNamedBindings(namedClause);\n const inner = bindings.length === 0\n ? `default: ${defaultLocal}`\n : `default: ${defaultLocal}, ${bindings}`;\n return `const { ${inner} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Default-only: `Foo from \"Button\"`\n const defaultOnly = body.match(/^(\\w[\\w$]*)\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (defaultOnly !== null) {\n const local = defaultOnly[1];\n const spec = defaultOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `const { default: ${local} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Named only: `{ A, B as Local } from \"react\"`\n const namedOnly = body.match(/^(\\{[^}]*\\})\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (namedOnly !== null) {\n const namedClause = namedOnly[1];\n const spec = namedOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n const bindings = convertNamedBindings(namedClause);\n return `const { ${bindings} } = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n // Namespace: `* as N from \"react\"`\n const namespaceOnly = body.match(/^\\*\\s+as\\s+(\\w[\\w$]*)\\s+from\\s+[\"']([^\"']+)[\"']$/);\n if (namespaceOnly !== null) {\n const local = namespaceOnly[1];\n const spec = namespaceOnly[2];\n if (!allowSet.has(spec)) {\n return null;\n }\n return `const ${local} = await globalThis.__ethisysSafeImport(${JSON.stringify(spec)});`;\n }\n\n return null;\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize, sep } from \"node:path\";\nimport { rewriteSafeImports } from \"./rewrite-imports\";\nimport type { Plugin } from \"vite\";\n\n// ── Frozen import-map allowlist (E4.S4) ────────────────────────────\n//\n// The Contract B worker realm can ONLY import these bare specifiers. The\n// runtime side (`WorkerBootstrapScriptProvider` in the API repo) enforces the\n// same allowlist by composing a frozen `IMPORT_MAP` at handshake time. The two\n// lists MUST agree — drift is caught by the `import-map-allowlist matches\n// extension-runtime CONTRACT_B_PRIMITIVES` test in `contract-b.test.ts`,\n// which imports `CONTRACT_B_PRIMITIVES` from the sibling extension-runtime\n// package and diffs it against {@link CONTRACT_B_SEMANTIC_PRIMITIVES} below.\n//\n// Plugin-supplied bare specifiers outside this list fail the build with a\n// structured error so authors get a build-time signal instead of a runtime\n// `import-map-violation` from the worker bootstrap.\n\n/**\n * Contract B semantic primitive vocabulary (the closed v1 set authored in\n * `sdk/extension-runtime/src/host/worker/component-registry.ts`). The names\n * mirror the registry exactly; a drift between the two breaks the cross-repo\n * agreement that E4.S4 locks in.\n */\nexport const CONTRACT_B_SEMANTIC_PRIMITIVES = [\n \"Button\",\n \"DataTable\",\n \"Form\",\n \"EntityPicker\",\n \"CommandBar\",\n \"Drawer\",\n \"Modal\",\n \"CanvasSurface\",\n \"WebGLSurface\",\n // Phase 1 additions (per Contract B + PlatformReact plan §Q6, frequency\n // survey of coreconnect-web Timesheets feature). Card / Tabs / Select /\n // Alert close the four most-common gaps in the v1 primitive set:\n // - Card: universal layout container, ~20 imports across surveyed pages.\n // - Tabs: settings / configuration surfaces (6 tabs in TimesheetSettings).\n // - Select: filter + form input, ~10 imports; Form's text input doesn't\n // cover dropdowns.\n // - Alert: lock/unlock warnings, validation banners, non-modal system\n // messages; Card doesn't carry severity semantics.\n \"Card\",\n \"Tabs\",\n \"Select\",\n \"Alert\",\n] as const;\n\n/**\n * Non-component import-map entries — the runtime libraries the worker is\n * permitted to resolve via bare specifiers. Authoring constraint: the plugin's\n * single ESM bundle (Contract B emits exactly one — see `worker-bundle.ts`)\n * can `import x from \"react\"` or `import { ... } from \"@ethisyscore/extension-runtime\"`\n * and nothing else off-bundle.\n */\nexport const CONTRACT_B_RUNTIME_IMPORTS = [\n \"react\",\n \"@ethisyscore/extension-runtime\",\n] as const;\n\n/**\n * Full allowlist of bare specifiers a Contract B plugin bundle may import.\n * Frozen at module load so plugins can't mutate it via a transitive dep.\n */\nexport const CONTRACT_B_IMPORT_MAP_ALLOWLIST: readonly string[] = Object.freeze([\n ...CONTRACT_B_RUNTIME_IMPORTS,\n ...CONTRACT_B_SEMANTIC_PRIMITIVES,\n]);\n\nconst ALLOWLIST_SET: ReadonlySet<string> = new Set(CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * The subset of a Contract B (`renderMode: remote-runtime`) plugin manifest\n * that this Vite pass consumes. Manifests are tolerated as a superset — extra\n * fields are ignored so newer-schema manifests still load.\n */\nexport interface ContractBManifest {\n renderMode?: string;\n /**\n * Worker bundle declaration. Required when `renderMode === \"remote-runtime\"`.\n * The `entry` is a relative path (POSIX or platform-native) from the\n * manifest's directory to the plugin's TypeScript/JavaScript entrypoint.\n *\n * Absolute paths, path-traversal, and non-host-origin URLs are rejected at\n * build time — Contract B requires the worker bundle to be a host-origin\n * asset (the import-map enforcement in E4.S4 builds on this guarantee).\n */\n worker?: {\n entry?: string;\n };\n [key: string]: unknown;\n}\n\n/**\n * Author-facing options for the Contract B Vite pass.\n */\nexport interface ContractBPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json`.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted worker assets and the worker-bundle manifest.\n * Defaults to `worker/`.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\n/** Reject path traversal, absolute paths, and remote URLs in author refs. */\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n // Remote URLs (any scheme + `://`) are forbidden — Contract B bundles must\n // be host-origin assets so the worker bootstrap's frozen import map can\n // enforce origin restrictions deterministically.\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n // Reject `data:` / `blob:` (no `//`) too — also non-host-origin.\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-contract-b] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n/** Normalise Windows backslashes for the Rollup input table. */\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore Contract B\n * (`renderMode: remote-runtime`) plugins.\n *\n * Behaviour:\n * - For `renderMode: \"remote-runtime\"`: declares a single ESM worker entry as\n * the Rollup input table. The output is forced to `format: \"es\"` and\n * `inlineDynamicImports: true` so a Contract B plugin always ships as ONE\n * bundled module — no chunk splitting, no shared chunks, no async imports\n * spread across multiple files. This is the precondition for E4.S4's\n * frozen import map.\n * - For any other `renderMode` (including `host-rendered` and `undefined`):\n * the pass is a no-op. The Wave 0 Contract A path (`ethisysContractAPlugin`)\n * continues to apply without interference. Composition is expected — the\n * recommended template registers both plugins so a manifest can switch\n * render modes without changing its Vite config.\n *\n * The pass also emits a `worker/worker-bundle.json` companion asset listing\n * the bundled entry so the host (or downstream packaging) can inspect what\n * the build produced without re-parsing the bundle.\n *\n * Origin enforcement on the import map (path-pinned host origin, no `data:` /\n * `blob:` imports) is the responsibility of E4.S4 (worker bootstrap) — this\n * pass only blocks remote/absolute paths at the manifest layer so a malformed\n * manifest fails fast.\n */\nexport function ethisysContractBPlugin(\n options: ContractBPluginOptions = {},\n): Plugin {\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n const outputPrefix = (options.outputPrefix ?? \"worker/\")\n .replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let workerEntryAbs: string | null = null;\n let workerEntryRel: string | null = null;\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): ContractBManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as ContractBManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-contract-b] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n /**\n * Validate the manifest and resolve the worker entry's absolute path.\n * Idempotent — repeated invocations return cached state.\n */\n function validate(): void {\n workerEntryAbs = null;\n workerEntryRel = null;\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n if (manifest.renderMode !== \"remote-runtime\") {\n // Non-Contract-B manifests are not our concern.\n return;\n }\n const entry = manifest.worker?.entry;\n if (typeof entry !== \"string\" || entry.length === 0) {\n throw new Error(\n `[ethisys-contract-b] manifest declares renderMode='remote-runtime' but no worker.entry. ` +\n `Set \"worker\": { \"entry\": \"src/worker.ts\" } (relative path).`,\n );\n }\n assertHostOriginRelativePath(entry, \"Worker entry\");\n\n const absPath = resolve(resolvedRoot, entry);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-contract-b] Worker entry file \"${entry}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n workerEntryAbs = absPath;\n workerEntryRel = entry;\n }\n\n return {\n name: \"ethisys-contract-b\",\n // `pre` ordering: validation should fire before user-supplied plugins.\n enforce: \"pre\",\n\n configResolved(config) {\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n },\n\n /**\n * Declares the Rollup input table and locks the output to a single ESM\n * module. Only fires when the manifest opts in (`renderMode: remote-runtime`).\n */\n config(_config, { command }) {\n if (command !== \"build\") {\n return;\n }\n // `config` runs before `buildStart`, so we validate here too — the user\n // needs the structured error at the same lifecycle gate that fails.\n validate();\n\n if (workerEntryAbs === null) {\n return; // Non-Contract-B manifest: no-op.\n }\n\n // The allowlist runtime libraries (`react`, `@ethisyscore/extension-runtime`)\n // and the semantic primitive names are NOT bundled — they're host-served\n // and resolved by the frozen import map at worker bootstrap time. Mark\n // them as `external` so Rollup leaves the bare specifiers intact in the\n // emitted bundle (which is what `generateBundle` then inspects).\n const externalSpecifiers = new Set<string>(CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n\n return {\n build: {\n rollupOptions: {\n input: { worker: slash(workerEntryAbs) },\n external: (id: string): boolean => externalSpecifiers.has(id),\n // CRITICAL: single-file output for the worker bundle. The\n // E4.S4 frozen import map presumes ONE module entry per plugin —\n // chunk splitting or dynamic-import shards would defeat it.\n output: {\n format: \"es\",\n inlineDynamicImports: true,\n entryFileNames: `${outputPrefix}[name].js`,\n chunkFileNames: `${outputPrefix}[name]-[hash].js`,\n assetFileNames: `${outputPrefix}[name][extname]`,\n },\n },\n },\n };\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing the manifest.\n validate();\n },\n\n /**\n * Reject `data:` / `blob:` / `javascript:` URL specifiers at resolve time.\n *\n * Rollup normally externalises unknown URL schemes silently, which would\n * mean a malicious `import(\"data:text/javascript,...\")` survives the\n * build untouched and only fails at runtime (where the bootstrap script's\n * `safeImport` would catch it). We want build-time failure too — the\n * import-map contract is enforced at BOTH ends.\n */\n resolveId(source) {\n if (workerEntryAbs === null) {\n return null;\n }\n if (/^(data|blob|javascript):/i.test(source)) {\n const scheme = source.split(\":\", 1)[0];\n this.error(\n `[ethisys-contract-b] Contract B bundle imports forbidden URL scheme '${scheme}:' ` +\n `(specifier: \"${source.slice(0, 80)}${source.length > 80 ? \"...\" : \"\"}\"). ` +\n `The worker realm rejects ${scheme}: imports at runtime; the build rejects them too.`,\n );\n }\n return null;\n },\n\n /**\n * Rewrite the emitted worker chunk's static bare-specifier imports into\n * top-level `await globalThis.__ethisysSafeImport(...)` calls. This is\n * the build-time complement to the worker bootstrap's frozen IMPORT_MAP\n * (defined in CoreConnect-Api's WorkerBootstrapScriptProvider.cs). The\n * worker realm has no `<script type=\"importmap\">` surface, so static\n * bare specifiers reach the browser's native ES loader as\n * `Failed to resolve module specifier` errors at module load time.\n *\n * Returns `null` (no transform) when the manifest is not Contract B —\n * the Contract A path's emitted chunks are left untouched.\n */\n renderChunk(code: string, chunk: { type: string; fileName: string }): { code: string } | null {\n if (workerEntryAbs === null) {\n return null;\n }\n if (chunk.type !== \"chunk\") {\n return null;\n }\n const rewritten = rewriteSafeImports(code, CONTRACT_B_IMPORT_MAP_ALLOWLIST);\n if (rewritten === code) {\n return null;\n }\n return { code: rewritten };\n },\n\n /**\n * Inspect the emitted bundle for out-of-allowlist bare specifiers and emit\n * the per-bundle `worker-bundle.import-map.json` manifest.\n *\n * Because we marked allowlist specifiers as `external` in `config`, any\n * other bare specifier that the plugin tried to import would have failed\n * Rollup's resolver upstream — but we re-check the surviving `chunk.imports`\n * here as belt-and-braces in case a future Rollup or Vite change relaxes\n * the resolver path. Defence in depth at the build layer matches the\n * defence in depth at the runtime layer (E4.S3 bootstrap).\n */\n generateBundle(_outputOptions, bundle) {\n if (workerEntryAbs === null || workerEntryRel === null) {\n return;\n }\n\n const importedSpecifiers = new Set<string>();\n const violations: string[] = [];\n\n for (const [, chunk] of Object.entries(bundle)) {\n if (chunk.type !== \"chunk\") {\n continue;\n }\n // Both static imports (`chunk.imports`) and dynamic imports\n // (`chunk.dynamicImports`) are surveyed. `inlineDynamicImports: true`\n // collapses dynamic-imported chunks INTO the host chunk, but the\n // specifiers themselves still surface here for externalised IDs.\n const candidates: string[] = [\n ...(chunk.imports ?? []),\n ...(chunk.dynamicImports ?? []),\n ];\n for (const spec of candidates) {\n // Relative / absolute paths are emitted bundle artefacts — not\n // bare specifiers, not subject to the import-map. Skip them.\n if (spec.startsWith(\".\") || spec.startsWith(\"/\") || isAbsolute(spec)) {\n continue;\n }\n // URL-scheme specifiers should have been caught in `resolveId`,\n // but a relaxed-resolver path could let one through. Reject here too.\n if (/^[a-z][a-z0-9+.-]*:/i.test(spec)) {\n violations.push(spec);\n continue;\n }\n if (!ALLOWLIST_SET.has(spec)) {\n violations.push(spec);\n continue;\n }\n importedSpecifiers.add(spec);\n }\n }\n\n if (violations.length > 0) {\n // Sort + de-dupe for deterministic error message ordering.\n const unique = [...new Set(violations)].sort();\n this.error(\n `[ethisys-contract-b] Worker bundle imports specifier(s) outside the frozen import-map ` +\n `allowlist: ${unique.map(s => `\"${s}\"`).join(\", \")}. ` +\n `Allowed bare specifiers: ${CONTRACT_B_IMPORT_MAP_ALLOWLIST.map(s => `\"${s}\"`).join(\", \")}.`,\n );\n }\n\n // Sort the resolved entries so the emitted manifest is deterministic\n // across builds — content-hashable downstream without spurious churn.\n const resolvedEntries = [...importedSpecifiers].sort();\n\n const workerBundleManifest = {\n version: 1,\n renderMode: \"remote-runtime\",\n worker: { entry: workerEntryRel },\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}worker-bundle.json`,\n source: JSON.stringify(workerBundleManifest),\n });\n\n // The import-map manifest — the host fetches this at extension activation\n // time to auto-derive the frozen `IMPORT_MAP` the worker bootstrap\n // composes. Values are `null` to signal \"host fills in canonical URL at\n // serve time\" — the manifest is the SDK's authoritative list of which\n // entries the bundle declares it consumes, not a URL table.\n const importMapManifest = {\n version: 1,\n // Authoring contract: the bundle's bare-specifier surface area, in\n // sorted order, restricted to the frozen allowlist.\n imports: Object.fromEntries(resolvedEntries.map(spec => [spec, null])),\n // Mirror the canonical allowlist so consumers diffing manifests\n // across plugin versions can see the contract the build verified\n // against without re-reading SDK source.\n allowlist: [...CONTRACT_B_IMPORT_MAP_ALLOWLIST],\n };\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}worker-bundle.import-map.json`,\n source: JSON.stringify(importMapManifest),\n });\n },\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize, sep } from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport type { Plugin } from \"vite\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * A single PlatformReact page declaration extracted from\n * `ui.platformReactPages[]` in the manifest. Aligns with the typed interface\n * defined in `ethisyscore-protocol` RFC 0003.\n *\n * - `id` is the host-side page identifier and the basename of the emitted\n * bundle (e.g. `id: \"dashboard\"` → `platform-react/dashboard.js`).\n * - `moduleSpecifier` is a host-origin relative path to the page module — the\n * plugin author's source entry that Rollup bundles.\n * - `exportName` is the named export Rollup keeps live in the bundle. The host\n * loader reads `bundle[exportName]` at mount time.\n * - `title` is an optional display label for the host's surface chrome.\n */\nexport interface PlatformReactPageDeclaration {\n id?: string;\n moduleSpecifier?: string;\n exportName?: string;\n title?: string;\n [key: string]: unknown;\n}\n\n/**\n * The subset of a manifest this pass consumes. Manifests are tolerated as a\n * superset — extra fields are ignored so newer-schema manifests still load.\n */\nexport interface PlatformReactManifest {\n type?: string;\n ui?: {\n platformReactPages?: PlatformReactPageDeclaration[];\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\n/**\n * Author-facing options for the PlatformReact Vite pass.\n */\nexport interface PlatformReactPluginOptions {\n /**\n * Root directory the manifest path is resolved against. When omitted,\n * Vite's `configResolved` populates it from `config.root`.\n */\n root?: string;\n /**\n * Manifest path. Relative paths resolve against `root`. Defaults to\n * `feature.manifest.json`.\n */\n manifestPath?: string;\n /**\n * Output prefix for emitted page assets and the companion manifest.\n * Defaults to `platform-react/`.\n */\n outputPrefix?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nconst ID_REGEX = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i;\n\n/** Reject path traversal, absolute paths, and remote URLs in author refs. */\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n/** Normalise Windows backslashes for the Rollup input table. */\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\ninterface ResolvedPage {\n id: string;\n exportName: string;\n title: string | null;\n moduleSpecifierRel: string;\n moduleSpecifierAbs: string;\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Build-time Vite/Rollup plugin pass for EthisysCore PlatformReact pages\n * (RFC 0003: the high-trust, host-extension tier). For each entry under\n * `ui.platformReactPages[]` in the manifest, registers a Rollup input that\n * emits an ESM bundle the host loads via `import()` at surface mount time.\n *\n * Behaviour:\n * - For each declared page: registers `{ \"platform-react/<id>\": <moduleSpecifier> }`\n * in Rollup's input table. Output is forced to `format: \"es\"` and\n * `inlineDynamicImports: true` so each page ships as ONE bundled module.\n * - Emits a `platform-react/platform-react-pages.json` companion asset listing\n * the declared pages so the host (and the `.ccpkg` packaging step) can\n * inspect what the build produced.\n * - When `ui.platformReactPages` is absent or empty: the pass is a no-op.\n * Composition is expected — the recommended template registers this pass\n * alongside Contract A / Contract B so a single Vite config covers every\n * render mode.\n *\n * Origin enforcement of the bundle URL at runtime is the host's responsibility\n * (see `PlatformReactSurfaceMount.tsx` in `coreconnect-web`). This pass only\n * blocks remote/absolute paths at the manifest layer so a malformed manifest\n * fails fast.\n */\nexport function ethisysPlatformReactPlugin(\n options: PlatformReactPluginOptions = {},\n): Plugin {\n const explicitRoot = options.root;\n const manifestRel = options.manifestPath ?? \"feature.manifest.json\";\n const outputPrefix = (options.outputPrefix ?? \"platform-react/\")\n .replace(/\\/+$/, \"/\")\n .replace(/^\\/+/, \"\");\n\n let resolvedRoot: string;\n let manifestAbsPath: string;\n let pages: ResolvedPage[] = [];\n\n function resolveRoot(): string {\n if (resolvedRoot) {\n return resolvedRoot;\n }\n // Vite hasn't called configResolved yet (or this plugin is being driven\n // outside Vite — e.g. a unit test that only invokes the validation\n // helper). Fall back to the explicit option then cwd. configResolved\n // will overwrite this with the correct Vite-resolved root when it\n // fires, before validate() is called for real.\n resolvedRoot = explicitRoot ?? process.cwd();\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n return resolvedRoot;\n }\n\n function readManifest(): PlatformReactManifest | null {\n resolveRoot();\n if (!existsSync(manifestAbsPath)) {\n return null;\n }\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n try {\n return JSON.parse(raw) as PlatformReactManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-platform-react] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n }\n\n /**\n * Validate the manifest and resolve each page's absolute source path.\n * Idempotent — repeated invocations rebuild from a fresh manifest read.\n */\n function validate(): void {\n pages = [];\n\n const manifest = readManifest();\n if (manifest === null) {\n return;\n }\n const declared = manifest.ui?.platformReactPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n return;\n }\n\n const seenIds = new Set<string>();\n\n for (let i = 0; i < declared.length; i++) {\n const decl = declared[i];\n const where = `ui.platformReactPages[${i}]`;\n\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id is required (non-empty string).`,\n );\n }\n if (!ID_REGEX.test(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id \"${decl.id}\" must match [a-z0-9_-]+ (URL-safe; case-insensitive).`,\n );\n }\n if (seenIds.has(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] Duplicate page id \"${decl.id}\".`,\n );\n }\n seenIds.add(decl.id);\n\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier is required (non-empty relative path).`,\n );\n }\n assertHostOriginRelativePath(decl.moduleSpecifier, `${where}.moduleSpecifier`);\n\n const absPath = resolve(resolvedRoot, decl.moduleSpecifier);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier \"${decl.moduleSpecifier}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n\n const exportName =\n typeof decl.exportName === \"string\" && decl.exportName.length > 0\n ? decl.exportName\n : \"default\";\n\n pages.push({\n id: decl.id,\n exportName,\n title: typeof decl.title === \"string\" && decl.title.length > 0 ? decl.title : null,\n moduleSpecifierRel: decl.moduleSpecifier,\n moduleSpecifierAbs: absPath,\n });\n }\n }\n\n let isBuild = false;\n\n return {\n name: \"ethisys-platform-react\",\n // `pre` ordering: validation should fire before user-supplied plugins.\n enforce: \"pre\",\n\n /**\n * Force ESM single-module output per page. Output options don't depend on\n * the resolved root, so they're safe to declare here — `config()` runs\n * before `configResolved()`. The Rollup input table is added later in\n * `configResolved()` once Vite has populated `resolvedRoot` correctly.\n */\n config(_config, { command }) {\n if (command !== \"build\") {\n return;\n }\n return {\n build: {\n rollupOptions: {\n // CRITICAL: single-file ESM output per page. The host loads each\n // page via `import(url)` at mount time and reads the declared\n // `exportName` from the resulting module namespace. Chunk-split\n // output would break that contract because the host has no\n // import-map surface to resolve sibling chunks.\n output: {\n format: \"es\",\n inlineDynamicImports: true,\n entryFileNames: `${outputPrefix}[name].js`,\n chunkFileNames: `${outputPrefix}[name]-[hash].js`,\n assetFileNames: `${outputPrefix}[name][extname]`,\n },\n // Auto-externalise the host-ui-externals specifier so the host's\n // module-registry rewriter resolves it to the live `@coreconnect/gogo-ui`\n // instance at runtime — Tier T remotes never ship their own Gogo copy.\n external: [\"@ethisyscore/host-ui-externals\"],\n },\n },\n };\n },\n\n /**\n * Resolve the actual root Vite is using (which may differ from\n * `process.cwd()`), validate the manifest against it, and mutate the\n * resolved config's Rollup input table so each declared page becomes a\n * build entry. Mutation in `configResolved` is the standard Vite-plugin\n * pattern for input contributions that depend on the resolved root —\n * `config()` runs too early to know the real value.\n */\n configResolved(config) {\n isBuild = config.command === \"build\";\n if (!explicitRoot) {\n resolvedRoot = config.root;\n manifestAbsPath = isAbsolute(manifestRel)\n ? manifestRel\n : resolve(resolvedRoot, manifestRel);\n }\n if (!isBuild) {\n return;\n }\n\n validate();\n if (pages.length === 0) {\n return;\n }\n\n const input: Record<string, string> = {};\n for (const page of pages) {\n // Input key = bare page id. The `outputPrefix` is applied by\n // `entryFileNames` so the final output is `<outputPrefix><id>.js`.\n input[page.id] = slash(page.moduleSpecifierAbs);\n }\n\n // Merge into Vite's resolved rollupOptions.input. The existing value\n // may be undefined, a single entry path, an array of entries, or an\n // already-keyed object — handle all four shapes so coexistence with\n // other Vite plugins (Contract A / Contract B passes that declare\n // their own entries) is non-destructive.\n //\n // Vite's `ResolvedConfig.build` is typed `readonly` in its public\n // declarations. The runtime object is mutable — Vite plugins that\n // need to contribute Rollup inputs from `configResolved` (which\n // requires the resolved root) widely follow this mutation pattern.\n // Cast through a writable view to bypass the type-level readonly\n // check; runtime semantics are unchanged.\n const writable = config as unknown as {\n build?: {\n rollupOptions?: {\n input?: Record<string, string> | string | string[];\n };\n };\n };\n writable.build ??= {};\n writable.build.rollupOptions ??= {};\n const rollupOptions = writable.build.rollupOptions;\n const existing = rollupOptions.input;\n if (existing && typeof existing === \"object\" && !Array.isArray(existing)) {\n rollupOptions.input = { ...(existing as Record<string, string>), ...input };\n } else if (typeof existing === \"string\") {\n rollupOptions.input = { _entry: existing, ...input };\n } else if (Array.isArray(existing)) {\n const indexed: Record<string, string> = {};\n existing.forEach((entry, idx) => {\n indexed[`_entry${idx}`] = entry;\n });\n rollupOptions.input = { ...indexed, ...input };\n } else {\n rollupOptions.input = input;\n }\n },\n\n buildStart() {\n // Re-validate at every build invocation — buildStart is called once per\n // build (including each watch cycle) so the author sees fresh feedback\n // after editing the manifest. resolvedRoot is already set by\n // configResolved at this point.\n validate();\n },\n\n /**\n * Emit the companion `platform-react-pages.json` listing every declared\n * page. The `.ccpkg` packaging step (and the host's runtime loader) read\n * this file to discover which page modules ship in the bundle without\n * having to re-parse the manifest.\n */\n generateBundle(_options, bundle) {\n if (pages.length === 0) {\n return;\n }\n\n // ── Per-asset SHA-256 digest map (WI 4858 sub-plan 3) ──────────\n // Hash EVERY emitted chunk (not just entries) so the host's verified\n // loader can check each asset against the manifest's `assetDigests`\n // before evaluation. The build forces `inlineDynamicImports: true`\n // (see `config()`), collapsing each page to a single chunk; if that is\n // ever relaxed, every emitted chunk URL MUST still be routed through the\n // host's `verifyAndLoadPlatformReactBundle` with this full map.\n const digests: Array<{ path: string; sha256: string }> = [];\n for (const chunk of Object.values(bundle ?? {})) {\n if ((chunk as { type?: string }).type !== \"chunk\") {\n continue;\n }\n // Rollup `OutputChunk` exposes `code` (string) + `fileName`. Cast\n // through unknown because the union narrows on `type`.\n const code = (chunk as unknown as { code: string }).code;\n const fileName = (chunk as unknown as { fileName: string }).fileName;\n const hash = createHash(\"sha256\").update(code, \"utf8\").digest(\"hex\");\n digests.push({ path: fileName, sha256: hash });\n }\n\n const summary = {\n pages: pages.map((p) => ({\n id: p.id,\n exportName: p.exportName,\n title: p.title,\n bundlePath: `${outputPrefix}${p.id}.js`,\n source: p.moduleSpecifierRel,\n })),\n };\n\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}platform-react-pages.json`,\n source: JSON.stringify(summary, null, 2),\n });\n\n this.emitFile({\n type: \"asset\",\n fileName: `${outputPrefix}platform-react-digest-map.json`,\n source: JSON.stringify({ digests }, null, 2),\n });\n },\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { resolve, isAbsolute, normalize } from \"node:path\";\nimport type {\n PlatformReactManifest,\n PlatformReactPageDeclaration,\n} from \"./page-bundles\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/**\n * A fully-validated PlatformReact page declaration. All fields are guaranteed\n * present (no `undefined`), `exportName` is defaulted to `\"default\"`, and the\n * `moduleSpecifier` is guaranteed to exist on disk when `verifyOnDisk: true`\n * was passed to {@link parsePlatformReactPages}.\n */\nexport interface ResolvedPlatformReactPage {\n id: string;\n moduleSpecifier: string;\n exportName: string;\n title: string | null;\n}\n\n/**\n * Options for {@link parsePlatformReactPages}.\n */\nexport interface ParsePlatformReactPagesOptions {\n /**\n * Root directory the manifest path and the page module specifiers are\n * resolved against. Defaults to `process.cwd()`.\n */\n root?: string;\n /**\n * When `true`, every declared `moduleSpecifier` must exist on disk (relative\n * to {@link root}). The default is `false` so the helper can be used to\n * snapshot-test a manifest without checking-out the page source files.\n */\n verifyOnDisk?: boolean;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nconst ID_REGEX = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i;\n\nfunction assertHostOriginRelativePath(value: string, label: string): void {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a remote URL.`,\n );\n }\n if (/^(data|blob|javascript):/i.test(value)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be a host-origin relative path, not a ${value.split(\":\")[0]}: URL.`,\n );\n }\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.split(/[\\\\/]/).includes(\"..\")) {\n throw new Error(\n `[ethisys-platform-react] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n// ── Public API ─────────────────────────────────────────────────────\n\n/**\n * Parse + validate `ui.platformReactPages[]` declarations from a manifest\n * file. Designed for plugin authors writing Vitest tests against their own\n * manifest — the helper applies the same shape and uniqueness rules the\n * build-time Vite pass enforces, so a passing unit test gives the same\n * guarantee a green build would.\n *\n * Returns an empty array when the manifest does not exist OR does not\n * declare `ui.platformReactPages` OR declares it as an empty array.\n *\n * Throws on any malformed declaration. The thrown message matches the\n * build-time error so a failing test reads identically to a failing build.\n *\n * @example\n * ```ts\n * import { parsePlatformReactPages } from \"@ethisyscore/vite-plugin\";\n *\n * test(\"manifest declares dashboard and admin pages\", () => {\n * const pages = parsePlatformReactPages(\"./feature.manifest.json\");\n * expect(pages).toEqual([\n * { id: \"dashboard\", moduleSpecifier: \"src/pages/Dashboard.tsx\", exportName: \"default\", title: \"Dashboard\" },\n * { id: \"admin\", moduleSpecifier: \"src/pages/Admin.tsx\", exportName: \"AdminPage\", title: null },\n * ]);\n * });\n * ```\n */\nexport function parsePlatformReactPages(\n manifestPath: string,\n options: ParsePlatformReactPagesOptions = {},\n): ResolvedPlatformReactPage[] {\n const root = options.root ?? process.cwd();\n const verifyOnDisk = options.verifyOnDisk ?? false;\n const manifestAbsPath = isAbsolute(manifestPath)\n ? manifestPath\n : resolve(root, manifestPath);\n\n if (!existsSync(manifestAbsPath)) {\n return [];\n }\n\n let manifest: PlatformReactManifest;\n try {\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n manifest = JSON.parse(raw) as PlatformReactManifest;\n } catch (e) {\n throw new Error(\n `[ethisys-platform-react] Failed to parse manifest at \"${manifestAbsPath}\": ${(e as Error).message}`,\n );\n }\n\n const declared = manifest.ui?.platformReactPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n return [];\n }\n\n const result: ResolvedPlatformReactPage[] = [];\n const seenIds = new Set<string>();\n\n for (let i = 0; i < declared.length; i++) {\n const decl: PlatformReactPageDeclaration = declared[i];\n const where = `ui.platformReactPages[${i}]`;\n\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id is required (non-empty string).`,\n );\n }\n if (!ID_REGEX.test(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.id \"${decl.id}\" must match [a-z0-9_-]+ (URL-safe; case-insensitive).`,\n );\n }\n if (seenIds.has(decl.id)) {\n throw new Error(\n `[ethisys-platform-react] Duplicate page id \"${decl.id}\".`,\n );\n }\n seenIds.add(decl.id);\n\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier is required (non-empty relative path).`,\n );\n }\n assertHostOriginRelativePath(decl.moduleSpecifier, `${where}.moduleSpecifier`);\n\n if (verifyOnDisk) {\n const absPath = resolve(root, decl.moduleSpecifier);\n if (!existsSync(absPath)) {\n throw new Error(\n `[ethisys-platform-react] ${where}.moduleSpecifier \"${decl.moduleSpecifier}\" does not exist on disk (resolved: ${absPath}).`,\n );\n }\n }\n\n result.push({\n id: decl.id,\n moduleSpecifier: decl.moduleSpecifier,\n exportName:\n typeof decl.exportName === \"string\" && decl.exportName.length > 0\n ? decl.exportName\n : \"default\",\n title:\n typeof decl.title === \"string\" && decl.title.length > 0\n ? decl.title\n : null,\n });\n }\n\n return result;\n}\n\n","import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\nimport type { InlineConfig, Plugin } from \"vite\";\n\n// ── The PlatformReact host-realm contract (shared defaults) ────────\n//\n// A PlatformReact page is ONE self-contained ESM bundle the host loads via\n// `import(url)` at mount time. These two lists are the build-side half of the\n// host contract; both are overridable, but every migration starts from them.\n\n/**\n * Specifiers the host realm provides at runtime — never bundled into a page.\n * A `components/ui/*` abstraction that re-exports `@mui/material` therefore\n * costs zero bundle weight and shares the host's MUI singleton + theme.\n */\nexport const PLATFORM_REACT_EXTERNALS: readonly string[] = [\n \"react\",\n \"react/jsx-runtime\",\n \"react-dom\",\n \"@mui/material\",\n \"@mui/icons-material\",\n \"@emotion/react\",\n \"@emotion/styled\",\n \"date-fns\",\n \"@ethisyscore/components-react\",\n \"@ethisyscore/extension-runtime\",\n \"@ethisyscore/extension-runtime/plugin\",\n];\n\n/**\n * Bundled deps that MUST resolve to a single copy. When a bundled dep (e.g.\n * `@tanstack/react-query`) is imported by BOTH the plugin's own hooks and the\n * SDK foundation (aliased cross-repo to a sibling `dist`), the bundler otherwise\n * resolves two copies — one per repo's `node_modules`. Two module instances =\n * two React contexts, so a provider in one is invisible to a consumer in the\n * other (the classic \"No QueryClient set\"). Pin them to one copy.\n */\nexport const PLATFORM_REACT_DEDUPE: readonly string[] = [\n \"@tanstack/react-query\",\n \"react\",\n \"react-dom\",\n \"@ethisyscore/extension-runtime\",\n];\n\nconst DEFAULT_OUT_DIR = \"dist\";\nconst DEFAULT_OUTPUT_PREFIX = \"platform-react\";\nconst DEFAULT_DEFINE_PLUGIN_PAGE = \"@/app/definePluginPage\";\nconst DEFAULT_SRC_DIR = \"src\";\nconst DEFAULT_ALIAS_PREFIX = \"@\";\nconst SUMMARY_FILENAME = \"platform-react-pages.json\";\nconst DIGEST_MAP_FILENAME = \"platform-react-digest-map.json\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/** A `resolve.alias` entry (string or regex find), as Vite accepts. */\nexport interface PlatformReactAlias {\n find: string | RegExp;\n replacement: string;\n}\n\n/**\n * One surface declared in `feature.manifest.json` (`ui.platformReactPages[]`).\n * `views` is the page's `useView` manifest slice — the adapter-view modules it\n * renders by name (`{ DayView: \"src/adapter/<feature>/DayView.tsx\" }`). It rides\n * along as an open extra field the SDK's manifest readers ignore.\n */\nexport interface PlatformReactPageInput {\n id: string;\n moduleSpecifier: string;\n exportName?: string;\n title?: string | null;\n views?: Record<string, string>;\n}\n\n/** The fully-resolved per-page build context handed to the (injectable) builder. */\nexport interface PlatformReactBuildContext {\n pageId: string;\n /** Virtual entry module id (`\\0virtual:surface/<id>`). */\n entryId: string;\n /** Rollup plugin that resolves + loads the synthesised virtual entry. */\n surfacePlugin: Plugin;\n root: string;\n outDir: string;\n outputPrefix: string;\n external: readonly string[];\n dedupe: readonly string[];\n alias: PlatformReactAlias[];\n plugins: Plugin[];\n target: string;\n minify: boolean;\n sourcemap: boolean;\n}\n\n/** Low-level Vite `build` function. Defaults to a dynamic `import(\"vite\")`. */\nexport type ViteBuildFn = (config: InlineConfig) => Promise<unknown>;\n\n/** Injectable per-page builder. Defaults to a real Vite library build. */\nexport type PlatformReactViteBuild = (ctx: PlatformReactBuildContext) => Promise<void>;\n\nexport interface BuildPlatformReactPagesOptions {\n /** Root the manifest + `src/…` paths resolve against. Default `process.cwd()`. */\n root?: string;\n /** Manifest path (relative to `root`). Default `feature.manifest.json`. */\n manifestPath?: string;\n /** Inline manifest object (test injection). When omitted, read from disk. */\n manifest?: unknown;\n /** Output directory the bundles + companion JSON land in. Default `dist`. */\n outDir?: string;\n /** Sub-directory + summary/digest key prefix. Default `platform-react`. */\n outputPrefix?: string;\n /** Plugin-specific `resolve.alias` entries (contracts, router shim, `@/`, …). */\n alias?: PlatformReactAlias[];\n /** Plugin-specific Vite plugins (e.g. `react()`, `tailwindcss()`). */\n plugins?: Plugin[];\n /** Bundled deps to dedupe. Default {@link PLATFORM_REACT_DEDUPE}. */\n dedupe?: readonly string[];\n /** Host externals. Default {@link PLATFORM_REACT_EXTERNALS}. */\n external?: readonly string[];\n /** Module specifier the generated entry imports `definePluginPage` from. */\n definePluginPageSpecifier?: string;\n /** Source dir stripped when rewriting manifest paths to the alias. Default `src`. */\n srcDir?: string;\n /** Alias prefix manifest `src/…` paths are rewritten to. Default `@` (→ `@/…`). */\n aliasPrefix?: string;\n /** Rollup build target. Default `es2022`. */\n target?: string;\n /** Minify output. Default `false` (digest stability + debuggability). */\n minify?: boolean;\n /** Emit sourcemaps. Default `true`. */\n sourcemap?: boolean;\n /** Wipe `outDir` before building. Default `true`. */\n clean?: boolean;\n /** Progress logger. Default `console`. */\n logger?: Pick<Console, \"log\" | \"warn\">;\n /** Low-level Vite `build` (production override so the CONSUMER's vite is used). */\n viteBuild?: ViteBuildFn;\n /** Injectable per-page builder (test injection — skips Vite entirely). */\n build?: PlatformReactViteBuild;\n /** Injectable bundle reader for digesting. Default `fs.readFileSync` (utf-8). */\n readFile?: (path: string) => string;\n /** Injectable file writer. Default `fs.writeFileSync` (creating dirs). */\n writeFile?: (path: string, contents: string) => void;\n}\n\nexport interface PlatformReactBuildSummary {\n pages: Array<{ id: string; exportName: string; title: string | null; bundlePath: string; source: string }>;\n digests: Array<{ path: string; sha256: string }>;\n summaryPath: string | null;\n digestMapPath: string | null;\n}\n\n// ── Generic transforms (exported for focused unit tests) ───────────\n\n/**\n * Rollup output pass: rewrite aliased named imports from host externals into the\n * namespace-import form the host's PlatformReact loader accepts.\n *\n * esbuild emits `import { Dialog as Dialog$1 } from \"@mui/material\"` to\n * deconflict a name collision (an adapter view imports MUI `Dialog` directly\n * while a feature component pulls in the `components/ui/dialog` wrapper of the\n * same name). The host loader handles `import * as X`, plain `import { Y }`,\n * default imports, and aliased EXPORTS — but throws \"Unexpected identifier 'as'\"\n * on aliased named IMPORTS `{ X as Y }`. In a final `inlineDynamicImports`\n * bundle every remaining `import { … } from \"…\"` is an EXTERNAL import, so\n * rewriting any that contain `as` into `import * as ns from \"…\"; const local =\n * ns.imported, …;` is safe and removes the only construct the loader rejects.\n * Runs in `renderChunk`, before the host-verified digest is computed.\n */\nexport function rewriteAliasedExternalImports(): Plugin {\n return {\n name: \"rewrite-aliased-external-imports\",\n renderChunk(code: string) {\n let counter = 0;\n let changed = false;\n const out = code.replace(\n // Optional default binding (`import Foo, { … }`) then the named braces.\n /\\bimport\\s+(?:([\\w$]+)\\s*,\\s*)?\\{([^{}]*)\\}\\s*from\\s*(\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*')\\s*;?/g,\n (full, def: string | undefined, specs: string, mod: string) => {\n if (!/\\sas\\s/.test(specs)) return full;\n changed = true;\n const ns = `__ns_imp_${counter++}`;\n const decls = specs\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n .map((s) => {\n const [imported, local] = s.split(/\\s+as\\s+/).map((t) => t.trim());\n return `${local ?? imported} = ${ns}.${imported}`;\n })\n .join(\", \");\n // Keep any default import as-is (no alias → host-safe), namespace the named part.\n const defPart = def ? `import ${def} from ${mod}; ` : \"\";\n return `${defPart}import * as ${ns} from ${mod}; const ${decls};`;\n },\n );\n return changed ? { code: out, map: null } : null;\n },\n };\n}\n\n/**\n * Synthesise one isolated PlatformReact entry per surface straight from its\n * manifest declaration: `definePluginPage(Page, { …views })`, importing ONLY\n * that surface's page (`moduleSpecifier`) + adapter views (`views`) so each\n * bundle stays self-contained. Returned as a Rollup virtual module so there are\n * no physical per-page entry files — the manifest is the single source of truth.\n * `src/…` paths are rewritten to the alias the build resolves (e.g. `@/…`).\n */\nexport function virtualPageEntry(\n page: PlatformReactPageInput,\n config: { definePluginPageSpecifier: string; toAlias: (p: string) => string },\n): { id: string; plugin: Plugin } {\n const VIRTUAL_ID = `\\0virtual:surface/${page.id}`;\n const views = page.views ?? {};\n const names = Object.keys(views);\n const viewImports = names\n .map((n) => `import { ${n} } from ${JSON.stringify(config.toAlias(views[n]))};`)\n .join(\"\\n\");\n const src =\n `import Page from ${JSON.stringify(config.toAlias(page.moduleSpecifier))};\\n` +\n `${viewImports}\\n` +\n `import { definePluginPage } from ${JSON.stringify(config.definePluginPageSpecifier)};\\n` +\n `export default definePluginPage(Page, { ${names.join(\", \")} });\\n`;\n return {\n id: VIRTUAL_ID,\n plugin: {\n name: `virtual-surface-${page.id}`,\n resolveId: (id: string) => (id === VIRTUAL_ID ? VIRTUAL_ID : null),\n load: (id: string) => (id === VIRTUAL_ID ? src : null),\n },\n };\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction defaultWriteFile(path: string, contents: string): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, contents);\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction readManifest(options: BuildPlatformReactPagesOptions, root: string): unknown {\n if (options.manifest !== undefined) {\n return options.manifest;\n }\n const rel = options.manifestPath ?? \"feature.manifest.json\";\n const abs = isAbsolute(rel) ? rel : resolve(root, rel);\n if (!existsSync(abs)) {\n return null;\n }\n const raw = readFileSync(abs, \"utf-8\");\n try {\n return JSON.parse(raw);\n } catch (e) {\n throw new Error(\n `[ethisys-platform-react] Failed to parse manifest at \"${abs}\": ${(e as Error).message}`,\n );\n }\n}\n\n/** Build the real per-page Vite config and run it through the (injectable) vite build. */\nfunction makeDefaultBuild(viteBuild?: ViteBuildFn): PlatformReactViteBuild {\n return async (ctx) => {\n const build: ViteBuildFn = viteBuild ?? (await import(\"vite\")).build;\n await build({\n root: ctx.root,\n configFile: false,\n plugins: [ctx.surfacePlugin, ...ctx.plugins, rewriteAliasedExternalImports()],\n resolve: {\n dedupe: [...ctx.dedupe],\n alias: ctx.alias,\n },\n build: {\n target: ctx.target,\n outDir: ctx.outDir,\n emptyOutDir: false,\n assetsDir: \"\",\n minify: ctx.minify,\n sourcemap: ctx.sourcemap,\n rollupOptions: {\n input: { [ctx.pageId]: ctx.entryId },\n preserveEntrySignatures: \"strict\",\n external: [...ctx.external],\n output: {\n format: \"es\",\n inlineDynamicImports: true,\n entryFileNames: `${ctx.outputPrefix}/[name].js`,\n chunkFileNames: `${ctx.outputPrefix}/[name]-[hash].js`,\n assetFileNames: `${ctx.outputPrefix}/[name][extname]`,\n },\n },\n },\n logLevel: \"warn\",\n });\n };\n}\n\n// ── Orchestration ──────────────────────────────────────────────────\n\n/**\n * Build every `ui.platformReactPages[]` surface as its own self-contained ESM\n * bundle and emit the companion `platform-react-pages.json` summary + the\n * per-asset SHA-256 `platform-react-digest-map.json` the host's verified loader\n * and the `.ccpkg` packaging step read.\n *\n * Each PlatformReact page must be ONE bundle (`inlineDynamicImports: true`), and\n * Rollup rejects that with more than one input — so this runs one Vite sub-build\n * per surface, each with a single synthesised virtual entry (see\n * {@link virtualPageEntry}). The generic seams (host externals, dedupe, the\n * host-loader aliased-import rewrite, the digest/summary contract) live here;\n * the plugin supplies only its `alias` entries + `plugins` (and, in production,\n * its own `viteBuild` so the consumer's Vite is used, not the SDK's).\n *\n * No-op (returns empty) when no pages are declared.\n */\nexport async function buildPlatformReactPages(\n options: BuildPlatformReactPagesOptions = {},\n): Promise<PlatformReactBuildSummary> {\n const root = options.root ?? process.cwd();\n const logger = options.logger ?? console;\n const manifest = readManifest(options, root);\n\n const declared = (manifest as { ui?: { platformReactPages?: unknown[] } } | null)?.ui\n ?.platformReactPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n logger.warn(\"[build-pages] no platformReactPages declared — nothing to build\");\n return { pages: [], digests: [], summaryPath: null, digestMapPath: null };\n }\n\n // Validate the fields this pass consumes (the open `views` field rides along).\n const seen = new Set<string>();\n const pages: PlatformReactPageInput[] = declared.map((raw, i) => {\n const decl = raw as PlatformReactPageInput;\n if (typeof decl?.id !== \"string\" || decl.id.length === 0) {\n throw new Error(`[build-pages] ui.platformReactPages[${i}].id is required (non-empty string).`);\n }\n if (seen.has(decl.id)) {\n throw new Error(`[build-pages] Duplicate page id \"${decl.id}\".`);\n }\n seen.add(decl.id);\n if (typeof decl.moduleSpecifier !== \"string\" || decl.moduleSpecifier.length === 0) {\n throw new Error(`[build-pages] surface \"${decl.id}\" has no moduleSpecifier in the manifest.`);\n }\n return decl;\n });\n\n const outDir = options.outDir ?? DEFAULT_OUT_DIR;\n const outDirAbs = isAbsolute(outDir) ? outDir : resolve(root, outDir);\n const outputPrefix = (options.outputPrefix ?? DEFAULT_OUTPUT_PREFIX).replace(/^\\/+|\\/+$/g, \"\");\n const outputPrefixDir = resolve(outDirAbs, outputPrefix);\n\n const external = options.external ?? PLATFORM_REACT_EXTERNALS;\n const dedupe = options.dedupe ?? PLATFORM_REACT_DEDUPE;\n const alias = options.alias ?? [];\n const plugins = options.plugins ?? [];\n const definePluginPageSpecifier = options.definePluginPageSpecifier ?? DEFAULT_DEFINE_PLUGIN_PAGE;\n const srcDir = options.srcDir ?? DEFAULT_SRC_DIR;\n const aliasPrefix = options.aliasPrefix ?? DEFAULT_ALIAS_PREFIX;\n const srcRe = new RegExp(`^${escapeRegExp(srcDir)}/`);\n const toAlias = (p: string) => `${aliasPrefix}/${p.replace(srcRe, \"\")}`;\n\n const write = options.writeFile ?? defaultWriteFile;\n const read = options.readFile ?? ((p: string) => readFileSync(p, \"utf-8\"));\n const runBuild = options.build ?? makeDefaultBuild(options.viteBuild);\n\n if (options.clean ?? true) {\n if (existsSync(outDirAbs)) {\n rmSync(outDirAbs, { recursive: true, force: true });\n }\n mkdirSync(outputPrefixDir, { recursive: true });\n }\n\n for (const page of pages) {\n const { id: entryId, plugin: surfacePlugin } = virtualPageEntry(page, {\n definePluginPageSpecifier,\n toAlias,\n });\n logger.log(`[build-pages] ${page.id} ← ${page.moduleSpecifier}`);\n await runBuild({\n pageId: page.id,\n entryId,\n surfacePlugin,\n root,\n outDir: outDirAbs,\n outputPrefix,\n external,\n dedupe,\n alias,\n plugins,\n target: options.target ?? \"es2022\",\n minify: options.minify ?? false,\n sourcemap: options.sourcemap ?? true,\n });\n }\n\n // Companion summary the host loader + `.ccpkg` packaging reads.\n const summaryPages = pages.map((p) => ({\n id: p.id,\n exportName: p.exportName ?? \"default\",\n title: p.title ?? null,\n bundlePath: `${outputPrefix}/${p.id}.js`,\n source: p.moduleSpecifier,\n }));\n const summaryPath = resolve(outputPrefixDir, SUMMARY_FILENAME);\n write(summaryPath, JSON.stringify({ pages: summaryPages }, null, 2));\n\n // Per-asset SHA-256 digest map. Hash each emitted bundle's UTF-8 bytes off\n // disk (one self-contained ESM chunk per page — `inlineDynamicImports`), keyed\n // by the dist-relative path, so the host's verified loader can check each\n // bundle before eval and packaging can lift these into `assetDigests`.\n const digests = pages\n .map((p) => `${outputPrefix}/${p.id}.js`)\n .sort()\n .map((relPath) => {\n const code = read(resolve(outDirAbs, relPath));\n return { path: relPath, sha256: createHash(\"sha256\").update(code, \"utf8\").digest(\"hex\") };\n });\n const digestMapPath = resolve(outputPrefixDir, DIGEST_MAP_FILENAME);\n write(digestMapPath, JSON.stringify({ digests }, null, 2));\n\n logger.log(\n `[build-pages] emitted ${pages.length} page(s) + summary + digest map (${digests.length} digests)`,\n );\n\n return { pages: summaryPages, digests, summaryPath, digestMapPath };\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve, sep } from \"node:path\";\nimport type { Plugin } from \"vite\";\n// Tier U manifest + integrity shapes are owned by the protocol SSOT (sub-plan 01 D1).\n// Consume them — do NOT re-declare a local copy.\nimport { AssetDigest, IframeSandboxPageDeclaration } from \"@ethisyscore/protocol\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\n/** One emitted artifact from a per-page Vite sub-build. */\nexport type IframeBuildOutputItem =\n | { type: \"chunk\"; fileName: string; code: string }\n | { type: \"asset\"; fileName: string; source: string | Uint8Array };\n\nexport interface IframeBuildResult {\n output: IframeBuildOutputItem[];\n}\n\n/** A single page handed to the (injectable) builder. */\nexport interface IframeBuildContext {\n id: string;\n title: string;\n entryPath: string;\n root: string;\n /** Per-page output directory (`<outputDir>/<id>`). */\n outDir: string;\n}\n\n/** Injectable per-page builder. Defaults to a real Vite library build. */\nexport type IframeViteBuild = (page: IframeBuildContext) => Promise<IframeBuildResult>;\n\nexport interface IframeSandboxPluginOptions {\n /** Root the manifest + entry paths resolve against. Defaults to Vite's resolved root / cwd. */\n root?: string;\n /** Manifest path (relative to `root`). Default `feature.manifest.json`. */\n manifestPath?: string;\n /** Output directory for per-page bundles + the digest map. Default `dist/iframe-sandbox`. */\n outputDir?: string;\n /** Inline manifest object (test injection). When omitted, the manifest is read from disk. */\n manifest?: unknown;\n /** Injectable per-page builder (test injection). When omitted, a real Vite build runs. */\n build?: IframeViteBuild;\n /** Injectable file writer (test injection). When omitted, writes via `fs` (creating dirs). */\n writeFile?: (path: string, contents: string) => void;\n}\n\nexport interface IframeSandboxBuildSummary {\n digests: Array<{ path: string; sha256: string }>;\n digestMapPath: string | null;\n}\n\nconst DEFAULT_MANIFEST = \"feature.manifest.json\";\nconst DEFAULT_OUTPUT_DIR = \"dist/iframe-sandbox\";\nconst DIGEST_MAP_FILENAME = \"iframe-sandbox-digest-map.json\";\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\nfunction defaultWriteFile(path: string, contents: string): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, contents);\n}\n\n/** Real per-page build via Vite's programmatic API. `vite` is an optional peer dep. */\nconst defaultBuild: IframeViteBuild = async (page) => {\n const { build } = await import(\"vite\");\n const result = await build({\n root: page.root,\n logLevel: \"warn\",\n build: {\n outDir: page.outDir,\n emptyOutDir: true,\n rollupOptions: {\n input: resolve(page.root, page.entryPath),\n },\n },\n });\n // `build()` returns RollupOutput | RollupOutput[] | RollupWatcher; the\n // library build (no watch) yields a single RollupOutput.\n const out = Array.isArray(result) ? result[0] : result;\n return { output: (out as unknown as IframeBuildResult).output };\n};\n\nfunction digestOf(item: IframeBuildOutputItem): string {\n const bytes = item.type === \"chunk\" ? item.code : item.source;\n return createHash(\"sha256\").update(bytes as string | Uint8Array).digest(\"hex\");\n}\n\nfunction readManifest(options: IframeSandboxPluginOptions, root: string): unknown {\n if (options.manifest !== undefined) {\n return options.manifest;\n }\n const rel = options.manifestPath ?? DEFAULT_MANIFEST;\n const abs = isAbsolute(rel) ? rel : resolve(root, rel);\n if (!existsSync(abs)) {\n return null;\n }\n const raw = readFileSync(abs, \"utf8\");\n try {\n return JSON.parse(raw);\n } catch (e) {\n throw new Error(`[ethisys-iframe-sandbox] Failed to parse manifest at \"${abs}\": ${(e as Error).message}`);\n }\n}\n\n// ── Orchestration (exposed for unit testing) ───────────────────────\n\n/**\n * Build each `ui.iframeSandboxPages[]` declaration as its own Vite app bundle and\n * emit a per-asset SHA-256 digest map in the SAME shape `ethisysPlatformReactPlugin`\n * produces (`{ digests: [{ path, sha256 }] }`). Tier U surfaces are independent\n * cross-origin apps, so each page is a separate sub-build under `<outputDir>/<id>/`;\n * every emitted artifact is hashed (and validated against the protocol `AssetDigest`\n * schema) so the edge integrity endpoint (sub-plan 5, Task 6) can verify served bytes.\n *\n * No-op when no pages are declared. Page shape is validated by the protocol\n * `IframeSandboxPageDeclaration` schema (a malformed entry rejects the build).\n */\nexport async function buildIframeSandboxPages(\n options: IframeSandboxPluginOptions = {},\n): Promise<IframeSandboxBuildSummary> {\n const root = options.root ?? process.cwd();\n const manifest = readManifest(options, root);\n\n const declared = (manifest as { ui?: { iframeSandboxPages?: unknown[] } } | null)?.ui?.iframeSandboxPages;\n if (!Array.isArray(declared) || declared.length === 0) {\n return { digests: [], digestMapPath: null };\n }\n\n // Validate every page against the protocol schema (SSOT) before building.\n const pages = declared.map((raw, i) => {\n try {\n return IframeSandboxPageDeclaration.parse(raw);\n } catch (e) {\n throw new Error(\n `[ethisys-iframe-sandbox] ui.iframeSandboxPages[${i}] is invalid: ${(e as Error).message}`,\n );\n }\n });\n\n const seen = new Set<string>();\n for (const p of pages) {\n if (seen.has(p.id)) {\n throw new Error(`[ethisys-iframe-sandbox] Duplicate iframe-sandbox page id \"${p.id}\".`);\n }\n seen.add(p.id);\n }\n\n const build = options.build ?? defaultBuild;\n const write = options.writeFile ?? defaultWriteFile;\n const outputDir = options.outputDir ?? DEFAULT_OUTPUT_DIR;\n const outDirAbs = isAbsolute(outputDir) ? outputDir : resolve(root, outputDir);\n\n const digests: Array<{ path: string; sha256: string }> = [];\n for (const page of pages) {\n const result = await build({\n id: page.id,\n title: page.title,\n entryPath: page.entryPath,\n root,\n outDir: resolve(outDirAbs, page.id),\n });\n for (const item of result.output) {\n const entry = { path: `${page.id}/${item.fileName}`, sha256: digestOf(item) };\n // The integrity entry conforms to the protocol AssetDigest contract.\n AssetDigest.parse(entry);\n digests.push(entry);\n }\n }\n\n const digestMapPath = resolve(outDirAbs, DIGEST_MAP_FILENAME);\n write(slash(digestMapPath), JSON.stringify({ digests }, null, 2));\n return { digests, digestMapPath };\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Tier U (iframe-sandbox) Vite build pass (WI 4858 sub-plan 5). Mirrors\n * `ethisysPlatformReactPlugin`: keyed off `ui.iframeSandboxPages[]` and a no-op\n * when absent, so a single Vite config can compose every render-mode pass.\n *\n * Unlike Tier T (ESM modules in the parent build), each Tier U page is an\n * independent cross-origin app — so the pass runs a separate Vite sub-build per\n * page in `closeBundle` and emits the integrity digest map the host verifies.\n */\nexport function ethisysIframeSandboxPlugin(options: IframeSandboxPluginOptions = {}): Plugin {\n let resolvedRoot = options.root;\n\n return {\n name: \"ethisys-iframe-sandbox\",\n enforce: \"pre\",\n\n configResolved(config) {\n if (!options.root) {\n resolvedRoot = config.root;\n }\n },\n\n async closeBundle() {\n await buildIframeSandboxPages({ ...options, root: options.root ?? resolvedRoot });\n },\n };\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport { isAbsolute, normalize, resolve, sep } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\n\n// ── Contract A (Wave 0): SDUI schema validation + emission ─────────\n//\n// Re-exports the Contract A pass so consumers can compose it alongside the\n// legacy manifest HTML-entry plugin (or use it on its own for host-rendered\n// plugins that ship no HTML at all).\nexport {\n ethisysContractAPlugin,\n type ContractAPluginOptions,\n type ContractAManifest,\n type ManifestResourceRef,\n type ManifestReactiveRuleRef,\n} from \"./contract-a/emit\";\nexport {\n validateDeclarativeResource,\n validateReactiveRule,\n type ValidationResult,\n type ValidationFailure,\n} from \"./contract-a/schema-validator\";\n\n// ── Contract B (Wave 1): Worker-bundle emission ────────────────────\n//\n// Re-export the Contract B pass so consumers can compose it alongside the\n// Contract A schema-validation pass. The two passes are non-interfering:\n// each pass keys off `renderMode` and exits early when the manifest is not\n// addressed to it. The recommended scaffold registers both plugins so a\n// manifest can switch render modes without changing its Vite config.\nexport {\n ethisysContractBPlugin,\n type ContractBPluginOptions,\n type ContractBManifest,\n CONTRACT_B_SEMANTIC_PRIMITIVES,\n CONTRACT_B_RUNTIME_IMPORTS,\n CONTRACT_B_IMPORT_MAP_ALLOWLIST,\n} from \"./contract-b/worker-bundle\";\n\n// ── PlatformReact pages (RFC 0003) ─────────────────────────────────\n//\n// Build pass for the high-trust host-extension tier. Reads\n// `ui.platformReactPages[]` from the manifest and emits one ESM bundle per\n// page. The host loads each bundle at surface mount time via `import(url)`\n// against the same-origin asset endpoint.\nexport {\n ethisysPlatformReactPlugin,\n type PlatformReactPluginOptions,\n type PlatformReactManifest,\n type PlatformReactPageDeclaration,\n} from \"./platform-react/page-bundles\";\n\n// Test-time helper for plugin authors who want to snapshot-test their\n// manifest's PlatformReact page declarations without spinning a Vite build.\n// Applies the same shape + uniqueness rules the build-time pass enforces.\nexport {\n parsePlatformReactPages,\n type ResolvedPlatformReactPage,\n type ParsePlatformReactPagesOptions,\n} from \"./platform-react/test-helpers\";\n\n// Multi-bundle orchestrator: one isolated Vite sub-build per declared page\n// (required because `inlineDynamicImports` is illegal with >1 Rollup input).\n// Owns the host externals, dedupe, the host-loader aliased-import rewrite, and\n// the digest/summary contract; the plugin supplies only its aliases + plugins.\n// Used by a plugin's `build-pages` script in place of a hand-rolled copy.\nexport {\n buildPlatformReactPages,\n rewriteAliasedExternalImports,\n virtualPageEntry,\n PLATFORM_REACT_EXTERNALS,\n PLATFORM_REACT_DEDUPE,\n type BuildPlatformReactPagesOptions,\n type PlatformReactBuildSummary,\n type PlatformReactBuildContext,\n type PlatformReactPageInput,\n type PlatformReactAlias,\n type PlatformReactViteBuild,\n type ViteBuildFn,\n} from \"./platform-react/build-pages\";\n\n// ── Tier U: iframe-sandbox pages (WI 4858 sub-plan 5) ──────────────\n//\n// Build pass for the cross-origin sandboxed tier. Reads `ui.iframeSandboxPages[]`\n// (typed by the protocol `IframeSandboxPageDeclaration`), runs one Vite sub-build\n// per page, and emits the per-asset SHA-256 digest map the edge integrity endpoint\n// verifies. No-op when no iframe-sandbox pages are declared.\nexport {\n ethisysIframeSandboxPlugin,\n buildIframeSandboxPages,\n type IframeSandboxPluginOptions,\n type IframeSandboxBuildSummary,\n type IframeViteBuild,\n type IframeBuildContext,\n type IframeBuildResult,\n type IframeBuildOutputItem,\n} from \"./iframeSandboxPlugin\";\n\n// ── Types ──────────────────────────────────────────────────────────\n\ninterface ManifestEntry {\n id?: string;\n entrypoint: string;\n source?: string;\n title?: string;\n template?: string;\n type?: string;\n route?: string;\n}\n\ninterface Manifest {\n ui?: {\n pages?: ManifestEntry[];\n surfaces?: ManifestEntry[];\n };\n}\n\nexport interface EthisysPluginOptions {\n /**\n * Path to the manifest file, relative to Vite's root directory.\n * @default \"../extension.manifest.json\"\n */\n manifestPath?: string;\n\n /**\n * ID of the mount element in the generated HTML.\n * React plugins use \"root\", Vue plugins use \"app\".\n * @default \"root\"\n */\n mountId?: string;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\n/** Normalize Windows backslashes to forward slashes for Vite/Rollup compatibility. */\nfunction slash(p: string): string {\n return sep === \"\\\\\" ? p.replace(/\\\\/g, \"/\") : p;\n}\n\n/** Escape HTML special characters to prevent XSS via manifest fields (e.g., title). */\nfunction escapeHtml(str: string): string {\n return str\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\n/** Validates a manifest path is relative with no traversal (cross-platform). */\nfunction assertSafeRelativePath(value: string, label: string): void {\n const normalized = normalize(value);\n if (isAbsolute(value) || isAbsolute(normalized)) {\n throw new Error(\n `[ethisys-manifest] ${label} \"${value}\" must be relative, not absolute.`,\n );\n }\n if (normalized.includes(\"..\")) {\n throw new Error(\n `[ethisys-manifest] ${label} \"${value}\" must not contain path traversal.`,\n );\n }\n}\n\n// ── Plugin ─────────────────────────────────────────────────────────\n\n/**\n * Vite plugin that reads `extension.manifest.json` (or a custom manifest path)\n * and auto-generates HTML entry points for all pages and surfaces that declare\n * a `source` field. No physical HTML files are required.\n *\n * Pages without a `source` field share the main entry point (SPA mode).\n * Surfaces (dialogs, panels) each get their own HTML shell.\n */\nexport function ethisysManifestPlugin(\n options: EthisysPluginOptions = {},\n): Plugin {\n const manifestRelPath = options.manifestPath ?? \"../extension.manifest.json\";\n const mountId = options.mountId ?? \"root\";\n let entries: ManifestEntry[] = [];\n let rootDir: string;\n let manifestAbsPath: string;\n // Cache generated HTML Promises to avoid stampede on concurrent requests (PERF-5)\n const htmlCache = new Map<string, Promise<string>>();\n\n // ── HTML generation ──────────────────────────────────────────────\n\n function generateHtml(entry: ManifestEntry): string {\n // Enterprise escape hatch: custom HTML template\n if (entry.template) {\n assertSafeRelativePath(entry.template, \"Template path\");\n\n const templatePath = resolve(rootDir, entry.template);\n if (existsSync(templatePath)) {\n let html = readFileSync(templatePath, \"utf-8\");\n\n // Validate template has a mount point (flexible — accepts any element/quoting)\n const safeMountId = escapeHtml(mountId);\n const mountPattern = new RegExp(`id=[\"']${safeMountId}[\"']`);\n if (!mountPattern.test(html)) {\n throw new Error(\n `[ethisys-manifest] Custom template \"${entry.template}\" must contain an element with id=\"${mountId}\".`,\n );\n }\n\n html = html.replaceAll(\"{{SOURCE}}\", escapeHtml(entry.source!));\n return html;\n }\n }\n\n // Default minimal HTML shell.\n // Uses relative src (no leading /) so Vite's transformIndexHtml resolves\n // it against config.base correctly for CDN/subdirectory deployments.\n const safeTitle = escapeHtml(entry.title ?? \"Plugin\");\n const safeSource = escapeHtml(entry.source!);\n const safeMountId = escapeHtml(mountId);\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${safeTitle}</title>\n </head>\n <body>\n <div id=\"${safeMountId}\"></div>\n <script type=\"module\" src=\"${safeSource}\"></script>\n </body>\n</html>`;\n }\n\n // ── Manifest parsing ─────────────────────────────────────────────\n\n function readManifest(): ManifestEntry[] {\n if (!existsSync(manifestAbsPath)) {\n return [];\n }\n\n const raw = readFileSync(manifestAbsPath, \"utf-8\");\n let manifest: Manifest;\n try {\n manifest = JSON.parse(raw) as Manifest;\n } catch {\n throw new Error(\n `[ethisys-manifest] Failed to parse manifest at \"${manifestAbsPath}\".`,\n );\n }\n\n const result: ManifestEntry[] = [];\n\n // Collect entries with a source field (pages + surfaces)\n for (const page of manifest.ui?.pages ?? []) {\n if (page.source) {\n result.push(page);\n }\n }\n for (const surface of manifest.ui?.surfaces ?? []) {\n if (surface.source) {\n result.push(surface);\n }\n }\n\n return result;\n }\n\n // ── Validation ───────────────────────────────────────────────────\n\n function validateEntries(): void {\n // Multiple routes can share the same entrypoint (SPA mode).\n // But each entrypoint can only have ONE source file.\n const entrypointSources = new Map<string, string>();\n\n for (const entry of entries) {\n const source = entry.source!;\n\n // Validate no path traversal or absolute paths (cross-platform)\n assertSafeRelativePath(source, \"Source path\");\n\n // Validate source file exists on disk\n const sourcePath = resolve(rootDir, source);\n if (!existsSync(sourcePath)) {\n throw new Error(\n `[ethisys-manifest] Source file \"${source}\" for entry \"${entry.entrypoint}\" does not exist.`,\n );\n }\n\n // Validate entrypoint → source uniqueness\n const existingSource = entrypointSources.get(entry.entrypoint);\n if (existingSource && existingSource !== source) {\n throw new Error(\n `[ethisys-manifest] Conflicting sources for entrypoint \"${entry.entrypoint}\": ` +\n `\"${existingSource}\" and \"${source}\". ` +\n `Only one source file can be mapped to a single entrypoint.`,\n );\n }\n entrypointSources.set(entry.entrypoint, source);\n }\n }\n\n // ── Vite Plugin Hooks ────────────────────────────────────────────\n\n return {\n name: \"ethisys-manifest\",\n enforce: \"pre\",\n\n config(config, { command }) {\n rootDir = config.root ?? process.cwd();\n manifestAbsPath = resolve(rootDir, manifestRelPath);\n entries = readManifest();\n\n if (entries.length === 0) {\n return;\n }\n\n validateEntries();\n\n // Inject Rollup inputs for build mode.\n // ALL entries are virtual — including index.html.\n if (command === \"build\") {\n const input: Record<string, string> = {};\n const seen = new Set<string>();\n\n for (const entry of entries) {\n if (seen.has(entry.entrypoint)) {\n continue;\n }\n seen.add(entry.entrypoint);\n\n const name = entry.entrypoint.replace(/\\.html$/, \"\");\n input[name] = slash(resolve(rootDir, entry.entrypoint));\n }\n\n return {\n build: {\n rollupOptions: {\n input,\n },\n },\n };\n }\n },\n\n // Dev server: intercept HTML requests and serve virtual HTML.\n // Pre-middleware — runs before Vite's built-in handlers.\n // Safe because we only respond to .html requests and SPA navigation;\n // module requests (/@vite/client, /@react-refresh, .ts/.tsx/.css files)\n // don't match our conditions and pass through to Vite's transform middleware.\n configureServer(server: ViteDevServer) {\n server.watcher.add(manifestAbsPath);\n\n server.middlewares.use(async (req, res, next) => {\n try {\n const url = req.url?.split(\"?\")[0] ?? \"\";\n const acceptsHtml = req.headers.accept?.includes(\"text/html\");\n\n // 1. Explicit .html or root requests → match against entry points\n if (url.endsWith(\".html\") || url === \"/\" || url === \"/index.html\") {\n const filename =\n url === \"/\" || url === \"/index.html\"\n ? \"index.html\"\n : url.slice(1);\n\n const entry = entries.find((e) => e.entrypoint === filename);\n if (entry) {\n // Cache the Promise to prevent stampede on concurrent requests (PERF-5)\n const cacheKey = `entry:${filename}`;\n if (!htmlCache.has(cacheKey)) {\n const rawHtml = generateHtml(entry);\n htmlCache.set(cacheKey, server.transformIndexHtml(url, rawHtml));\n }\n const html = await htmlCache.get(cacheKey)!;\n res.setHeader(\"Content-Type\", \"text/html\");\n res.statusCode = 200;\n res.end(html);\n return;\n }\n }\n\n // 2. SPA fallback: non-file navigation requests (e.g., /books/catalog\n // refreshed in the browser) → serve index.html for client-side routing.\n // Only triggers for requests that explicitly Accept text/html (browser\n // navigation), not module/asset requests which use Accept: */*.\n if (acceptsHtml && !url.includes(\".\")) {\n const mainEntry = entries.find(\n (e) => e.entrypoint === \"index.html\",\n );\n if (mainEntry) {\n // SPA uses entrypoint as cache key (not url) to avoid unbounded cache growth\n const cacheKey = \"spa:index.html\";\n if (!htmlCache.has(cacheKey)) {\n const rawHtml = generateHtml(mainEntry);\n htmlCache.set(cacheKey, server.transformIndexHtml(\"/\", rawHtml));\n }\n const html = await htmlCache.get(cacheKey)!;\n res.setHeader(\"Content-Type\", \"text/html\");\n res.statusCode = 200;\n res.end(html);\n return;\n }\n }\n\n next();\n } catch (err) {\n next(err);\n }\n });\n },\n\n // Watch manifest for changes during dev — reload entries on edit.\n // Entire handler is wrapped in try/catch so JSON syntax errors in the\n // manifest don't crash the dev server (common during active editing).\n handleHotUpdate({ file, server }) {\n if (slash(file) === slash(manifestAbsPath)) {\n try {\n entries = readManifest();\n validateEntries();\n // Invalidate HTML cache on manifest change (PERF-5)\n htmlCache.clear();\n } catch (e) {\n server.config.logger.error(String(e));\n return [];\n }\n\n server.config.logger.info(\n \"[ethisys-manifest] Manifest changed — reloading entries\",\n );\n server.hot.send({ type: \"full-reload\" });\n return [];\n }\n },\n\n // Build: resolve virtual HTML module IDs (no physical files exist on disk)\n resolveId(id) {\n const normalizedId = slash(id);\n const match = entries.find(\n (e) => slash(resolve(rootDir, e.entrypoint)) === normalizedId,\n );\n if (match) {\n return id;\n }\n },\n\n // Build: provide virtual HTML content for Rollup\n load(id) {\n const normalizedId = slash(id);\n const match = entries.find(\n (e) => slash(resolve(rootDir, e.entrypoint)) === normalizedId,\n );\n if (match) {\n return generateHtml(match);\n }\n },\n };\n}\n"]}