@forgeax/engine-pack 0.1.7 → 0.1.20

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/errors.ts","../src/guid.ts","../src/scriptable-pack.ts","../src/evidence/source-inventory.ts","../src/scriptable-pack-node.ts"],"names":["resolve","dirname","readFile","createHash","executor","err","ok","relative","sep","actual"],"mappings":";;;;;;;;;;;;;;AA2BO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACA,QAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EAET,YAAY,IAAA,EAKT;AACD,IAAA,KAAA,CAAM,CAAA,WAAA,EAAc,KAAK,IAAI,CAAA,YAAA,EAAe,KAAK,QAAQ,CAAA,QAAA,EAAW,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AAC/E,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AACrB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AAAA,EACrB;AACF,CAAA;AC/BA,SAAS,MAAM,KAAA,EAA8B;AAC3C,EAAA,OAAO,KAAA;AACT;AAEA,IAAM,WAAW,KAAA,CAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAI,EAAG,CAAC,CAAA,EAAG,CAAA,KAAM,EAAE,QAAA,CAAS,EAAE,EAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAC,CAAA;AAEtF,SAAS,gBAAgB,KAAA,EAA2B;AAClD,EAAA,MAAM,CAAA,GAAI,QAAA;AAEV,EAAA,OAAO,CAAA,EAAG,EAAE,KAAA,CAAM,CAAC,CAAE,CAAC,CAAA,EAAG,EAAE,KAAA,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,UACV,QAAQ,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AAAA,UAC7D,IAAA,EAAM,iFAAA;AAAA,UACN,SAAA,EAAW,IAAA;AAAA,UACX,eAAA,EAAiB,CAAC,oBAAA,EAAsB,iBAAiB,CAAA;AAAA,UACzD,WAAW,SAAA,CAAU,SAAA;AAAA,UACrB,UAAA,EAAY,OAAO,KAAA,CAAM;AAAA,SAC1B;AAAA,OACH;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,SAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,MAAM,OAAA,CAAQ,UAAA,EAAY,IAAA,EAAM;AAC9B,MAAA,MAAM,IAAA,GAAO,YAAY,UAAU,CAAA;AACnC,MAAA,IAAI,CAAC,IAAA,CAAK,EAAA,EAAI,OAAO,IAAA;AACrB,MAAA,MAAM,OAAA,GAAW,MAAM,OAAA,CAAQ,OAAA,GAAU,IAAA,CAAK,MAAM,QAAA,EAAU,IAAI,CAAA,IAAMC,EAAAA,CAAG,MAAS,CAAA;AACpF,MAAA,OAAO,QAAQ,EAAA,GAAK,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,QAAQ,CAAA,GAAI,OAAA;AAAA,IACrD;AAAA,GACF;AACF","file":"scriptable-pack-node.mjs","sourcesContent":["// errors.ts — PackError class (feat-20260513-guid-asset-package-system w15)\n//\n// Four-field surface: .code / .expected / .hint / .detail\n// Structurally parallel to AssetError / RhiError / RemoteError\n// (charter proposition 5 consistent abstraction).\n//\n// .detail is narrowed per .code via PackErrorDetail discriminated union\n// (requirements §6.2 AC-07; plan-strategy §D-5).\n\nimport type { PackErrorCode, PackErrorDetail } from '@forgeax/engine-types';\n\n/**\n * Structured error for the engine-pack disk scanner fail-fast chain.\n *\n * AI users consume via exhaustive switch on .code — no default case needed:\n * ```ts\n * switch (err.code) {\n * case 'pack-guid-collision':\n * console.error(err.detail.paths);\n * break;\n * case 'pack-cyclic-reference':\n * console.error(err.detail.cycle);\n * break;\n * // ...all 8 cases\n * }\n * ```\n */\nexport class PackError extends Error {\n readonly code: PackErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: PackErrorDetail;\n\n constructor(args: {\n code: PackErrorCode;\n expected: string;\n hint: string;\n detail: PackErrorDetail;\n }) {\n super(`[PackError ${args.code}] expected: ${args.expected}; hint: ${args.hint}`);\n this.name = 'PackError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n","import { uuidv7obj } from 'uuidv7';\nimport { PackError } from './errors.js';\n\n/**\n * 16-byte UUID branded ABI. Prevents assignment from plain Uint8Array or string.\n * Brand field mirrors the declaration in @forgeax/engine-types for cross-package\n * structural compatibility (both use __guidBrand: 'AssetGuid').\n */\nexport type AssetGuid = Uint8Array & { readonly __guidBrand: 'AssetGuid' };\n\n/** Minimal Result alias for this module (structurally compatible with ScanResult). */\nexport type GuidResult<T, E> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: E };\n\nfunction brand(bytes: Uint8Array): AssetGuid {\n return bytes as AssetGuid;\n}\n\nconst HEX_BYTE = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n\nfunction bytesToDashForm(bytes: Uint8Array): string {\n const h = HEX_BYTE;\n // biome-ignore lint/style/noNonNullAssertion: length guaranteed 16\n return `${h[bytes[0]!]}${h[bytes[1]!]}${h[bytes[2]!]}${h[bytes[3]!]}-${h[bytes[4]!]}${h[bytes[5]!]}-${h[bytes[6]!]}${h[bytes[7]!]}-${h[bytes[8]!]}${h[bytes[9]!]}-${h[bytes[10]!]}${h[bytes[11]!]}${h[bytes[12]!]}${h[bytes[13]!]}${h[bytes[14]!]}${h[bytes[15]!]}`;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport function isValidAssetGuidString(value: unknown): value is string {\n return typeof value === 'string' && UUID_RE.test(value);\n}\n\nfunction dashFormToBytes(dashForm: string): Uint8Array {\n const hex = dashForm.replace(/-/g, '');\n const bytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++) {\n bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Utilities for the AssetGuid branded 16-byte UUID type.\n * Declare the type via `import type { AssetGuid } from '@forgeax/engine-pack/guid'`\n * or `import type { AssetGuid } from '@forgeax/engine-types'`.\n */\nexport const AssetGuid = {\n /**\n * Parse a 36-char RFC 4122 dash-form UUID string into an AssetGuid.\n * Returns Ok(AssetGuid) on success or Err(PackError) with code 'pack-guid-malformed' on failure.\n * Never throws for expected failures (requirements §4.2 / §14 / charter proposition 4).\n */\n parse(dashForm: string): GuidResult<AssetGuid, PackError> {\n if (!isValidAssetGuidString(dashForm)) {\n return {\n ok: false,\n error: new PackError({\n code: 'pack-guid-malformed',\n expected: '36-char RFC 4122 dash-form UUID',\n hint: 'use AssetGuid.random() or a UUIDv7 generator; all GUID fields must be 36-char RFC 4122 dash-form',\n detail: {\n raw: dashForm,\n reason: 'expected 36-char RFC 4122 dash-form UUID',\n },\n }),\n };\n }\n return { ok: true, value: brand(dashFormToBytes(dashForm)) };\n },\n\n /**\n * Format an AssetGuid as a 36-char RFC 4122 lowercase dash-form string.\n */\n format(guid: AssetGuid): string {\n return bytesToDashForm(guid);\n },\n\n /**\n * Test byte-by-byte equality between two AssetGuids.\n */\n equals(a: AssetGuid, b: AssetGuid): boolean {\n for (let i = 0; i < 16; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n },\n\n /**\n * Mint a new time-ordered UUIDv7 as an AssetGuid.\n * Works in both Node.js and browser environments.\n */\n random(): AssetGuid {\n const uuid = uuidv7obj();\n const bytes = new Uint8Array(16);\n bytes.set(uuid.bytes);\n return brand(bytes);\n },\n} as const;\n","import type { Asset, AssetGuid, AssetPublicationEnvelope, Result } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport { AssetGuid as AssetGuidCodec } from './guid.js';\n\n/** Closed ordinary kind vocabulary shared by authoring, producers, and loaders. */\nexport type ScriptablePackAssetKind = Asset['kind'];\n\n/** Complete ordinary Asset kind vocabulary exposed by ScriptablePack discovery. */\nexport const SCRIPTABLE_PACK_ASSET_KINDS = [\n 'mesh',\n 'material',\n 'scene',\n 'texture',\n 'equirect',\n 'sampler',\n 'font',\n 'render-pipeline',\n 'tileset',\n 'video',\n 'skeleton',\n 'skin',\n 'animation-clip',\n 'animation-graph',\n 'audio',\n 'particle-effect',\n] as const satisfies readonly ScriptablePackAssetKind[];\n\n/** Machine-readable producer/loader floor owned by engine-pack. */\nexport const SCRIPTABLE_PACK_CAPABILITY_MANIFEST = {\n assetKinds: SCRIPTABLE_PACK_ASSET_KINDS,\n durablePayload: true,\n refs: true,\n artifacts: true,\n hostCapabilities: ['audio-install', 'video-play', 'particle-execute'] as const,\n} as const;\n\nexport function isScriptablePackAssetKind(value: string): value is ScriptablePackAssetKind {\n return (SCRIPTABLE_PACK_ASSET_KINDS as readonly string[]).includes(value);\n}\n\nexport interface ScriptablePackAssetDeclaration<\n TKind extends ScriptablePackAssetKind = ScriptablePackAssetKind,\n> {\n readonly guid: AssetGuid;\n readonly kind: TKind;\n readonly name?: string;\n}\n\nexport type ScriptablePackAssetDeclarations = Readonly<\n Record<string, ScriptablePackAssetDeclaration>\n>;\n\nexport type ScriptablePackExternalAssets = Readonly<Record<string, AssetGuid>>;\n\n/**\n * Component-shaped input accepted by a ScriptablePack scene declaration.\n * Engine component tokens satisfy this shape; plain `{ type }` rows keep the\n * Pack contract independent of ECS and survive the isolated module worker.\n */\nexport interface ScriptablePackSceneComponentInput {\n readonly name: string;\n readonly fields: Readonly<Record<string, string | { readonly type: string }>>;\n}\n\n/** Neutral scene schema projection owned by the Pack definition. */\nexport interface ScriptablePackSceneComponent {\n readonly name: string;\n readonly fields: Readonly<Record<string, string>>;\n}\n\nfunction sceneComponentFieldType(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (isRecord(value) && typeof value.type === 'string') return value.type;\n return undefined;\n}\n\n/** Derive the frozen, ECS-neutral schema used by scene output producers. */\nexport function projectScriptablePackSceneComponents(\n components: readonly ScriptablePackSceneComponentInput[] | undefined,\n): readonly ScriptablePackSceneComponent[] {\n return (components ?? []).map((component) => ({\n name: component.name,\n fields: Object.fromEntries(\n Object.entries(component.fields).map(([fieldName, field]) => [\n fieldName,\n sceneComponentFieldType(field) as string,\n ]),\n ),\n }));\n}\n\n/** Pack-facing name for the shared Engine publication envelope. */\nexport type ScriptablePackPublicationEnvelope = AssetPublicationEnvelope;\n\n/** Structured domain failure permitted to cross the isolated build-time AssetReader seam. */\nexport interface ScriptablePackErrorProvenance {\n /** Published source generation observed by the reader, when available. */\n readonly generation?: number;\n /** Stable producer identity for the failed output, when available. */\n readonly sourceKey?: string;\n /** GUID associated with the failed read or output, when available. */\n readonly guid?: string;\n}\n\nexport interface ScriptablePackReadError {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail?: unknown;\n readonly provenance?: ScriptablePackErrorProvenance;\n}\n\nexport type ScriptablePackAssetFor<TDescriptor extends ScriptablePackAssetDeclaration> =\n TDescriptor extends { readonly kind: infer TKind extends ScriptablePackAssetKind }\n ? Extract<Asset, { readonly kind: TKind }>\n : never;\n\nexport type ScriptablePackOutputs<TAssets extends ScriptablePackAssetDeclarations> = {\n readonly [TKey in keyof TAssets]: TAssets[TKey] extends ScriptablePackAssetDeclaration\n ? ScriptablePackAssetFor<TAssets[TKey]>\n : never;\n};\n\nexport interface AssetReader {\n /** Load a declared GUID as a durable payload; this never mints a World handle. */\n readByGuid<TAsset extends Asset = Asset>(\n guid: AssetGuid,\n ): Promise<Result<TAsset, ScriptablePackReadError>>;\n}\n\nexport type ScriptablePackBuildResult<\n TAssets extends ScriptablePackAssetDeclarations,\n TError,\n> = Result<ScriptablePackOutputs<TAssets>, TError>;\n\nexport interface ScriptablePackDefinition<\n TAssets extends ScriptablePackAssetDeclarations = ScriptablePackAssetDeclarations,\n TExternal extends ScriptablePackExternalAssets = ScriptablePackExternalAssets,\n TError = ScriptablePackReadError,\n> {\n readonly schemaVersion: '1.0.0';\n readonly packageId: AssetGuid;\n readonly name?: string;\n readonly assets: TAssets;\n /** Component tokens/schema rows used by scene ref externalization. */\n readonly sceneComponents?: readonly ScriptablePackSceneComponentInput[];\n readonly externalAssets: TExternal;\n readonly build: (\n assetReader: AssetReader,\n ) =>\n | ScriptablePackBuildResult<TAssets, TError>\n | Promise<ScriptablePackBuildResult<TAssets, TError>>;\n}\n\nexport interface ScriptablePackSourceClosureEntry {\n readonly path: string;\n readonly digest: string;\n}\n\nexport interface ScriptablePackMetaJson {\n readonly schemaVersion: '1.0.0';\n readonly kind: 'external-asset-package';\n readonly packageId: string;\n readonly name?: string;\n readonly importer: 'pack-ts';\n readonly source: string;\n readonly importSettings: {\n readonly contractVersion: '1.0.0';\n readonly externalAssets: readonly {\n readonly alias: string;\n readonly guid: string;\n }[];\n };\n readonly subAssets: readonly {\n readonly guid: string;\n readonly sourceIndex: number;\n readonly sourceKey: string;\n readonly kind: ScriptablePackAssetKind;\n readonly name?: string;\n }[];\n}\n\nexport interface ScriptablePackOperationEnvelope {\n readonly requestId: string;\n readonly expectedRevision?: string;\n}\n\nexport type ScriptablePackGatewayOperation =\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'preflight';\n readonly sourcePath: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'create-scriptable-pack';\n readonly sourcePath: string;\n readonly name?: string;\n readonly initialOutput: {\n readonly sourceKey: string;\n readonly kind: ScriptablePackAssetKind;\n readonly name?: string;\n };\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'add-output';\n readonly sourcePath: string;\n readonly sourceKey: string;\n readonly assetKind: ScriptablePackAssetKind;\n readonly name?: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'add-external-asset';\n readonly sourcePath: string;\n readonly alias: string;\n readonly guid: AssetGuid;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'rename-display';\n readonly sourcePath: string;\n readonly target:\n | { readonly kind: 'package' }\n | { readonly kind: 'output'; readonly sourceKey: string };\n readonly name: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'remove-output';\n readonly sourcePath: string;\n readonly sourceKey: string;\n /** Exact incoming reference identities acknowledged by the caller. */\n readonly confirmIncomingRefs?: readonly string[];\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'clone-scriptable-pack';\n readonly sourcePath: string;\n readonly targetPath: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'inspect-meta';\n readonly sourcePath: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'rebuild' | 'cold-cook';\n readonly sourcePath: string;\n });\n\nexport interface ScriptablePackMutationCapabilities {\n readonly inspect: true;\n readonly rebuild: true;\n readonly coldCook: true;\n readonly create?: true;\n readonly addOutput?: true;\n readonly addExternalAsset?: true;\n readonly renameDisplay?: true;\n readonly removeOutput?: true;\n readonly clone?: true;\n readonly reason?: string;\n}\n\nexport interface ScriptablePackPreflight {\n readonly sourcePath: string;\n readonly revision: string;\n readonly meta: ScriptablePackMetaJson;\n readonly capabilities: ScriptablePackMutationCapabilities;\n readonly incomingRefs: readonly string[];\n}\n\nexport interface ScriptablePackGatewayMutation {\n readonly sourcePath: string;\n readonly revision: string;\n readonly meta: ScriptablePackMetaJson;\n}\n\nexport interface ScriptablePackAuthoringGateway {\n execute(\n operation: ScriptablePackGatewayOperation,\n ): Promise<Result<ScriptablePackGatewayMutation | ScriptablePackPreflight, ScriptablePackError>>;\n}\n\nexport type ScriptablePackAuthoringMutation =\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'create-scriptable-pack';\n readonly sourcePath: string;\n readonly packageId: AssetGuid;\n readonly name?: string;\n readonly initialOutput: {\n readonly sourceKey: string;\n readonly kind: ScriptablePackAssetKind;\n readonly guid: AssetGuid;\n readonly name?: string;\n };\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'add-output';\n readonly sourcePath: string;\n readonly sourceKey: string;\n readonly assetKind: ScriptablePackAssetKind;\n readonly guid: AssetGuid;\n readonly name?: string;\n })\n | Extract<\n ScriptablePackGatewayOperation,\n { readonly kind: 'add-external-asset' | 'rename-display' | 'remove-output' }\n >\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'clone-scriptable-pack';\n readonly sourcePath: string;\n readonly targetPath: string;\n readonly packageId: AssetGuid;\n readonly outputGuids: Readonly<Record<string, AssetGuid>>;\n });\n\nexport interface ScriptablePackAuthoringPort {\n preflight(\n sourcePath: string,\n ): Promise<Result<Omit<ScriptablePackPreflight, 'sourcePath'>, ScriptablePackError>>;\n mutate(\n operation: ScriptablePackAuthoringMutation,\n ): Promise<\n Result<{ readonly sourcePath: string; readonly revision: string }, ScriptablePackError>\n >;\n inspect(\n sourcePath: string,\n ): Promise<\n Result<\n { readonly revision: string; readonly meta: ScriptablePackMetaJson },\n ScriptablePackError\n >\n >;\n rebuild(\n sourcePath: string,\n mode: 'rebuild' | 'cold-cook',\n ): Promise<\n Result<\n { readonly revision: string; readonly meta: ScriptablePackMetaJson },\n ScriptablePackError\n >\n >;\n}\n\n/** Keep GUID allocation and multi-identity operations in one auditable gateway transaction. */\nexport function createScriptablePackAuthoringGateway(\n port: ScriptablePackAuthoringPort,\n allocateGuid: () => AssetGuid = AssetGuidCodec.random,\n): ScriptablePackAuthoringGateway {\n const requests = new Map<\n string,\n {\n readonly fingerprint: string;\n readonly result: Promise<\n Result<ScriptablePackGatewayMutation | ScriptablePackPreflight, ScriptablePackError>\n >;\n }\n >();\n\n async function mutationResult(\n result: Awaited<ReturnType<ScriptablePackAuthoringPort['mutate']>>,\n ): Promise<Result<ScriptablePackGatewayMutation, ScriptablePackError>> {\n if (!result.ok) return result;\n const inspected = await port.inspect(result.value.sourcePath);\n if (!inspected.ok) return inspected;\n return ok({\n sourcePath: result.value.sourcePath,\n revision: inspected.value.revision,\n meta: inspected.value.meta,\n });\n }\n\n async function dispatch(\n operation: ScriptablePackGatewayOperation,\n ): Promise<Result<ScriptablePackGatewayMutation | ScriptablePackPreflight, ScriptablePackError>> {\n switch (operation.kind) {\n case 'preflight': {\n const preflight = await port.preflight(operation.sourcePath);\n return preflight.ok\n ? ok({ sourcePath: operation.sourcePath, ...preflight.value })\n : preflight;\n }\n case 'inspect-meta': {\n const inspected = await port.inspect(operation.sourcePath);\n return inspected.ok\n ? ok({ sourcePath: operation.sourcePath, ...inspected.value })\n : inspected;\n }\n case 'rebuild':\n case 'cold-cook': {\n const preflight = await port.preflight(operation.sourcePath);\n if (!preflight.ok) return preflight;\n if (\n operation.expectedRevision !== undefined &&\n operation.expectedRevision !== preflight.value.revision\n ) {\n return err({\n code: 'pack-source-revision-conflict',\n expected: operation.expectedRevision,\n actual: preflight.value.revision,\n hint: 'inspect the current source revision, then retry the build with a new requestId',\n retryable: true,\n recoveryActions: ['asset.preflight', 'mint-request-id'],\n detail: { requestId: operation.requestId, sourcePath: operation.sourcePath },\n });\n }\n const rebuilt = await port.rebuild(operation.sourcePath, operation.kind);\n return rebuilt.ok ? ok({ sourcePath: operation.sourcePath, ...rebuilt.value }) : rebuilt;\n }\n case 'create-scriptable-pack':\n return mutationResult(\n await port.mutate({\n ...operation,\n packageId: allocateGuid(),\n initialOutput: { ...operation.initialOutput, guid: allocateGuid() },\n }),\n );\n case 'add-output':\n return mutationResult(await port.mutate({ ...operation, guid: allocateGuid() }));\n case 'clone-scriptable-pack': {\n const inspected = await port.inspect(operation.sourcePath);\n if (!inspected.ok) return inspected;\n const outputGuids = Object.fromEntries(\n inspected.value.meta.subAssets.map((asset) => [asset.sourceKey, allocateGuid()]),\n );\n return mutationResult(\n await port.mutate({\n ...operation,\n packageId: allocateGuid(),\n outputGuids,\n }),\n );\n }\n case 'add-external-asset':\n case 'rename-display':\n case 'remove-output':\n return mutationResult(await port.mutate(operation));\n }\n }\n\n return {\n execute(operation) {\n if (operation.requestId.trim().length === 0) {\n return Promise.resolve(\n err({\n code: 'pack-source-operation-committed',\n expected: 'a non-empty caller-minted requestId',\n actual: operation.requestId,\n hint: 'mint a new requestId and retry the operation once',\n retryable: true,\n recoveryActions: ['mint-request-id'],\n detail: { requestId: operation.requestId, sourcePath: operation.sourcePath },\n }),\n );\n }\n const fingerprint = JSON.stringify(operation);\n const prior = requests.get(operation.requestId);\n if (prior !== undefined) {\n if (prior.fingerprint === fingerprint) return prior.result;\n return Promise.resolve(\n err({\n code: 'pack-source-operation-committed',\n expected: 'one immutable operation per requestId',\n actual: operation.kind,\n hint: 'read the original operation result or mint a new requestId',\n retryable: false,\n recoveryActions: ['read-operation-run', 'mint-request-id'],\n detail: { requestId: operation.requestId, sourcePath: operation.sourcePath },\n }),\n );\n }\n const result = dispatch(operation);\n requests.set(operation.requestId, { fingerprint, result });\n return result;\n },\n };\n}\n\nconst SCRIPTABLE_PACK_REQUEST_ID_SCHEMA = {\n type: 'string',\n minLength: 1,\n maxLength: 128,\n pattern: '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$',\n description: 'Caller-minted identity for one idempotent ScriptablePack operation.',\n} as const;\nconst SCRIPTABLE_PACK_SOURCE_PATH_SCHEMA = {\n type: 'string',\n minLength: 8,\n pattern: '^[^/].*\\\\.pack\\\\.ts$',\n description: 'Game-root-relative ScriptablePack source path.',\n} as const;\nconst SCRIPTABLE_PACK_OWNER_GUID_SCHEMA = {\n type: 'string',\n format: 'uuid',\n description: 'Catalog GUID used to resolve the producer-owned source subject.',\n} as const;\nconst SCRIPTABLE_PACK_REVISION_SCHEMA = {\n type: 'string',\n minLength: 64,\n maxLength: 64,\n pattern: '^[a-f0-9]{64}$',\n description: 'SHA-256 source revision returned by preflight.',\n} as const;\nconst SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA = { type: 'string', minLength: 1 } as const;\nconst SCRIPTABLE_PACK_ASSET_KIND_SCHEMA = {\n enum: SCRIPTABLE_PACK_ASSET_KINDS,\n description: 'Ordinary Asset kind supported by the ScriptablePack producer/loader matrix.',\n} as const;\nconst SCRIPTABLE_PACK_NAME_SCHEMA = { type: 'string', minLength: 1 } as const;\n\nfunction scriptablePackArgsSchema(\n properties: Readonly<Record<string, unknown>>,\n required: readonly string[],\n options: { readonly subject?: boolean; readonly guidSubject?: boolean } = {},\n) {\n const subjectRequired = ['requestId', ...required];\n return {\n type: 'object',\n properties: {\n sourcePath: SCRIPTABLE_PACK_SOURCE_PATH_SCHEMA,\n ownerGuid: SCRIPTABLE_PACK_OWNER_GUID_SCHEMA,\n requestId: SCRIPTABLE_PACK_REQUEST_ID_SCHEMA,\n ...properties,\n },\n required: subjectRequired,\n ...(options.subject === false\n ? {}\n : {\n anyOf: [\n { required: [...subjectRequired, 'sourcePath'] },\n { required: [...subjectRequired, 'ownerGuid'] },\n ...(options.guidSubject === false ? [] : [{ required: [...subjectRequired, 'guid'] }]),\n ],\n }),\n additionalProperties: false,\n } as const;\n}\n\nexport const SOURCE_AUTHORING_OPERATION_DESCRIPTORS = [\n {\n id: 'asset-source.create',\n kind: 'create',\n domain: 'session',\n title: 'Create Asset Source',\n argsSchema: scriptablePackArgsSchema(\n {\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n initialOutput: {\n type: 'object',\n properties: {\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n kind: SCRIPTABLE_PACK_ASSET_KIND_SCHEMA,\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n },\n required: ['sourceKey', 'kind'],\n additionalProperties: false,\n },\n },\n ['sourcePath', 'initialOutput'],\n { subject: false },\n ),\n },\n {\n id: 'asset-source.add-output',\n kind: 'add-output',\n domain: 'session',\n title: 'Add Asset Source Output',\n argsSchema: scriptablePackArgsSchema(\n {\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n assetKind: SCRIPTABLE_PACK_ASSET_KIND_SCHEMA,\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['sourceKey', 'assetKind', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.add-external-asset',\n kind: 'add-external-asset',\n domain: 'session',\n title: 'Add Asset Source External Asset',\n argsSchema: scriptablePackArgsSchema(\n {\n alias: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n guid: { type: 'string', format: 'uuid' },\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['alias', 'guid', 'expectedRevision'],\n { guidSubject: false },\n ),\n },\n {\n id: 'asset-source.rename',\n kind: 'rename',\n domain: 'session',\n title: 'Rename Asset Source Display Name',\n argsSchema: scriptablePackArgsSchema(\n {\n target: {\n oneOf: [\n {\n type: 'object',\n properties: { kind: { const: 'package' } },\n required: ['kind'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n kind: { const: 'output' },\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n },\n required: ['kind', 'sourceKey'],\n additionalProperties: false,\n },\n ],\n },\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['target', 'name', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.remove-output',\n kind: 'remove-output',\n domain: 'session',\n title: 'Remove Asset Source Output',\n destructive: true,\n argsSchema: scriptablePackArgsSchema(\n {\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n confirmIncomingRefs: { type: 'array', items: { type: 'string' } },\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['sourceKey', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.clone',\n kind: 'clone',\n domain: 'session',\n title: 'Clone Asset Source',\n argsSchema: scriptablePackArgsSchema(\n {\n targetPath: SCRIPTABLE_PACK_SOURCE_PATH_SCHEMA,\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['targetPath', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.rebuild',\n kind: 'rebuild',\n domain: 'session',\n title: 'Rebuild Asset Source',\n argsSchema: scriptablePackArgsSchema({ expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA }, [\n 'expectedRevision',\n ]),\n },\n {\n id: 'asset-source.cold-cook',\n kind: 'cold-cook',\n domain: 'session',\n title: 'Cold Cook Asset Source',\n argsSchema: scriptablePackArgsSchema({ expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA }, [\n 'expectedRevision',\n ]),\n },\n] as const;\n\nexport type ScriptablePackError =\n | {\n readonly code: 'pack-source-load-failed';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly sourcePath: string;\n readonly reason: 'module-load' | 'timeout' | 'source-changed';\n readonly phase: 'module-load' | 'build';\n readonly diagnostic: string;\n readonly timeoutMs?: number;\n };\n }\n | {\n readonly code: 'pack-source-definition-invalid';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly sourcePath?: string;\n readonly propertyPath: string;\n readonly actual: string;\n };\n }\n | {\n readonly code: 'pack-source-output-invalid';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly missingGuids: readonly string[];\n readonly unexpectedSourceKeys: readonly string[];\n readonly kindMismatches: readonly {\n readonly sourceKey: string;\n readonly expected: string;\n readonly actual: string;\n }[];\n };\n }\n | {\n readonly code: 'pack-source-external-closure-mismatch';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly undeclaredReferencedGuids: readonly string[];\n readonly undeclaredReadGuids: readonly string[];\n readonly unusedDeclaredGuids: readonly string[];\n };\n }\n | {\n readonly code:\n | 'pack-source-path-invalid'\n | 'pack-source-revision-conflict'\n | 'pack-source-mutation-unsupported'\n | 'pack-source-reference-conflict'\n | 'pack-source-write-failed'\n | 'pack-source-build-cycle'\n | 'pack-source-publication-timeout'\n | 'pack-source-operation-committed';\n readonly expected: string;\n readonly actual?: string;\n readonly hint: string;\n readonly retryable: boolean;\n readonly recoveryActions: readonly string[];\n readonly detail: {\n readonly requestId?: string;\n readonly sourcePath?: string;\n readonly packageId?: string;\n readonly sourceKey?: string;\n readonly incomingRefs?: readonly string[];\n };\n };\n\nfunction actual(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n if (ArrayBuffer.isView(value)) return value.constructor.name;\n return typeof value;\n}\n\nfunction invalid(\n propertyPath: string,\n expected: string,\n value: unknown,\n sourcePath?: string,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-definition-invalid',\n expected,\n hint: 'repair the default exported ScriptablePack definition, then inspect Meta again',\n detail: {\n ...(sourcePath === undefined ? {} : { sourcePath }),\n propertyPath,\n actual: actual(value),\n },\n });\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isAssetGuid(value: unknown): value is AssetGuid {\n return value instanceof Uint8Array && value.byteLength === 16;\n}\n\nfunction guidKey(guid: AssetGuid): string {\n return AssetGuidCodec.format(guid);\n}\n\nfunction freezeDefinition(\n definition: ScriptablePackDefinition,\n): Readonly<ScriptablePackDefinition> {\n const assets = Object.fromEntries(\n Object.entries(definition.assets).map(([sourceKey, descriptor]) => [\n sourceKey,\n Object.freeze({ ...descriptor, guid: descriptor.guid.slice() as AssetGuid }),\n ]),\n );\n const externalAssets = Object.fromEntries(\n Object.entries(definition.externalAssets).map(([alias, guid]) => [\n alias,\n guid.slice() as AssetGuid,\n ]),\n );\n const sceneComponents =\n definition.sceneComponents === undefined\n ? undefined\n : Object.freeze(\n projectScriptablePackSceneComponents(definition.sceneComponents).map((component) =>\n Object.freeze({\n ...component,\n fields: Object.freeze({ ...component.fields }),\n }),\n ),\n );\n return Object.freeze({\n ...definition,\n packageId: definition.packageId.slice() as AssetGuid,\n assets: Object.freeze(assets),\n externalAssets: Object.freeze(externalAssets),\n ...(sceneComponents === undefined ? {} : { sceneComponents }),\n });\n}\n\nexport function validateScriptablePackDefinition(\n value: unknown,\n sourcePath?: string,\n): Result<Readonly<ScriptablePackDefinition>, ScriptablePackError> {\n if (!isRecord(value))\n return invalid('$', 'a ScriptablePack definition object', value, sourcePath);\n if (value.schemaVersion !== '1.0.0') {\n return invalid('$.schemaVersion', \"the literal '1.0.0'\", value.schemaVersion, sourcePath);\n }\n if (!isAssetGuid(value.packageId)) {\n return invalid('$.packageId', 'a 16-byte AssetGuid', value.packageId, sourcePath);\n }\n if (value.name !== undefined && typeof value.name !== 'string') {\n return invalid('$.name', 'a string when present', value.name, sourcePath);\n }\n if (!isRecord(value.assets) || Object.keys(value.assets).length === 0) {\n return invalid(\n '$.assets',\n 'a non-empty sourceKey to descriptor object',\n value.assets,\n sourcePath,\n );\n }\n if (!isRecord(value.externalAssets)) {\n return invalid(\n '$.externalAssets',\n 'an alias to AssetGuid object',\n value.externalAssets,\n sourcePath,\n );\n }\n if (value.sceneComponents !== undefined) {\n if (!Array.isArray(value.sceneComponents)) {\n return invalid(\n '$.sceneComponents',\n 'an array of component tokens or neutral schema rows when present',\n value.sceneComponents,\n sourcePath,\n );\n }\n const componentNames = new Set<string>();\n for (const [componentIndex, component] of value.sceneComponents.entries()) {\n if (!isRecord(component)) {\n return invalid(\n `$.sceneComponents[${componentIndex}]`,\n 'a component token or neutral schema row',\n component,\n sourcePath,\n );\n }\n if (typeof component.name !== 'string' || component.name.trim().length === 0) {\n return invalid(\n `$.sceneComponents[${componentIndex}].name`,\n 'a non-empty component name',\n component.name,\n sourcePath,\n );\n }\n if (componentNames.has(component.name)) {\n return invalid(\n `$.sceneComponents[${componentIndex}].name`,\n 'component names to be unique within one ScriptablePack',\n component.name,\n sourcePath,\n );\n }\n componentNames.add(component.name);\n if (!isRecord(component.fields)) {\n return invalid(\n `$.sceneComponents[${componentIndex}].fields`,\n 'a field-name to schema-type object',\n component.fields,\n sourcePath,\n );\n }\n for (const [fieldName, field] of Object.entries(component.fields)) {\n const type = sceneComponentFieldType(field);\n if (fieldName.trim().length === 0 || type === undefined || type.trim().length === 0) {\n return invalid(\n `$.sceneComponents[${componentIndex}].fields`,\n 'field names with non-empty string schema types',\n field,\n sourcePath,\n );\n }\n }\n }\n }\n if (typeof value.build !== 'function') {\n return invalid('$.build', 'a build(assetReader) function', value.build, sourcePath);\n }\n\n const packageGuid = guidKey(value.packageId);\n const localGuids = new Set<string>();\n for (const [sourceKey, descriptor] of Object.entries(value.assets)) {\n if (sourceKey.trim().length === 0) {\n return invalid('$.assets', 'non-empty sourceKey object keys', sourceKey, sourcePath);\n }\n if (!isRecord(descriptor)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}]`,\n 'an asset descriptor',\n descriptor,\n sourcePath,\n );\n }\n if (!isAssetGuid(descriptor.guid)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].guid`,\n 'a 16-byte AssetGuid',\n descriptor.guid,\n sourcePath,\n );\n }\n if (typeof descriptor.kind !== 'string' || !isScriptablePackAssetKind(descriptor.kind)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].kind`,\n 'one of SCRIPTABLE_PACK_ASSET_KINDS',\n descriptor.kind,\n sourcePath,\n );\n }\n if (descriptor.name !== undefined && typeof descriptor.name !== 'string') {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].name`,\n 'a string when present',\n descriptor.name,\n sourcePath,\n );\n }\n const guid = guidKey(descriptor.guid);\n if (guid === packageGuid || localGuids.has(guid)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].guid`,\n 'a GUID unique within the package and distinct from packageId',\n descriptor.guid,\n sourcePath,\n );\n }\n localGuids.add(guid);\n }\n\n const externalGuids = new Set<string>();\n for (const [alias, guidValue] of Object.entries(value.externalAssets)) {\n if (alias.trim().length === 0) {\n return invalid('$.externalAssets', 'non-empty alias object keys', alias, sourcePath);\n }\n if (!isAssetGuid(guidValue)) {\n return invalid(\n `$.externalAssets[${JSON.stringify(alias)}]`,\n 'a 16-byte AssetGuid',\n guidValue,\n sourcePath,\n );\n }\n const guid = guidKey(guidValue);\n if (guid === packageGuid || localGuids.has(guid) || externalGuids.has(guid)) {\n return invalid(\n `$.externalAssets[${JSON.stringify(alias)}]`,\n 'a unique foreign GUID not owned by this package',\n guidValue,\n sourcePath,\n );\n }\n externalGuids.add(guid);\n }\n\n return ok(freezeDefinition(value as unknown as ScriptablePackDefinition));\n}\n\nexport function projectScriptablePackMeta(\n definition: ScriptablePackDefinition,\n source: string,\n): ScriptablePackMetaJson {\n const subAssets = Object.entries(definition.assets)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([sourceKey, descriptor], sourceIndex) => ({\n guid: guidKey(descriptor.guid),\n sourceIndex,\n sourceKey,\n kind: descriptor.kind,\n ...(descriptor.name === undefined ? {} : { name: descriptor.name }),\n }));\n const externalAssets = Object.entries(definition.externalAssets)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([alias, guid]) => ({ alias, guid: guidKey(guid) }));\n return {\n schemaVersion: '1.0.0',\n kind: 'external-asset-package',\n packageId: guidKey(definition.packageId),\n ...(definition.name === undefined ? {} : { name: definition.name }),\n importer: 'pack-ts',\n source,\n importSettings: { contractVersion: '1.0.0', externalAssets },\n subAssets,\n };\n}\n","import { createHash } from 'node:crypto';\nimport { readdir, readFile } from 'node:fs/promises';\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path';\nimport type { SourceDeclarationEvidence } from '@forgeax/engine-types';\nimport { SCANNER_BLACKLIST, scan } from '../scanner.js';\nimport { projectScriptablePackMeta } from '../scriptable-pack.js';\nimport { loadScriptablePack } from '../scriptable-pack-node.js';\n\n/** Project root and GUID used to locate an authoritative source declaration. */\nexport interface SourceInventoryRequest {\n readonly projectRoot: string;\n readonly guid: string;\n}\n\nexport interface ProducerSemanticIdentityInput {\n readonly producerRoot: string;\n readonly sourcePath: string;\n readonly sourceDigest: string;\n readonly schemaVersion: string;\n readonly importer: string;\n readonly codec: string;\n readonly settings: unknown;\n readonly producer: string;\n readonly profile: string;\n readonly declaredGuids?: readonly string[];\n}\n\nexport interface ProducerRelativeDdcIdentity {\n readonly logicalPath: string;\n readonly sourceDigest: string;\n readonly key: string;\n}\n\nfunction stableValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stableValue);\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => [key, stableValue(entry)]),\n );\n }\n return value;\n}\n\nexport function producerRelativeLogicalPath(producerRoot: string, sourcePath: string): string {\n const root = resolve(producerRoot);\n const source = resolve(sourcePath);\n const path = relative(root, source);\n if (\n path.length === 0 ||\n path === '..' ||\n path.startsWith(`..${sep}`) ||\n resolve(root, path) !== source\n ) {\n throw new Error('producer source must be inside the injected producer root');\n }\n return path.split(sep).join('/');\n}\n\nexport function producerRelativeDdcKey(input: ProducerSemanticIdentityInput): string {\n const logicalPath = producerRelativeLogicalPath(input.producerRoot, input.sourcePath);\n const semantic = {\n schemaVersion: input.schemaVersion,\n logicalPath,\n sourceDigest: input.sourceDigest,\n importer: input.importer,\n codec: input.codec,\n settings: stableValue(input.settings),\n producer: input.producer,\n profile: input.profile,\n declaredGuids: [...(input.declaredGuids ?? [])].sort(),\n };\n return createHash('sha256').update(JSON.stringify(semantic)).digest('hex');\n}\n\nexport function producerRelativeDdcIdentity(\n input: ProducerSemanticIdentityInput,\n): ProducerRelativeDdcIdentity {\n return {\n logicalPath: producerRelativeLogicalPath(input.producerRoot, input.sourcePath),\n sourceDigest: input.sourceDigest,\n key: producerRelativeDdcKey(input),\n };\n}\n\nfunction fingerprint(meta: string, source: Uint8Array | undefined): string {\n const hash = createHash('sha256').update(meta);\n if (source !== undefined) hash.update(source);\n return hash.digest('base64');\n}\n\nfunction sourceFromMeta(\n metaPath: string,\n meta: {\n readonly source?: unknown;\n readonly inputFingerprint?: unknown;\n readonly importSettings?: unknown;\n readonly subAssets?: readonly { readonly guid?: unknown }[];\n },\n guid: string,\n raw: string,\n): SourceDeclarationEvidence | undefined {\n if (\n !meta.subAssets?.some(\n (asset) => typeof asset.guid === 'string' && asset.guid.toLowerCase() === guid.toLowerCase(),\n )\n ) {\n return undefined;\n }\n const source =\n typeof meta.source === 'string' ? meta.source : basename(metaPath).replace(/\\.meta\\.json$/, '');\n const sourcePath = resolve(dirname(metaPath), source);\n const inputFingerprint =\n typeof meta.inputFingerprint === 'string' ? meta.inputFingerprint : fingerprint(raw, undefined);\n return { origin: 'sourceMeta', sourcePath, inputFingerprint };\n}\n\nasync function collectDeclarationPaths(root: string): Promise<string[]> {\n const paths: string[] = [];\n async function visit(dir: string): Promise<void> {\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (!SCANNER_BLACKLIST.has(entry.name)) await visit(path);\n continue;\n }\n if (\n entry.isFile() &&\n (entry.name.endsWith('.meta.json') ||\n entry.name.endsWith('.pack.json') ||\n entry.name.endsWith('.pack.ts'))\n ) {\n paths.push(path);\n }\n }\n }\n await visit(root);\n return paths;\n}\n\n/** Read `.meta.json` or `.pack.json` source declarations without runtime imports. */\nexport async function readSourceInventory(\n request: SourceInventoryRequest,\n): Promise<SourceDeclarationEvidence | undefined> {\n const result = await scan([request.projectRoot]);\n const paths = result.ok ? result.value : await collectDeclarationPaths(request.projectRoot);\n const guid = request.guid.toLowerCase();\n let authored: SourceDeclarationEvidence | undefined;\n for (const path of paths) {\n if (path.endsWith('.pack.ts')) {\n const loaded = await loadScriptablePack(path, { metadataOnly: true });\n if (!loaded.ok) continue;\n const meta = projectScriptablePackMeta(loaded.value, path);\n if (meta.subAssets.some((asset) => asset.guid.toLowerCase() === guid)) {\n return { origin: 'sourceMeta', sourcePath: path };\n }\n continue;\n }\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) continue;\n let parsed: {\n readonly assets?: readonly { readonly guid?: unknown }[];\n readonly source?: unknown;\n readonly inputFingerprint?: unknown;\n readonly importSettings?: unknown;\n readonly subAssets?: readonly { readonly guid?: unknown }[];\n };\n try {\n parsed = JSON.parse(raw) as typeof parsed;\n } catch {\n continue;\n }\n if (path.endsWith('.pack.json')) {\n if (\n parsed.assets?.some(\n (asset) =>\n typeof asset.guid === 'string' &&\n (asset.guid === request.guid || asset.guid.toLowerCase() === guid),\n )\n ) {\n authored = { origin: 'authoredPack', sourcePath: path };\n }\n continue;\n }\n if (path.endsWith('.meta.json')) {\n const source = sourceFromMeta(path, parsed, request.guid, raw);\n if (source !== undefined) return source;\n }\n }\n return authored;\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdir, mkdtemp, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, isAbsolute, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Worker } from 'node:worker_threads';\nimport type { AssetGuid, Result } from '@forgeax/engine-types';\nimport { AssetError, err, ImportError, ok } from '@forgeax/engine-types';\nimport ts from 'typescript';\nimport {\n type ProducerSemanticIdentityInput,\n producerRelativeDdcKey,\n} from './evidence/source-inventory.js';\nimport { AssetGuid as AssetGuidCodec } from './guid.js';\nimport {\n type AssetReader,\n projectScriptablePackMeta,\n type ScriptablePackAssetKind,\n type ScriptablePackAuthoringMutation,\n type ScriptablePackAuthoringPort,\n type ScriptablePackDefinition,\n type ScriptablePackError,\n type ScriptablePackReadError,\n type ScriptablePackSourceClosureEntry,\n validateScriptablePackDefinition,\n} from './scriptable-pack.js';\n\nconst IMPORT_META_RESOLVE_FLAG = '--experimental-import-meta-resolve';\n\nfunction scriptablePackWorkerExecArgv(): string[] {\n // import.meta.resolve(parentURL) is the canonical ESM resolver, but Node\n // keeps its parentURL overload behind this flag. Filter --input-type as\n // well: stdin/eval hosts may pass it through process.execArgv, and Node\n // rejects that option inside a file-backed worker.\n const inherited = process.execArgv.filter((arg) => !arg.startsWith('--input-type'));\n return inherited.includes(IMPORT_META_RESOLVE_FLAG)\n ? inherited\n : [...inherited, IMPORT_META_RESOLVE_FLAG];\n}\n\nexport interface ScriptablePackModuleExecutor {\n load(sourcePath: string): Promise<unknown>;\n dispose?(reason: 'complete' | 'timeout' | 'failure'): void | Promise<void>;\n}\n\nexport interface ScriptablePackModuleExecutorPool {\n acquire(): Promise<ScriptablePackModuleExecutor>;\n dispose(): Promise<void>;\n}\n\nexport interface ScriptablePackModuleExecutorPoolOptions {\n readonly maxWorkers?: number;\n readonly maxTasksPerWorker?: number;\n}\n\nexport function scriptablePackDdcKey(input: ProducerSemanticIdentityInput): string {\n return producerRelativeDdcKey(input);\n}\n\nexport interface OptionalBuildCache<T> {\n readonly read: () => Promise<T | null>;\n readonly coldCook: () => Promise<T>;\n}\n\n/** Build CAS is a performance hint; source cold cook remains the correctness path. */\nexport async function readOptionalBuildCache<T>(cache: OptionalBuildCache<T>): Promise<{\n readonly value: T;\n readonly fromCache: boolean;\n}> {\n try {\n const cached = await cache.read();\n if (cached !== null) return { value: cached, fromCache: true };\n } catch {\n // Cache deletion, read-only storage, and corrupt optional objects fail open.\n }\n return { value: await cache.coldCook(), fromCache: false };\n}\n\nexport interface LoadScriptablePackOptions {\n /** Maximum time allowed for module initialization in the isolated worker. */\n readonly timeoutMs?: number;\n /** Maximum time allowed for one definition.build(reader) in the isolated worker. */\n readonly buildTimeoutMs?: number;\n readonly executor?: ScriptablePackModuleExecutor;\n /** Release the isolated loader after identity projection when build will not be called. */\n readonly metadataOnly?: boolean;\n}\n\nasync function resolveRelativeImport(\n sourcePath: string,\n specifier: string,\n): Promise<string | undefined> {\n if (!specifier.startsWith('.')) return undefined;\n const raw = resolve(dirname(sourcePath), specifier);\n const candidates =\n extname(raw).length > 0\n ? [raw]\n : [\n raw,\n `${raw}.ts`,\n `${raw}.tsx`,\n `${raw}.mts`,\n `${raw}.js`,\n `${raw}.mjs`,\n `${raw}.json`,\n resolve(raw, 'index.ts'),\n ];\n for (const candidate of candidates) {\n try {\n if ((await stat(candidate)).isFile()) return candidate;\n } catch {\n // Continue through deterministic extension candidates.\n }\n }\n return undefined;\n}\n\n/** Capture one immutable ScriptablePack module closure for inventory and production. */\nexport async function inventoryScriptablePackSource(\n sourcePath: string,\n initialSourceText?: string,\n): Promise<readonly ScriptablePackSourceClosureEntry[]> {\n const root = await realpath(sourcePath);\n const pending = [root];\n const seen = new Set<string>();\n const entries: ScriptablePackSourceClosureEntry[] = [];\n while (pending.length > 0) {\n const path = pending.pop();\n if (path === undefined || seen.has(path)) continue;\n seen.add(path);\n const bytes =\n path === root && initialSourceText !== undefined\n ? new TextEncoder().encode(initialSourceText)\n : await readFile(path);\n entries.push({ path, digest: `sha256:${createHash('sha256').update(bytes).digest('hex')}` });\n const source = new TextDecoder().decode(bytes);\n for (const imported of ts.preProcessFile(source, true, true).importedFiles) {\n const resolved = await resolveRelativeImport(path, imported.fileName);\n if (resolved !== undefined) pending.push(await realpath(resolved));\n }\n }\n return entries.sort((left, right) => left.path.localeCompare(right.path));\n}\n\ninterface StructuredFailure {\n readonly name?: unknown;\n readonly code?: unknown;\n readonly expected?: unknown;\n readonly actual?: unknown;\n readonly hint?: unknown;\n readonly detail?: unknown;\n readonly message?: unknown;\n}\n\nfunction serializeFailure(value: unknown): StructuredFailure {\n if (value !== null && typeof value === 'object') {\n const failure = value as Record<string, unknown>;\n return {\n name: failure.name,\n code: failure.code,\n expected: failure.expected,\n actual: failure.actual,\n hint: failure.hint,\n detail: failure.detail,\n message: failure.message,\n };\n }\n return { message: String(value) };\n}\n\nfunction hydrateFailure(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n const failure = value as StructuredFailure;\n if (\n failure.name === 'AssetError' &&\n typeof failure.code === 'string' &&\n typeof failure.expected === 'string' &&\n typeof failure.hint === 'string'\n ) {\n const args = {\n code: failure.code as ConstructorParameters<typeof AssetError>[0]['code'],\n expected: failure.expected,\n hint: failure.hint,\n };\n return failure.detail === undefined\n ? new AssetError(args)\n : new AssetError({\n ...args,\n detail: failure.detail as NonNullable<\n ConstructorParameters<typeof AssetError>[0]['detail']\n >,\n });\n }\n if (\n failure.name === 'ImportError' &&\n typeof failure.code === 'string' &&\n typeof failure.expected === 'string' &&\n typeof failure.hint === 'string' &&\n failure.detail !== undefined\n ) {\n return new ImportError({\n code: failure.code as ConstructorParameters<typeof ImportError>[0]['code'],\n expected: failure.expected,\n hint: failure.hint,\n detail: failure.detail as ConstructorParameters<typeof ImportError>[0]['detail'],\n ...(typeof failure.actual === 'string' ? { actual: failure.actual } : {}),\n });\n }\n if (typeof failure.message === 'string') {\n const error = new Error(failure.message);\n if (typeof failure.name === 'string') error.name = failure.name;\n return error;\n }\n return value;\n}\n\nclass WorkerScriptablePackExecutor implements ScriptablePackModuleExecutor {\n private worker: Worker | undefined;\n private compileRoot: string | undefined;\n private nextBuildId = 0;\n private disposal: Promise<void> | undefined;\n private build:\n | {\n readonly id: number;\n readonly reader: AssetReader;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n\n async load(sourcePath: string): Promise<unknown> {\n const workerUrl = scriptablePackWorkerUrl();\n const compileRoot = await mkdtemp(resolve(tmpdir(), 'forgeax-scriptable-pack-'));\n this.compileRoot = compileRoot;\n const worker = new Worker(workerUrl, {\n workerData: { sourcePath: resolve(sourcePath), compileRoot },\n execArgv: scriptablePackWorkerExecArgv(),\n resourceLimits: { maxOldGenerationSizeMb: 256, maxYoungGenerationSizeMb: 64 },\n });\n this.worker = worker;\n worker.on('message', (message: unknown) => this.onMessage(message));\n worker.unref();\n return new Promise((resolveLoad, rejectLoad) => {\n const onMessage = (message: unknown): void => {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n if (value.kind === 'loaded') {\n // The scan keeps this executor alive for the later no-reopen build\n // route, but an idle source worker must not keep a Vite/Vitest host\n // process alive after its own work has settled.\n worker.unref();\n worker.off('message', onMessage);\n resolveLoad({\n default:\n value.definition === undefined\n ? undefined\n : {\n ...(value.definition as Record<string, unknown>),\n build: (reader: AssetReader) => this.runBuild(reader),\n },\n });\n } else if (value.kind === 'load-threw') {\n worker.off('message', onMessage);\n rejectLoad(hydrateFailure(value.error));\n }\n };\n worker.on('message', onMessage);\n worker.once('error', rejectLoad);\n worker.once('exit', (code) => {\n if (code !== 0) rejectLoad(new Error(`ScriptablePack worker exited with code ${code}`));\n });\n });\n }\n\n dispose(reason: 'complete' | 'timeout' | 'failure' = 'complete'): Promise<void> {\n if (this.disposal !== undefined) return this.disposal;\n const worker = this.worker;\n this.worker = undefined;\n const compileRoot = this.compileRoot;\n this.compileRoot = undefined;\n const active = this.build;\n this.build = undefined;\n if (active !== undefined) {\n active.reject(new Error(`ScriptablePack build disposed during ${reason}`));\n }\n this.disposal = (async () => {\n if (worker !== undefined) await worker.terminate();\n if (compileRoot !== undefined) await rm(compileRoot, { recursive: true, force: true });\n })();\n return this.disposal;\n }\n\n private runBuild(reader: AssetReader): Promise<unknown> {\n const worker = this.worker;\n if (worker === undefined) return Promise.reject(new Error('ScriptablePack worker is closed'));\n if (this.build !== undefined)\n return Promise.reject(new Error('ScriptablePack worker already has an active build'));\n const id = this.nextBuildId++;\n return new Promise((resolveBuild, rejectBuild) => {\n this.build = { id, reader, resolve: resolveBuild, reject: rejectBuild };\n worker.postMessage({ kind: 'build', buildId: id });\n });\n }\n\n private onMessage(message: unknown): void {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n const active = this.build;\n if (active === undefined || value.buildId !== active.id) return;\n if (value.kind === 'asset-read' && typeof value.readId === 'number') {\n void active.reader\n .readByGuid(value.guid as AssetGuid)\n .then((result) =>\n this.worker?.postMessage({\n kind: 'asset-result',\n readId: value.readId,\n result:\n result.ok === true ? result : { ...result, error: serializeFailure(result.error) },\n }),\n )\n .catch((error: unknown) => {\n if (this.build?.id !== active.id) return;\n this.build = undefined;\n active.reject(error);\n void this.dispose('failure');\n });\n return;\n }\n this.build = undefined;\n if (value.kind === 'build-result') active.resolve(value.result);\n else if (value.kind === 'build-threw') active.reject(hydrateFailure(value.error));\n else this.build = active;\n }\n}\n\nfunction scriptablePackWorkerUrl(): URL {\n const bundledWorker = new URL('./scriptable-pack-worker.mjs', import.meta.url);\n return existsSync(fileURLToPath(bundledWorker))\n ? bundledWorker\n : new URL('../dist/scriptable-pack-worker.mjs', import.meta.url);\n}\n\nclass ReusableWorkerScriptablePackExecutor implements ScriptablePackModuleExecutor {\n private readonly worker: Worker;\n private readonly compileRootReady = mkdtemp(resolve(tmpdir(), 'forgeax-scriptable-pack-pool-'));\n private compileRoot: string | undefined;\n private nextLoadId = 0;\n private nextBuildId = 0;\n private pendingLoad:\n | {\n readonly id: number;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n private build:\n | {\n readonly id: number;\n readonly reader: AssetReader;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n private disposal: Promise<void> | undefined;\n private forceDispose = false;\n private failed = false;\n private taskCount = 0;\n private released = false;\n\n constructor(\n private readonly maxTasksPerWorker: number,\n private readonly release: (\n executor: ReusableWorkerScriptablePackExecutor,\n reusable: boolean,\n ) => void,\n ) {\n this.worker = new Worker(scriptablePackWorkerUrl(), {\n workerData: { mode: 'reusable' },\n execArgv: scriptablePackWorkerExecArgv(),\n resourceLimits: { maxOldGenerationSizeMb: 256, maxYoungGenerationSizeMb: 64 },\n });\n this.worker.on('message', (message: unknown) => this.onMessage(message));\n this.worker.on('error', (error: Error) => {\n this.failed = true;\n this.rejectActive(error);\n void this.dispose('failure');\n });\n this.worker.on('exit', (code) => {\n if (code === 0 || this.disposal !== undefined) return;\n this.failed = true;\n this.rejectActive(new Error(`ScriptablePack worker exited with code ${code}`));\n void this.dispose('failure');\n });\n // Listener registration can retain the worker's MessagePort in Node.\n // A reusable worker must not keep a completed Vite build alive while its\n // pool is draining; it still processes messages while the host is live.\n this.worker.unref();\n }\n\n async load(sourcePath: string): Promise<unknown> {\n const activeDisposal = this.disposal;\n if (activeDisposal !== undefined) {\n await activeDisposal;\n if (this.failed) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n this.disposal = undefined;\n }\n this.released = false;\n if (this.pendingLoad !== undefined || this.build !== undefined) {\n return Promise.reject(new Error('ScriptablePack executor already has an active task'));\n }\n const compileRoot = this.compileRoot ?? (await this.compileRootReady);\n if (this.disposal !== undefined) {\n const disposal = this.disposal;\n await disposal;\n if (this.failed) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n this.disposal = undefined;\n }\n const loadId = this.nextLoadId++;\n this.compileRoot = compileRoot;\n this.taskCount += 1;\n return new Promise((resolveLoad, rejectLoad) => {\n this.pendingLoad = { id: loadId, resolve: resolveLoad, reject: rejectLoad };\n try {\n this.worker.postMessage({\n kind: 'load',\n loadId,\n sourcePath: resolve(sourcePath),\n compileRoot,\n });\n } catch (error) {\n this.pendingLoad = undefined;\n rejectLoad(error);\n void this.dispose('failure');\n }\n });\n }\n\n dispose(reason: 'complete' | 'timeout' | 'failure' = 'complete'): Promise<void> {\n if (reason === 'failure') this.forceDispose = true;\n const activeDisposal = this.disposal;\n if (activeDisposal !== undefined) {\n return activeDisposal;\n }\n this.rejectActive(new Error(`ScriptablePack task disposed during ${reason}`));\n this.disposal = (async () => {\n const compileRoot = this.compileRoot ?? (await this.compileRootReady);\n const reusable =\n reason === 'complete' &&\n !this.failed &&\n !this.forceDispose &&\n this.taskCount < this.maxTasksPerWorker;\n this.forceDispose = false;\n if (!reusable) {\n this.compileRoot = undefined;\n await this.worker.terminate();\n await rm(compileRoot, { recursive: true, force: true });\n }\n this.released = true;\n this.disposal = undefined;\n this.release(this, reusable);\n })();\n return this.disposal;\n }\n\n private rejectActive(error: unknown): void {\n const loading = this.pendingLoad;\n this.pendingLoad = undefined;\n loading?.reject(error);\n const building = this.build;\n this.build = undefined;\n building?.reject(error);\n }\n\n private runBuild(reader: AssetReader): Promise<unknown> {\n if (this.released || this.disposal !== undefined) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n if (this.build !== undefined) {\n return Promise.reject(new Error('ScriptablePack worker already has an active build'));\n }\n const id = this.nextBuildId++;\n return new Promise((resolveBuild, rejectBuild) => {\n this.build = { id, reader, resolve: resolveBuild, reject: rejectBuild };\n try {\n this.worker.postMessage({ kind: 'build', buildId: id });\n } catch (error) {\n this.build = undefined;\n rejectBuild(error);\n void this.dispose('failure');\n }\n });\n }\n\n private onMessage(message: unknown): void {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n const loading = this.pendingLoad;\n if (loading !== undefined && value.kind === 'loaded' && value.loadId === loading.id) {\n this.pendingLoad = undefined;\n loading.resolve({\n default:\n value.definition === undefined\n ? undefined\n : {\n ...(value.definition as Record<string, unknown>),\n build: (reader: AssetReader) => this.runBuild(reader),\n },\n });\n return;\n }\n if (loading !== undefined && value.kind === 'load-threw' && value.loadId === loading.id) {\n this.pendingLoad = undefined;\n loading.reject(hydrateFailure(value.error));\n return;\n }\n const active = this.build;\n if (active === undefined || value.buildId !== active.id) return;\n if (value.kind === 'asset-read' && typeof value.readId === 'number') {\n void active.reader\n .readByGuid(value.guid as AssetGuid)\n .then((result) =>\n this.worker.postMessage({\n kind: 'asset-result',\n readId: value.readId,\n result:\n result.ok === true ? result : { ...result, error: serializeFailure(result.error) },\n }),\n )\n .catch((error: unknown) => {\n if (this.build?.id !== active.id) return;\n this.build = undefined;\n active.reject(error);\n void this.dispose('failure');\n });\n return;\n }\n this.build = undefined;\n if (value.kind === 'build-result') active.resolve(value.result);\n else if (value.kind === 'build-threw') active.reject(hydrateFailure(value.error));\n else this.build = active;\n }\n}\n\nclass DefaultScriptablePackModuleExecutorPool implements ScriptablePackModuleExecutorPool {\n private readonly maxWorkers: number;\n private readonly maxTasksPerWorker: number;\n private readonly idle: ReusableWorkerScriptablePackExecutor[] = [];\n private readonly waiters: {\n readonly resolve: (executor: ScriptablePackModuleExecutor) => void;\n readonly reject: (reason: unknown) => void;\n }[] = [];\n private readonly executors = new Set<ReusableWorkerScriptablePackExecutor>();\n private workerCount = 0;\n private closed = false;\n\n constructor(options: ScriptablePackModuleExecutorPoolOptions = {}) {\n this.maxWorkers = Math.max(1, Math.trunc(options.maxWorkers ?? 2));\n this.maxTasksPerWorker = Math.max(1, Math.trunc(options.maxTasksPerWorker ?? 32));\n }\n\n acquire(): Promise<ScriptablePackModuleExecutor> {\n if (this.closed) return Promise.reject(new Error('ScriptablePack executor pool is closed'));\n const executor = this.idle.pop();\n if (executor !== undefined) return Promise.resolve(executor);\n if (this.workerCount < this.maxWorkers) {\n this.workerCount += 1;\n return Promise.resolve(this.createExecutor());\n }\n return new Promise((resolveAcquire, rejectAcquire) =>\n this.waiters.push({ resolve: resolveAcquire, reject: rejectAcquire }),\n );\n }\n\n async dispose(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n const waiters = this.waiters.splice(0);\n for (const waiter of waiters) {\n waiter.reject(new Error('ScriptablePack executor pool is closed'));\n }\n this.idle.splice(0);\n await Promise.all([...this.executors].map((executor) => executor.dispose('failure')));\n }\n\n private createExecutor(): ReusableWorkerScriptablePackExecutor {\n const executor = new ReusableWorkerScriptablePackExecutor(\n this.maxTasksPerWorker,\n (executor, reusable) => {\n if (this.closed) {\n this.executors.delete(executor);\n if (!reusable) this.workerCount -= 1;\n return;\n }\n if (!reusable) {\n this.executors.delete(executor);\n this.workerCount -= 1;\n } else {\n this.idle.push(executor);\n }\n this.drain();\n },\n );\n this.executors.add(executor);\n return executor;\n }\n\n private drain(): void {\n if (this.closed) return;\n while (this.waiters.length > 0) {\n const idle = this.idle.pop();\n if (idle !== undefined) {\n this.waiters.shift()?.resolve(idle);\n continue;\n }\n if (this.workerCount >= this.maxWorkers) return;\n this.workerCount += 1;\n this.waiters.shift()?.resolve(this.createExecutor());\n }\n }\n}\n\nexport function createScriptablePackModuleExecutorPool(\n options: ScriptablePackModuleExecutorPoolOptions = {},\n): ScriptablePackModuleExecutorPool {\n return new DefaultScriptablePackModuleExecutorPool(options);\n}\n\nfunction loadFailure(\n sourcePath: string,\n reason: 'module-load' | 'timeout',\n phase: 'module-load' | 'build',\n diagnostic: string,\n timeoutMs?: number,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-load-failed',\n expected: 'a trusted synchronous module with a valid default ScriptablePack export',\n hint: 'repair the module load or initialization failure, then inspect Meta again',\n detail: {\n sourcePath,\n reason,\n phase,\n diagnostic,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n },\n });\n}\n\nfunction buildTimeoutFailure(sourcePath: string, timeoutMs: number): ScriptablePackReadError {\n return {\n code: 'pack-source-load-failed',\n expected: 'a ScriptablePack build to settle within the configured build timeout',\n hint: 'repair the authored build, then retry through a fresh ScriptablePack generation',\n detail: {\n sourcePath,\n reason: 'timeout',\n phase: 'build',\n timeoutMs,\n diagnostic: `ScriptablePack build exceeded ${timeoutMs}ms`,\n },\n };\n}\n\nexport async function loadScriptablePack(\n sourcePath: string,\n options: LoadScriptablePackOptions = {},\n): Promise<Result<Readonly<ScriptablePackDefinition>, ScriptablePackError>> {\n const timeoutMs = options.timeoutMs ?? 5_000;\n const buildTimeoutMs = options.buildTimeoutMs ?? 5_000;\n const executor = options.executor ?? new WorkerScriptablePackExecutor();\n let disposeReason: 'complete' | 'timeout' | 'failure' | undefined;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n const timeoutSignal = Symbol('scriptable-pack-module-timeout');\n const loaded = await Promise.race([\n executor.load(sourcePath),\n new Promise<typeof timeoutSignal>((resolve) => {\n timeout = setTimeout(() => resolve(timeoutSignal), timeoutMs);\n }),\n ]);\n if (loaded === timeoutSignal) {\n disposeReason = 'timeout';\n return loadFailure(\n sourcePath,\n 'timeout',\n 'module-load',\n `ScriptablePack module initialization exceeded ${timeoutMs}ms`,\n timeoutMs,\n );\n }\n const moduleValue =\n loaded !== null && typeof loaded === 'object' && 'default' in loaded\n ? (loaded as { readonly default: unknown }).default\n : undefined;\n const validated = validateScriptablePackDefinition(moduleValue, sourcePath);\n if (!validated.ok) {\n disposeReason = 'failure';\n return validated;\n }\n if (options.metadataOnly === true) {\n disposeReason = 'complete';\n return validated;\n }\n const definition = validated.value;\n type BuildOutcome = Awaited<ReturnType<ScriptablePackDefinition['build']>>;\n return ok({\n ...definition,\n build: async (reader: AssetReader): Promise<BuildOutcome> => {\n let buildTimedOut = false;\n let buildTimeout: ReturnType<typeof setTimeout> | undefined;\n const timeoutResult = err(buildTimeoutFailure(sourcePath, buildTimeoutMs));\n try {\n const built = await Promise.race([\n Promise.resolve(definition.build(reader)),\n new Promise<BuildOutcome>((resolve) => {\n buildTimeout = setTimeout(() => {\n buildTimedOut = true;\n resolve(timeoutResult as BuildOutcome);\n }, buildTimeoutMs);\n }),\n ]);\n if (buildTimedOut) {\n await executor.dispose?.('timeout');\n return built;\n }\n await executor.dispose?.('complete');\n return built;\n } catch (error) {\n await executor.dispose?.('failure');\n throw error;\n } finally {\n if (buildTimeout !== undefined) clearTimeout(buildTimeout);\n }\n },\n });\n } catch (error) {\n const diagnostic = error instanceof Error ? error.message : String(error);\n disposeReason = 'failure';\n return loadFailure(sourcePath, 'module-load', 'module-load', diagnostic);\n } finally {\n if (timeout !== undefined) clearTimeout(timeout);\n if (disposeReason !== undefined) await executor.dispose?.(disposeReason);\n }\n}\n\nconst CANONICAL_SCAFFOLD_MARKER = '// @forgeax-scriptable-pack canonical-v1';\nconst CANONICAL_MANIFEST_NAME = 'canonicalManifest';\nconst CANONICAL_MUTABLE_KINDS = new Set<ScriptablePackAssetKind>(['scene', 'mesh', 'material']);\n\ninterface CanonicalOutput {\n readonly guid: string;\n readonly kind: ScriptablePackAssetKind;\n readonly name?: string;\n}\n\ninterface CanonicalManifest {\n readonly schemaVersion: '1.0.0';\n readonly packageId: string;\n readonly name?: string;\n readonly assets: Readonly<Record<string, CanonicalOutput>>;\n readonly externalAssets: Readonly<Record<string, string>>;\n}\n\nexport interface FileSystemScriptablePackAuthoringOptions {\n /** All source and target paths are confined to this game root. */\n readonly gameRoot: string;\n readonly incomingRefs?: (sourcePath: string, sourceKey?: string) => Promise<readonly string[]>;\n readonly rebuild?: (\n sourcePath: string,\n mode: 'rebuild' | 'cold-cook',\n ) => Promise<Result<void, ScriptablePackError>>;\n}\n\nfunction authoringError(\n code:\n | 'pack-source-path-invalid'\n | 'pack-source-revision-conflict'\n | 'pack-source-mutation-unsupported'\n | 'pack-source-reference-conflict'\n | 'pack-source-write-failed',\n input: {\n readonly expected: string;\n readonly actual?: string;\n readonly hint: string;\n readonly retryable: boolean;\n readonly recoveryActions: readonly string[];\n readonly requestId?: string;\n readonly sourcePath?: string;\n readonly sourceKey?: string;\n readonly incomingRefs?: readonly string[];\n },\n): ScriptablePackError {\n return {\n code,\n expected: input.expected,\n ...(input.actual === undefined ? {} : { actual: input.actual }),\n hint: input.hint,\n retryable: input.retryable,\n recoveryActions: input.recoveryActions,\n detail: {\n ...(input.requestId === undefined ? {} : { requestId: input.requestId }),\n ...(input.sourcePath === undefined ? {} : { sourcePath: input.sourcePath }),\n ...(input.sourceKey === undefined ? {} : { sourceKey: input.sourceKey }),\n ...(input.incomingRefs === undefined ? {} : { incomingRefs: input.incomingRefs }),\n },\n };\n}\n\nfunction confinedSourcePath(\n gameRoot: string,\n sourcePath: string,\n): Result<{ readonly absolute: string; readonly relative: string }, ScriptablePackError> {\n const root = resolve(gameRoot);\n const absolute = resolve(root, sourcePath);\n const rel = relative(root, absolute);\n if (\n rel.length === 0 ||\n rel === '..' ||\n rel.startsWith(`..${sep}`) ||\n isAbsolute(sourcePath) ||\n !rel.endsWith('.pack.ts')\n ) {\n return err(\n authoringError('pack-source-path-invalid', {\n expected: 'a game-root-relative *.pack.ts path confined to the selected game',\n actual: sourcePath,\n hint: 'choose a relative ScriptablePack source path inside the selected game root',\n retryable: false,\n recoveryActions: ['choose-game-relative-source-path'],\n sourcePath,\n }),\n );\n }\n return ok({ absolute, relative: rel.split(sep).join('/') });\n}\n\nfunction revisionOf(source: string): string {\n return createHash('sha256').update(source).digest('hex');\n}\n\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n if (\n ts.isAsExpression(expression) ||\n ts.isSatisfiesExpression(expression) ||\n ts.isParenthesizedExpression(expression)\n ) {\n return unwrapExpression(expression.expression);\n }\n return expression;\n}\n\nfunction literalValue(expression: ts.Expression): unknown {\n const value = unwrapExpression(expression);\n if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value)) return value.text;\n if (value.kind === ts.SyntaxKind.TrueKeyword) return true;\n if (value.kind === ts.SyntaxKind.FalseKeyword) return false;\n if (value.kind === ts.SyntaxKind.NullKeyword) return null;\n if (ts.isNumericLiteral(value)) return Number(value.text);\n if (ts.isArrayLiteralExpression(value)) return value.elements.map(literalValue);\n if (ts.isObjectLiteralExpression(value)) {\n const result: Record<string, unknown> = {};\n for (const property of value.properties) {\n if (!ts.isPropertyAssignment(property))\n throw new TypeError('manifest properties must be data');\n const name = property.name;\n const key =\n ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)\n ? name.text\n : undefined;\n if (key === undefined) throw new TypeError('manifest property names must be static');\n result[key] = literalValue(property.initializer);\n }\n return result;\n }\n throw new TypeError('manifest values must be literal data');\n}\n\nfunction parseCanonicalManifest(source: string, sourcePath: string): CanonicalManifest | undefined {\n if (!source.startsWith(`${CANONICAL_SCAFFOLD_MARKER}\\n`)) return undefined;\n const file = ts.createSourceFile(\n sourcePath,\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n );\n for (const statement of file.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (\n ts.isIdentifier(declaration.name) &&\n declaration.name.text === CANONICAL_MANIFEST_NAME &&\n declaration.initializer !== undefined\n ) {\n const value = literalValue(declaration.initializer);\n if (value === null || typeof value !== 'object') return undefined;\n return value as CanonicalManifest;\n }\n }\n }\n return undefined;\n}\n\nfunction guidExpression(value: string): string {\n return `parseGuid(${JSON.stringify(value)})`;\n}\n\n/** Render the one source shape that the file authoring port may mutate structurally. */\nexport function renderCanonicalScriptablePack(manifest: CanonicalManifest): string {\n const data = JSON.stringify(manifest, null, 2);\n return `${CANONICAL_SCAFFOLD_MARKER}\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { buildMeshAttributeMapForUvSets } from '@forgeax/engine-geometry';\nimport type { ScriptablePackDefinition } from '@forgeax/engine-pack/source';\nimport type { Asset, AssetGuid as AssetGuidType } from '@forgeax/engine-types';\nimport { ok } from '@forgeax/engine-types';\n\nconst ${CANONICAL_MANIFEST_NAME} = ${data} as const;\n\nfunction parseGuid(value: string): AssetGuidType {\n const parsed = AssetGuid.parse(value);\n if (!parsed.ok) throw parsed.error;\n return parsed.value;\n}\n\nfunction createOutput(kind: string): Asset {\n switch (kind) {\n case 'scene':\n return { kind: 'scene', entities: [], mounts: [] };\n case 'material':\n return { kind: 'material', values: {} };\n case 'mesh': {\n const vertices = new Float32Array([\n 0, 0.7, 0, 0, 0, 1, 0.5, 1, 0, 0, 0, 1,\n -0.7, -0.6, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1,\n 0.7, -0.6, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1,\n ]);\n return {\n kind: 'mesh',\n vertices,\n indices: new Uint16Array([0, 1, 2]),\n attributes: { ...buildMeshAttributeMapForUvSets(1), position: vertices },\n aabb: new Float32Array([-0.7, -0.6, 0, 0.7, 0.7, 0]),\n submeshes: [{ indexOffset: 0, indexCount: 3, vertexCount: 3, topology: 'triangle-list', materialSlot: 0 }],\n materialSlots: [{ slotName: 'Default' }],\n };\n }\n default:\n throw new Error(\\`canonical ScriptablePack output kind is not mutable: \\${kind}\\`);\n }\n}\n\nconst assets = Object.fromEntries(\n Object.entries(${CANONICAL_MANIFEST_NAME}.assets).map(([sourceKey, asset]) => [\n sourceKey,\n { ...asset, guid: parseGuid(asset.guid) },\n ]),\n);\nconst externalAssets = Object.fromEntries(\n Object.entries(${CANONICAL_MANIFEST_NAME}.externalAssets).map(([alias, guid]) => [alias, parseGuid(guid)]),\n);\n\nexport default {\n schemaVersion: '1.0.0',\n packageId: ${guidExpression(manifest.packageId)},\n ${manifest.name === undefined ? '' : `name: ${JSON.stringify(manifest.name)},\\n `}assets,\n externalAssets,\n build: () => ok(Object.fromEntries(Object.entries(assets).map(([sourceKey, asset]) => [sourceKey, createOutput(asset.kind)])) as Record<string, Asset>),\n} satisfies ScriptablePackDefinition;\n`;\n}\n\nfunction definitionFromCanonical(\n manifest: CanonicalManifest,\n): Result<ScriptablePackDefinition, ScriptablePackError> {\n const packageId = AssetGuidCodec.parse(manifest.packageId);\n if (!packageId.ok) return invalidCanonicalGuid('$.packageId', manifest.packageId);\n const assets: Record<string, { guid: AssetGuid; kind: ScriptablePackAssetKind; name?: string }> =\n {};\n for (const [sourceKey, output] of Object.entries(manifest.assets)) {\n const guid = AssetGuidCodec.parse(output.guid);\n if (!guid.ok)\n return invalidCanonicalGuid(`$.assets[${JSON.stringify(sourceKey)}].guid`, output.guid);\n assets[sourceKey] = {\n guid: guid.value,\n kind: output.kind,\n ...(output.name === undefined ? {} : { name: output.name }),\n };\n }\n const externalAssets: Record<string, AssetGuid> = {};\n for (const [alias, value] of Object.entries(manifest.externalAssets)) {\n const guid = AssetGuidCodec.parse(value);\n if (!guid.ok) return invalidCanonicalGuid(`$.externalAssets[${JSON.stringify(alias)}]`, value);\n externalAssets[alias] = guid.value;\n }\n return validateScriptablePackDefinition({\n schemaVersion: '1.0.0',\n packageId: packageId.value,\n ...(manifest.name === undefined ? {} : { name: manifest.name }),\n assets,\n externalAssets,\n build: () => ok({} as Record<string, never>),\n });\n}\n\nfunction invalidCanonicalGuid(\n propertyPath: string,\n actual: string,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-definition-invalid',\n expected: 'a canonical UUID string',\n hint: 'repair the canonical scaffold manifest GUID and inspect Meta again',\n detail: { propertyPath, actual },\n });\n}\n\nfunction invalidCanonicalSource(\n sourcePath: string,\n error: unknown,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-definition-invalid',\n expected: 'a literal canonical-v1 manifest with the required package/assets/external fields',\n hint: 'repair the canonical scaffold or open it as custom source without structured mutation',\n detail: {\n sourcePath,\n propertyPath: '$.canonicalManifest',\n actual: error instanceof Error ? error.message : String(error),\n },\n });\n}\n\nasync function atomicWrite(path: string, source: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;\n try {\n await writeFile(temporary, source, { encoding: 'utf8', flag: 'wx' });\n await rename(temporary, path);\n } catch (error) {\n await rm(temporary, { force: true });\n throw error;\n }\n}\n\nfunction sameStrings(left: readonly string[], right: readonly string[]): boolean {\n return [...left].sort().join('\\0') === [...right].sort().join('\\0');\n}\n\n/** Node filesystem adapter for the public ScriptablePack authoring gateway. */\nexport function createFileSystemScriptablePackAuthoringPort(\n options: FileSystemScriptablePackAuthoringOptions,\n): ScriptablePackAuthoringPort {\n const resolvePath = (sourcePath: string) => confinedSourcePath(options.gameRoot, sourcePath);\n\n async function readSource(sourcePath: string) {\n const path = resolvePath(sourcePath);\n if (!path.ok) return path;\n try {\n const source = await readFile(path.value.absolute, 'utf8');\n return ok({ ...path.value, source, revision: revisionOf(source) });\n } catch (error) {\n return err(\n authoringError('pack-source-write-failed', {\n expected: 'a readable ScriptablePack source file',\n actual: error instanceof Error ? error.message : String(error),\n hint: 'restore the source file or create it through the ScriptablePack gateway',\n retryable: true,\n recoveryActions: ['inspect-source-path', 'retry'],\n sourcePath,\n }),\n );\n }\n }\n\n async function inspect(sourcePath: string) {\n const read = await readSource(sourcePath);\n if (!read.ok) return read;\n let canonical: CanonicalManifest | undefined;\n try {\n canonical = parseCanonicalManifest(read.value.source, read.value.relative);\n } catch (error) {\n return invalidCanonicalSource(read.value.relative, error);\n }\n const loaded =\n canonical === undefined\n ? await loadScriptablePack(read.value.absolute, { metadataOnly: true })\n : definitionFromCanonical(canonical);\n if (!loaded.ok) return loaded;\n return ok({\n revision: read.value.revision,\n meta: projectScriptablePackMeta(loaded.value, read.value.relative),\n });\n }\n\n async function preflight(sourcePath: string) {\n const read = await readSource(sourcePath);\n if (!read.ok) return read;\n const inspected = await inspect(sourcePath);\n if (!inspected.ok) return inspected;\n let canonical: CanonicalManifest | undefined;\n try {\n canonical = parseCanonicalManifest(read.value.source, read.value.relative);\n } catch (error) {\n return invalidCanonicalSource(read.value.relative, error);\n }\n const incomingRefs = (await options.incomingRefs?.(read.value.relative)) ?? [];\n return ok({\n revision: inspected.value.revision,\n meta: inspected.value.meta,\n capabilities:\n canonical === undefined\n ? ({\n inspect: true,\n rebuild: true,\n coldCook: true,\n reason: 'structured mutation is available only for canonical-v1 scaffolds',\n } as const)\n : ({\n inspect: true,\n rebuild: true,\n coldCook: true,\n addOutput: true,\n addExternalAsset: true,\n renameDisplay: true,\n removeOutput: true,\n clone: true,\n } as const),\n incomingRefs,\n });\n }\n\n async function mutate(operation: ScriptablePackAuthoringMutation) {\n const targetPath =\n operation.kind === 'clone-scriptable-pack' ? operation.targetPath : operation.sourcePath;\n const target = resolvePath(targetPath);\n if (!target.ok) return target;\n\n let manifest: CanonicalManifest;\n let currentRevision: string | undefined;\n if (operation.kind === 'create-scriptable-pack') {\n if (!CANONICAL_MUTABLE_KINDS.has(operation.initialOutput.kind)) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'a canonical scene, mesh, or material initial output',\n actual: operation.initialOutput.kind,\n hint: 'create one of the canonical output kinds, then hand-author advanced outputs',\n retryable: false,\n recoveryActions: ['choose-supported-output-kind'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n }\n try {\n await stat(target.value.absolute);\n return err(\n authoringError('pack-source-revision-conflict', {\n expected: 'an unused target source path',\n actual: 'source already exists',\n hint: 'inspect the existing source or choose a new path',\n retryable: false,\n recoveryActions: ['asset.preflight', 'choose-new-source-path'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n } catch {\n // Missing is the required create precondition.\n }\n manifest = {\n schemaVersion: '1.0.0',\n packageId: AssetGuidCodec.format(operation.packageId),\n ...(operation.name === undefined ? {} : { name: operation.name }),\n assets: {\n [operation.initialOutput.sourceKey]: {\n guid: AssetGuidCodec.format(operation.initialOutput.guid),\n kind: operation.initialOutput.kind,\n ...(operation.initialOutput.name === undefined\n ? {}\n : { name: operation.initialOutput.name }),\n },\n },\n externalAssets: {},\n };\n } else {\n const read = await readSource(operation.sourcePath);\n if (!read.ok) return read;\n currentRevision = read.value.revision;\n if (\n operation.expectedRevision !== undefined &&\n operation.expectedRevision !== currentRevision\n ) {\n return err(\n authoringError('pack-source-revision-conflict', {\n expected: operation.expectedRevision,\n actual: currentRevision,\n hint: 'inspect the current source revision, reconcile the edit, then retry with a new requestId',\n retryable: true,\n recoveryActions: ['asset.preflight', 'mint-request-id'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n }\n let parsed: CanonicalManifest | undefined;\n try {\n parsed = parseCanonicalManifest(read.value.source, read.value.relative);\n } catch (error) {\n return invalidCanonicalSource(read.value.relative, error);\n }\n if (parsed === undefined) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'a canonical-v1 scaffold for structured source mutation',\n actual: 'custom ScriptablePack source',\n hint: 'clone into a canonical scaffold or edit custom source with a code editor',\n retryable: false,\n recoveryActions: ['clone-scriptable-pack', 'open-code-editor'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n }\n manifest = parsed;\n }\n\n if (operation.kind === 'clone-scriptable-pack') {\n try {\n await stat(target.value.absolute);\n return err(\n authoringError('pack-source-revision-conflict', {\n expected: 'an unused clone target source path',\n actual: 'source already exists',\n hint: 'inspect the existing target or choose a new path',\n retryable: false,\n recoveryActions: ['asset.preflight', 'choose-new-source-path'],\n requestId: operation.requestId,\n sourcePath: target.value.relative,\n }),\n );\n } catch {\n // Missing is the required clone precondition.\n }\n }\n\n if (operation.kind === 'add-output') {\n if (!CANONICAL_MUTABLE_KINDS.has(operation.assetKind)) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'a canonical scene, mesh, or material output',\n actual: operation.assetKind,\n hint: 'hand-author advanced output kinds in the source module',\n retryable: false,\n recoveryActions: ['open-code-editor'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.sourceKey,\n }),\n );\n }\n manifest = {\n ...manifest,\n assets: {\n ...manifest.assets,\n [operation.sourceKey]: {\n guid: AssetGuidCodec.format(operation.guid),\n kind: operation.assetKind,\n ...(operation.name === undefined ? {} : { name: operation.name }),\n },\n },\n };\n } else if (operation.kind === 'add-external-asset') {\n manifest = {\n ...manifest,\n externalAssets: {\n ...manifest.externalAssets,\n [operation.alias]: AssetGuidCodec.format(operation.guid),\n },\n };\n } else if (operation.kind === 'rename-display') {\n if (operation.target.kind === 'package') manifest = { ...manifest, name: operation.name };\n else {\n const output = manifest.assets[operation.target.sourceKey];\n if (output === undefined)\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'an existing sourceKey',\n actual: operation.target.sourceKey,\n hint: 'inspect Meta and choose a current output',\n retryable: true,\n recoveryActions: ['asset.preflight'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.target.sourceKey,\n }),\n );\n manifest = {\n ...manifest,\n assets: {\n ...manifest.assets,\n [operation.target.sourceKey]: { ...output, name: operation.name },\n },\n };\n }\n } else if (operation.kind === 'remove-output') {\n const incomingRefs =\n (await options.incomingRefs?.(operation.sourcePath, operation.sourceKey)) ?? [];\n if (\n incomingRefs.length > 0 &&\n !sameStrings(incomingRefs, operation.confirmIncomingRefs ?? [])\n ) {\n return err(\n authoringError('pack-source-reference-conflict', {\n expected: 'explicit acknowledgement of every current incoming reference',\n actual: `${incomingRefs.length} incoming references`,\n hint: 'inspect dependents, then confirm the exact incoming reference identities or cancel',\n retryable: true,\n recoveryActions: ['inspect-incoming-refs', 'confirm-remove-output'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.sourceKey,\n incomingRefs,\n }),\n );\n }\n const { [operation.sourceKey]: removed, ...assets } = manifest.assets;\n if (removed === undefined || Object.keys(assets).length === 0) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'an existing output while retaining at least one package output',\n actual: operation.sourceKey,\n hint: 'keep one output or remove the entire source file through an explicit file operation',\n retryable: false,\n recoveryActions: ['asset.preflight'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.sourceKey,\n }),\n );\n }\n manifest = { ...manifest, assets };\n } else if (operation.kind === 'clone-scriptable-pack') {\n manifest = {\n ...manifest,\n packageId: AssetGuidCodec.format(operation.packageId),\n assets: Object.fromEntries(\n Object.entries(manifest.assets).map(([sourceKey, output]) => [\n sourceKey,\n {\n ...output,\n guid: AssetGuidCodec.format(operation.outputGuids[sourceKey] as AssetGuid),\n },\n ]),\n ),\n };\n }\n\n const source = renderCanonicalScriptablePack(manifest);\n try {\n await atomicWrite(target.value.absolute, source);\n return ok({ sourcePath: target.value.relative, revision: revisionOf(source) });\n } catch (error) {\n return err(\n authoringError('pack-source-write-failed', {\n expected: 'an atomic source-file replacement',\n actual: error instanceof Error ? error.message : String(error),\n hint: 'repair filesystem permissions or disk capacity, then retry with a new requestId',\n retryable: true,\n recoveryActions: ['inspect-filesystem', 'mint-request-id'],\n requestId: operation.requestId,\n sourcePath: target.value.relative,\n }),\n );\n }\n }\n\n return {\n preflight,\n mutate,\n inspect,\n async rebuild(sourcePath, mode) {\n const path = resolvePath(sourcePath);\n if (!path.ok) return path;\n const rebuilt = (await options.rebuild?.(path.value.relative, mode)) ?? ok(undefined);\n return rebuilt.ok ? inspect(path.value.relative) : rebuilt;\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/guid.ts","../src/scriptable-pack.ts","../src/evidence/source-inventory.ts","../src/scriptable-pack-node.ts"],"names":["resolve","dirname","readFile","createHash","executor","err","ok","relative","sep","actual"],"mappings":";;;;;;;;;;;;;;AA2BO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACA,QAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EAET,YAAY,IAAA,EAKT;AACD,IAAA,KAAA,CAAM,CAAA,WAAA,EAAc,KAAK,IAAI,CAAA,YAAA,EAAe,KAAK,QAAQ,CAAA,QAAA,EAAW,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AAC/E,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AACrB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AAAA,EACrB;AACF,CAAA;AC/BA,SAAS,MAAM,KAAA,EAA8B;AAC3C,EAAA,OAAO,KAAA;AACT;AAEA,IAAM,WAAW,KAAA,CAAM,IAAA,CAAK,EAAE,MAAA,EAAQ,KAAI,EAAG,CAAC,CAAA,EAAG,CAAA,KAAM,EAAE,QAAA,CAAS,EAAE,EAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAC,CAAA;AAEtF,SAAS,gBAAgB,KAAA,EAA2B;AAClD,EAAA,MAAM,CAAA,GAAI,QAAA;AAEV,EAAA,OAAO,CAAA,EAAG,EAAE,KAAA,CAAM,CAAC,CAAE,CAAC,CAAA,EAAG,EAAE,KAAA,CAAM,CAAC,CAAE,CAAC,CAAA,EAAG,EAAE,KAAA,CAAM,CAAC,CAAE,CAAC,CAAA,EAAG,EAAE,KAAA,CAAM,CAAC,CAAE,CAAC,CAAA,CAAA,EAAI,EAAE,KAAA,CAAM,CAAC,CAAE,CAAC,CAAA,EAAG,EAAE,KA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,CAAA;AAAA,UACzD,WAAW,SAAA,CAAU,SAAA;AAAA,UACrB,UAAA,EAAY,OAAO,KAAA,CAAM;AAAA,SAC1B;AAAA,OACH;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,SAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,MAAM,OAAA,CAAQ,UAAA,EAAY,IAAA,EAAM;AAC9B,MAAA,MAAM,IAAA,GAAO,YAAY,UAAU,CAAA;AACnC,MAAA,IAAI,CAAC,IAAA,CAAK,EAAA,EAAI,OAAO,IAAA;AACrB,MAAA,MAAM,OAAA,GAAW,MAAM,OAAA,CAAQ,OAAA,GAAU,IAAA,CAAK,MAAM,QAAA,EAAU,IAAI,CAAA,IAAMC,EAAAA,CAAG,MAAS,CAAA;AACpF,MAAA,OAAO,QAAQ,EAAA,GAAK,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,QAAQ,CAAA,GAAI,OAAA;AAAA,IACrD;AAAA,GACF;AACF","file":"scriptable-pack-node.mjs","sourcesContent":["// errors.ts — PackError class (feat-20260513-guid-asset-package-system w15)\n//\n// Four-field surface: .code / .expected / .hint / .detail\n// Structurally parallel to AssetError / RhiError / RemoteError\n// (charter proposition 5 consistent abstraction).\n//\n// .detail is narrowed per .code via PackErrorDetail discriminated union\n// (requirements §6.2 AC-07; plan-strategy §D-5).\n\nimport type { PackErrorCode, PackErrorDetail } from '@forgeax/engine-types';\n\n/**\n * Structured error for the engine-pack disk scanner fail-fast chain.\n *\n * AI users consume via exhaustive switch on .code — no default case needed:\n * ```ts\n * switch (err.code) {\n * case 'pack-guid-collision':\n * console.error(err.detail.paths);\n * break;\n * case 'pack-cyclic-reference':\n * console.error(err.detail.cycle);\n * break;\n * // ...all 8 cases\n * }\n * ```\n */\nexport class PackError extends Error {\n readonly code: PackErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: PackErrorDetail;\n\n constructor(args: {\n code: PackErrorCode;\n expected: string;\n hint: string;\n detail: PackErrorDetail;\n }) {\n super(`[PackError ${args.code}] expected: ${args.expected}; hint: ${args.hint}`);\n this.name = 'PackError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n","import { uuidv7obj } from 'uuidv7';\nimport { PackError } from './errors.js';\n\n/**\n * 16-byte UUID branded ABI. Prevents assignment from plain Uint8Array or string.\n * Brand field mirrors the declaration in @forgeax/engine-types for cross-package\n * structural compatibility (both use __guidBrand: 'AssetGuid').\n */\nexport type AssetGuid = Uint8Array & { readonly __guidBrand: 'AssetGuid' };\n\n/** Minimal Result alias for this module (structurally compatible with ScanResult). */\nexport type GuidResult<T, E> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: E };\n\nfunction brand(bytes: Uint8Array): AssetGuid {\n return bytes as AssetGuid;\n}\n\nconst HEX_BYTE = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n\nfunction bytesToDashForm(bytes: Uint8Array): string {\n const h = HEX_BYTE;\n // biome-ignore lint/style/noNonNullAssertion: length guaranteed 16\n return `${h[bytes[0]!]}${h[bytes[1]!]}${h[bytes[2]!]}${h[bytes[3]!]}-${h[bytes[4]!]}${h[bytes[5]!]}-${h[bytes[6]!]}${h[bytes[7]!]}-${h[bytes[8]!]}${h[bytes[9]!]}-${h[bytes[10]!]}${h[bytes[11]!]}${h[bytes[12]!]}${h[bytes[13]!]}${h[bytes[14]!]}${h[bytes[15]!]}`;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport function isValidAssetGuidString(value: unknown): value is string {\n return typeof value === 'string' && UUID_RE.test(value);\n}\n\nfunction dashFormToBytes(dashForm: string): Uint8Array {\n const hex = dashForm.replace(/-/g, '');\n const bytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++) {\n bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Utilities for the AssetGuid branded 16-byte UUID type.\n * Declare the type via `import type { AssetGuid } from '@forgeax/engine-pack/guid'`\n * or `import type { AssetGuid } from '@forgeax/engine-types'`.\n */\nexport const AssetGuid = {\n /**\n * Parse a 36-char RFC 4122 dash-form UUID string into an AssetGuid.\n * Returns Ok(AssetGuid) on success or Err(PackError) with code 'pack-guid-malformed' on failure.\n * Never throws for expected failures (requirements §4.2 / §14 / charter proposition 4).\n */\n parse(dashForm: string): GuidResult<AssetGuid, PackError> {\n if (!isValidAssetGuidString(dashForm)) {\n return {\n ok: false,\n error: new PackError({\n code: 'pack-guid-malformed',\n expected: '36-char RFC 4122 dash-form UUID',\n hint: 'use AssetGuid.random() or a UUIDv7 generator; all GUID fields must be 36-char RFC 4122 dash-form',\n detail: {\n raw: dashForm,\n reason: 'expected 36-char RFC 4122 dash-form UUID',\n },\n }),\n };\n }\n return { ok: true, value: brand(dashFormToBytes(dashForm)) };\n },\n\n /**\n * Format an AssetGuid as a 36-char RFC 4122 lowercase dash-form string.\n */\n format(guid: AssetGuid): string {\n return bytesToDashForm(guid);\n },\n\n /**\n * Test byte-by-byte equality between two AssetGuids.\n */\n equals(a: AssetGuid, b: AssetGuid): boolean {\n for (let i = 0; i < 16; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n },\n\n /**\n * Mint a new time-ordered UUIDv7 as an AssetGuid.\n * Works in both Node.js and browser environments.\n */\n random(): AssetGuid {\n const uuid = uuidv7obj();\n const bytes = new Uint8Array(16);\n bytes.set(uuid.bytes);\n return brand(bytes);\n },\n} as const;\n","import type { Asset, AssetGuid, AssetPublicationEnvelope, Result } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport { AssetGuid as AssetGuidCodec } from './guid.js';\n\n/** Closed ordinary kind vocabulary shared by authoring, producers, and loaders. */\nexport type ScriptablePackAssetKind = Asset['kind'];\n\n/** Complete ordinary Asset kind vocabulary exposed by ScriptablePack discovery. */\nexport const SCRIPTABLE_PACK_ASSET_KINDS = [\n 'mesh',\n 'material',\n 'scene',\n 'texture',\n 'equirect',\n 'sampler',\n 'font',\n 'render-pipeline',\n 'tileset',\n 'video',\n 'skeleton',\n 'skin',\n 'animation-clip',\n 'animation-graph',\n 'audio',\n 'particle-effect',\n] as const satisfies readonly ScriptablePackAssetKind[];\n\n/** Machine-readable producer/loader floor owned by engine-pack. */\nexport const SCRIPTABLE_PACK_CAPABILITY_MANIFEST = {\n assetKinds: SCRIPTABLE_PACK_ASSET_KINDS,\n durablePayload: true,\n refs: true,\n artifacts: true,\n hostCapabilities: ['audio-install', 'video-play', 'particle-execute'] as const,\n} as const;\n\nexport function isScriptablePackAssetKind(value: string): value is ScriptablePackAssetKind {\n return (SCRIPTABLE_PACK_ASSET_KINDS as readonly string[]).includes(value);\n}\n\nexport interface ScriptablePackAssetDeclaration<\n TKind extends ScriptablePackAssetKind = ScriptablePackAssetKind,\n> {\n readonly guid: AssetGuid;\n readonly kind: TKind;\n readonly name?: string;\n}\n\nexport type ScriptablePackAssetDeclarations = Readonly<\n Record<string, ScriptablePackAssetDeclaration>\n>;\n\nexport type ScriptablePackExternalAssets = Readonly<Record<string, AssetGuid>>;\n\n/**\n * Component-shaped input accepted by a ScriptablePack scene declaration.\n * Engine component tokens satisfy this shape; plain `{ type }` rows keep the\n * Pack contract independent of ECS and survive the isolated module worker.\n */\nexport interface ScriptablePackSceneComponentInput {\n readonly name: string;\n readonly fields: Readonly<Record<string, string | { readonly type: string }>>;\n}\n\n/** Neutral scene schema projection owned by the Pack definition. */\nexport interface ScriptablePackSceneComponent {\n readonly name: string;\n readonly fields: Readonly<Record<string, string>>;\n}\n\nfunction sceneComponentFieldType(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (isRecord(value) && typeof value.type === 'string') return value.type;\n return undefined;\n}\n\n/** Derive the frozen, ECS-neutral schema used by scene output producers. */\nexport function projectScriptablePackSceneComponents(\n components: readonly ScriptablePackSceneComponentInput[] | undefined,\n): readonly ScriptablePackSceneComponent[] {\n return (components ?? []).map((component) => ({\n name: component.name,\n fields: Object.fromEntries(\n Object.entries(component.fields).map(([fieldName, field]) => [\n fieldName,\n sceneComponentFieldType(field) as string,\n ]),\n ),\n }));\n}\n\n/** Pack-facing name for the shared Engine publication envelope. */\nexport type ScriptablePackPublicationEnvelope = AssetPublicationEnvelope;\n\n/** Structured domain failure permitted to cross the isolated build-time AssetReader seam. */\nexport interface ScriptablePackErrorProvenance {\n /** Published source generation observed by the reader, when available. */\n readonly generation?: number;\n /** Stable producer identity for the failed output, when available. */\n readonly sourceKey?: string;\n /** GUID associated with the failed read or output, when available. */\n readonly guid?: string;\n}\n\nexport interface ScriptablePackReadError {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail?: unknown;\n readonly provenance?: ScriptablePackErrorProvenance;\n}\n\nexport type ScriptablePackAssetFor<TDescriptor extends ScriptablePackAssetDeclaration> =\n TDescriptor extends { readonly kind: infer TKind extends ScriptablePackAssetKind }\n ? Extract<Asset, { readonly kind: TKind }>\n : never;\n\nexport type ScriptablePackOutputs<TAssets extends ScriptablePackAssetDeclarations> = {\n readonly [TKey in keyof TAssets]: TAssets[TKey] extends ScriptablePackAssetDeclaration\n ? ScriptablePackAssetFor<TAssets[TKey]>\n : never;\n};\n\nexport interface AssetReader {\n /** Load a declared GUID as a durable payload; this never mints a World handle. */\n readByGuid<TAsset extends Asset = Asset>(\n guid: AssetGuid,\n ): Promise<Result<TAsset, ScriptablePackReadError>>;\n}\n\nexport type ScriptablePackBuildResult<\n TAssets extends ScriptablePackAssetDeclarations,\n TError,\n> = Result<ScriptablePackOutputs<TAssets>, TError>;\n\nexport interface ScriptablePackDefinition<\n TAssets extends ScriptablePackAssetDeclarations = ScriptablePackAssetDeclarations,\n TExternal extends ScriptablePackExternalAssets = ScriptablePackExternalAssets,\n TError = ScriptablePackReadError,\n> {\n readonly schemaVersion: '1.0.0';\n readonly packageId: AssetGuid;\n readonly name?: string;\n readonly assets: TAssets;\n /** Component tokens/schema rows used by scene ref externalization. */\n readonly sceneComponents?: readonly ScriptablePackSceneComponentInput[];\n readonly externalAssets: TExternal;\n readonly build: (\n assetReader: AssetReader,\n ) =>\n | ScriptablePackBuildResult<TAssets, TError>\n | Promise<ScriptablePackBuildResult<TAssets, TError>>;\n}\n\nexport interface ScriptablePackSourceClosureEntry {\n readonly path: string;\n readonly digest: string;\n}\n\nexport interface ScriptablePackMetaJson {\n readonly schemaVersion: '1.0.0';\n readonly kind: 'external-asset-package';\n readonly packageId: string;\n readonly name?: string;\n readonly importer: 'pack-ts';\n readonly source: string;\n readonly importSettings: {\n readonly contractVersion: '1.0.0';\n readonly externalAssets: readonly {\n readonly alias: string;\n readonly guid: string;\n }[];\n };\n readonly subAssets: readonly {\n readonly guid: string;\n readonly sourceIndex: number;\n readonly sourceKey: string;\n readonly kind: ScriptablePackAssetKind;\n readonly name?: string;\n }[];\n}\n\nexport interface ScriptablePackOperationEnvelope {\n readonly requestId: string;\n readonly expectedRevision?: string;\n}\n\nexport type ScriptablePackGatewayOperation =\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'preflight';\n readonly sourcePath: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'create-scriptable-pack';\n readonly sourcePath: string;\n readonly name?: string;\n readonly initialOutput: {\n readonly sourceKey: string;\n readonly kind: ScriptablePackAssetKind;\n readonly name?: string;\n };\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'add-output';\n readonly sourcePath: string;\n readonly sourceKey: string;\n readonly assetKind: ScriptablePackAssetKind;\n readonly name?: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'add-external-asset';\n readonly sourcePath: string;\n readonly alias: string;\n readonly guid: AssetGuid;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'rename-display';\n readonly sourcePath: string;\n readonly target:\n | { readonly kind: 'package' }\n | { readonly kind: 'output'; readonly sourceKey: string };\n readonly name: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'remove-output';\n readonly sourcePath: string;\n readonly sourceKey: string;\n /** Exact incoming reference identities acknowledged by the caller. */\n readonly confirmIncomingRefs?: readonly string[];\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'clone-scriptable-pack';\n readonly sourcePath: string;\n readonly targetPath: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'inspect-meta';\n readonly sourcePath: string;\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'rebuild' | 'cold-cook';\n readonly sourcePath: string;\n });\n\nexport interface ScriptablePackMutationCapabilities {\n readonly inspect: true;\n readonly rebuild: true;\n readonly coldCook: true;\n readonly create?: true;\n readonly addOutput?: true;\n readonly addExternalAsset?: true;\n readonly renameDisplay?: true;\n readonly removeOutput?: true;\n readonly clone?: true;\n readonly reason?: string;\n}\n\nexport interface ScriptablePackPreflight {\n readonly sourcePath: string;\n readonly revision: string;\n readonly meta: ScriptablePackMetaJson;\n readonly capabilities: ScriptablePackMutationCapabilities;\n readonly incomingRefs: readonly string[];\n}\n\nexport interface ScriptablePackGatewayMutation {\n readonly sourcePath: string;\n readonly revision: string;\n readonly meta: ScriptablePackMetaJson;\n}\n\nexport interface ScriptablePackAuthoringGateway {\n execute(\n operation: ScriptablePackGatewayOperation,\n ): Promise<Result<ScriptablePackGatewayMutation | ScriptablePackPreflight, ScriptablePackError>>;\n}\n\nexport type ScriptablePackAuthoringMutation =\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'create-scriptable-pack';\n readonly sourcePath: string;\n readonly packageId: AssetGuid;\n readonly name?: string;\n readonly initialOutput: {\n readonly sourceKey: string;\n readonly kind: ScriptablePackAssetKind;\n readonly guid: AssetGuid;\n readonly name?: string;\n };\n })\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'add-output';\n readonly sourcePath: string;\n readonly sourceKey: string;\n readonly assetKind: ScriptablePackAssetKind;\n readonly guid: AssetGuid;\n readonly name?: string;\n })\n | Extract<\n ScriptablePackGatewayOperation,\n { readonly kind: 'add-external-asset' | 'rename-display' | 'remove-output' }\n >\n | (ScriptablePackOperationEnvelope & {\n readonly kind: 'clone-scriptable-pack';\n readonly sourcePath: string;\n readonly targetPath: string;\n readonly packageId: AssetGuid;\n readonly outputGuids: Readonly<Record<string, AssetGuid>>;\n });\n\nexport interface ScriptablePackAuthoringPort {\n preflight(\n sourcePath: string,\n ): Promise<Result<Omit<ScriptablePackPreflight, 'sourcePath'>, ScriptablePackError>>;\n mutate(\n operation: ScriptablePackAuthoringMutation,\n ): Promise<\n Result<{ readonly sourcePath: string; readonly revision: string }, ScriptablePackError>\n >;\n inspect(\n sourcePath: string,\n ): Promise<\n Result<\n { readonly revision: string; readonly meta: ScriptablePackMetaJson },\n ScriptablePackError\n >\n >;\n rebuild(\n sourcePath: string,\n mode: 'rebuild' | 'cold-cook',\n ): Promise<\n Result<\n { readonly revision: string; readonly meta: ScriptablePackMetaJson },\n ScriptablePackError\n >\n >;\n}\n\n/** Keep GUID allocation and multi-identity operations in one auditable gateway transaction. */\nexport function createScriptablePackAuthoringGateway(\n port: ScriptablePackAuthoringPort,\n allocateGuid: () => AssetGuid = AssetGuidCodec.random,\n): ScriptablePackAuthoringGateway {\n const requests = new Map<\n string,\n {\n readonly fingerprint: string;\n readonly result: Promise<\n Result<ScriptablePackGatewayMutation | ScriptablePackPreflight, ScriptablePackError>\n >;\n }\n >();\n\n async function mutationResult(\n result: Awaited<ReturnType<ScriptablePackAuthoringPort['mutate']>>,\n ): Promise<Result<ScriptablePackGatewayMutation, ScriptablePackError>> {\n if (!result.ok) return result;\n const inspected = await port.inspect(result.value.sourcePath);\n if (!inspected.ok) return inspected;\n return ok({\n sourcePath: result.value.sourcePath,\n revision: inspected.value.revision,\n meta: inspected.value.meta,\n });\n }\n\n async function dispatch(\n operation: ScriptablePackGatewayOperation,\n ): Promise<Result<ScriptablePackGatewayMutation | ScriptablePackPreflight, ScriptablePackError>> {\n switch (operation.kind) {\n case 'preflight': {\n const preflight = await port.preflight(operation.sourcePath);\n return preflight.ok\n ? ok({ sourcePath: operation.sourcePath, ...preflight.value })\n : preflight;\n }\n case 'inspect-meta': {\n const inspected = await port.inspect(operation.sourcePath);\n return inspected.ok\n ? ok({ sourcePath: operation.sourcePath, ...inspected.value })\n : inspected;\n }\n case 'rebuild':\n case 'cold-cook': {\n const preflight = await port.preflight(operation.sourcePath);\n if (!preflight.ok) return preflight;\n if (\n operation.expectedRevision !== undefined &&\n operation.expectedRevision !== preflight.value.revision\n ) {\n return err({\n code: 'pack-source-revision-conflict',\n expected: operation.expectedRevision,\n actual: preflight.value.revision,\n hint: 'inspect the current source revision, then retry the build with a new requestId',\n retryable: true,\n recoveryActions: ['asset.preflight', 'mint-request-id'],\n detail: { requestId: operation.requestId, sourcePath: operation.sourcePath },\n });\n }\n const rebuilt = await port.rebuild(operation.sourcePath, operation.kind);\n return rebuilt.ok ? ok({ sourcePath: operation.sourcePath, ...rebuilt.value }) : rebuilt;\n }\n case 'create-scriptable-pack':\n return mutationResult(\n await port.mutate({\n ...operation,\n packageId: allocateGuid(),\n initialOutput: { ...operation.initialOutput, guid: allocateGuid() },\n }),\n );\n case 'add-output':\n return mutationResult(await port.mutate({ ...operation, guid: allocateGuid() }));\n case 'clone-scriptable-pack': {\n const inspected = await port.inspect(operation.sourcePath);\n if (!inspected.ok) return inspected;\n const outputGuids = Object.fromEntries(\n inspected.value.meta.subAssets.map((asset) => [asset.sourceKey, allocateGuid()]),\n );\n return mutationResult(\n await port.mutate({\n ...operation,\n packageId: allocateGuid(),\n outputGuids,\n }),\n );\n }\n case 'add-external-asset':\n case 'rename-display':\n case 'remove-output':\n return mutationResult(await port.mutate(operation));\n }\n }\n\n return {\n execute(operation) {\n if (operation.requestId.trim().length === 0) {\n return Promise.resolve(\n err({\n code: 'pack-source-operation-committed',\n expected: 'a non-empty caller-minted requestId',\n actual: operation.requestId,\n hint: 'mint a new requestId and retry the operation once',\n retryable: true,\n recoveryActions: ['mint-request-id'],\n detail: { requestId: operation.requestId, sourcePath: operation.sourcePath },\n }),\n );\n }\n const fingerprint = JSON.stringify(operation);\n const prior = requests.get(operation.requestId);\n if (prior !== undefined) {\n if (prior.fingerprint === fingerprint) return prior.result;\n return Promise.resolve(\n err({\n code: 'pack-source-operation-committed',\n expected: 'one immutable operation per requestId',\n actual: operation.kind,\n hint: 'read the original operation result or mint a new requestId',\n retryable: false,\n recoveryActions: ['read-operation-run', 'mint-request-id'],\n detail: { requestId: operation.requestId, sourcePath: operation.sourcePath },\n }),\n );\n }\n const result = dispatch(operation);\n requests.set(operation.requestId, { fingerprint, result });\n return result;\n },\n };\n}\n\nconst SCRIPTABLE_PACK_REQUEST_ID_SCHEMA = {\n type: 'string',\n minLength: 1,\n maxLength: 128,\n pattern: '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$',\n description: 'Caller-minted identity for one idempotent ScriptablePack operation.',\n} as const;\nconst SCRIPTABLE_PACK_SOURCE_PATH_SCHEMA = {\n type: 'string',\n minLength: 8,\n pattern: '^[^/].*\\\\.pack\\\\.ts$',\n description: 'Game-root-relative ScriptablePack source path.',\n} as const;\nconst SCRIPTABLE_PACK_OWNER_GUID_SCHEMA = {\n type: 'string',\n format: 'uuid',\n description: 'Catalog GUID used to resolve the producer-owned source subject.',\n} as const;\nconst SCRIPTABLE_PACK_REVISION_SCHEMA = {\n type: 'string',\n minLength: 64,\n maxLength: 64,\n pattern: '^[a-f0-9]{64}$',\n description: 'SHA-256 source revision returned by preflight.',\n} as const;\nconst SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA = { type: 'string', minLength: 1 } as const;\nconst SCRIPTABLE_PACK_ASSET_KIND_SCHEMA = {\n enum: SCRIPTABLE_PACK_ASSET_KINDS,\n description: 'Ordinary Asset kind supported by the ScriptablePack producer/loader matrix.',\n} as const;\nconst SCRIPTABLE_PACK_NAME_SCHEMA = { type: 'string', minLength: 1 } as const;\n\nfunction scriptablePackArgsSchema(\n properties: Readonly<Record<string, unknown>>,\n required: readonly string[],\n options: { readonly subject?: boolean; readonly guidSubject?: boolean } = {},\n) {\n const subjectRequired = ['requestId', ...required];\n return {\n type: 'object',\n properties: {\n sourcePath: SCRIPTABLE_PACK_SOURCE_PATH_SCHEMA,\n ownerGuid: SCRIPTABLE_PACK_OWNER_GUID_SCHEMA,\n requestId: SCRIPTABLE_PACK_REQUEST_ID_SCHEMA,\n ...properties,\n },\n required: subjectRequired,\n ...(options.subject === false\n ? {}\n : {\n anyOf: [\n { required: [...subjectRequired, 'sourcePath'] },\n { required: [...subjectRequired, 'ownerGuid'] },\n ...(options.guidSubject === false ? [] : [{ required: [...subjectRequired, 'guid'] }]),\n ],\n }),\n additionalProperties: false,\n } as const;\n}\n\nexport const SOURCE_AUTHORING_OPERATION_DESCRIPTORS = [\n {\n id: 'asset-source.create',\n kind: 'create',\n domain: 'session',\n title: 'Create Asset Source',\n argsSchema: scriptablePackArgsSchema(\n {\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n initialOutput: {\n type: 'object',\n properties: {\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n kind: SCRIPTABLE_PACK_ASSET_KIND_SCHEMA,\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n },\n required: ['sourceKey', 'kind'],\n additionalProperties: false,\n },\n },\n ['sourcePath', 'initialOutput'],\n { subject: false },\n ),\n },\n {\n id: 'asset-source.add-output',\n kind: 'add-output',\n domain: 'session',\n title: 'Add Asset Source Output',\n argsSchema: scriptablePackArgsSchema(\n {\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n assetKind: SCRIPTABLE_PACK_ASSET_KIND_SCHEMA,\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['sourceKey', 'assetKind', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.add-external-asset',\n kind: 'add-external-asset',\n domain: 'session',\n title: 'Add Asset Source External Asset',\n argsSchema: scriptablePackArgsSchema(\n {\n alias: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n guid: { type: 'string', format: 'uuid' },\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['alias', 'guid', 'expectedRevision'],\n { guidSubject: false },\n ),\n },\n {\n id: 'asset-source.rename',\n kind: 'rename',\n domain: 'session',\n title: 'Rename Asset Source Display Name',\n argsSchema: scriptablePackArgsSchema(\n {\n target: {\n oneOf: [\n {\n type: 'object',\n properties: { kind: { const: 'package' } },\n required: ['kind'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n kind: { const: 'output' },\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n },\n required: ['kind', 'sourceKey'],\n additionalProperties: false,\n },\n ],\n },\n name: SCRIPTABLE_PACK_NAME_SCHEMA,\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['target', 'name', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.remove-output',\n kind: 'remove-output',\n domain: 'session',\n title: 'Remove Asset Source Output',\n destructive: true,\n argsSchema: scriptablePackArgsSchema(\n {\n sourceKey: SCRIPTABLE_PACK_SOURCE_KEY_SCHEMA,\n confirmIncomingRefs: { type: 'array', items: { type: 'string' } },\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['sourceKey', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.clone',\n kind: 'clone',\n domain: 'session',\n title: 'Clone Asset Source',\n argsSchema: scriptablePackArgsSchema(\n {\n targetPath: SCRIPTABLE_PACK_SOURCE_PATH_SCHEMA,\n expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA,\n },\n ['targetPath', 'expectedRevision'],\n ),\n },\n {\n id: 'asset-source.rebuild',\n kind: 'rebuild',\n domain: 'session',\n title: 'Rebuild Asset Source',\n argsSchema: scriptablePackArgsSchema({ expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA }, [\n 'expectedRevision',\n ]),\n },\n {\n id: 'asset-source.cold-cook',\n kind: 'cold-cook',\n domain: 'session',\n title: 'Cold Cook Asset Source',\n argsSchema: scriptablePackArgsSchema({ expectedRevision: SCRIPTABLE_PACK_REVISION_SCHEMA }, [\n 'expectedRevision',\n ]),\n },\n] as const;\n\nexport type ScriptablePackError =\n | {\n readonly code: 'pack-source-load-failed';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly sourcePath: string;\n readonly reason: 'module-load' | 'timeout' | 'source-changed';\n readonly phase: 'module-load' | 'build';\n readonly diagnostic: string;\n readonly timeoutMs?: number;\n };\n }\n | {\n readonly code: 'pack-source-definition-invalid';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly sourcePath?: string;\n readonly propertyPath: string;\n readonly actual: string;\n };\n }\n | {\n readonly code: 'pack-source-output-invalid';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly missingGuids: readonly string[];\n readonly unexpectedSourceKeys: readonly string[];\n readonly kindMismatches: readonly {\n readonly sourceKey: string;\n readonly expected: string;\n readonly actual: string;\n }[];\n };\n }\n | {\n readonly code: 'pack-source-external-closure-mismatch';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly undeclaredReferencedGuids: readonly string[];\n readonly undeclaredReadGuids: readonly string[];\n readonly unusedDeclaredGuids: readonly string[];\n };\n }\n | {\n readonly code:\n | 'pack-source-path-invalid'\n | 'pack-source-revision-conflict'\n | 'pack-source-mutation-unsupported'\n | 'pack-source-reference-conflict'\n | 'pack-source-write-failed'\n | 'pack-source-build-cycle'\n | 'pack-source-publication-timeout'\n | 'pack-source-operation-committed';\n readonly expected: string;\n readonly actual?: string;\n readonly hint: string;\n readonly retryable: boolean;\n readonly recoveryActions: readonly string[];\n readonly detail: {\n readonly requestId?: string;\n readonly sourcePath?: string;\n readonly packageId?: string;\n readonly sourceKey?: string;\n readonly incomingRefs?: readonly string[];\n };\n };\n\nfunction actual(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n if (ArrayBuffer.isView(value)) return value.constructor.name;\n return typeof value;\n}\n\nfunction invalid(\n propertyPath: string,\n expected: string,\n value: unknown,\n sourcePath?: string,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-definition-invalid',\n expected,\n hint: 'repair the default exported ScriptablePack definition, then inspect Meta again',\n detail: {\n ...(sourcePath === undefined ? {} : { sourcePath }),\n propertyPath,\n actual: actual(value),\n },\n });\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isAssetGuid(value: unknown): value is AssetGuid {\n return value instanceof Uint8Array && value.byteLength === 16;\n}\n\nfunction guidKey(guid: AssetGuid): string {\n return AssetGuidCodec.format(guid);\n}\n\nfunction freezeDefinition(\n definition: ScriptablePackDefinition,\n): Readonly<ScriptablePackDefinition> {\n const assets = Object.fromEntries(\n Object.entries(definition.assets).map(([sourceKey, descriptor]) => [\n sourceKey,\n Object.freeze({ ...descriptor, guid: descriptor.guid.slice() as AssetGuid }),\n ]),\n );\n const externalAssets = Object.fromEntries(\n Object.entries(definition.externalAssets).map(([alias, guid]) => [\n alias,\n guid.slice() as AssetGuid,\n ]),\n );\n const sceneComponents =\n definition.sceneComponents === undefined\n ? undefined\n : Object.freeze(\n projectScriptablePackSceneComponents(definition.sceneComponents).map((component) =>\n Object.freeze({\n ...component,\n fields: Object.freeze({ ...component.fields }),\n }),\n ),\n );\n return Object.freeze({\n ...definition,\n packageId: definition.packageId.slice() as AssetGuid,\n assets: Object.freeze(assets),\n externalAssets: Object.freeze(externalAssets),\n ...(sceneComponents === undefined ? {} : { sceneComponents }),\n });\n}\n\nexport function validateScriptablePackDefinition(\n value: unknown,\n sourcePath?: string,\n): Result<Readonly<ScriptablePackDefinition>, ScriptablePackError> {\n if (!isRecord(value))\n return invalid('$', 'a ScriptablePack definition object', value, sourcePath);\n if (value.schemaVersion !== '1.0.0') {\n return invalid('$.schemaVersion', \"the literal '1.0.0'\", value.schemaVersion, sourcePath);\n }\n if (!isAssetGuid(value.packageId)) {\n return invalid('$.packageId', 'a 16-byte AssetGuid', value.packageId, sourcePath);\n }\n if (value.name !== undefined && typeof value.name !== 'string') {\n return invalid('$.name', 'a string when present', value.name, sourcePath);\n }\n if (!isRecord(value.assets) || Object.keys(value.assets).length === 0) {\n return invalid(\n '$.assets',\n 'a non-empty sourceKey to descriptor object',\n value.assets,\n sourcePath,\n );\n }\n if (!isRecord(value.externalAssets)) {\n return invalid(\n '$.externalAssets',\n 'an alias to AssetGuid object',\n value.externalAssets,\n sourcePath,\n );\n }\n if (value.sceneComponents !== undefined) {\n if (!Array.isArray(value.sceneComponents)) {\n return invalid(\n '$.sceneComponents',\n 'an array of component tokens or neutral schema rows when present',\n value.sceneComponents,\n sourcePath,\n );\n }\n const componentNames = new Set<string>();\n for (const [componentIndex, component] of value.sceneComponents.entries()) {\n if (!isRecord(component)) {\n return invalid(\n `$.sceneComponents[${componentIndex}]`,\n 'a component token or neutral schema row',\n component,\n sourcePath,\n );\n }\n if (typeof component.name !== 'string' || component.name.trim().length === 0) {\n return invalid(\n `$.sceneComponents[${componentIndex}].name`,\n 'a non-empty component name',\n component.name,\n sourcePath,\n );\n }\n if (componentNames.has(component.name)) {\n return invalid(\n `$.sceneComponents[${componentIndex}].name`,\n 'component names to be unique within one ScriptablePack',\n component.name,\n sourcePath,\n );\n }\n componentNames.add(component.name);\n if (!isRecord(component.fields)) {\n return invalid(\n `$.sceneComponents[${componentIndex}].fields`,\n 'a field-name to schema-type object',\n component.fields,\n sourcePath,\n );\n }\n for (const [fieldName, field] of Object.entries(component.fields)) {\n const type = sceneComponentFieldType(field);\n if (fieldName.trim().length === 0 || type === undefined || type.trim().length === 0) {\n return invalid(\n `$.sceneComponents[${componentIndex}].fields`,\n 'field names with non-empty string schema types',\n field,\n sourcePath,\n );\n }\n }\n }\n }\n if (typeof value.build !== 'function') {\n return invalid('$.build', 'a build(assetReader) function', value.build, sourcePath);\n }\n\n const packageGuid = guidKey(value.packageId);\n const localGuids = new Set<string>();\n for (const [sourceKey, descriptor] of Object.entries(value.assets)) {\n if (sourceKey.trim().length === 0) {\n return invalid('$.assets', 'non-empty sourceKey object keys', sourceKey, sourcePath);\n }\n if (!isRecord(descriptor)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}]`,\n 'an asset descriptor',\n descriptor,\n sourcePath,\n );\n }\n if (!isAssetGuid(descriptor.guid)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].guid`,\n 'a 16-byte AssetGuid',\n descriptor.guid,\n sourcePath,\n );\n }\n if (typeof descriptor.kind !== 'string' || !isScriptablePackAssetKind(descriptor.kind)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].kind`,\n 'one of SCRIPTABLE_PACK_ASSET_KINDS',\n descriptor.kind,\n sourcePath,\n );\n }\n if (descriptor.name !== undefined && typeof descriptor.name !== 'string') {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].name`,\n 'a string when present',\n descriptor.name,\n sourcePath,\n );\n }\n const guid = guidKey(descriptor.guid);\n if (guid === packageGuid || localGuids.has(guid)) {\n return invalid(\n `$.assets[${JSON.stringify(sourceKey)}].guid`,\n 'a GUID unique within the package and distinct from packageId',\n descriptor.guid,\n sourcePath,\n );\n }\n localGuids.add(guid);\n }\n\n const externalGuids = new Set<string>();\n for (const [alias, guidValue] of Object.entries(value.externalAssets)) {\n if (alias.trim().length === 0) {\n return invalid('$.externalAssets', 'non-empty alias object keys', alias, sourcePath);\n }\n if (!isAssetGuid(guidValue)) {\n return invalid(\n `$.externalAssets[${JSON.stringify(alias)}]`,\n 'a 16-byte AssetGuid',\n guidValue,\n sourcePath,\n );\n }\n const guid = guidKey(guidValue);\n if (guid === packageGuid || localGuids.has(guid) || externalGuids.has(guid)) {\n return invalid(\n `$.externalAssets[${JSON.stringify(alias)}]`,\n 'a unique foreign GUID not owned by this package',\n guidValue,\n sourcePath,\n );\n }\n externalGuids.add(guid);\n }\n\n return ok(freezeDefinition(value as unknown as ScriptablePackDefinition));\n}\n\nexport function projectScriptablePackMeta(\n definition: ScriptablePackDefinition,\n source: string,\n): ScriptablePackMetaJson {\n const subAssets = Object.entries(definition.assets)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([sourceKey, descriptor], sourceIndex) => ({\n guid: guidKey(descriptor.guid),\n sourceIndex,\n sourceKey,\n kind: descriptor.kind,\n ...(descriptor.name === undefined ? {} : { name: descriptor.name }),\n }));\n const externalAssets = Object.entries(definition.externalAssets)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([alias, guid]) => ({ alias, guid: guidKey(guid) }));\n return {\n schemaVersion: '1.0.0',\n kind: 'external-asset-package',\n packageId: guidKey(definition.packageId),\n ...(definition.name === undefined ? {} : { name: definition.name }),\n importer: 'pack-ts',\n source,\n importSettings: { contractVersion: '1.0.0', externalAssets },\n subAssets,\n };\n}\n","import { createHash } from 'node:crypto';\nimport { readdir, readFile } from 'node:fs/promises';\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path';\nimport type { SourceDeclarationEvidence } from '@forgeax/engine-types';\nimport { SCANNER_BLACKLIST, scan } from '../scanner.js';\nimport { projectScriptablePackMeta } from '../scriptable-pack.js';\nimport { loadScriptablePack } from '../scriptable-pack-node.js';\n\n/** Project root and GUID used to locate an authoritative source declaration. */\nexport interface SourceInventoryRequest {\n readonly projectRoot: string;\n readonly guid: string;\n}\n\nexport interface ProducerSemanticIdentityInput {\n readonly producerRoot: string;\n readonly sourcePath: string;\n readonly sourceDigest: string;\n readonly schemaVersion: string;\n readonly importer: string;\n readonly codec: string;\n readonly settings: unknown;\n readonly producer: string;\n readonly profile: string;\n readonly declaredGuids?: readonly string[];\n}\n\nexport interface ProducerRelativeDdcIdentity {\n readonly logicalPath: string;\n readonly sourceDigest: string;\n readonly key: string;\n}\n\nfunction stableValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stableValue);\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => [key, stableValue(entry)]),\n );\n }\n return value;\n}\n\nexport function producerRelativeLogicalPath(producerRoot: string, sourcePath: string): string {\n const root = resolve(producerRoot);\n const source = resolve(sourcePath);\n const path = relative(root, source);\n if (\n path.length === 0 ||\n path === '..' ||\n path.startsWith(`..${sep}`) ||\n resolve(root, path) !== source\n ) {\n throw new Error('producer source must be inside the injected producer root');\n }\n return path.split(sep).join('/');\n}\n\nexport function producerRelativeDdcKey(input: ProducerSemanticIdentityInput): string {\n const logicalPath = producerRelativeLogicalPath(input.producerRoot, input.sourcePath);\n const semantic = {\n schemaVersion: input.schemaVersion,\n logicalPath,\n sourceDigest: input.sourceDigest,\n importer: input.importer,\n codec: input.codec,\n settings: stableValue(input.settings),\n producer: input.producer,\n profile: input.profile,\n declaredGuids: [...(input.declaredGuids ?? [])].sort(),\n };\n return createHash('sha256').update(JSON.stringify(semantic)).digest('hex');\n}\n\nexport function producerRelativeDdcIdentity(\n input: ProducerSemanticIdentityInput,\n): ProducerRelativeDdcIdentity {\n return {\n logicalPath: producerRelativeLogicalPath(input.producerRoot, input.sourcePath),\n sourceDigest: input.sourceDigest,\n key: producerRelativeDdcKey(input),\n };\n}\n\nfunction fingerprint(meta: string, source: Uint8Array | undefined): string {\n const hash = createHash('sha256').update(meta);\n if (source !== undefined) hash.update(source);\n return hash.digest('base64');\n}\n\nfunction sourceFromMeta(\n metaPath: string,\n meta: {\n readonly source?: unknown;\n readonly inputFingerprint?: unknown;\n readonly importSettings?: unknown;\n readonly subAssets?: readonly { readonly guid?: unknown }[];\n },\n guid: string,\n raw: string,\n): SourceDeclarationEvidence | undefined {\n if (\n !meta.subAssets?.some(\n (asset) => typeof asset.guid === 'string' && asset.guid.toLowerCase() === guid.toLowerCase(),\n )\n ) {\n return undefined;\n }\n const source =\n typeof meta.source === 'string' ? meta.source : basename(metaPath).replace(/\\.meta\\.json$/, '');\n const sourcePath = resolve(dirname(metaPath), source);\n const inputFingerprint =\n typeof meta.inputFingerprint === 'string' ? meta.inputFingerprint : fingerprint(raw, undefined);\n return { origin: 'sourceMeta', sourcePath, inputFingerprint };\n}\n\nasync function collectDeclarationPaths(root: string): Promise<string[]> {\n const paths: string[] = [];\n async function visit(dir: string): Promise<void> {\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (!SCANNER_BLACKLIST.has(entry.name)) await visit(path);\n continue;\n }\n if (\n entry.isFile() &&\n (entry.name.endsWith('.meta.json') ||\n entry.name.endsWith('.pack.json') ||\n entry.name.endsWith('.pack.ts'))\n ) {\n paths.push(path);\n }\n }\n }\n await visit(root);\n return paths;\n}\n\n/** Read `.meta.json` or `.pack.json` source declarations without runtime imports. */\nexport async function readSourceInventory(\n request: SourceInventoryRequest,\n): Promise<SourceDeclarationEvidence | undefined> {\n const result = await scan([request.projectRoot]);\n const paths = result.ok ? result.value : await collectDeclarationPaths(request.projectRoot);\n const guid = request.guid.toLowerCase();\n let authored: SourceDeclarationEvidence | undefined;\n for (const path of paths) {\n if (path.endsWith('.pack.ts')) {\n const loaded = await loadScriptablePack(path, { metadataOnly: true });\n if (!loaded.ok) continue;\n const meta = projectScriptablePackMeta(loaded.value, path);\n if (meta.subAssets.some((asset) => asset.guid.toLowerCase() === guid)) {\n return { origin: 'sourceMeta', sourcePath: path };\n }\n continue;\n }\n const raw = await readFile(path, 'utf8').catch(() => undefined);\n if (raw === undefined) continue;\n let parsed: {\n readonly assets?: readonly { readonly guid?: unknown }[];\n readonly source?: unknown;\n readonly inputFingerprint?: unknown;\n readonly importSettings?: unknown;\n readonly subAssets?: readonly { readonly guid?: unknown }[];\n };\n try {\n parsed = JSON.parse(raw) as typeof parsed;\n } catch {\n continue;\n }\n if (path.endsWith('.pack.json')) {\n if (\n parsed.assets?.some(\n (asset) =>\n typeof asset.guid === 'string' &&\n (asset.guid === request.guid || asset.guid.toLowerCase() === guid),\n )\n ) {\n authored = { origin: 'authoredPack', sourcePath: path };\n }\n continue;\n }\n if (path.endsWith('.meta.json')) {\n const source = sourceFromMeta(path, parsed, request.guid, raw);\n if (source !== undefined) return source;\n }\n }\n return authored;\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdir, mkdtemp, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { dirname, extname, isAbsolute, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Worker } from 'node:worker_threads';\nimport type { AssetGuid, Result } from '@forgeax/engine-types';\nimport { AssetError, err, ImportError, ok } from '@forgeax/engine-types';\nimport ts from 'typescript';\nimport {\n type ProducerSemanticIdentityInput,\n producerRelativeDdcKey,\n} from './evidence/source-inventory.js';\nimport { AssetGuid as AssetGuidCodec } from './guid.js';\nimport {\n type AssetReader,\n projectScriptablePackMeta,\n type ScriptablePackAssetKind,\n type ScriptablePackAuthoringMutation,\n type ScriptablePackAuthoringPort,\n type ScriptablePackDefinition,\n type ScriptablePackError,\n type ScriptablePackReadError,\n type ScriptablePackSourceClosureEntry,\n validateScriptablePackDefinition,\n} from './scriptable-pack.js';\n\nconst IMPORT_META_RESOLVE_FLAG = '--experimental-import-meta-resolve';\n\nfunction scriptablePackWorkerExecArgv(): string[] {\n // import.meta.resolve(parentURL) is the canonical ESM resolver, but Node\n // keeps its parentURL overload behind this flag. Filter --input-type as\n // well: stdin/eval hosts may pass it through process.execArgv, and Node\n // rejects that option inside a file-backed worker.\n const inherited = process.execArgv.filter((arg) => !arg.startsWith('--input-type'));\n return inherited.includes(IMPORT_META_RESOLVE_FLAG)\n ? inherited\n : [...inherited, IMPORT_META_RESOLVE_FLAG];\n}\n\nexport interface ScriptablePackModuleExecutor {\n load(sourcePath: string): Promise<unknown>;\n dispose?(reason: 'complete' | 'timeout' | 'failure'): void | Promise<void>;\n}\n\nexport interface ScriptablePackModuleExecutorPool {\n acquire(): Promise<ScriptablePackModuleExecutor>;\n dispose(): Promise<void>;\n}\n\nexport interface ScriptablePackModuleExecutorPoolOptions {\n readonly maxWorkers?: number;\n readonly maxTasksPerWorker?: number;\n}\n\nexport function scriptablePackDdcKey(input: ProducerSemanticIdentityInput): string {\n return producerRelativeDdcKey(input);\n}\n\nexport interface OptionalBuildCache<T> {\n readonly read: () => Promise<T | null>;\n readonly coldCook: () => Promise<T>;\n}\n\n/** Build CAS is a performance hint; source cold cook remains the correctness path. */\nexport async function readOptionalBuildCache<T>(cache: OptionalBuildCache<T>): Promise<{\n readonly value: T;\n readonly fromCache: boolean;\n}> {\n try {\n const cached = await cache.read();\n if (cached !== null) return { value: cached, fromCache: true };\n } catch {\n // Cache deletion, read-only storage, and corrupt optional objects fail open.\n }\n return { value: await cache.coldCook(), fromCache: false };\n}\n\nexport interface LoadScriptablePackOptions {\n /** Maximum time allowed for module initialization in the isolated worker. */\n readonly timeoutMs?: number;\n /** Maximum time allowed for one definition.build(reader) in the isolated worker. */\n readonly buildTimeoutMs?: number;\n readonly executor?: ScriptablePackModuleExecutor;\n /** Release the isolated loader after identity projection when build will not be called. */\n readonly metadataOnly?: boolean;\n}\n\nasync function resolveRelativeImport(\n sourcePath: string,\n specifier: string,\n): Promise<string | undefined> {\n if (!specifier.startsWith('.')) return undefined;\n const raw = resolve(dirname(sourcePath), specifier);\n const candidates =\n extname(raw).length > 0\n ? [raw]\n : [\n raw,\n `${raw}.ts`,\n `${raw}.tsx`,\n `${raw}.mts`,\n `${raw}.js`,\n `${raw}.mjs`,\n `${raw}.json`,\n resolve(raw, 'index.ts'),\n ];\n for (const candidate of candidates) {\n try {\n if ((await stat(candidate)).isFile()) return candidate;\n } catch {\n // Continue through deterministic extension candidates.\n }\n }\n return undefined;\n}\n\n/** Capture one immutable ScriptablePack module closure for inventory and production. */\nexport async function inventoryScriptablePackSource(\n sourcePath: string,\n initialSourceText?: string,\n): Promise<readonly ScriptablePackSourceClosureEntry[]> {\n const root = await realpath(sourcePath);\n const pending = [root];\n const seen = new Set<string>();\n const entries: ScriptablePackSourceClosureEntry[] = [];\n while (pending.length > 0) {\n const path = pending.pop();\n if (path === undefined || seen.has(path)) continue;\n seen.add(path);\n const bytes =\n path === root && initialSourceText !== undefined\n ? new TextEncoder().encode(initialSourceText)\n : await readFile(path);\n entries.push({ path, digest: `sha256:${createHash('sha256').update(bytes).digest('hex')}` });\n const source = new TextDecoder().decode(bytes);\n for (const imported of ts.preProcessFile(source, true, true).importedFiles) {\n const resolved = await resolveRelativeImport(path, imported.fileName);\n if (resolved !== undefined) pending.push(await realpath(resolved));\n }\n }\n return entries.sort((left, right) => left.path.localeCompare(right.path));\n}\n\ninterface StructuredFailure {\n readonly name?: unknown;\n readonly code?: unknown;\n readonly expected?: unknown;\n readonly actual?: unknown;\n readonly hint?: unknown;\n readonly detail?: unknown;\n readonly message?: unknown;\n}\n\nfunction serializeFailure(value: unknown): StructuredFailure {\n if (value !== null && typeof value === 'object') {\n const failure = value as Record<string, unknown>;\n return {\n name: failure.name,\n code: failure.code,\n expected: failure.expected,\n actual: failure.actual,\n hint: failure.hint,\n detail: failure.detail,\n message: failure.message,\n };\n }\n return { message: String(value) };\n}\n\nfunction hydrateFailure(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value;\n const failure = value as StructuredFailure;\n if (\n failure.name === 'AssetError' &&\n typeof failure.code === 'string' &&\n typeof failure.expected === 'string' &&\n typeof failure.hint === 'string'\n ) {\n const args = {\n code: failure.code as ConstructorParameters<typeof AssetError>[0]['code'],\n expected: failure.expected,\n hint: failure.hint,\n };\n return failure.detail === undefined\n ? new AssetError(args)\n : new AssetError({\n ...args,\n detail: failure.detail as NonNullable<\n ConstructorParameters<typeof AssetError>[0]['detail']\n >,\n });\n }\n if (\n failure.name === 'ImportError' &&\n typeof failure.code === 'string' &&\n typeof failure.expected === 'string' &&\n typeof failure.hint === 'string' &&\n failure.detail !== undefined\n ) {\n return new ImportError({\n code: failure.code as ConstructorParameters<typeof ImportError>[0]['code'],\n expected: failure.expected,\n hint: failure.hint,\n detail: failure.detail as ConstructorParameters<typeof ImportError>[0]['detail'],\n ...(typeof failure.actual === 'string' ? { actual: failure.actual } : {}),\n });\n }\n if (typeof failure.message === 'string') {\n const error = new Error(failure.message);\n if (typeof failure.name === 'string') error.name = failure.name;\n return error;\n }\n return value;\n}\n\nclass WorkerScriptablePackExecutor implements ScriptablePackModuleExecutor {\n private worker: Worker | undefined;\n private compileRoot: string | undefined;\n private nextBuildId = 0;\n private disposal: Promise<void> | undefined;\n private build:\n | {\n readonly id: number;\n readonly reader: AssetReader;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n\n async load(sourcePath: string): Promise<unknown> {\n const workerUrl = scriptablePackWorkerUrl();\n const compileRoot = await mkdtemp(resolve(tmpdir(), 'forgeax-scriptable-pack-'));\n this.compileRoot = compileRoot;\n const worker = new Worker(workerUrl, {\n workerData: { sourcePath: resolve(sourcePath), compileRoot },\n execArgv: scriptablePackWorkerExecArgv(),\n resourceLimits: { maxOldGenerationSizeMb: 256, maxYoungGenerationSizeMb: 64 },\n });\n this.worker = worker;\n worker.on('message', (message: unknown) => this.onMessage(message));\n worker.unref();\n return new Promise((resolveLoad, rejectLoad) => {\n const onMessage = (message: unknown): void => {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n if (value.kind === 'loaded') {\n // The scan keeps this executor alive for the later no-reopen build\n // route, but an idle source worker must not keep a Vite/Vitest host\n // process alive after its own work has settled.\n worker.unref();\n worker.off('message', onMessage);\n resolveLoad({\n default:\n value.definition === undefined\n ? undefined\n : {\n ...(value.definition as Record<string, unknown>),\n build: (reader: AssetReader) => this.runBuild(reader),\n },\n });\n } else if (value.kind === 'load-threw') {\n worker.off('message', onMessage);\n rejectLoad(hydrateFailure(value.error));\n }\n };\n worker.on('message', onMessage);\n worker.once('error', rejectLoad);\n worker.once('exit', (code) => {\n if (code !== 0) rejectLoad(new Error(`ScriptablePack worker exited with code ${code}`));\n });\n });\n }\n\n dispose(reason: 'complete' | 'timeout' | 'failure' = 'complete'): Promise<void> {\n if (this.disposal !== undefined) return this.disposal;\n const worker = this.worker;\n this.worker = undefined;\n const compileRoot = this.compileRoot;\n this.compileRoot = undefined;\n const active = this.build;\n this.build = undefined;\n if (active !== undefined) {\n active.reject(new Error(`ScriptablePack build disposed during ${reason}`));\n }\n this.disposal = (async () => {\n if (worker !== undefined) await worker.terminate();\n if (compileRoot !== undefined) await rm(compileRoot, { recursive: true, force: true });\n })();\n return this.disposal;\n }\n\n private runBuild(reader: AssetReader): Promise<unknown> {\n const worker = this.worker;\n if (worker === undefined) return Promise.reject(new Error('ScriptablePack worker is closed'));\n if (this.build !== undefined)\n return Promise.reject(new Error('ScriptablePack worker already has an active build'));\n const id = this.nextBuildId++;\n return new Promise((resolveBuild, rejectBuild) => {\n this.build = { id, reader, resolve: resolveBuild, reject: rejectBuild };\n worker.postMessage({ kind: 'build', buildId: id });\n });\n }\n\n private onMessage(message: unknown): void {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n const active = this.build;\n if (active === undefined || value.buildId !== active.id) return;\n if (value.kind === 'asset-read' && typeof value.readId === 'number') {\n void active.reader\n .readByGuid(value.guid as AssetGuid)\n .then((result) =>\n this.worker?.postMessage({\n kind: 'asset-result',\n readId: value.readId,\n result:\n result.ok === true ? result : { ...result, error: serializeFailure(result.error) },\n }),\n )\n .catch((error: unknown) => {\n if (this.build?.id !== active.id) return;\n this.build = undefined;\n active.reject(error);\n void this.dispose('failure');\n });\n return;\n }\n this.build = undefined;\n if (value.kind === 'build-result') active.resolve(value.result);\n else if (value.kind === 'build-threw') active.reject(hydrateFailure(value.error));\n else this.build = active;\n }\n}\n\nfunction scriptablePackWorkerUrl(): URL {\n const bundledWorker = new URL('./scriptable-pack-worker.mjs', import.meta.url);\n return existsSync(fileURLToPath(bundledWorker))\n ? bundledWorker\n : new URL('../dist/scriptable-pack-worker.mjs', import.meta.url);\n}\n\nclass ReusableWorkerScriptablePackExecutor implements ScriptablePackModuleExecutor {\n private readonly worker: Worker;\n private readonly compileRootReady = mkdtemp(resolve(tmpdir(), 'forgeax-scriptable-pack-pool-'));\n private compileRoot: string | undefined;\n private nextLoadId = 0;\n private nextBuildId = 0;\n private pendingLoad:\n | {\n readonly id: number;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n private build:\n | {\n readonly id: number;\n readonly reader: AssetReader;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n }\n | undefined;\n private disposal: Promise<void> | undefined;\n private forceDispose = false;\n private failed = false;\n private taskCount = 0;\n private released = false;\n\n constructor(\n private readonly maxTasksPerWorker: number,\n private readonly release: (\n executor: ReusableWorkerScriptablePackExecutor,\n reusable: boolean,\n ) => void,\n ) {\n this.worker = new Worker(scriptablePackWorkerUrl(), {\n workerData: { mode: 'reusable' },\n execArgv: scriptablePackWorkerExecArgv(),\n resourceLimits: { maxOldGenerationSizeMb: 256, maxYoungGenerationSizeMb: 64 },\n });\n this.worker.on('message', (message: unknown) => this.onMessage(message));\n this.worker.on('error', (error: Error) => {\n this.failed = true;\n this.rejectActive(error);\n void this.dispose('failure');\n });\n this.worker.on('exit', (code) => {\n if (code === 0 || this.disposal !== undefined) return;\n this.failed = true;\n this.rejectActive(new Error(`ScriptablePack worker exited with code ${code}`));\n void this.dispose('failure');\n });\n // Listener registration can retain the worker's MessagePort in Node.\n // A reusable worker must not keep a completed Vite build alive while its\n // pool is draining; it still processes messages while the host is live.\n this.worker.unref();\n }\n\n async load(sourcePath: string): Promise<unknown> {\n const activeDisposal = this.disposal;\n if (activeDisposal !== undefined) {\n await activeDisposal;\n if (this.failed) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n this.disposal = undefined;\n }\n this.released = false;\n if (this.pendingLoad !== undefined || this.build !== undefined) {\n return Promise.reject(new Error('ScriptablePack executor already has an active task'));\n }\n const compileRoot = this.compileRoot ?? (await this.compileRootReady);\n if (this.disposal !== undefined) {\n const disposal = this.disposal;\n await disposal;\n if (this.failed) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n this.disposal = undefined;\n }\n const loadId = this.nextLoadId++;\n this.compileRoot = compileRoot;\n this.taskCount += 1;\n return new Promise((resolveLoad, rejectLoad) => {\n this.pendingLoad = { id: loadId, resolve: resolveLoad, reject: rejectLoad };\n try {\n this.worker.postMessage({\n kind: 'load',\n loadId,\n sourcePath: resolve(sourcePath),\n compileRoot,\n });\n } catch (error) {\n this.pendingLoad = undefined;\n rejectLoad(error);\n void this.dispose('failure');\n }\n });\n }\n\n dispose(reason: 'complete' | 'timeout' | 'failure' = 'complete'): Promise<void> {\n if (reason === 'failure') this.forceDispose = true;\n const activeDisposal = this.disposal;\n if (activeDisposal !== undefined) {\n return activeDisposal;\n }\n this.rejectActive(new Error(`ScriptablePack task disposed during ${reason}`));\n this.disposal = (async () => {\n const compileRoot = this.compileRoot ?? (await this.compileRootReady);\n const reusable =\n reason === 'complete' &&\n !this.failed &&\n !this.forceDispose &&\n this.taskCount < this.maxTasksPerWorker;\n this.forceDispose = false;\n if (!reusable) {\n this.compileRoot = undefined;\n await this.worker.terminate();\n await rm(compileRoot, { recursive: true, force: true });\n }\n this.released = true;\n this.disposal = undefined;\n this.release(this, reusable);\n })();\n return this.disposal;\n }\n\n private rejectActive(error: unknown): void {\n const loading = this.pendingLoad;\n this.pendingLoad = undefined;\n loading?.reject(error);\n const building = this.build;\n this.build = undefined;\n building?.reject(error);\n }\n\n private runBuild(reader: AssetReader): Promise<unknown> {\n if (this.released || this.disposal !== undefined) {\n return Promise.reject(new Error('ScriptablePack executor is not leased'));\n }\n if (this.build !== undefined) {\n return Promise.reject(new Error('ScriptablePack worker already has an active build'));\n }\n const id = this.nextBuildId++;\n return new Promise((resolveBuild, rejectBuild) => {\n this.build = { id, reader, resolve: resolveBuild, reject: rejectBuild };\n try {\n this.worker.postMessage({ kind: 'build', buildId: id });\n } catch (error) {\n this.build = undefined;\n rejectBuild(error);\n void this.dispose('failure');\n }\n });\n }\n\n private onMessage(message: unknown): void {\n if (message === null || typeof message !== 'object') return;\n const value = message as Record<string, unknown>;\n const loading = this.pendingLoad;\n if (loading !== undefined && value.kind === 'loaded' && value.loadId === loading.id) {\n this.pendingLoad = undefined;\n loading.resolve({\n default:\n value.definition === undefined\n ? undefined\n : {\n ...(value.definition as Record<string, unknown>),\n build: (reader: AssetReader) => this.runBuild(reader),\n },\n });\n return;\n }\n if (loading !== undefined && value.kind === 'load-threw' && value.loadId === loading.id) {\n this.pendingLoad = undefined;\n loading.reject(hydrateFailure(value.error));\n return;\n }\n const active = this.build;\n if (active === undefined || value.buildId !== active.id) return;\n if (value.kind === 'asset-read' && typeof value.readId === 'number') {\n void active.reader\n .readByGuid(value.guid as AssetGuid)\n .then((result) =>\n this.worker.postMessage({\n kind: 'asset-result',\n readId: value.readId,\n result:\n result.ok === true ? result : { ...result, error: serializeFailure(result.error) },\n }),\n )\n .catch((error: unknown) => {\n if (this.build?.id !== active.id) return;\n this.build = undefined;\n active.reject(error);\n void this.dispose('failure');\n });\n return;\n }\n this.build = undefined;\n if (value.kind === 'build-result') active.resolve(value.result);\n else if (value.kind === 'build-threw') active.reject(hydrateFailure(value.error));\n else this.build = active;\n }\n}\n\nclass DefaultScriptablePackModuleExecutorPool implements ScriptablePackModuleExecutorPool {\n private readonly maxWorkers: number;\n private readonly maxTasksPerWorker: number;\n private readonly idle: ReusableWorkerScriptablePackExecutor[] = [];\n private readonly waiters: {\n readonly resolve: (executor: ScriptablePackModuleExecutor) => void;\n readonly reject: (reason: unknown) => void;\n }[] = [];\n private readonly executors = new Set<ReusableWorkerScriptablePackExecutor>();\n private workerCount = 0;\n private closed = false;\n\n constructor(options: ScriptablePackModuleExecutorPoolOptions = {}) {\n this.maxWorkers = Math.max(1, Math.trunc(options.maxWorkers ?? 2));\n this.maxTasksPerWorker = Math.max(1, Math.trunc(options.maxTasksPerWorker ?? 32));\n }\n\n acquire(): Promise<ScriptablePackModuleExecutor> {\n if (this.closed) return Promise.reject(new Error('ScriptablePack executor pool is closed'));\n const executor = this.idle.pop();\n if (executor !== undefined) return Promise.resolve(executor);\n if (this.workerCount < this.maxWorkers) {\n this.workerCount += 1;\n return Promise.resolve(this.createExecutor());\n }\n return new Promise((resolveAcquire, rejectAcquire) =>\n this.waiters.push({ resolve: resolveAcquire, reject: rejectAcquire }),\n );\n }\n\n async dispose(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n const waiters = this.waiters.splice(0);\n for (const waiter of waiters) {\n waiter.reject(new Error('ScriptablePack executor pool is closed'));\n }\n this.idle.splice(0);\n await Promise.all([...this.executors].map((executor) => executor.dispose('failure')));\n }\n\n private createExecutor(): ReusableWorkerScriptablePackExecutor {\n const executor = new ReusableWorkerScriptablePackExecutor(\n this.maxTasksPerWorker,\n (executor, reusable) => {\n if (this.closed) {\n this.executors.delete(executor);\n if (!reusable) this.workerCount -= 1;\n return;\n }\n if (!reusable) {\n this.executors.delete(executor);\n this.workerCount -= 1;\n } else {\n this.idle.push(executor);\n }\n this.drain();\n },\n );\n this.executors.add(executor);\n return executor;\n }\n\n private drain(): void {\n if (this.closed) return;\n while (this.waiters.length > 0) {\n const idle = this.idle.pop();\n if (idle !== undefined) {\n this.waiters.shift()?.resolve(idle);\n continue;\n }\n if (this.workerCount >= this.maxWorkers) return;\n this.workerCount += 1;\n this.waiters.shift()?.resolve(this.createExecutor());\n }\n }\n}\n\nexport function createScriptablePackModuleExecutorPool(\n options: ScriptablePackModuleExecutorPoolOptions = {},\n): ScriptablePackModuleExecutorPool {\n return new DefaultScriptablePackModuleExecutorPool(options);\n}\n\nfunction loadFailure(\n sourcePath: string,\n reason: 'module-load' | 'timeout',\n phase: 'module-load' | 'build',\n diagnostic: string,\n timeoutMs?: number,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-load-failed',\n expected: 'a trusted synchronous module with a valid default ScriptablePack export',\n hint: 'repair the module load or initialization failure, then inspect Meta again',\n detail: {\n sourcePath,\n reason,\n phase,\n diagnostic,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n },\n });\n}\n\nfunction buildTimeoutFailure(sourcePath: string, timeoutMs: number): ScriptablePackReadError {\n return {\n code: 'pack-source-load-failed',\n expected: 'a ScriptablePack build to settle within the configured build timeout',\n hint: 'repair the authored build, then retry through a fresh ScriptablePack generation',\n detail: {\n sourcePath,\n reason: 'timeout',\n phase: 'build',\n timeoutMs,\n diagnostic: `ScriptablePack build exceeded ${timeoutMs}ms`,\n },\n };\n}\n\nexport async function loadScriptablePack(\n sourcePath: string,\n options: LoadScriptablePackOptions = {},\n): Promise<Result<Readonly<ScriptablePackDefinition>, ScriptablePackError>> {\n // Module initialization includes transpiling the trusted TypeScript source\n // closure in a fresh Worker. A cold SDK workspace can legitimately exceed\n // the build execution budget before any authored build() code has run.\n const timeoutMs = options.timeoutMs ?? 15_000;\n const buildTimeoutMs = options.buildTimeoutMs ?? 5_000;\n const executor = options.executor ?? new WorkerScriptablePackExecutor();\n let disposeReason: 'complete' | 'timeout' | 'failure' | undefined;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n const timeoutSignal = Symbol('scriptable-pack-module-timeout');\n const loaded = await Promise.race([\n executor.load(sourcePath),\n new Promise<typeof timeoutSignal>((resolve) => {\n timeout = setTimeout(() => resolve(timeoutSignal), timeoutMs);\n }),\n ]);\n if (loaded === timeoutSignal) {\n disposeReason = 'timeout';\n return loadFailure(\n sourcePath,\n 'timeout',\n 'module-load',\n `ScriptablePack module initialization exceeded ${timeoutMs}ms`,\n timeoutMs,\n );\n }\n const moduleValue =\n loaded !== null && typeof loaded === 'object' && 'default' in loaded\n ? (loaded as { readonly default: unknown }).default\n : undefined;\n const validated = validateScriptablePackDefinition(moduleValue, sourcePath);\n if (!validated.ok) {\n disposeReason = 'failure';\n return validated;\n }\n if (options.metadataOnly === true) {\n disposeReason = 'complete';\n return validated;\n }\n const definition = validated.value;\n type BuildOutcome = Awaited<ReturnType<ScriptablePackDefinition['build']>>;\n return ok({\n ...definition,\n build: async (reader: AssetReader): Promise<BuildOutcome> => {\n let buildTimedOut = false;\n let buildTimeout: ReturnType<typeof setTimeout> | undefined;\n const timeoutResult = err(buildTimeoutFailure(sourcePath, buildTimeoutMs));\n try {\n const built = await Promise.race([\n Promise.resolve(definition.build(reader)),\n new Promise<BuildOutcome>((resolve) => {\n buildTimeout = setTimeout(() => {\n buildTimedOut = true;\n resolve(timeoutResult as BuildOutcome);\n }, buildTimeoutMs);\n }),\n ]);\n if (buildTimedOut) {\n await executor.dispose?.('timeout');\n return built;\n }\n await executor.dispose?.('complete');\n return built;\n } catch (error) {\n await executor.dispose?.('failure');\n throw error;\n } finally {\n if (buildTimeout !== undefined) clearTimeout(buildTimeout);\n }\n },\n });\n } catch (error) {\n const diagnostic = error instanceof Error ? error.message : String(error);\n disposeReason = 'failure';\n return loadFailure(sourcePath, 'module-load', 'module-load', diagnostic);\n } finally {\n if (timeout !== undefined) clearTimeout(timeout);\n if (disposeReason !== undefined) await executor.dispose?.(disposeReason);\n }\n}\n\nconst CANONICAL_SCAFFOLD_MARKER = '// @forgeax-scriptable-pack canonical-v1';\nconst CANONICAL_MANIFEST_NAME = 'canonicalManifest';\nconst CANONICAL_MUTABLE_KINDS = new Set<ScriptablePackAssetKind>(['scene', 'mesh', 'material']);\n\ninterface CanonicalOutput {\n readonly guid: string;\n readonly kind: ScriptablePackAssetKind;\n readonly name?: string;\n}\n\ninterface CanonicalManifest {\n readonly schemaVersion: '1.0.0';\n readonly packageId: string;\n readonly name?: string;\n readonly assets: Readonly<Record<string, CanonicalOutput>>;\n readonly externalAssets: Readonly<Record<string, string>>;\n}\n\nexport interface FileSystemScriptablePackAuthoringOptions {\n /** All source and target paths are confined to this game root. */\n readonly gameRoot: string;\n readonly incomingRefs?: (sourcePath: string, sourceKey?: string) => Promise<readonly string[]>;\n readonly rebuild?: (\n sourcePath: string,\n mode: 'rebuild' | 'cold-cook',\n ) => Promise<Result<void, ScriptablePackError>>;\n}\n\nfunction authoringError(\n code:\n | 'pack-source-path-invalid'\n | 'pack-source-revision-conflict'\n | 'pack-source-mutation-unsupported'\n | 'pack-source-reference-conflict'\n | 'pack-source-write-failed',\n input: {\n readonly expected: string;\n readonly actual?: string;\n readonly hint: string;\n readonly retryable: boolean;\n readonly recoveryActions: readonly string[];\n readonly requestId?: string;\n readonly sourcePath?: string;\n readonly sourceKey?: string;\n readonly incomingRefs?: readonly string[];\n },\n): ScriptablePackError {\n return {\n code,\n expected: input.expected,\n ...(input.actual === undefined ? {} : { actual: input.actual }),\n hint: input.hint,\n retryable: input.retryable,\n recoveryActions: input.recoveryActions,\n detail: {\n ...(input.requestId === undefined ? {} : { requestId: input.requestId }),\n ...(input.sourcePath === undefined ? {} : { sourcePath: input.sourcePath }),\n ...(input.sourceKey === undefined ? {} : { sourceKey: input.sourceKey }),\n ...(input.incomingRefs === undefined ? {} : { incomingRefs: input.incomingRefs }),\n },\n };\n}\n\nfunction confinedSourcePath(\n gameRoot: string,\n sourcePath: string,\n): Result<{ readonly absolute: string; readonly relative: string }, ScriptablePackError> {\n const root = resolve(gameRoot);\n const absolute = resolve(root, sourcePath);\n const rel = relative(root, absolute);\n if (\n rel.length === 0 ||\n rel === '..' ||\n rel.startsWith(`..${sep}`) ||\n isAbsolute(sourcePath) ||\n !rel.endsWith('.pack.ts')\n ) {\n return err(\n authoringError('pack-source-path-invalid', {\n expected: 'a game-root-relative *.pack.ts path confined to the selected game',\n actual: sourcePath,\n hint: 'choose a relative ScriptablePack source path inside the selected game root',\n retryable: false,\n recoveryActions: ['choose-game-relative-source-path'],\n sourcePath,\n }),\n );\n }\n return ok({ absolute, relative: rel.split(sep).join('/') });\n}\n\nfunction revisionOf(source: string): string {\n return createHash('sha256').update(source).digest('hex');\n}\n\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n if (\n ts.isAsExpression(expression) ||\n ts.isSatisfiesExpression(expression) ||\n ts.isParenthesizedExpression(expression)\n ) {\n return unwrapExpression(expression.expression);\n }\n return expression;\n}\n\nfunction literalValue(expression: ts.Expression): unknown {\n const value = unwrapExpression(expression);\n if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value)) return value.text;\n if (value.kind === ts.SyntaxKind.TrueKeyword) return true;\n if (value.kind === ts.SyntaxKind.FalseKeyword) return false;\n if (value.kind === ts.SyntaxKind.NullKeyword) return null;\n if (ts.isNumericLiteral(value)) return Number(value.text);\n if (ts.isArrayLiteralExpression(value)) return value.elements.map(literalValue);\n if (ts.isObjectLiteralExpression(value)) {\n const result: Record<string, unknown> = {};\n for (const property of value.properties) {\n if (!ts.isPropertyAssignment(property))\n throw new TypeError('manifest properties must be data');\n const name = property.name;\n const key =\n ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)\n ? name.text\n : undefined;\n if (key === undefined) throw new TypeError('manifest property names must be static');\n result[key] = literalValue(property.initializer);\n }\n return result;\n }\n throw new TypeError('manifest values must be literal data');\n}\n\nfunction parseCanonicalManifest(source: string, sourcePath: string): CanonicalManifest | undefined {\n if (!source.startsWith(`${CANONICAL_SCAFFOLD_MARKER}\\n`)) return undefined;\n const file = ts.createSourceFile(\n sourcePath,\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TS,\n );\n for (const statement of file.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (\n ts.isIdentifier(declaration.name) &&\n declaration.name.text === CANONICAL_MANIFEST_NAME &&\n declaration.initializer !== undefined\n ) {\n const value = literalValue(declaration.initializer);\n if (value === null || typeof value !== 'object') return undefined;\n return value as CanonicalManifest;\n }\n }\n }\n return undefined;\n}\n\nfunction guidExpression(value: string): string {\n return `parseGuid(${JSON.stringify(value)})`;\n}\n\n/** Render the one source shape that the file authoring port may mutate structurally. */\nexport function renderCanonicalScriptablePack(manifest: CanonicalManifest): string {\n const data = JSON.stringify(manifest, null, 2);\n return `${CANONICAL_SCAFFOLD_MARKER}\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { buildMeshAttributeMapForUvSets } from '@forgeax/engine-geometry';\nimport type { ScriptablePackDefinition } from '@forgeax/engine-pack/source';\nimport type { Asset, AssetGuid as AssetGuidType } from '@forgeax/engine-types';\nimport { ok } from '@forgeax/engine-types';\n\nconst ${CANONICAL_MANIFEST_NAME} = ${data} as const;\n\nfunction parseGuid(value: string): AssetGuidType {\n const parsed = AssetGuid.parse(value);\n if (!parsed.ok) throw parsed.error;\n return parsed.value;\n}\n\nfunction createOutput(kind: string): Asset {\n switch (kind) {\n case 'scene':\n return { kind: 'scene', entities: [], mounts: [] };\n case 'material':\n return { kind: 'material', values: {} };\n case 'mesh': {\n const vertices = new Float32Array([\n 0, 0.7, 0, 0, 0, 1, 0.5, 1, 0, 0, 0, 1,\n -0.7, -0.6, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1,\n 0.7, -0.6, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1,\n ]);\n return {\n kind: 'mesh',\n vertices,\n indices: new Uint16Array([0, 1, 2]),\n attributes: { ...buildMeshAttributeMapForUvSets(1), position: vertices },\n aabb: new Float32Array([-0.7, -0.6, 0, 0.7, 0.7, 0]),\n submeshes: [{ indexOffset: 0, indexCount: 3, vertexCount: 3, topology: 'triangle-list', materialSlot: 0 }],\n materialSlots: [{ slotName: 'Default' }],\n };\n }\n default:\n throw new Error(\\`canonical ScriptablePack output kind is not mutable: \\${kind}\\`);\n }\n}\n\nconst assets = Object.fromEntries(\n Object.entries(${CANONICAL_MANIFEST_NAME}.assets).map(([sourceKey, asset]) => [\n sourceKey,\n { ...asset, guid: parseGuid(asset.guid) },\n ]),\n);\nconst externalAssets = Object.fromEntries(\n Object.entries(${CANONICAL_MANIFEST_NAME}.externalAssets).map(([alias, guid]) => [alias, parseGuid(guid)]),\n);\n\nexport default {\n schemaVersion: '1.0.0',\n packageId: ${guidExpression(manifest.packageId)},\n ${manifest.name === undefined ? '' : `name: ${JSON.stringify(manifest.name)},\\n `}assets,\n externalAssets,\n build: () => ok(Object.fromEntries(Object.entries(assets).map(([sourceKey, asset]) => [sourceKey, createOutput(asset.kind)])) as Record<string, Asset>),\n} satisfies ScriptablePackDefinition;\n`;\n}\n\nfunction definitionFromCanonical(\n manifest: CanonicalManifest,\n): Result<ScriptablePackDefinition, ScriptablePackError> {\n const packageId = AssetGuidCodec.parse(manifest.packageId);\n if (!packageId.ok) return invalidCanonicalGuid('$.packageId', manifest.packageId);\n const assets: Record<string, { guid: AssetGuid; kind: ScriptablePackAssetKind; name?: string }> =\n {};\n for (const [sourceKey, output] of Object.entries(manifest.assets)) {\n const guid = AssetGuidCodec.parse(output.guid);\n if (!guid.ok)\n return invalidCanonicalGuid(`$.assets[${JSON.stringify(sourceKey)}].guid`, output.guid);\n assets[sourceKey] = {\n guid: guid.value,\n kind: output.kind,\n ...(output.name === undefined ? {} : { name: output.name }),\n };\n }\n const externalAssets: Record<string, AssetGuid> = {};\n for (const [alias, value] of Object.entries(manifest.externalAssets)) {\n const guid = AssetGuidCodec.parse(value);\n if (!guid.ok) return invalidCanonicalGuid(`$.externalAssets[${JSON.stringify(alias)}]`, value);\n externalAssets[alias] = guid.value;\n }\n return validateScriptablePackDefinition({\n schemaVersion: '1.0.0',\n packageId: packageId.value,\n ...(manifest.name === undefined ? {} : { name: manifest.name }),\n assets,\n externalAssets,\n build: () => ok({} as Record<string, never>),\n });\n}\n\nfunction invalidCanonicalGuid(\n propertyPath: string,\n actual: string,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-definition-invalid',\n expected: 'a canonical UUID string',\n hint: 'repair the canonical scaffold manifest GUID and inspect Meta again',\n detail: { propertyPath, actual },\n });\n}\n\nfunction invalidCanonicalSource(\n sourcePath: string,\n error: unknown,\n): Result<never, ScriptablePackError> {\n return err({\n code: 'pack-source-definition-invalid',\n expected: 'a literal canonical-v1 manifest with the required package/assets/external fields',\n hint: 'repair the canonical scaffold or open it as custom source without structured mutation',\n detail: {\n sourcePath,\n propertyPath: '$.canonicalManifest',\n actual: error instanceof Error ? error.message : String(error),\n },\n });\n}\n\nasync function atomicWrite(path: string, source: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;\n try {\n await writeFile(temporary, source, { encoding: 'utf8', flag: 'wx' });\n await rename(temporary, path);\n } catch (error) {\n await rm(temporary, { force: true });\n throw error;\n }\n}\n\nfunction sameStrings(left: readonly string[], right: readonly string[]): boolean {\n return [...left].sort().join('\\0') === [...right].sort().join('\\0');\n}\n\n/** Node filesystem adapter for the public ScriptablePack authoring gateway. */\nexport function createFileSystemScriptablePackAuthoringPort(\n options: FileSystemScriptablePackAuthoringOptions,\n): ScriptablePackAuthoringPort {\n const resolvePath = (sourcePath: string) => confinedSourcePath(options.gameRoot, sourcePath);\n\n async function readSource(sourcePath: string) {\n const path = resolvePath(sourcePath);\n if (!path.ok) return path;\n try {\n const source = await readFile(path.value.absolute, 'utf8');\n return ok({ ...path.value, source, revision: revisionOf(source) });\n } catch (error) {\n return err(\n authoringError('pack-source-write-failed', {\n expected: 'a readable ScriptablePack source file',\n actual: error instanceof Error ? error.message : String(error),\n hint: 'restore the source file or create it through the ScriptablePack gateway',\n retryable: true,\n recoveryActions: ['inspect-source-path', 'retry'],\n sourcePath,\n }),\n );\n }\n }\n\n async function inspect(sourcePath: string) {\n const read = await readSource(sourcePath);\n if (!read.ok) return read;\n let canonical: CanonicalManifest | undefined;\n try {\n canonical = parseCanonicalManifest(read.value.source, read.value.relative);\n } catch (error) {\n return invalidCanonicalSource(read.value.relative, error);\n }\n const loaded =\n canonical === undefined\n ? await loadScriptablePack(read.value.absolute, { metadataOnly: true })\n : definitionFromCanonical(canonical);\n if (!loaded.ok) return loaded;\n return ok({\n revision: read.value.revision,\n meta: projectScriptablePackMeta(loaded.value, read.value.relative),\n });\n }\n\n async function preflight(sourcePath: string) {\n const read = await readSource(sourcePath);\n if (!read.ok) return read;\n const inspected = await inspect(sourcePath);\n if (!inspected.ok) return inspected;\n let canonical: CanonicalManifest | undefined;\n try {\n canonical = parseCanonicalManifest(read.value.source, read.value.relative);\n } catch (error) {\n return invalidCanonicalSource(read.value.relative, error);\n }\n const incomingRefs = (await options.incomingRefs?.(read.value.relative)) ?? [];\n return ok({\n revision: inspected.value.revision,\n meta: inspected.value.meta,\n capabilities:\n canonical === undefined\n ? ({\n inspect: true,\n rebuild: true,\n coldCook: true,\n reason: 'structured mutation is available only for canonical-v1 scaffolds',\n } as const)\n : ({\n inspect: true,\n rebuild: true,\n coldCook: true,\n addOutput: true,\n addExternalAsset: true,\n renameDisplay: true,\n removeOutput: true,\n clone: true,\n } as const),\n incomingRefs,\n });\n }\n\n async function mutate(operation: ScriptablePackAuthoringMutation) {\n const targetPath =\n operation.kind === 'clone-scriptable-pack' ? operation.targetPath : operation.sourcePath;\n const target = resolvePath(targetPath);\n if (!target.ok) return target;\n\n let manifest: CanonicalManifest;\n let currentRevision: string | undefined;\n if (operation.kind === 'create-scriptable-pack') {\n if (!CANONICAL_MUTABLE_KINDS.has(operation.initialOutput.kind)) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'a canonical scene, mesh, or material initial output',\n actual: operation.initialOutput.kind,\n hint: 'create one of the canonical output kinds, then hand-author advanced outputs',\n retryable: false,\n recoveryActions: ['choose-supported-output-kind'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n }\n try {\n await stat(target.value.absolute);\n return err(\n authoringError('pack-source-revision-conflict', {\n expected: 'an unused target source path',\n actual: 'source already exists',\n hint: 'inspect the existing source or choose a new path',\n retryable: false,\n recoveryActions: ['asset.preflight', 'choose-new-source-path'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n } catch {\n // Missing is the required create precondition.\n }\n manifest = {\n schemaVersion: '1.0.0',\n packageId: AssetGuidCodec.format(operation.packageId),\n ...(operation.name === undefined ? {} : { name: operation.name }),\n assets: {\n [operation.initialOutput.sourceKey]: {\n guid: AssetGuidCodec.format(operation.initialOutput.guid),\n kind: operation.initialOutput.kind,\n ...(operation.initialOutput.name === undefined\n ? {}\n : { name: operation.initialOutput.name }),\n },\n },\n externalAssets: {},\n };\n } else {\n const read = await readSource(operation.sourcePath);\n if (!read.ok) return read;\n currentRevision = read.value.revision;\n if (\n operation.expectedRevision !== undefined &&\n operation.expectedRevision !== currentRevision\n ) {\n return err(\n authoringError('pack-source-revision-conflict', {\n expected: operation.expectedRevision,\n actual: currentRevision,\n hint: 'inspect the current source revision, reconcile the edit, then retry with a new requestId',\n retryable: true,\n recoveryActions: ['asset.preflight', 'mint-request-id'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n }\n let parsed: CanonicalManifest | undefined;\n try {\n parsed = parseCanonicalManifest(read.value.source, read.value.relative);\n } catch (error) {\n return invalidCanonicalSource(read.value.relative, error);\n }\n if (parsed === undefined) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'a canonical-v1 scaffold for structured source mutation',\n actual: 'custom ScriptablePack source',\n hint: 'clone into a canonical scaffold or edit custom source with a code editor',\n retryable: false,\n recoveryActions: ['clone-scriptable-pack', 'open-code-editor'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n }),\n );\n }\n manifest = parsed;\n }\n\n if (operation.kind === 'clone-scriptable-pack') {\n try {\n await stat(target.value.absolute);\n return err(\n authoringError('pack-source-revision-conflict', {\n expected: 'an unused clone target source path',\n actual: 'source already exists',\n hint: 'inspect the existing target or choose a new path',\n retryable: false,\n recoveryActions: ['asset.preflight', 'choose-new-source-path'],\n requestId: operation.requestId,\n sourcePath: target.value.relative,\n }),\n );\n } catch {\n // Missing is the required clone precondition.\n }\n }\n\n if (operation.kind === 'add-output') {\n if (!CANONICAL_MUTABLE_KINDS.has(operation.assetKind)) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'a canonical scene, mesh, or material output',\n actual: operation.assetKind,\n hint: 'hand-author advanced output kinds in the source module',\n retryable: false,\n recoveryActions: ['open-code-editor'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.sourceKey,\n }),\n );\n }\n manifest = {\n ...manifest,\n assets: {\n ...manifest.assets,\n [operation.sourceKey]: {\n guid: AssetGuidCodec.format(operation.guid),\n kind: operation.assetKind,\n ...(operation.name === undefined ? {} : { name: operation.name }),\n },\n },\n };\n } else if (operation.kind === 'add-external-asset') {\n manifest = {\n ...manifest,\n externalAssets: {\n ...manifest.externalAssets,\n [operation.alias]: AssetGuidCodec.format(operation.guid),\n },\n };\n } else if (operation.kind === 'rename-display') {\n if (operation.target.kind === 'package') manifest = { ...manifest, name: operation.name };\n else {\n const output = manifest.assets[operation.target.sourceKey];\n if (output === undefined)\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'an existing sourceKey',\n actual: operation.target.sourceKey,\n hint: 'inspect Meta and choose a current output',\n retryable: true,\n recoveryActions: ['asset.preflight'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.target.sourceKey,\n }),\n );\n manifest = {\n ...manifest,\n assets: {\n ...manifest.assets,\n [operation.target.sourceKey]: { ...output, name: operation.name },\n },\n };\n }\n } else if (operation.kind === 'remove-output') {\n const incomingRefs =\n (await options.incomingRefs?.(operation.sourcePath, operation.sourceKey)) ?? [];\n if (\n incomingRefs.length > 0 &&\n !sameStrings(incomingRefs, operation.confirmIncomingRefs ?? [])\n ) {\n return err(\n authoringError('pack-source-reference-conflict', {\n expected: 'explicit acknowledgement of every current incoming reference',\n actual: `${incomingRefs.length} incoming references`,\n hint: 'inspect dependents, then confirm the exact incoming reference identities or cancel',\n retryable: true,\n recoveryActions: ['inspect-incoming-refs', 'confirm-remove-output'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.sourceKey,\n incomingRefs,\n }),\n );\n }\n const { [operation.sourceKey]: removed, ...assets } = manifest.assets;\n if (removed === undefined || Object.keys(assets).length === 0) {\n return err(\n authoringError('pack-source-mutation-unsupported', {\n expected: 'an existing output while retaining at least one package output',\n actual: operation.sourceKey,\n hint: 'keep one output or remove the entire source file through an explicit file operation',\n retryable: false,\n recoveryActions: ['asset.preflight'],\n requestId: operation.requestId,\n sourcePath: operation.sourcePath,\n sourceKey: operation.sourceKey,\n }),\n );\n }\n manifest = { ...manifest, assets };\n } else if (operation.kind === 'clone-scriptable-pack') {\n manifest = {\n ...manifest,\n packageId: AssetGuidCodec.format(operation.packageId),\n assets: Object.fromEntries(\n Object.entries(manifest.assets).map(([sourceKey, output]) => [\n sourceKey,\n {\n ...output,\n guid: AssetGuidCodec.format(operation.outputGuids[sourceKey] as AssetGuid),\n },\n ]),\n ),\n };\n }\n\n const source = renderCanonicalScriptablePack(manifest);\n try {\n await atomicWrite(target.value.absolute, source);\n return ok({ sourcePath: target.value.relative, revision: revisionOf(source) });\n } catch (error) {\n return err(\n authoringError('pack-source-write-failed', {\n expected: 'an atomic source-file replacement',\n actual: error instanceof Error ? error.message : String(error),\n hint: 'repair filesystem permissions or disk capacity, then retry with a new requestId',\n retryable: true,\n recoveryActions: ['inspect-filesystem', 'mint-request-id'],\n requestId: operation.requestId,\n sourcePath: target.value.relative,\n }),\n );\n }\n }\n\n return {\n preflight,\n mutate,\n inspect,\n async rebuild(sourcePath, mode) {\n const path = resolvePath(sourcePath);\n if (!path.ok) return path;\n const rebuilt = (await options.rebuild?.(path.value.relative, mode)) ?? ok(undefined);\n return rebuilt.ok ? inspect(path.value.relative) : rebuilt;\n },\n };\n}\n"]}