@earendil-works/chord 0.87.1 → 0.99.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +80 -27
  2. package/dist/api.d.ts +6 -1
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/api.js +8 -3
  5. package/dist/api.js.map +1 -1
  6. package/dist/bundler.d.ts.map +1 -1
  7. package/dist/context/index.d.ts.map +1 -1
  8. package/dist/context/index.js.map +1 -1
  9. package/dist/delta/apply-immutable-trusted.d.ts +4 -0
  10. package/dist/delta/apply-immutable-trusted.d.ts.map +1 -0
  11. package/dist/delta/apply-immutable-trusted.js +127 -0
  12. package/dist/delta/apply-immutable-trusted.js.map +1 -0
  13. package/dist/{state → delta}/diff.d.ts +1 -1
  14. package/dist/delta/diff.d.ts.map +1 -0
  15. package/dist/delta/diff.js +433 -0
  16. package/dist/delta/diff.js.map +1 -0
  17. package/dist/delta/draft.d.ts +5 -0
  18. package/dist/delta/draft.d.ts.map +1 -0
  19. package/dist/delta/draft.js +2 -0
  20. package/dist/delta/draft.js.map +1 -0
  21. package/dist/delta/index.d.ts +11 -21
  22. package/dist/delta/index.d.ts.map +1 -1
  23. package/dist/delta/index.js +43 -1341
  24. package/dist/delta/index.js.map +1 -1
  25. package/dist/delta/revision-validator.d.ts +7 -0
  26. package/dist/delta/revision-validator.d.ts.map +1 -0
  27. package/dist/delta/revision-validator.js +71 -0
  28. package/dist/delta/revision-validator.js.map +1 -0
  29. package/dist/delta/tracker.d.ts +26 -0
  30. package/dist/delta/tracker.d.ts.map +1 -0
  31. package/dist/delta/tracker.js +2069 -0
  32. package/dist/delta/tracker.js.map +1 -0
  33. package/dist/facets/host.d.ts.map +1 -1
  34. package/dist/facets/host.js.map +1 -1
  35. package/dist/facets/loader.d.ts.map +1 -1
  36. package/dist/facets/loader.js.map +1 -1
  37. package/dist/index.d.ts +3 -3
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +1 -1
  40. package/dist/index.js.map +1 -1
  41. package/dist/json.d.ts +6 -0
  42. package/dist/json.d.ts.map +1 -1
  43. package/dist/json.js +73 -6
  44. package/dist/json.js.map +1 -1
  45. package/dist/node/bundle-loader.d.ts.map +1 -1
  46. package/dist/node/bundle-loader.js.map +1 -1
  47. package/dist/node/bundle.d.ts.map +1 -1
  48. package/dist/node/bundle.js.map +1 -1
  49. package/dist/node/manifest.d.ts.map +1 -1
  50. package/dist/node/package.d.ts.map +1 -1
  51. package/dist/node/package.js.map +1 -1
  52. package/dist/node.d.ts.map +1 -1
  53. package/dist/services/consumer.d.ts.map +1 -1
  54. package/dist/services/consumer.js +49 -1
  55. package/dist/services/consumer.js.map +1 -1
  56. package/dist/services/errors.d.ts.map +1 -1
  57. package/dist/services/errors.js.map +1 -1
  58. package/dist/services/handle.d.ts.map +1 -1
  59. package/dist/services/handle.js +3 -1
  60. package/dist/services/handle.js.map +1 -1
  61. package/dist/services/instances.d.ts +1 -0
  62. package/dist/services/instances.d.ts.map +1 -1
  63. package/dist/services/instances.js +3 -0
  64. package/dist/services/instances.js.map +1 -1
  65. package/dist/services/loopback.d.ts.map +1 -1
  66. package/dist/services/loopback.js.map +1 -1
  67. package/dist/services/provider.d.ts.map +1 -1
  68. package/dist/services/provider.js +48 -29
  69. package/dist/services/provider.js.map +1 -1
  70. package/dist/services/state-codec.d.ts.map +1 -1
  71. package/dist/services/state-codec.js +18 -0
  72. package/dist/services/state-codec.js.map +1 -1
  73. package/dist/services/state-internals.d.ts +5 -2
  74. package/dist/services/state-internals.d.ts.map +1 -1
  75. package/dist/services/state-internals.js.map +1 -1
  76. package/dist/services/state.d.ts +8 -3
  77. package/dist/services/state.d.ts.map +1 -1
  78. package/dist/services/state.js +288 -88
  79. package/dist/services/state.js.map +1 -1
  80. package/dist/services/wire.d.ts +3 -0
  81. package/dist/services/wire.d.ts.map +1 -1
  82. package/dist/services/wire.js +13 -0
  83. package/dist/services/wire.js.map +1 -1
  84. package/dist/types.d.ts +74 -8
  85. package/dist/types.d.ts.map +1 -1
  86. package/dist/types.js.map +1 -1
  87. package/package.json +3 -3
  88. package/src/delta/README.md +143 -360
  89. package/dist/state/diff.d.ts.map +0 -1
  90. package/dist/state/diff.js +0 -259
  91. package/dist/state/diff.js.map +0 -1
  92. package/dist/state/draft.d.ts +0 -13
  93. package/dist/state/draft.d.ts.map +0 -1
  94. package/dist/state/draft.js +0 -540
  95. package/dist/state/draft.js.map +0 -1
  96. package/dist/state/value.d.ts +0 -9
  97. package/dist/state/value.d.ts.map +0 -1
  98. package/dist/state/value.js +0 -175
  99. package/dist/state/value.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"bundle-loader.d.ts","sourceRoot":"","sources":["../../src/node/bundle-loader.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAS,WAAW,EAAgB,MAAM,aAAa,CAAC;AACpE,OAAO,EAMN,KAAK,mBAAmB,EAExB,KAAK,mBAAmB,EACxB,MAAM,eAAe,CAAC;AAEvB,MAAM,MAAM,2BAA2B,GAAG,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,GAAG,GAAG,GAAG,SAAS,CAAC;AAE1F,MAAM,WAAW,wBAAwB;IACxC,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,GAAG,CAAC;IACpC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,mFAAmF;IACnF,QAAQ,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IACnC,iGAAiG;IACjG,QAAQ,CAAC,eAAe,CAAC,EAAE,2BAA2B,CAAC;CACvD;AAED,MAAM,WAAW,gCAAgC;IAChD,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,gFAAgF;IAChF,QAAQ,CAAC,eAAe,CAAC,EAAE,2BAA2B,CAAC;IACvD,6GAA6G;IAC7G,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;CACrC;AAMD,2DAA2D;AAC3D,wBAAsB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAS9F;AAED,2EAA2E;AAC3E,wBAAsB,uBAAuB,CAAC,OAAO,EAAE;IACtD,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,GAAG,CAAC;IACpC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACvB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAsB/B;AAED,2GAA2G;AAC3G,wBAAgB,+BAA+B,CAAC,OAAO,EAAE,gCAAgC,GAAG,WAAW,CA+CtG;AAED,gFAAgF;AAChF,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,wBAAwB,GAAG,WAAW,CAmCtF","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { mkdir, mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { createRequire, isBuiltin } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { compileFunction } from \"node:vm\";\nimport type { Facet, FacetLoader, LoadedFacets } from \"../types.ts\";\nimport {\n\tFACET_BUNDLE_ARTIFACT_FORMAT,\n\tFACET_BUNDLE_ARTIFACT_FORMAT_VERSION,\n\tFACET_BUNDLE_FORMAT,\n\tFACET_BUNDLE_FORMAT_VERSION,\n\tFACET_BUNDLE_MANIFEST_FILE,\n\ttype FacetBundleArtifact,\n\ttype FacetBundleEntry,\n\ttype FacetBundleManifest,\n} from \"./manifest.ts\";\n\nexport type FacetBundleExternalResolver = (specifier: string) => string | URL | undefined;\n\nexport interface FacetBundleLoaderOptions {\n\treadonly manifestPath: string | URL;\n\treadonly entry: string;\n\t/** Verify the entry's SHA-256 integrity before evaluating it. Defaults to true. */\n\treadonly verifyIntegrity?: boolean;\n\t/** Resolve host-provided external imports when the bundle is outside the host's package tree. */\n\treadonly resolveExternal?: FacetBundleExternalResolver;\n}\n\nexport interface FacetBundleArtifactLoaderOptions {\n\treadonly artifact: unknown;\n\t/** Resolve host-provided external imports against the receiving application. */\n\treadonly resolveExternal?: FacetBundleExternalResolver;\n\t/** Parent directory for materialized module generations. Defaults to the operating system temp directory. */\n\treadonly temporaryDirectory?: string;\n}\n\ninterface CommonJsModule {\n\texports: unknown;\n}\n\n/** Read and validate a versioned facet bundle manifest. */\nexport async function readFacetBundleManifest(path: string | URL): Promise<FacetBundleManifest> {\n\tconst manifestPath = toFilePath(path);\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(await readFile(manifestPath, \"utf8\"));\n\t} catch (error) {\n\t\tthrow new Error(`Could not read facet bundle manifest ${manifestPath}`, { cause: error });\n\t}\n\treturn validateManifest(parsed, manifestPath);\n}\n\n/** Read and verify one transportable entry from a facet bundle on disk. */\nexport async function readFacetBundleArtifact(options: {\n\treadonly manifestPath: string | URL;\n\treadonly entry: string;\n}): Promise<FacetBundleArtifact> {\n\tif (options.entry.length === 0) throw new TypeError(\"Facet bundle entry name must not be empty\");\n\tconst manifestPath = toFilePath(options.manifestPath);\n\tconst manifest = await readFacetBundleManifest(manifestPath);\n\tconst entry = manifest.entries[options.entry];\n\tif (entry === undefined) throw new Error(`Facet bundle ${manifest.plugin.id} has no entry named ${options.entry}`);\n\tconst modulePath = resolveBundleFile(manifestPath, entry.file, \"entry\");\n\tconst source = await readFile(modulePath, \"utf8\");\n\tverifySource(source, entry);\n\tconst sourceMapContents =\n\t\tentry.sourceMap === undefined\n\t\t\t? undefined\n\t\t\t: await readFile(resolveBundleFile(manifestPath, entry.sourceMap, \"source map\"), \"utf8\");\n\treturn Object.freeze({\n\t\tformat: FACET_BUNDLE_ARTIFACT_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_ARTIFACT_FORMAT_VERSION,\n\t\tplugin: manifest.plugin,\n\t\tentryName: options.entry,\n\t\tentry,\n\t\tsource,\n\t\t...(sourceMapContents === undefined ? {} : { sourceMapContents }),\n\t});\n}\n\n/** Materialize a transported artifact and create a fresh VM-compiled CommonJS generation for each load. */\nexport function createFacetBundleArtifactLoader(options: FacetBundleArtifactLoaderOptions): FacetLoader {\n\tconst artifact = validateArtifact(options.artifact);\n\tconst temporaryParent = resolve(options.temporaryDirectory ?? tmpdir());\n\treturn {\n\t\tasync load(): Promise<LoadedFacets> {\n\t\t\tawait mkdir(temporaryParent, { recursive: true });\n\t\t\tconst directory = await mkdtemp(join(temporaryParent, \"chord-facet-\"));\n\t\t\ttry {\n\t\t\t\tawait materializeArtifact(directory, artifact);\n\t\t\t\tconst loaded = await createFacetBundleLoader({\n\t\t\t\t\tmanifestPath: join(directory, FACET_BUNDLE_MANIFEST_FILE),\n\t\t\t\t\tentry: artifact.entryName,\n\t\t\t\t\tresolveExternal: options.resolveExternal,\n\t\t\t\t}).load();\n\t\t\t\tlet disposed = false;\n\t\t\t\treturn {\n\t\t\t\t\tget facets() {\n\t\t\t\t\t\treturn loaded.facets;\n\t\t\t\t\t},\n\t\t\t\t\tasync dispose() {\n\t\t\t\t\t\tif (disposed) return;\n\t\t\t\t\t\tdisposed = true;\n\t\t\t\t\t\tconst errors: unknown[] = [];\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait loaded.dispose();\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\terrors.push(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait rm(directory, { force: true, recursive: true });\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\terrors.push(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (errors.length === 1) throw errors[0];\n\t\t\t\t\t\tif (errors.length > 1) throw new AggregateError(errors, \"Failed to dispose facet bundle artifact\");\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait rm(directory, { force: true, recursive: true });\n\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\tthrow new AggregateError([error, cleanupError], \"Facet bundle artifact loading and cleanup failed\");\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** Create a reusable loader for one opaque entry in a facet bundle manifest. */\nexport function createFacetBundleLoader(options: FacetBundleLoaderOptions): FacetLoader {\n\tif (options.entry.length === 0) throw new TypeError(\"Facet bundle entry name must not be empty\");\n\tconst manifestPath = toFilePath(options.manifestPath);\n\treturn {\n\t\tasync load(): Promise<LoadedFacets> {\n\t\t\tconst manifest = await readFacetBundleManifest(manifestPath);\n\t\t\tconst entry = manifest.entries[options.entry];\n\t\t\tif (entry === undefined) {\n\t\t\t\tthrow new Error(`Facet bundle ${manifest.plugin.id} has no entry named ${options.entry}`);\n\t\t\t}\n\t\t\tconst modulePath = resolveBundleFile(manifestPath, entry.file, \"entry\");\n\t\t\ttry {\n\t\t\t\tconst source = await readFile(modulePath, \"utf8\");\n\t\t\t\tif (options.verifyIntegrity !== false) verifySource(source, entry);\n\t\t\t\tconst exported = executeCommonJsModule(source, modulePath, entry.externalImports, options.resolveExternal);\n\t\t\t\tlet facets = facetsFromModule(exported, manifest.plugin.id, options.entry);\n\t\t\t\tlet disposed = false;\n\t\t\t\treturn {\n\t\t\t\t\tget facets() {\n\t\t\t\t\t\treturn facets;\n\t\t\t\t\t},\n\t\t\t\t\tasync dispose() {\n\t\t\t\t\t\tif (disposed) return;\n\t\t\t\t\t\tdisposed = true;\n\t\t\t\t\t\tfacets = Object.freeze([]);\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tconst detail = error instanceof Error ? `: ${error.message}` : \"\";\n\t\t\t\tthrow new Error(`Could not load facet bundle entry ${manifest.plugin.id}/${options.entry}${detail}`, {\n\t\t\t\t\tcause: error,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t};\n}\n\nfunction executeCommonJsModule(\n\tsource: string,\n\tmodulePath: string,\n\texternalImports: readonly string[],\n\tresolver?: FacetBundleExternalResolver,\n): unknown {\n\tconst requireFromModule = createRequire(modulePath);\n\tconst externalTargets = new Map<string, string>();\n\tfor (const specifier of externalImports) {\n\t\tif (!isBuiltin(specifier)) validatePackageSpecifier(specifier);\n\t\texternalTargets.set(specifier, toRequireSpecifier(resolveExternalTarget(specifier, resolver)));\n\t}\n\tconst targetFor = (specifier: string): string => {\n\t\tconst target = externalTargets.get(specifier);\n\t\tif (target === undefined) throw new Error(`Facet bundle required undeclared external import: ${specifier}`);\n\t\treturn target;\n\t};\n\tconst requireExternal = Object.assign((specifier: string): unknown => requireFromModule(targetFor(specifier)), {\n\t\tresolve: (specifier: string): string => requireFromModule.resolve(targetFor(specifier)),\n\t});\n\tconst commonJsModule: CommonJsModule = { exports: Object.create(null) };\n\tconst compiled = compileFunction(source, [\"exports\", \"require\", \"module\", \"__filename\", \"__dirname\"], {\n\t\tfilename: modulePath,\n\t});\n\tReflect.apply(compiled, commonJsModule.exports, [\n\t\tcommonJsModule.exports,\n\t\trequireExternal,\n\t\tcommonJsModule,\n\t\tmodulePath,\n\t\tdirname(modulePath),\n\t]);\n\treturn commonJsModule.exports;\n}\n\nfunction toRequireSpecifier(target: string): string {\n\tif (isAbsolute(target) || isBuiltin(target)) return target;\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(target);\n\t} catch {\n\t\treturn target;\n\t}\n\tif (url.protocol === \"file:\") return fileURLToPath(url);\n\tif (url.protocol === \"node:\") return url.href;\n\tthrow new Error(`Facet bundle external target must be a file, package, or built-in module: ${target}`);\n}\n\nfunction toFilePath(path: string | URL): string {\n\tif (typeof path === \"string\") return resolve(path);\n\tif (path.protocol !== \"file:\") throw new TypeError(`Facet bundle manifest must be a file URL, not ${path.protocol}`);\n\treturn fileURLToPath(path);\n}\n\nfunction resolveBundleFile(manifestPath: string, file: string, label: string): string {\n\tif (file.length === 0 || isAbsolute(file) || basename(file) !== file || file === \".\" || file === \"..\") {\n\t\tthrow new Error(`Facet bundle ${label} must be a filename relative to its manifest`);\n\t}\n\treturn resolve(dirname(manifestPath), file);\n}\n\nfunction verifySource(source: string, entry: FacetBundleEntry): void {\n\tconst expected = parseIntegrity(entry.integrity);\n\tconst actual = createHash(\"sha256\").update(source, \"utf8\").digest(\"base64\");\n\tif (actual !== expected) throw new Error(`Facet bundle integrity check failed for ${entry.file}`);\n}\n\nfunction parseIntegrity(integrity: string): string {\n\tconst prefix = \"sha256-\";\n\tif (!integrity.startsWith(prefix) || integrity.length === prefix.length) {\n\t\tthrow new Error(\"Facet bundle entry has an invalid SHA-256 integrity value\");\n\t}\n\treturn integrity.slice(prefix.length);\n}\n\nfunction facetsFromModule(imported: unknown, pluginId: string, entryName: string): readonly Facet[] {\n\tif (!isRecord(imported)) throw new Error(`Facet bundle entry ${pluginId}/${entryName} did not export a module`);\n\tconst exported = imported.default;\n\tconst candidates: readonly unknown[] = Array.isArray(exported) ? (exported as readonly unknown[]) : [exported];\n\tif (candidates.length === 0) {\n\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} exported no facets`);\n\t}\n\tconst facets: Facet[] = [];\n\tfor (const candidate of candidates) {\n\t\tif (!isRecord(candidate) || typeof candidate.id !== \"string\" || candidate.id.length === 0) {\n\t\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} has a facet with an invalid ID`);\n\t\t}\n\t\tif (typeof candidate.setup !== \"function\") {\n\t\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} facet ${candidate.id} has no setup function`);\n\t\t}\n\t\tfacets.push(candidate as unknown as Facet);\n\t}\n\tconst ids = facets.map(({ id }) => id);\n\tif (new Set(ids).size !== ids.length) {\n\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} exports duplicate facet IDs`);\n\t}\n\treturn Object.freeze(facets);\n}\n\nfunction validateArtifact(value: unknown): FacetBundleArtifact {\n\tif (\n\t\t!isRecord(value) ||\n\t\tvalue.format !== FACET_BUNDLE_ARTIFACT_FORMAT ||\n\t\tvalue.formatVersion !== FACET_BUNDLE_ARTIFACT_FORMAT_VERSION ||\n\t\ttypeof value.entryName !== \"string\" ||\n\t\tvalue.entryName.length === 0 ||\n\t\ttypeof value.source !== \"string\"\n\t) {\n\t\tthrow new Error(\"Invalid facet bundle artifact\");\n\t}\n\tconst manifest = validateManifest(\n\t\t{\n\t\t\tformat: FACET_BUNDLE_FORMAT,\n\t\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\t\tplugin: value.plugin,\n\t\t\tentries: { [value.entryName]: value.entry },\n\t\t},\n\t\t\"facet bundle artifact\",\n\t);\n\tconst entry = manifest.entries[value.entryName]!;\n\tif (entry.sourceMap === undefined) {\n\t\tif (value.sourceMapContents !== undefined) {\n\t\t\tthrow new Error(\"Facet bundle artifact has source map contents without a source map\");\n\t\t}\n\t} else if (typeof value.sourceMapContents !== \"string\") {\n\t\tthrow new Error(\"Facet bundle artifact is missing its source map contents\");\n\t}\n\tverifySource(value.source, entry);\n\treturn Object.freeze({\n\t\tformat: FACET_BUNDLE_ARTIFACT_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_ARTIFACT_FORMAT_VERSION,\n\t\tplugin: manifest.plugin,\n\t\tentryName: value.entryName,\n\t\tentry,\n\t\tsource: value.source,\n\t\t...(value.sourceMapContents === undefined ? {} : { sourceMapContents: value.sourceMapContents }),\n\t});\n}\n\nasync function materializeArtifact(directory: string, artifact: FacetBundleArtifact): Promise<void> {\n\tconst manifest: FacetBundleManifest = {\n\t\tformat: FACET_BUNDLE_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\tplugin: artifact.plugin,\n\t\tentries: { [artifact.entryName]: artifact.entry },\n\t};\n\tawait Promise.all([\n\t\twriteFile(join(directory, artifact.entry.file), artifact.source, \"utf8\"),\n\t\twriteFile(join(directory, FACET_BUNDLE_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\\n`, \"utf8\"),\n\t\t...(artifact.entry.sourceMap === undefined\n\t\t\t? []\n\t\t\t: [writeFile(join(directory, artifact.entry.sourceMap), artifact.sourceMapContents!, \"utf8\")]),\n\t]);\n}\n\nfunction resolveExternalTarget(specifier: string, resolver?: FacetBundleExternalResolver): string {\n\tconst resolved = resolver?.(specifier);\n\tif (resolved !== undefined) return typeof resolved === \"string\" ? resolved : resolved.href;\n\tconst extension = import.meta.url.endsWith(\".ts\") ? \"ts\" : \"js\";\n\tif (specifier === \"@earendil-works/chord\") return new URL(`../index.${extension}`, import.meta.url).href;\n\tif (specifier === \"@earendil-works/chord/context\") {\n\t\treturn new URL(`../context/index.${extension}`, import.meta.url).href;\n\t}\n\tif (specifier === \"@earendil-works/chord/node\") return new URL(`../node.${extension}`, import.meta.url).href;\n\treturn import.meta.resolve(specifier);\n}\n\nfunction validatePackageSpecifier(specifier: string): void {\n\tconst segments = specifier.split(\"/\");\n\tconst packageParts = specifier.startsWith(\"@\") ? 2 : 1;\n\tif (\n\t\tspecifier.startsWith(\".\") ||\n\t\tspecifier.startsWith(\"/\") ||\n\t\tspecifier.startsWith(\"#\") ||\n\t\tspecifier.includes(\":\") ||\n\t\tspecifier.includes(\"\\\\\") ||\n\t\tsegments.length < packageParts ||\n\t\tsegments.some((part) => part.length === 0 || part === \".\" || part === \"..\")\n\t) {\n\t\tthrow new Error(`Facet bundle artifact has an unsupported external import: ${specifier}`);\n\t}\n}\n\nfunction validateManifest(value: unknown, path: string): FacetBundleManifest {\n\tif (!isRecord(value) || value.format !== FACET_BUNDLE_FORMAT) {\n\t\tthrow new Error(`Invalid facet bundle manifest format in ${path}`);\n\t}\n\tif (value.formatVersion !== FACET_BUNDLE_FORMAT_VERSION) {\n\t\tthrow new Error(`Unsupported facet bundle manifest version in ${path}: ${String(value.formatVersion)}`);\n\t}\n\tif (!isRecord(value.plugin) || typeof value.plugin.id !== \"string\" || value.plugin.id.length === 0) {\n\t\tthrow new Error(`Facet bundle manifest has an invalid plugin identity in ${path}`);\n\t}\n\tif (\n\t\tvalue.plugin.version !== undefined &&\n\t\t(typeof value.plugin.version !== \"string\" || value.plugin.version.length === 0)\n\t) {\n\t\tthrow new Error(`Facet bundle manifest has an invalid plugin version in ${path}`);\n\t}\n\tif (!isRecord(value.entries) || Object.keys(value.entries).length === 0) {\n\t\tthrow new Error(`Facet bundle manifest has no entries in ${path}`);\n\t}\n\tconst entries: Record<string, FacetBundleEntry> = {};\n\tfor (const [name, candidate] of Object.entries(value.entries)) {\n\t\tif (name.length === 0 || !isRecord(candidate)) {\n\t\t\tthrow new Error(`Facet bundle manifest has an invalid entry in ${path}`);\n\t\t}\n\t\tif (typeof candidate.file !== \"string\") throw new Error(`Facet bundle entry ${name} has no file`);\n\t\tresolveBundleFile(path, candidate.file, `entry ${name}`);\n\t\tif (typeof candidate.integrity !== \"string\") throw new Error(`Facet bundle entry ${name} has no integrity`);\n\t\tparseIntegrity(candidate.integrity);\n\t\tif (\n\t\t\t!Array.isArray(candidate.externalImports) ||\n\t\t\tcandidate.externalImports.some((item) => typeof item !== \"string\")\n\t\t) {\n\t\t\tthrow new Error(`Facet bundle entry ${name} has invalid external imports`);\n\t\t}\n\t\tconst externalImports = Object.freeze([...(candidate.externalImports as readonly string[])]);\n\t\tif (new Set(externalImports).size !== externalImports.length) {\n\t\t\tthrow new Error(`Facet bundle entry ${name} has duplicate external imports`);\n\t\t}\n\t\tif (candidate.sourceMap !== undefined) {\n\t\t\tif (typeof candidate.sourceMap !== \"string\")\n\t\t\t\tthrow new Error(`Facet bundle entry ${name} has an invalid source map`);\n\t\t\tresolveBundleFile(path, candidate.sourceMap, `entry ${name} source map`);\n\t\t}\n\t\tentries[name] = Object.freeze({\n\t\t\tfile: candidate.file,\n\t\t\tintegrity: candidate.integrity,\n\t\t\texternalImports,\n\t\t\t...(candidate.sourceMap === undefined ? {} : { sourceMap: candidate.sourceMap }),\n\t\t});\n\t}\n\treturn Object.freeze({\n\t\tformat: FACET_BUNDLE_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\tplugin: Object.freeze({\n\t\t\tid: value.plugin.id,\n\t\t\t...(value.plugin.version === undefined ? {} : { version: value.plugin.version }),\n\t\t}),\n\t\tentries: Object.freeze(entries),\n\t});\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
1
+ {"version":3,"file":"bundle-loader.d.ts","sourceRoot":"","sources":["../../src/node/bundle-loader.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAS,WAAW,EAAgB,MAAM,aAAa,CAAC;AACpE,OAAO,EAMN,KAAK,mBAAmB,EAExB,KAAK,mBAAmB,EACxB,MAAM,eAAe,CAAC;AAEvB,MAAM,MAAM,2BAA2B,GAAG,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,GAAG,GAAG,GAAG,SAAS,CAAC;AAE1F,MAAM,WAAW,wBAAwB;IACxC,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,GAAG,CAAC;IACpC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,mFAAmF;IACnF,QAAQ,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;IACnC,iGAAiG;IACjG,QAAQ,CAAC,eAAe,CAAC,EAAE,2BAA2B,CAAC;CACvD;AAED,MAAM,WAAW,gCAAgC;IAChD,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,gFAAgF;IAChF,QAAQ,CAAC,eAAe,CAAC,EAAE,2BAA2B,CAAC;IACvD,6GAA6G;IAC7G,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;CACrC;AAMD,2DAA2D;AAC3D,wBAAsB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAS9F;AAED,2EAA2E;AAC3E,wBAAsB,uBAAuB,CAAC,OAAO,EAAE;IACtD,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,GAAG,CAAC;IACpC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACvB,GAAG,OAAO,CAAC,mBAA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K,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { mkdir, mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { createRequire, isBuiltin } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { compileFunction } from \"node:vm\";\nimport type { Facet, FacetLoader, LoadedFacets } from \"../types.ts\";\nimport {\n\tFACET_BUNDLE_ARTIFACT_FORMAT,\n\tFACET_BUNDLE_ARTIFACT_FORMAT_VERSION,\n\tFACET_BUNDLE_FORMAT,\n\tFACET_BUNDLE_FORMAT_VERSION,\n\tFACET_BUNDLE_MANIFEST_FILE,\n\ttype FacetBundleArtifact,\n\ttype FacetBundleEntry,\n\ttype FacetBundleManifest,\n} from \"./manifest.ts\";\n\nexport type FacetBundleExternalResolver = (specifier: string) => string | URL | undefined;\n\nexport interface FacetBundleLoaderOptions {\n\treadonly manifestPath: string | URL;\n\treadonly entry: string;\n\t/** Verify the entry's SHA-256 integrity before evaluating it. Defaults to true. */\n\treadonly verifyIntegrity?: boolean;\n\t/** Resolve host-provided external imports when the bundle is outside the host's package tree. */\n\treadonly resolveExternal?: FacetBundleExternalResolver;\n}\n\nexport interface FacetBundleArtifactLoaderOptions {\n\treadonly artifact: unknown;\n\t/** Resolve host-provided external imports against the receiving application. */\n\treadonly resolveExternal?: FacetBundleExternalResolver;\n\t/** Parent directory for materialized module generations. Defaults to the operating system temp directory. */\n\treadonly temporaryDirectory?: string;\n}\n\ninterface CommonJsModule {\n\texports: unknown;\n}\n\n/** Read and validate a versioned facet bundle manifest. */\nexport async function readFacetBundleManifest(path: string | URL): Promise<FacetBundleManifest> {\n\tconst manifestPath = toFilePath(path);\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(await readFile(manifestPath, \"utf8\"));\n\t} catch (error) {\n\t\tthrow new Error(`Could not read facet bundle manifest ${manifestPath}`, { cause: error });\n\t}\n\treturn validateManifest(parsed, manifestPath);\n}\n\n/** Read and verify one transportable entry from a facet bundle on disk. */\nexport async function readFacetBundleArtifact(options: {\n\treadonly manifestPath: string | URL;\n\treadonly entry: string;\n}): Promise<FacetBundleArtifact> {\n\tif (options.entry.length === 0) throw new TypeError(\"Facet bundle entry name must not be empty\");\n\tconst manifestPath = toFilePath(options.manifestPath);\n\tconst manifest = await readFacetBundleManifest(manifestPath);\n\tconst entry = manifest.entries[options.entry];\n\tif (entry === undefined) throw new Error(`Facet bundle ${manifest.plugin.id} has no entry named ${options.entry}`);\n\tconst modulePath = resolveBundleFile(manifestPath, entry.file, \"entry\");\n\tconst source = await readFile(modulePath, \"utf8\");\n\tverifySource(source, entry);\n\tconst sourceMapContents =\n\t\tentry.sourceMap === undefined\n\t\t\t? undefined\n\t\t\t: await readFile(resolveBundleFile(manifestPath, entry.sourceMap, \"source map\"), \"utf8\");\n\treturn Object.freeze({\n\t\tformat: FACET_BUNDLE_ARTIFACT_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_ARTIFACT_FORMAT_VERSION,\n\t\tplugin: manifest.plugin,\n\t\tentryName: options.entry,\n\t\tentry,\n\t\tsource,\n\t\t...(sourceMapContents === undefined ? {} : { sourceMapContents }),\n\t});\n}\n\n/** Materialize a transported artifact and create a fresh VM-compiled CommonJS generation for each load. */\nexport function createFacetBundleArtifactLoader(options: FacetBundleArtifactLoaderOptions): FacetLoader {\n\tconst artifact = validateArtifact(options.artifact);\n\tconst temporaryParent = resolve(options.temporaryDirectory ?? tmpdir());\n\treturn {\n\t\tasync load(): Promise<LoadedFacets> {\n\t\t\tawait mkdir(temporaryParent, { recursive: true });\n\t\t\tconst directory = await mkdtemp(join(temporaryParent, \"chord-facet-\"));\n\t\t\ttry {\n\t\t\t\tawait materializeArtifact(directory, artifact);\n\t\t\t\tconst loaded = await createFacetBundleLoader({\n\t\t\t\t\tmanifestPath: join(directory, FACET_BUNDLE_MANIFEST_FILE),\n\t\t\t\t\tentry: artifact.entryName,\n\t\t\t\t\tresolveExternal: options.resolveExternal,\n\t\t\t\t}).load();\n\t\t\t\tlet disposed = false;\n\t\t\t\treturn {\n\t\t\t\t\tget facets() {\n\t\t\t\t\t\treturn loaded.facets;\n\t\t\t\t\t},\n\t\t\t\t\tasync dispose() {\n\t\t\t\t\t\tif (disposed) return;\n\t\t\t\t\t\tdisposed = true;\n\t\t\t\t\t\tconst errors: unknown[] = [];\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait loaded.dispose();\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\terrors.push(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait rm(directory, { force: true, recursive: true });\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\terrors.push(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (errors.length === 1) throw errors[0];\n\t\t\t\t\t\tif (errors.length > 1) throw new AggregateError(errors, \"Failed to dispose facet bundle artifact\");\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait rm(directory, { force: true, recursive: true });\n\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\tthrow new AggregateError([error, cleanupError], \"Facet bundle artifact loading and cleanup failed\");\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** Create a reusable loader for one opaque entry in a facet bundle manifest. */\nexport function createFacetBundleLoader(options: FacetBundleLoaderOptions): FacetLoader {\n\tif (options.entry.length === 0) throw new TypeError(\"Facet bundle entry name must not be empty\");\n\tconst manifestPath = toFilePath(options.manifestPath);\n\treturn {\n\t\tasync load(): Promise<LoadedFacets> {\n\t\t\tconst manifest = await readFacetBundleManifest(manifestPath);\n\t\t\tconst entry = manifest.entries[options.entry];\n\t\t\tif (entry === undefined) {\n\t\t\t\tthrow new Error(`Facet bundle ${manifest.plugin.id} has no entry named ${options.entry}`);\n\t\t\t}\n\t\t\tconst modulePath = resolveBundleFile(manifestPath, entry.file, \"entry\");\n\t\t\ttry {\n\t\t\t\tconst source = await readFile(modulePath, \"utf8\");\n\t\t\t\tif (options.verifyIntegrity !== false) verifySource(source, entry);\n\t\t\t\tconst exported = executeCommonJsModule(source, modulePath, entry.externalImports, options.resolveExternal);\n\t\t\t\tlet facets = facetsFromModule(exported, manifest.plugin.id, options.entry);\n\t\t\t\tlet disposed = false;\n\t\t\t\treturn {\n\t\t\t\t\tget facets() {\n\t\t\t\t\t\treturn facets;\n\t\t\t\t\t},\n\t\t\t\t\tasync dispose() {\n\t\t\t\t\t\tif (disposed) return;\n\t\t\t\t\t\tdisposed = true;\n\t\t\t\t\t\tfacets = Object.freeze([]);\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tconst detail = error instanceof Error ? `: ${error.message}` : \"\";\n\t\t\t\tthrow new Error(`Could not load facet bundle entry ${manifest.plugin.id}/${options.entry}${detail}`, {\n\t\t\t\t\tcause: error,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t};\n}\n\nfunction executeCommonJsModule(\n\tsource: string,\n\tmodulePath: string,\n\texternalImports: readonly string[],\n\tresolver?: FacetBundleExternalResolver,\n): unknown {\n\tconst requireFromModule = createRequire(modulePath);\n\tconst externalTargets = new Map<string, string>();\n\tfor (const specifier of externalImports) {\n\t\tif (!isBuiltin(specifier)) validatePackageSpecifier(specifier);\n\t\texternalTargets.set(specifier, toRequireSpecifier(resolveExternalTarget(specifier, resolver)));\n\t}\n\tconst targetFor = (specifier: string): string => {\n\t\tconst target = externalTargets.get(specifier);\n\t\tif (target === undefined) throw new Error(`Facet bundle required undeclared external import: ${specifier}`);\n\t\treturn target;\n\t};\n\tconst requireExternal = Object.assign((specifier: string): unknown => requireFromModule(targetFor(specifier)), {\n\t\tresolve: (specifier: string): string => requireFromModule.resolve(targetFor(specifier)),\n\t});\n\tconst commonJsModule: CommonJsModule = { exports: Object.create(null) };\n\tconst compiled = compileFunction(source, [\"exports\", \"require\", \"module\", \"__filename\", \"__dirname\"], {\n\t\tfilename: modulePath,\n\t});\n\tReflect.apply(compiled, commonJsModule.exports, [\n\t\tcommonJsModule.exports,\n\t\trequireExternal,\n\t\tcommonJsModule,\n\t\tmodulePath,\n\t\tdirname(modulePath),\n\t]);\n\treturn commonJsModule.exports;\n}\n\nfunction toRequireSpecifier(target: string): string {\n\tif (isAbsolute(target) || isBuiltin(target)) return target;\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(target);\n\t} catch {\n\t\treturn target;\n\t}\n\tif (url.protocol === \"file:\") return fileURLToPath(url);\n\tif (url.protocol === \"node:\") return url.href;\n\tthrow new Error(`Facet bundle external target must be a file, package, or built-in module: ${target}`);\n}\n\nfunction toFilePath(path: string | URL): string {\n\tif (typeof path === \"string\") return resolve(path);\n\tif (path.protocol !== \"file:\") throw new TypeError(`Facet bundle manifest must be a file URL, not ${path.protocol}`);\n\treturn fileURLToPath(path);\n}\n\nfunction resolveBundleFile(manifestPath: string, file: string, label: string): string {\n\tif (file.length === 0 || isAbsolute(file) || basename(file) !== file || file === \".\" || file === \"..\") {\n\t\tthrow new Error(`Facet bundle ${label} must be a filename relative to its manifest`);\n\t}\n\treturn resolve(dirname(manifestPath), file);\n}\n\nfunction verifySource(source: string, entry: FacetBundleEntry): void {\n\tconst expected = parseIntegrity(entry.integrity);\n\tconst actual = createHash(\"sha256\").update(source, \"utf8\").digest(\"base64\");\n\tif (actual !== expected) throw new Error(`Facet bundle integrity check failed for ${entry.file}`);\n}\n\nfunction parseIntegrity(integrity: string): string {\n\tconst prefix = \"sha256-\";\n\tif (!integrity.startsWith(prefix) || integrity.length === prefix.length) {\n\t\tthrow new Error(\"Facet bundle entry has an invalid SHA-256 integrity value\");\n\t}\n\treturn integrity.slice(prefix.length);\n}\n\nfunction facetsFromModule(imported: unknown, pluginId: string, entryName: string): readonly Facet[] {\n\tif (!isRecord(imported)) throw new Error(`Facet bundle entry ${pluginId}/${entryName} did not export a module`);\n\tconst exported = imported.default;\n\tconst candidates: readonly unknown[] = Array.isArray(exported) ? (exported as readonly unknown[]) : [exported];\n\tif (candidates.length === 0) {\n\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} exported no facets`);\n\t}\n\tconst facets: Facet[] = [];\n\tfor (const candidate of candidates) {\n\t\tif (!isRecord(candidate) || typeof candidate.id !== \"string\" || candidate.id.length === 0) {\n\t\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} has a facet with an invalid ID`);\n\t\t}\n\t\tif (typeof candidate.setup !== \"function\") {\n\t\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} facet ${candidate.id} has no setup function`);\n\t\t}\n\t\tfacets.push(candidate as unknown as Facet);\n\t}\n\tconst ids = facets.map(({ id }) => id);\n\tif (new Set(ids).size !== ids.length) {\n\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} exports duplicate facet IDs`);\n\t}\n\treturn Object.freeze(facets);\n}\n\nfunction validateArtifact(value: unknown): FacetBundleArtifact {\n\tif (\n\t\t!isRecord(value) ||\n\t\tvalue.format !== FACET_BUNDLE_ARTIFACT_FORMAT ||\n\t\tvalue.formatVersion !== FACET_BUNDLE_ARTIFACT_FORMAT_VERSION ||\n\t\ttypeof value.entryName !== \"string\" ||\n\t\tvalue.entryName.length === 0 ||\n\t\ttypeof value.source !== \"string\"\n\t) {\n\t\tthrow new Error(\"Invalid facet bundle artifact\");\n\t}\n\tconst manifest = validateManifest(\n\t\t{\n\t\t\tformat: FACET_BUNDLE_FORMAT,\n\t\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\t\tplugin: value.plugin,\n\t\t\tentries: { [value.entryName]: value.entry },\n\t\t},\n\t\t\"facet bundle artifact\",\n\t);\n\tconst entry = manifest.entries[value.entryName]!;\n\tif (entry.sourceMap === undefined) {\n\t\tif (value.sourceMapContents !== undefined) {\n\t\t\tthrow new Error(\"Facet bundle artifact has source map contents without a source map\");\n\t\t}\n\t} else if (typeof value.sourceMapContents !== \"string\") {\n\t\tthrow new Error(\"Facet bundle artifact is missing its source map contents\");\n\t}\n\tverifySource(value.source, entry);\n\treturn Object.freeze({\n\t\tformat: FACET_BUNDLE_ARTIFACT_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_ARTIFACT_FORMAT_VERSION,\n\t\tplugin: manifest.plugin,\n\t\tentryName: value.entryName,\n\t\tentry,\n\t\tsource: value.source,\n\t\t...(value.sourceMapContents === undefined ? {} : { sourceMapContents: value.sourceMapContents }),\n\t});\n}\n\nasync function materializeArtifact(directory: string, artifact: FacetBundleArtifact): Promise<void> {\n\tconst manifest: FacetBundleManifest = {\n\t\tformat: FACET_BUNDLE_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\tplugin: artifact.plugin,\n\t\tentries: { [artifact.entryName]: artifact.entry },\n\t};\n\tawait Promise.all([\n\t\twriteFile(join(directory, artifact.entry.file), artifact.source, \"utf8\"),\n\t\twriteFile(join(directory, FACET_BUNDLE_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\\n`, \"utf8\"),\n\t\t...(artifact.entry.sourceMap === undefined\n\t\t\t? []\n\t\t\t: [writeFile(join(directory, artifact.entry.sourceMap), artifact.sourceMapContents!, \"utf8\")]),\n\t]);\n}\n\nfunction resolveExternalTarget(specifier: string, resolver?: FacetBundleExternalResolver): string {\n\tconst resolved = resolver?.(specifier);\n\tif (resolved !== undefined) return typeof resolved === \"string\" ? resolved : resolved.href;\n\tconst extension = import.meta.url.endsWith(\".ts\") ? \"ts\" : \"js\";\n\tif (specifier === \"@earendil-works/chord\") return new URL(`../index.${extension}`, import.meta.url).href;\n\tif (specifier === \"@earendil-works/chord/context\") {\n\t\treturn new URL(`../context/index.${extension}`, import.meta.url).href;\n\t}\n\tif (specifier === \"@earendil-works/chord/node\") return new URL(`../node.${extension}`, import.meta.url).href;\n\treturn import.meta.resolve(specifier);\n}\n\nfunction validatePackageSpecifier(specifier: string): void {\n\tconst segments = specifier.split(\"/\");\n\tconst packageParts = specifier.startsWith(\"@\") ? 2 : 1;\n\tif (\n\t\tspecifier.startsWith(\".\") ||\n\t\tspecifier.startsWith(\"/\") ||\n\t\tspecifier.startsWith(\"#\") ||\n\t\tspecifier.includes(\":\") ||\n\t\tspecifier.includes(\"\\\\\") ||\n\t\tsegments.length < packageParts ||\n\t\tsegments.some((part) => part.length === 0 || part === \".\" || part === \"..\")\n\t) {\n\t\tthrow new Error(`Facet bundle artifact has an unsupported external import: ${specifier}`);\n\t}\n}\n\nfunction validateManifest(value: unknown, path: string): FacetBundleManifest {\n\tif (!isRecord(value) || value.format !== FACET_BUNDLE_FORMAT) {\n\t\tthrow new Error(`Invalid facet bundle manifest format in ${path}`);\n\t}\n\tif (value.formatVersion !== FACET_BUNDLE_FORMAT_VERSION) {\n\t\tthrow new Error(`Unsupported facet bundle manifest version in ${path}: ${String(value.formatVersion)}`);\n\t}\n\tif (!isRecord(value.plugin) || typeof value.plugin.id !== \"string\" || value.plugin.id.length === 0) {\n\t\tthrow new Error(`Facet bundle manifest has an invalid plugin identity in ${path}`);\n\t}\n\tif (\n\t\tvalue.plugin.version !== undefined &&\n\t\t(typeof value.plugin.version !== \"string\" || value.plugin.version.length === 0)\n\t) {\n\t\tthrow new Error(`Facet bundle manifest has an invalid plugin version in ${path}`);\n\t}\n\tif (!isRecord(value.entries) || Object.keys(value.entries).length === 0) {\n\t\tthrow new Error(`Facet bundle manifest has no entries in ${path}`);\n\t}\n\tconst entries: Record<string, FacetBundleEntry> = {};\n\tfor (const [name, candidate] of Object.entries(value.entries)) {\n\t\tif (name.length === 0 || !isRecord(candidate)) {\n\t\t\tthrow new Error(`Facet bundle manifest has an invalid entry in ${path}`);\n\t\t}\n\t\tif (typeof candidate.file !== \"string\") throw new Error(`Facet bundle entry ${name} has no file`);\n\t\tresolveBundleFile(path, candidate.file, `entry ${name}`);\n\t\tif (typeof candidate.integrity !== \"string\") throw new Error(`Facet bundle entry ${name} has no integrity`);\n\t\tparseIntegrity(candidate.integrity);\n\t\tif (\n\t\t\t!Array.isArray(candidate.externalImports) ||\n\t\t\tcandidate.externalImports.some((item) => typeof item !== \"string\")\n\t\t) {\n\t\t\tthrow new Error(`Facet bundle entry ${name} has invalid external imports`);\n\t\t}\n\t\tconst externalImports = Object.freeze([...(candidate.externalImports as readonly string[])]);\n\t\tif (new Set(externalImports).size !== externalImports.length) {\n\t\t\tthrow new Error(`Facet bundle entry ${name} has duplicate external imports`);\n\t\t}\n\t\tif (candidate.sourceMap !== undefined) {\n\t\t\tif (typeof candidate.sourceMap !== \"string\")\n\t\t\t\tthrow new Error(`Facet bundle entry ${name} has an invalid source map`);\n\t\t\tresolveBundleFile(path, candidate.sourceMap, `entry ${name} source map`);\n\t\t}\n\t\tentries[name] = Object.freeze({\n\t\t\tfile: candidate.file,\n\t\t\tintegrity: candidate.integrity,\n\t\t\texternalImports,\n\t\t\t...(candidate.sourceMap === undefined ? {} : { sourceMap: candidate.sourceMap }),\n\t\t});\n\t}\n\treturn Object.freeze({\n\t\tformat: FACET_BUNDLE_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\tplugin: Object.freeze({\n\t\t\tid: value.plugin.id,\n\t\t\t...(value.plugin.version === undefined ? {} : { version: value.plugin.version }),\n\t\t}),\n\t\tentries: Object.freeze(entries),\n\t});\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
1
+ {"version":3,"file":"bundle-loader.js","sourceRoot":"","sources":["../../src/node/bundle-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,SAAS,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YAC9B,eAAe;YACf,GAAG,CAAC,SAAS,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,SAAS,CAAC,SAAS,EAAE,CAAC;SAChF,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC;QACpB,MAAM,EAAE,mBAAmB;QAC3B,aAAa,EAAE,2BAA2B;QAC1C,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC;YACrB,EAAE,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE;YACnB,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;SAChF,CAAC;QACF,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC;KAC/B,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { mkdir, mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { createRequire, isBuiltin } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { compileFunction } from \"node:vm\";\nimport type { Facet, FacetLoader, LoadedFacets } from \"../types.ts\";\nimport {\n\tFACET_BUNDLE_ARTIFACT_FORMAT,\n\tFACET_BUNDLE_ARTIFACT_FORMAT_VERSION,\n\tFACET_BUNDLE_FORMAT,\n\tFACET_BUNDLE_FORMAT_VERSION,\n\tFACET_BUNDLE_MANIFEST_FILE,\n\ttype FacetBundleArtifact,\n\ttype FacetBundleEntry,\n\ttype FacetBundleManifest,\n} from \"./manifest.ts\";\n\nexport type FacetBundleExternalResolver = (specifier: string) => string | URL | undefined;\n\nexport interface FacetBundleLoaderOptions {\n\treadonly manifestPath: string | URL;\n\treadonly entry: string;\n\t/** Verify the entry's SHA-256 integrity before evaluating it. Defaults to true. */\n\treadonly verifyIntegrity?: boolean;\n\t/** Resolve host-provided external imports when the bundle is outside the host's package tree. */\n\treadonly resolveExternal?: FacetBundleExternalResolver;\n}\n\nexport interface FacetBundleArtifactLoaderOptions {\n\treadonly artifact: unknown;\n\t/** Resolve host-provided external imports against the receiving application. */\n\treadonly resolveExternal?: FacetBundleExternalResolver;\n\t/** Parent directory for materialized module generations. Defaults to the operating system temp directory. */\n\treadonly temporaryDirectory?: string;\n}\n\ninterface CommonJsModule {\n\texports: unknown;\n}\n\n/** Read and validate a versioned facet bundle manifest. */\nexport async function readFacetBundleManifest(path: string | URL): Promise<FacetBundleManifest> {\n\tconst manifestPath = toFilePath(path);\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(await readFile(manifestPath, \"utf8\"));\n\t} catch (error) {\n\t\tthrow new Error(`Could not read facet bundle manifest ${manifestPath}`, { cause: error });\n\t}\n\treturn validateManifest(parsed, manifestPath);\n}\n\n/** Read and verify one transportable entry from a facet bundle on disk. */\nexport async function readFacetBundleArtifact(options: {\n\treadonly manifestPath: string | URL;\n\treadonly entry: string;\n}): Promise<FacetBundleArtifact> {\n\tif (options.entry.length === 0) throw new TypeError(\"Facet bundle entry name must not be empty\");\n\tconst manifestPath = toFilePath(options.manifestPath);\n\tconst manifest = await readFacetBundleManifest(manifestPath);\n\tconst entry = manifest.entries[options.entry];\n\tif (entry === undefined) throw new Error(`Facet bundle ${manifest.plugin.id} has no entry named ${options.entry}`);\n\tconst modulePath = resolveBundleFile(manifestPath, entry.file, \"entry\");\n\tconst source = await readFile(modulePath, \"utf8\");\n\tverifySource(source, entry);\n\tconst sourceMapContents =\n\t\tentry.sourceMap === undefined\n\t\t\t? undefined\n\t\t\t: await readFile(resolveBundleFile(manifestPath, entry.sourceMap, \"source map\"), \"utf8\");\n\treturn Object.freeze({\n\t\tformat: FACET_BUNDLE_ARTIFACT_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_ARTIFACT_FORMAT_VERSION,\n\t\tplugin: manifest.plugin,\n\t\tentryName: options.entry,\n\t\tentry,\n\t\tsource,\n\t\t...(sourceMapContents === undefined ? {} : { sourceMapContents }),\n\t});\n}\n\n/** Materialize a transported artifact and create a fresh VM-compiled CommonJS generation for each load. */\nexport function createFacetBundleArtifactLoader(options: FacetBundleArtifactLoaderOptions): FacetLoader {\n\tconst artifact = validateArtifact(options.artifact);\n\tconst temporaryParent = resolve(options.temporaryDirectory ?? tmpdir());\n\treturn {\n\t\tasync load(): Promise<LoadedFacets> {\n\t\t\tawait mkdir(temporaryParent, { recursive: true });\n\t\t\tconst directory = await mkdtemp(join(temporaryParent, \"chord-facet-\"));\n\t\t\ttry {\n\t\t\t\tawait materializeArtifact(directory, artifact);\n\t\t\t\tconst loaded = await createFacetBundleLoader({\n\t\t\t\t\tmanifestPath: join(directory, FACET_BUNDLE_MANIFEST_FILE),\n\t\t\t\t\tentry: artifact.entryName,\n\t\t\t\t\tresolveExternal: options.resolveExternal,\n\t\t\t\t}).load();\n\t\t\t\tlet disposed = false;\n\t\t\t\treturn {\n\t\t\t\t\tget facets() {\n\t\t\t\t\t\treturn loaded.facets;\n\t\t\t\t\t},\n\t\t\t\t\tasync dispose() {\n\t\t\t\t\t\tif (disposed) return;\n\t\t\t\t\t\tdisposed = true;\n\t\t\t\t\t\tconst errors: unknown[] = [];\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait loaded.dispose();\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\terrors.push(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait rm(directory, { force: true, recursive: true });\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\terrors.push(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (errors.length === 1) throw errors[0];\n\t\t\t\t\t\tif (errors.length > 1) throw new AggregateError(errors, \"Failed to dispose facet bundle artifact\");\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait rm(directory, { force: true, recursive: true });\n\t\t\t\t} catch (cleanupError) {\n\t\t\t\t\tthrow new AggregateError([error, cleanupError], \"Facet bundle artifact loading and cleanup failed\");\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t};\n}\n\n/** Create a reusable loader for one opaque entry in a facet bundle manifest. */\nexport function createFacetBundleLoader(options: FacetBundleLoaderOptions): FacetLoader {\n\tif (options.entry.length === 0) throw new TypeError(\"Facet bundle entry name must not be empty\");\n\tconst manifestPath = toFilePath(options.manifestPath);\n\treturn {\n\t\tasync load(): Promise<LoadedFacets> {\n\t\t\tconst manifest = await readFacetBundleManifest(manifestPath);\n\t\t\tconst entry = manifest.entries[options.entry];\n\t\t\tif (entry === undefined) {\n\t\t\t\tthrow new Error(`Facet bundle ${manifest.plugin.id} has no entry named ${options.entry}`);\n\t\t\t}\n\t\t\tconst modulePath = resolveBundleFile(manifestPath, entry.file, \"entry\");\n\t\t\ttry {\n\t\t\t\tconst source = await readFile(modulePath, \"utf8\");\n\t\t\t\tif (options.verifyIntegrity !== false) verifySource(source, entry);\n\t\t\t\tconst exported = executeCommonJsModule(source, modulePath, entry.externalImports, options.resolveExternal);\n\t\t\t\tlet facets = facetsFromModule(exported, manifest.plugin.id, options.entry);\n\t\t\t\tlet disposed = false;\n\t\t\t\treturn {\n\t\t\t\t\tget facets() {\n\t\t\t\t\t\treturn facets;\n\t\t\t\t\t},\n\t\t\t\t\tasync dispose() {\n\t\t\t\t\t\tif (disposed) return;\n\t\t\t\t\t\tdisposed = true;\n\t\t\t\t\t\tfacets = Object.freeze([]);\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\tconst detail = error instanceof Error ? `: ${error.message}` : \"\";\n\t\t\t\tthrow new Error(`Could not load facet bundle entry ${manifest.plugin.id}/${options.entry}${detail}`, {\n\t\t\t\t\tcause: error,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t};\n}\n\nfunction executeCommonJsModule(\n\tsource: string,\n\tmodulePath: string,\n\texternalImports: readonly string[],\n\tresolver?: FacetBundleExternalResolver,\n): unknown {\n\tconst requireFromModule = createRequire(modulePath);\n\tconst externalTargets = new Map<string, string>();\n\tfor (const specifier of externalImports) {\n\t\tif (!isBuiltin(specifier)) validatePackageSpecifier(specifier);\n\t\texternalTargets.set(specifier, toRequireSpecifier(resolveExternalTarget(specifier, resolver)));\n\t}\n\tconst targetFor = (specifier: string): string => {\n\t\tconst target = externalTargets.get(specifier);\n\t\tif (target === undefined) throw new Error(`Facet bundle required undeclared external import: ${specifier}`);\n\t\treturn target;\n\t};\n\tconst requireExternal = Object.assign((specifier: string): unknown => requireFromModule(targetFor(specifier)), {\n\t\tresolve: (specifier: string): string => requireFromModule.resolve(targetFor(specifier)),\n\t});\n\tconst commonJsModule: CommonJsModule = { exports: Object.create(null) };\n\tconst compiled = compileFunction(source, [\"exports\", \"require\", \"module\", \"__filename\", \"__dirname\"], {\n\t\tfilename: modulePath,\n\t});\n\tReflect.apply(compiled, commonJsModule.exports, [\n\t\tcommonJsModule.exports,\n\t\trequireExternal,\n\t\tcommonJsModule,\n\t\tmodulePath,\n\t\tdirname(modulePath),\n\t]);\n\treturn commonJsModule.exports;\n}\n\nfunction toRequireSpecifier(target: string): string {\n\tif (isAbsolute(target) || isBuiltin(target)) return target;\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(target);\n\t} catch {\n\t\treturn target;\n\t}\n\tif (url.protocol === \"file:\") return fileURLToPath(url);\n\tif (url.protocol === \"node:\") return url.href;\n\tthrow new Error(`Facet bundle external target must be a file, package, or built-in module: ${target}`);\n}\n\nfunction toFilePath(path: string | URL): string {\n\tif (typeof path === \"string\") return resolve(path);\n\tif (path.protocol !== \"file:\") throw new TypeError(`Facet bundle manifest must be a file URL, not ${path.protocol}`);\n\treturn fileURLToPath(path);\n}\n\nfunction resolveBundleFile(manifestPath: string, file: string, label: string): string {\n\tif (file.length === 0 || isAbsolute(file) || basename(file) !== file || file === \".\" || file === \"..\") {\n\t\tthrow new Error(`Facet bundle ${label} must be a filename relative to its manifest`);\n\t}\n\treturn resolve(dirname(manifestPath), file);\n}\n\nfunction verifySource(source: string, entry: FacetBundleEntry): void {\n\tconst expected = parseIntegrity(entry.integrity);\n\tconst actual = createHash(\"sha256\").update(source, \"utf8\").digest(\"base64\");\n\tif (actual !== expected) throw new Error(`Facet bundle integrity check failed for ${entry.file}`);\n}\n\nfunction parseIntegrity(integrity: string): string {\n\tconst prefix = \"sha256-\";\n\tif (!integrity.startsWith(prefix) || integrity.length === prefix.length) {\n\t\tthrow new Error(\"Facet bundle entry has an invalid SHA-256 integrity value\");\n\t}\n\treturn integrity.slice(prefix.length);\n}\n\nfunction facetsFromModule(imported: unknown, pluginId: string, entryName: string): readonly Facet[] {\n\tif (!isRecord(imported)) throw new Error(`Facet bundle entry ${pluginId}/${entryName} did not export a module`);\n\tconst exported = imported.default;\n\tconst candidates: readonly unknown[] = Array.isArray(exported) ? (exported as readonly unknown[]) : [exported];\n\tif (candidates.length === 0) {\n\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} exported no facets`);\n\t}\n\tconst facets: Facet[] = [];\n\tfor (const candidate of candidates) {\n\t\tif (!isRecord(candidate) || typeof candidate.id !== \"string\" || candidate.id.length === 0) {\n\t\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} has a facet with an invalid ID`);\n\t\t}\n\t\tif (typeof candidate.setup !== \"function\") {\n\t\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} facet ${candidate.id} has no setup function`);\n\t\t}\n\t\tfacets.push(candidate as unknown as Facet);\n\t}\n\tconst ids = facets.map(({ id }) => id);\n\tif (new Set(ids).size !== ids.length) {\n\t\tthrow new Error(`Facet bundle entry ${pluginId}/${entryName} exports duplicate facet IDs`);\n\t}\n\treturn Object.freeze(facets);\n}\n\nfunction validateArtifact(value: unknown): FacetBundleArtifact {\n\tif (\n\t\t!isRecord(value) ||\n\t\tvalue.format !== FACET_BUNDLE_ARTIFACT_FORMAT ||\n\t\tvalue.formatVersion !== FACET_BUNDLE_ARTIFACT_FORMAT_VERSION ||\n\t\ttypeof value.entryName !== \"string\" ||\n\t\tvalue.entryName.length === 0 ||\n\t\ttypeof value.source !== \"string\"\n\t) {\n\t\tthrow new Error(\"Invalid facet bundle artifact\");\n\t}\n\tconst manifest = validateManifest(\n\t\t{\n\t\t\tformat: FACET_BUNDLE_FORMAT,\n\t\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\t\tplugin: value.plugin,\n\t\t\tentries: { [value.entryName]: value.entry },\n\t\t},\n\t\t\"facet bundle artifact\",\n\t);\n\tconst entry = manifest.entries[value.entryName]!;\n\tif (entry.sourceMap === undefined) {\n\t\tif (value.sourceMapContents !== undefined) {\n\t\t\tthrow new Error(\"Facet bundle artifact has source map contents without a source map\");\n\t\t}\n\t} else if (typeof value.sourceMapContents !== \"string\") {\n\t\tthrow new Error(\"Facet bundle artifact is missing its source map contents\");\n\t}\n\tverifySource(value.source, entry);\n\treturn Object.freeze({\n\t\tformat: FACET_BUNDLE_ARTIFACT_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_ARTIFACT_FORMAT_VERSION,\n\t\tplugin: manifest.plugin,\n\t\tentryName: value.entryName,\n\t\tentry,\n\t\tsource: value.source,\n\t\t...(value.sourceMapContents === undefined ? {} : { sourceMapContents: value.sourceMapContents }),\n\t});\n}\n\nasync function materializeArtifact(directory: string, artifact: FacetBundleArtifact): Promise<void> {\n\tconst manifest: FacetBundleManifest = {\n\t\tformat: FACET_BUNDLE_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\tplugin: artifact.plugin,\n\t\tentries: { [artifact.entryName]: artifact.entry },\n\t};\n\tawait Promise.all([\n\t\twriteFile(join(directory, artifact.entry.file), artifact.source, \"utf8\"),\n\t\twriteFile(join(directory, FACET_BUNDLE_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\\n`, \"utf8\"),\n\t\t...(artifact.entry.sourceMap === undefined\n\t\t\t? []\n\t\t\t: [writeFile(join(directory, artifact.entry.sourceMap), artifact.sourceMapContents!, \"utf8\")]),\n\t]);\n}\n\nfunction resolveExternalTarget(specifier: string, resolver?: FacetBundleExternalResolver): string {\n\tconst resolved = resolver?.(specifier);\n\tif (resolved !== undefined) return typeof resolved === \"string\" ? resolved : resolved.href;\n\tconst extension = import.meta.url.endsWith(\".ts\") ? \"ts\" : \"js\";\n\tif (specifier === \"@earendil-works/chord\") return new URL(`../index.${extension}`, import.meta.url).href;\n\tif (specifier === \"@earendil-works/chord/context\") {\n\t\treturn new URL(`../context/index.${extension}`, import.meta.url).href;\n\t}\n\tif (specifier === \"@earendil-works/chord/node\") return new URL(`../node.${extension}`, import.meta.url).href;\n\treturn import.meta.resolve(specifier);\n}\n\nfunction validatePackageSpecifier(specifier: string): void {\n\tconst segments = specifier.split(\"/\");\n\tconst packageParts = specifier.startsWith(\"@\") ? 2 : 1;\n\tif (\n\t\tspecifier.startsWith(\".\") ||\n\t\tspecifier.startsWith(\"/\") ||\n\t\tspecifier.startsWith(\"#\") ||\n\t\tspecifier.includes(\":\") ||\n\t\tspecifier.includes(\"\\\\\") ||\n\t\tsegments.length < packageParts ||\n\t\tsegments.some((part) => part.length === 0 || part === \".\" || part === \"..\")\n\t) {\n\t\tthrow new Error(`Facet bundle artifact has an unsupported external import: ${specifier}`);\n\t}\n}\n\nfunction validateManifest(value: unknown, path: string): FacetBundleManifest {\n\tif (!isRecord(value) || value.format !== FACET_BUNDLE_FORMAT) {\n\t\tthrow new Error(`Invalid facet bundle manifest format in ${path}`);\n\t}\n\tif (value.formatVersion !== FACET_BUNDLE_FORMAT_VERSION) {\n\t\tthrow new Error(`Unsupported facet bundle manifest version in ${path}: ${String(value.formatVersion)}`);\n\t}\n\tif (!isRecord(value.plugin) || typeof value.plugin.id !== \"string\" || value.plugin.id.length === 0) {\n\t\tthrow new Error(`Facet bundle manifest has an invalid plugin identity in ${path}`);\n\t}\n\tif (\n\t\tvalue.plugin.version !== undefined &&\n\t\t(typeof value.plugin.version !== \"string\" || value.plugin.version.length === 0)\n\t) {\n\t\tthrow new Error(`Facet bundle manifest has an invalid plugin version in ${path}`);\n\t}\n\tif (!isRecord(value.entries) || Object.keys(value.entries).length === 0) {\n\t\tthrow new Error(`Facet bundle manifest has no entries in ${path}`);\n\t}\n\tconst entries: Record<string, FacetBundleEntry> = {};\n\tfor (const [name, candidate] of Object.entries(value.entries)) {\n\t\tif (name.length === 0 || !isRecord(candidate)) {\n\t\t\tthrow new Error(`Facet bundle manifest has an invalid entry in ${path}`);\n\t\t}\n\t\tif (typeof candidate.file !== \"string\") throw new Error(`Facet bundle entry ${name} has no file`);\n\t\tresolveBundleFile(path, candidate.file, `entry ${name}`);\n\t\tif (typeof candidate.integrity !== \"string\") throw new Error(`Facet bundle entry ${name} has no integrity`);\n\t\tparseIntegrity(candidate.integrity);\n\t\tif (\n\t\t\t!Array.isArray(candidate.externalImports) ||\n\t\t\tcandidate.externalImports.some((item) => typeof item !== \"string\")\n\t\t) {\n\t\t\tthrow new Error(`Facet bundle entry ${name} has invalid external imports`);\n\t\t}\n\t\tconst externalImports = Object.freeze([...(candidate.externalImports as readonly string[])]);\n\t\tif (new Set(externalImports).size !== externalImports.length) {\n\t\t\tthrow new Error(`Facet bundle entry ${name} has duplicate external imports`);\n\t\t}\n\t\tif (candidate.sourceMap !== undefined) {\n\t\t\tif (typeof candidate.sourceMap !== \"string\")\n\t\t\t\tthrow new Error(`Facet bundle entry ${name} has an invalid source map`);\n\t\t\tresolveBundleFile(path, candidate.sourceMap, `entry ${name} source map`);\n\t\t}\n\t\tentries[name] = Object.freeze({\n\t\t\tfile: candidate.file,\n\t\t\tintegrity: candidate.integrity,\n\t\t\texternalImports,\n\t\t\t...(candidate.sourceMap === undefined ? {} : { sourceMap: candidate.sourceMap }),\n\t\t});\n\t}\n\treturn Object.freeze({\n\t\tformat: FACET_BUNDLE_FORMAT,\n\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\tplugin: Object.freeze({\n\t\t\tid: value.plugin.id,\n\t\t\t...(value.plugin.version === undefined ? {} : { version: value.plugin.version }),\n\t\t}),\n\t\tentries: Object.freeze(entries),\n\t});\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.d.ts","sourceRoot":"","sources":["../../src/node/bundle.ts"],"names":[],"mappings":"AAIA,OAAO,EAKN,KAAK,mBAAmB,EACxB,MAAM,eAAe,CAAC;AAEvB,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,SAAS,GAAG,SAAS,CAAC;AAEjE,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,MAAM,EAAE;QAChB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;QACpB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;KAC1B,CAAC;IACF,+FAA+F;IAC/F,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACnD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,4FAA4F;IAC5F,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAC7B,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACnD,QAAQ,CAAC,QAAQ,CAAC,EAAE,mBAAmB,CAAC;IACxC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;CAC7C;AAED,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,CAAC;IACvC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;CAC9B;AAED,0FAA0F;AAC1F,wBAAsB,YAAY,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAwC5F","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, extname, join, relative, resolve, sep } from \"node:path\";\nimport { type BuildOptions, build, type Message } from \"esbuild\";\nimport {\n\tFACET_BUNDLE_FORMAT,\n\tFACET_BUNDLE_FORMAT_VERSION,\n\tFACET_BUNDLE_MANIFEST_FILE,\n\ttype FacetBundleEntry,\n\ttype FacetBundleManifest,\n} from \"./manifest.ts\";\n\nexport type FacetBundlePlatform = \"node\" | \"browser\" | \"neutral\";\n\nexport interface BundleFacetsOptions {\n\treadonly plugin: {\n\t\treadonly id: string;\n\t\treadonly version?: string;\n\t};\n\t/** Opaque application-selected entry names mapped to TypeScript or JavaScript source files. */\n\treadonly entries: Readonly<Record<string, string>>;\n\treadonly outdir: string;\n\treadonly workingDirectory?: string;\n\t/** Additional package imports intentionally left for the loading application to resolve. */\n\treadonly external?: readonly string[];\n\treadonly sourceMap?: boolean;\n\treadonly minify?: boolean;\n\treadonly define?: Readonly<Record<string, string>>;\n\treadonly platform?: FacetBundlePlatform;\n\treadonly target?: string | readonly string[];\n}\n\nexport interface BundleFacetsResult {\n\treadonly manifest: FacetBundleManifest;\n\treadonly manifestPath: string;\n}\n\n/** Bundle each opaque facet entry into an independent content-addressed CommonJS file. */\nexport async function bundleFacets(options: BundleFacetsOptions): Promise<BundleFacetsResult> {\n\tvalidateOptions(options);\n\tconst workingDirectory = resolve(options.workingDirectory ?? process.cwd());\n\tconst outputDirectory = resolve(workingDirectory, options.outdir);\n\tconst outputParent = dirname(outputDirectory);\n\tawait mkdir(outputParent, { recursive: true });\n\tconst temporaryDirectory = join(outputParent, `.${basename(outputDirectory)}.tmp-${randomUUID()}`);\n\tawait mkdir(temporaryDirectory);\n\ttry {\n\t\tconst entries: Record<string, FacetBundleEntry> = {};\n\t\tfor (const [entryName, source] of Object.entries(options.entries).sort(([left], [right]) =>\n\t\t\tleft.localeCompare(right),\n\t\t)) {\n\t\t\tentries[entryName] = await bundleEntry({\n\t\t\t\tentryName,\n\t\t\t\tsource: resolve(workingDirectory, source),\n\t\t\t\ttemporaryDirectory,\n\t\t\t\tworkingDirectory,\n\t\t\t\toptions,\n\t\t\t});\n\t\t}\n\t\tconst manifest: FacetBundleManifest = Object.freeze({\n\t\t\tformat: FACET_BUNDLE_FORMAT,\n\t\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\t\tplugin: Object.freeze({\n\t\t\t\tid: options.plugin.id,\n\t\t\t\t...(options.plugin.version === undefined ? {} : { version: options.plugin.version }),\n\t\t\t}),\n\t\t\tentries: Object.freeze(entries),\n\t\t});\n\t\tawait writeFile(join(temporaryDirectory, FACET_BUNDLE_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\\n`);\n\t\tawait replaceDirectory(temporaryDirectory, outputDirectory);\n\t\treturn Object.freeze({\n\t\t\tmanifest,\n\t\t\tmanifestPath: join(outputDirectory, FACET_BUNDLE_MANIFEST_FILE),\n\t\t});\n\t} catch (error) {\n\t\tawait rm(temporaryDirectory, { force: true, recursive: true });\n\t\tthrow error;\n\t}\n}\n\nasync function bundleEntry(input: {\n\treadonly entryName: string;\n\treadonly source: string;\n\treadonly temporaryDirectory: string;\n\treadonly workingDirectory: string;\n\treadonly options: BundleFacetsOptions;\n}): Promise<FacetBundleEntry> {\n\tconst entryPrefix = `facet-${shortHash(input.entryName)}`;\n\tconst requestedPlatform = input.options.platform ?? \"node\";\n\tconst buildOptions: BuildOptions = {\n\t\tabsWorkingDir: input.workingDirectory,\n\t\tbanner: { js: '\"use strict\";' },\n\t\tbundle: true,\n\t\tdefine: input.options.define,\n\t\tentryNames: `${entryPrefix}-[hash]`,\n\t\tentryPoints: [input.source],\n\t\texternal: [...new Set([\"@earendil-works/chord\", \"@earendil-works/chord/*\", ...(input.options.external ?? [])])],\n\t\tformat: \"cjs\",\n\t\tlegalComments: \"none\",\n\t\tlogLevel: \"silent\",\n\t\tmetafile: true,\n\t\tminify: input.options.minify ?? false,\n\t\toutdir: input.temporaryDirectory,\n\t\toutExtension: { \".js\": \".cjs\" },\n\t\tplatform: requestedPlatform,\n\t\tsourcemap: input.options.sourceMap === true ? \"external\" : false,\n\t\tsupported: { \"dynamic-import\": false },\n\t\ttarget:\n\t\t\tinput.options.target === undefined\n\t\t\t\t? requestedPlatform === \"node\"\n\t\t\t\t\t? \"node22.19\"\n\t\t\t\t\t: \"es2022\"\n\t\t\t\t: typeof input.options.target === \"string\"\n\t\t\t\t\t? input.options.target\n\t\t\t\t\t: [...input.options.target],\n\t\twrite: true,\n\t};\n\tlet result: Awaited<ReturnType<typeof build>>;\n\ttry {\n\t\tresult = await build(buildOptions);\n\t} catch (error) {\n\t\tconst diagnostics = esbuildMessages(error);\n\t\tconst detail = diagnostics.length === 0 ? \"\" : `\\n${diagnostics.join(\"\\n\")}`;\n\t\tthrow new Error(`Could not bundle facet entry ${input.entryName}${detail}`, { cause: error });\n\t}\n\tconst metafile = result.metafile;\n\tif (metafile === undefined) throw new Error(`Facet entry ${input.entryName} produced no build metadata`);\n\tconst outputs = Object.entries(metafile.outputs).filter(\n\t\t([path, output]) => output.entryPoint !== undefined && extname(path) === \".cjs\",\n\t);\n\tif (outputs.length !== 1)\n\t\tthrow new Error(`Facet entry ${input.entryName} did not produce exactly one JavaScript file`);\n\tconst [outputPath, metadata] = outputs[0]!;\n\tconst absoluteOutputPath = resolve(input.workingDirectory, outputPath);\n\tconst file = relative(input.temporaryDirectory, absoluteOutputPath);\n\tif (file.length === 0 || file.startsWith(`..${sep}`) || basename(file) !== file) {\n\t\tthrow new Error(`Facet entry ${input.entryName} produced an invalid output path`);\n\t}\n\tconst sourceMap = input.options.sourceMap === true ? `${file}.map` : undefined;\n\tconst allowedOutputs = new Set([absoluteOutputPath]);\n\tif (sourceMap !== undefined) allowedOutputs.add(join(input.temporaryDirectory, sourceMap));\n\tconst unexpectedOutputs = Object.keys(metafile.outputs)\n\t\t.map((path) => resolve(input.workingDirectory, path))\n\t\t.filter((path) => !allowedOutputs.has(path));\n\tif (unexpectedOutputs.length > 0) {\n\t\tthrow new Error(`Facet entry ${input.entryName} produced files other than its JavaScript bundle and source map`);\n\t}\n\tconst contents = await readFile(absoluteOutputPath);\n\tif (sourceMap !== undefined) await stat(join(input.temporaryDirectory, sourceMap));\n\treturn Object.freeze({\n\t\tfile,\n\t\tintegrity: `sha256-${createHash(\"sha256\").update(contents).digest(\"base64\")}`,\n\t\texternalImports: Object.freeze(\n\t\t\t[...new Set(metadata.imports.filter(({ external }) => external).map(({ path }) => path))].sort(),\n\t\t),\n\t\t...(sourceMap === undefined ? {} : { sourceMap }),\n\t});\n}\n\nfunction validateOptions(options: BundleFacetsOptions): void {\n\tif (options.plugin.id.length === 0) throw new TypeError(\"Facet bundle plugin ID must not be empty\");\n\tif (options.plugin.version !== undefined && options.plugin.version.length === 0) {\n\t\tthrow new TypeError(\"Facet bundle plugin version must not be empty\");\n\t}\n\tconst entries = Object.entries(options.entries);\n\tif (entries.length === 0) throw new TypeError(\"Facet bundle must contain at least one entry\");\n\tfor (const [name, source] of entries) {\n\t\tif (name.length === 0) throw new TypeError(\"Facet bundle entry name must not be empty\");\n\t\tif (source.length === 0) throw new TypeError(`Facet bundle entry ${name} must have a source path`);\n\t}\n\tfor (const external of options.external ?? []) {\n\t\tif (external.length === 0) throw new TypeError(\"Facet bundle external import must not be empty\");\n\t}\n}\n\nasync function replaceDirectory(temporaryDirectory: string, outputDirectory: string): Promise<void> {\n\tconst backupDirectory = `${outputDirectory}.old-${randomUUID()}`;\n\tlet movedExisting = false;\n\ttry {\n\t\tawait rename(outputDirectory, backupDirectory);\n\t\tmovedExisting = true;\n\t} catch (error) {\n\t\tif (!isMissingPath(error)) throw error;\n\t}\n\ttry {\n\t\tawait rename(temporaryDirectory, outputDirectory);\n\t} catch (error) {\n\t\tif (movedExisting) await rename(backupDirectory, outputDirectory);\n\t\tthrow error;\n\t}\n\tif (movedExisting) await rm(backupDirectory, { force: true, recursive: true });\n}\n\nfunction shortHash(value: string): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\").slice(0, 12);\n}\n\nfunction esbuildMessages(error: unknown): string[] {\n\tif (!isRecord(error) || !Array.isArray(error.errors)) return [];\n\treturn (error.errors as readonly unknown[]).flatMap((candidate) =>\n\t\tisEsbuildMessage(candidate) ? [formatEsbuildMessage(candidate)] : [],\n\t);\n}\n\nfunction formatEsbuildMessage(message: Message): string {\n\tconst location = message.location;\n\treturn location === null\n\t\t? message.text\n\t\t: `${location.file}:${location.line}:${location.column + 1}: ${message.text}`;\n}\n\nfunction isEsbuildMessage(value: unknown): value is Message {\n\treturn isRecord(value) && typeof value.text === \"string\" && (value.location === null || isRecord(value.location));\n}\n\nfunction isMissingPath(error: unknown): boolean {\n\treturn isRecord(error) && error.code === \"ENOENT\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
1
+ {"version":3,"file":"bundle.d.ts","sourceRoot":"","sources":["../../src/node/bundle.ts"],"names":[],"mappings":"AAIA,OAAO,EAKN,KAAK,mBAAmB,EACxB,MAAM,eAAe,CAAC;AAEvB,MAAM,MAAM,mBAAmB,GAAG,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AAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, extname, join, relative, resolve, sep } from \"node:path\";\nimport { type BuildOptions, build, type Message } from \"esbuild\";\nimport {\n\tFACET_BUNDLE_FORMAT,\n\tFACET_BUNDLE_FORMAT_VERSION,\n\tFACET_BUNDLE_MANIFEST_FILE,\n\ttype FacetBundleEntry,\n\ttype FacetBundleManifest,\n} from \"./manifest.ts\";\n\nexport type FacetBundlePlatform = \"node\" | \"browser\" | \"neutral\";\n\nexport interface BundleFacetsOptions {\n\treadonly plugin: {\n\t\treadonly id: string;\n\t\treadonly version?: string;\n\t};\n\t/** Opaque application-selected entry names mapped to TypeScript or JavaScript source files. */\n\treadonly entries: Readonly<Record<string, string>>;\n\treadonly outdir: string;\n\treadonly workingDirectory?: string;\n\t/** Additional package imports intentionally left for the loading application to resolve. */\n\treadonly external?: readonly string[];\n\treadonly sourceMap?: boolean;\n\treadonly minify?: boolean;\n\treadonly define?: Readonly<Record<string, string>>;\n\treadonly platform?: FacetBundlePlatform;\n\treadonly target?: string | readonly string[];\n}\n\nexport interface BundleFacetsResult {\n\treadonly manifest: FacetBundleManifest;\n\treadonly manifestPath: string;\n}\n\n/** Bundle each opaque facet entry into an independent content-addressed CommonJS file. */\nexport async function bundleFacets(options: BundleFacetsOptions): Promise<BundleFacetsResult> {\n\tvalidateOptions(options);\n\tconst workingDirectory = resolve(options.workingDirectory ?? process.cwd());\n\tconst outputDirectory = resolve(workingDirectory, options.outdir);\n\tconst outputParent = dirname(outputDirectory);\n\tawait mkdir(outputParent, { recursive: true });\n\tconst temporaryDirectory = join(outputParent, `.${basename(outputDirectory)}.tmp-${randomUUID()}`);\n\tawait mkdir(temporaryDirectory);\n\ttry {\n\t\tconst entries: Record<string, FacetBundleEntry> = {};\n\t\tfor (const [entryName, source] of Object.entries(options.entries).sort(([left], [right]) =>\n\t\t\tleft.localeCompare(right),\n\t\t)) {\n\t\t\tentries[entryName] = await bundleEntry({\n\t\t\t\tentryName,\n\t\t\t\tsource: resolve(workingDirectory, source),\n\t\t\t\ttemporaryDirectory,\n\t\t\t\tworkingDirectory,\n\t\t\t\toptions,\n\t\t\t});\n\t\t}\n\t\tconst manifest: FacetBundleManifest = Object.freeze({\n\t\t\tformat: FACET_BUNDLE_FORMAT,\n\t\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\t\tplugin: Object.freeze({\n\t\t\t\tid: options.plugin.id,\n\t\t\t\t...(options.plugin.version === undefined ? {} : { version: options.plugin.version }),\n\t\t\t}),\n\t\t\tentries: Object.freeze(entries),\n\t\t});\n\t\tawait writeFile(join(temporaryDirectory, FACET_BUNDLE_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\\n`);\n\t\tawait replaceDirectory(temporaryDirectory, outputDirectory);\n\t\treturn Object.freeze({\n\t\t\tmanifest,\n\t\t\tmanifestPath: join(outputDirectory, FACET_BUNDLE_MANIFEST_FILE),\n\t\t});\n\t} catch (error) {\n\t\tawait rm(temporaryDirectory, { force: true, recursive: true });\n\t\tthrow error;\n\t}\n}\n\nasync function bundleEntry(input: {\n\treadonly entryName: string;\n\treadonly source: string;\n\treadonly temporaryDirectory: string;\n\treadonly workingDirectory: string;\n\treadonly options: BundleFacetsOptions;\n}): Promise<FacetBundleEntry> {\n\tconst entryPrefix = `facet-${shortHash(input.entryName)}`;\n\tconst requestedPlatform = input.options.platform ?? \"node\";\n\tconst buildOptions: BuildOptions = {\n\t\tabsWorkingDir: input.workingDirectory,\n\t\tbanner: { js: '\"use strict\";' },\n\t\tbundle: true,\n\t\tdefine: input.options.define,\n\t\tentryNames: `${entryPrefix}-[hash]`,\n\t\tentryPoints: [input.source],\n\t\texternal: [...new Set([\"@earendil-works/chord\", \"@earendil-works/chord/*\", ...(input.options.external ?? [])])],\n\t\tformat: \"cjs\",\n\t\tlegalComments: \"none\",\n\t\tlogLevel: \"silent\",\n\t\tmetafile: true,\n\t\tminify: input.options.minify ?? false,\n\t\toutdir: input.temporaryDirectory,\n\t\toutExtension: { \".js\": \".cjs\" },\n\t\tplatform: requestedPlatform,\n\t\tsourcemap: input.options.sourceMap === true ? \"external\" : false,\n\t\tsupported: { \"dynamic-import\": false },\n\t\ttarget:\n\t\t\tinput.options.target === undefined\n\t\t\t\t? requestedPlatform === \"node\"\n\t\t\t\t\t? \"node22.19\"\n\t\t\t\t\t: \"es2022\"\n\t\t\t\t: typeof input.options.target === \"string\"\n\t\t\t\t\t? input.options.target\n\t\t\t\t\t: [...input.options.target],\n\t\twrite: true,\n\t};\n\tlet result: Awaited<ReturnType<typeof build>>;\n\ttry {\n\t\tresult = await build(buildOptions);\n\t} catch (error) {\n\t\tconst diagnostics = esbuildMessages(error);\n\t\tconst detail = diagnostics.length === 0 ? \"\" : `\\n${diagnostics.join(\"\\n\")}`;\n\t\tthrow new Error(`Could not bundle facet entry ${input.entryName}${detail}`, { cause: error });\n\t}\n\tconst metafile = result.metafile;\n\tif (metafile === undefined) throw new Error(`Facet entry ${input.entryName} produced no build metadata`);\n\tconst outputs = Object.entries(metafile.outputs).filter(\n\t\t([path, output]) => output.entryPoint !== undefined && extname(path) === \".cjs\",\n\t);\n\tif (outputs.length !== 1)\n\t\tthrow new Error(`Facet entry ${input.entryName} did not produce exactly one JavaScript file`);\n\tconst [outputPath, metadata] = outputs[0]!;\n\tconst absoluteOutputPath = resolve(input.workingDirectory, outputPath);\n\tconst file = relative(input.temporaryDirectory, absoluteOutputPath);\n\tif (file.length === 0 || file.startsWith(`..${sep}`) || basename(file) !== file) {\n\t\tthrow new Error(`Facet entry ${input.entryName} produced an invalid output path`);\n\t}\n\tconst sourceMap = input.options.sourceMap === true ? `${file}.map` : undefined;\n\tconst allowedOutputs = new Set([absoluteOutputPath]);\n\tif (sourceMap !== undefined) allowedOutputs.add(join(input.temporaryDirectory, sourceMap));\n\tconst unexpectedOutputs = Object.keys(metafile.outputs)\n\t\t.map((path) => resolve(input.workingDirectory, path))\n\t\t.filter((path) => !allowedOutputs.has(path));\n\tif (unexpectedOutputs.length > 0) {\n\t\tthrow new Error(`Facet entry ${input.entryName} produced files other than its JavaScript bundle and source map`);\n\t}\n\tconst contents = await readFile(absoluteOutputPath);\n\tif (sourceMap !== undefined) await stat(join(input.temporaryDirectory, sourceMap));\n\treturn Object.freeze({\n\t\tfile,\n\t\tintegrity: `sha256-${createHash(\"sha256\").update(contents).digest(\"base64\")}`,\n\t\texternalImports: Object.freeze(\n\t\t\t[...new Set(metadata.imports.filter(({ external }) => external).map(({ path }) => path))].sort(),\n\t\t),\n\t\t...(sourceMap === undefined ? {} : { sourceMap }),\n\t});\n}\n\nfunction validateOptions(options: BundleFacetsOptions): void {\n\tif (options.plugin.id.length === 0) throw new TypeError(\"Facet bundle plugin ID must not be empty\");\n\tif (options.plugin.version !== undefined && options.plugin.version.length === 0) {\n\t\tthrow new TypeError(\"Facet bundle plugin version must not be empty\");\n\t}\n\tconst entries = Object.entries(options.entries);\n\tif (entries.length === 0) throw new TypeError(\"Facet bundle must contain at least one entry\");\n\tfor (const [name, source] of entries) {\n\t\tif (name.length === 0) throw new TypeError(\"Facet bundle entry name must not be empty\");\n\t\tif (source.length === 0) throw new TypeError(`Facet bundle entry ${name} must have a source path`);\n\t}\n\tfor (const external of options.external ?? []) {\n\t\tif (external.length === 0) throw new TypeError(\"Facet bundle external import must not be empty\");\n\t}\n}\n\nasync function replaceDirectory(temporaryDirectory: string, outputDirectory: string): Promise<void> {\n\tconst backupDirectory = `${outputDirectory}.old-${randomUUID()}`;\n\tlet movedExisting = false;\n\ttry {\n\t\tawait rename(outputDirectory, backupDirectory);\n\t\tmovedExisting = true;\n\t} catch (error) {\n\t\tif (!isMissingPath(error)) throw error;\n\t}\n\ttry {\n\t\tawait rename(temporaryDirectory, outputDirectory);\n\t} catch (error) {\n\t\tif (movedExisting) await rename(backupDirectory, outputDirectory);\n\t\tthrow error;\n\t}\n\tif (movedExisting) await rm(backupDirectory, { force: true, recursive: true });\n}\n\nfunction shortHash(value: string): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\").slice(0, 12);\n}\n\nfunction esbuildMessages(error: unknown): string[] {\n\tif (!isRecord(error) || !Array.isArray(error.errors)) return [];\n\treturn (error.errors as readonly unknown[]).flatMap((candidate) =>\n\t\tisEsbuildMessage(candidate) ? [formatEsbuildMessage(candidate)] : [],\n\t);\n}\n\nfunction formatEsbuildMessage(message: Message): string {\n\tconst location = message.location;\n\treturn location === null\n\t\t? message.text\n\t\t: `${location.file}:${location.line}:${location.column + 1}: ${message.text}`;\n}\n\nfunction isEsbuildMessage(value: unknown): value is Message {\n\treturn isRecord(value) && typeof value.text === \"string\" && (value.location === null || isRecord(value.location));\n}\n\nfunction isMissingPath(error: unknown): boolean {\n\treturn isRecord(error) && error.code === \"ENOENT\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
1
+ {"version":3,"file":"bundle.js","sourceRoot":"","sources":["../../src/node/bundle.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAChF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACrF,OAAO,EAAqB,KAAK,EAAgB,MAAM,SAAS,CAAC;AACjE,OAAO,EACN,mBAAmB,EACnB,2BAA2B,EAC3B,0BAA0B,GAG1B,MAAM,eAAe,CAAC;AA2BvB,0FAA0F;AAC1F,MAAM,CAAC,KAAK,UAAU,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AC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CACpE,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB,CAAC,OAAgB;IAC7C,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;IAClC,OAAO,QAAQ,KAAK,IAAI;QACvB,CAAC,CAAC,OAAO,CAAC,IAAI;QACd,CAAC,CAAC,GAAG,QAAQ,CAAC,IAAI,IAAI,QAAQ,CAAC,IAAI,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,KAAK,OAAO,CAAC,IAAI,EAAE,CAAC;AAChF,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAc;IACvC,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,QAAQ,KAAK,IAAI,IAAI,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC;AACnH,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACpC,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC;AACnD,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, extname, join, relative, resolve, sep } from \"node:path\";\nimport { type BuildOptions, build, type Message } from \"esbuild\";\nimport {\n\tFACET_BUNDLE_FORMAT,\n\tFACET_BUNDLE_FORMAT_VERSION,\n\tFACET_BUNDLE_MANIFEST_FILE,\n\ttype FacetBundleEntry,\n\ttype FacetBundleManifest,\n} from \"./manifest.ts\";\n\nexport type FacetBundlePlatform = \"node\" | \"browser\" | \"neutral\";\n\nexport interface BundleFacetsOptions {\n\treadonly plugin: {\n\t\treadonly id: string;\n\t\treadonly version?: string;\n\t};\n\t/** Opaque application-selected entry names mapped to TypeScript or JavaScript source files. */\n\treadonly entries: Readonly<Record<string, string>>;\n\treadonly outdir: string;\n\treadonly workingDirectory?: string;\n\t/** Additional package imports intentionally left for the loading application to resolve. */\n\treadonly external?: readonly string[];\n\treadonly sourceMap?: boolean;\n\treadonly minify?: boolean;\n\treadonly define?: Readonly<Record<string, string>>;\n\treadonly platform?: FacetBundlePlatform;\n\treadonly target?: string | readonly string[];\n}\n\nexport interface BundleFacetsResult {\n\treadonly manifest: FacetBundleManifest;\n\treadonly manifestPath: string;\n}\n\n/** Bundle each opaque facet entry into an independent content-addressed CommonJS file. */\nexport async function bundleFacets(options: BundleFacetsOptions): Promise<BundleFacetsResult> {\n\tvalidateOptions(options);\n\tconst workingDirectory = resolve(options.workingDirectory ?? process.cwd());\n\tconst outputDirectory = resolve(workingDirectory, options.outdir);\n\tconst outputParent = dirname(outputDirectory);\n\tawait mkdir(outputParent, { recursive: true });\n\tconst temporaryDirectory = join(outputParent, `.${basename(outputDirectory)}.tmp-${randomUUID()}`);\n\tawait mkdir(temporaryDirectory);\n\ttry {\n\t\tconst entries: Record<string, FacetBundleEntry> = {};\n\t\tfor (const [entryName, source] of Object.entries(options.entries).sort(([left], [right]) =>\n\t\t\tleft.localeCompare(right),\n\t\t)) {\n\t\t\tentries[entryName] = await bundleEntry({\n\t\t\t\tentryName,\n\t\t\t\tsource: resolve(workingDirectory, source),\n\t\t\t\ttemporaryDirectory,\n\t\t\t\tworkingDirectory,\n\t\t\t\toptions,\n\t\t\t});\n\t\t}\n\t\tconst manifest: FacetBundleManifest = Object.freeze({\n\t\t\tformat: FACET_BUNDLE_FORMAT,\n\t\t\tformatVersion: FACET_BUNDLE_FORMAT_VERSION,\n\t\t\tplugin: Object.freeze({\n\t\t\t\tid: options.plugin.id,\n\t\t\t\t...(options.plugin.version === undefined ? {} : { version: options.plugin.version }),\n\t\t\t}),\n\t\t\tentries: Object.freeze(entries),\n\t\t});\n\t\tawait writeFile(join(temporaryDirectory, FACET_BUNDLE_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\\n`);\n\t\tawait replaceDirectory(temporaryDirectory, outputDirectory);\n\t\treturn Object.freeze({\n\t\t\tmanifest,\n\t\t\tmanifestPath: join(outputDirectory, FACET_BUNDLE_MANIFEST_FILE),\n\t\t});\n\t} catch (error) {\n\t\tawait rm(temporaryDirectory, { force: true, recursive: true });\n\t\tthrow error;\n\t}\n}\n\nasync function bundleEntry(input: {\n\treadonly entryName: string;\n\treadonly source: string;\n\treadonly temporaryDirectory: string;\n\treadonly workingDirectory: string;\n\treadonly options: BundleFacetsOptions;\n}): Promise<FacetBundleEntry> {\n\tconst entryPrefix = `facet-${shortHash(input.entryName)}`;\n\tconst requestedPlatform = input.options.platform ?? \"node\";\n\tconst buildOptions: BuildOptions = {\n\t\tabsWorkingDir: input.workingDirectory,\n\t\tbanner: { js: '\"use strict\";' },\n\t\tbundle: true,\n\t\tdefine: input.options.define,\n\t\tentryNames: `${entryPrefix}-[hash]`,\n\t\tentryPoints: [input.source],\n\t\texternal: [...new Set([\"@earendil-works/chord\", \"@earendil-works/chord/*\", ...(input.options.external ?? [])])],\n\t\tformat: \"cjs\",\n\t\tlegalComments: \"none\",\n\t\tlogLevel: \"silent\",\n\t\tmetafile: true,\n\t\tminify: input.options.minify ?? false,\n\t\toutdir: input.temporaryDirectory,\n\t\toutExtension: { \".js\": \".cjs\" },\n\t\tplatform: requestedPlatform,\n\t\tsourcemap: input.options.sourceMap === true ? \"external\" : false,\n\t\tsupported: { \"dynamic-import\": false },\n\t\ttarget:\n\t\t\tinput.options.target === undefined\n\t\t\t\t? requestedPlatform === \"node\"\n\t\t\t\t\t? \"node22.19\"\n\t\t\t\t\t: \"es2022\"\n\t\t\t\t: typeof input.options.target === \"string\"\n\t\t\t\t\t? input.options.target\n\t\t\t\t\t: [...input.options.target],\n\t\twrite: true,\n\t};\n\tlet result: Awaited<ReturnType<typeof build>>;\n\ttry {\n\t\tresult = await build(buildOptions);\n\t} catch (error) {\n\t\tconst diagnostics = esbuildMessages(error);\n\t\tconst detail = diagnostics.length === 0 ? \"\" : `\\n${diagnostics.join(\"\\n\")}`;\n\t\tthrow new Error(`Could not bundle facet entry ${input.entryName}${detail}`, { cause: error });\n\t}\n\tconst metafile = result.metafile;\n\tif (metafile === undefined) throw new Error(`Facet entry ${input.entryName} produced no build metadata`);\n\tconst outputs = Object.entries(metafile.outputs).filter(\n\t\t([path, output]) => output.entryPoint !== undefined && extname(path) === \".cjs\",\n\t);\n\tif (outputs.length !== 1)\n\t\tthrow new Error(`Facet entry ${input.entryName} did not produce exactly one JavaScript file`);\n\tconst [outputPath, metadata] = outputs[0]!;\n\tconst absoluteOutputPath = resolve(input.workingDirectory, outputPath);\n\tconst file = relative(input.temporaryDirectory, absoluteOutputPath);\n\tif (file.length === 0 || file.startsWith(`..${sep}`) || basename(file) !== file) {\n\t\tthrow new Error(`Facet entry ${input.entryName} produced an invalid output path`);\n\t}\n\tconst sourceMap = input.options.sourceMap === true ? `${file}.map` : undefined;\n\tconst allowedOutputs = new Set([absoluteOutputPath]);\n\tif (sourceMap !== undefined) allowedOutputs.add(join(input.temporaryDirectory, sourceMap));\n\tconst unexpectedOutputs = Object.keys(metafile.outputs)\n\t\t.map((path) => resolve(input.workingDirectory, path))\n\t\t.filter((path) => !allowedOutputs.has(path));\n\tif (unexpectedOutputs.length > 0) {\n\t\tthrow new Error(`Facet entry ${input.entryName} produced files other than its JavaScript bundle and source map`);\n\t}\n\tconst contents = await readFile(absoluteOutputPath);\n\tif (sourceMap !== undefined) await stat(join(input.temporaryDirectory, sourceMap));\n\treturn Object.freeze({\n\t\tfile,\n\t\tintegrity: `sha256-${createHash(\"sha256\").update(contents).digest(\"base64\")}`,\n\t\texternalImports: Object.freeze(\n\t\t\t[...new Set(metadata.imports.filter(({ external }) => external).map(({ path }) => path))].sort(),\n\t\t),\n\t\t...(sourceMap === undefined ? {} : { sourceMap }),\n\t});\n}\n\nfunction validateOptions(options: BundleFacetsOptions): void {\n\tif (options.plugin.id.length === 0) throw new TypeError(\"Facet bundle plugin ID must not be empty\");\n\tif (options.plugin.version !== undefined && options.plugin.version.length === 0) {\n\t\tthrow new TypeError(\"Facet bundle plugin version must not be empty\");\n\t}\n\tconst entries = Object.entries(options.entries);\n\tif (entries.length === 0) throw new TypeError(\"Facet bundle must contain at least one entry\");\n\tfor (const [name, source] of entries) {\n\t\tif (name.length === 0) throw new TypeError(\"Facet bundle entry name must not be empty\");\n\t\tif (source.length === 0) throw new TypeError(`Facet bundle entry ${name} must have a source path`);\n\t}\n\tfor (const external of options.external ?? []) {\n\t\tif (external.length === 0) throw new TypeError(\"Facet bundle external import must not be empty\");\n\t}\n}\n\nasync function replaceDirectory(temporaryDirectory: string, outputDirectory: string): Promise<void> {\n\tconst backupDirectory = `${outputDirectory}.old-${randomUUID()}`;\n\tlet movedExisting = false;\n\ttry {\n\t\tawait rename(outputDirectory, backupDirectory);\n\t\tmovedExisting = true;\n\t} catch (error) {\n\t\tif (!isMissingPath(error)) throw error;\n\t}\n\ttry {\n\t\tawait rename(temporaryDirectory, outputDirectory);\n\t} catch (error) {\n\t\tif (movedExisting) await rename(backupDirectory, outputDirectory);\n\t\tthrow error;\n\t}\n\tif (movedExisting) await rm(backupDirectory, { force: true, recursive: true });\n}\n\nfunction shortHash(value: string): string {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\").slice(0, 12);\n}\n\nfunction esbuildMessages(error: unknown): string[] {\n\tif (!isRecord(error) || !Array.isArray(error.errors)) return [];\n\treturn (error.errors as readonly unknown[]).flatMap((candidate) =>\n\t\tisEsbuildMessage(candidate) ? [formatEsbuildMessage(candidate)] : [],\n\t);\n}\n\nfunction formatEsbuildMessage(message: Message): string {\n\tconst location = message.location;\n\treturn location === null\n\t\t? message.text\n\t\t: `${location.file}:${location.line}:${location.column + 1}: ${message.text}`;\n}\n\nfunction isEsbuildMessage(value: unknown): value is Message {\n\treturn isRecord(value) && typeof value.text === \"string\" && (value.location === null || isRecord(value.location));\n}\n\nfunction isMissingPath(error: unknown): boolean {\n\treturn isRecord(error) && error.code === \"ENOENT\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../../src/node/manifest.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,mBAAmB,uBAAuB,CAAC;AACxD,eAAO,MAAM,2BAA2B,IAAI,CAAC;AAC7C,eAAO,MAAM,0BAA0B,sBAAsB,CAAC;AAC9D,eAAO,MAAM,4BAA4B,gCAAgC,CAAC;AAC1E,eAAO,MAAM,oCAAoC,IAAI,CAAC;AAEtD,MAAM,WAAW,gBAAgB;IAChC,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,mEAAmE;IACnE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,yEAAyE;IACzE,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,kEAAkE;IAClE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,MAAM,EAAE,OAAO,mBAAmB,CAAC;IAC5C,QAAQ,CAAC,aAAa,EAAE,OAAO,2BAA2B,CAAC;IAC3D,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IACnC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC;CAC7D;AAED,MAAM,WAAW,iBAAiB;IACjC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,gGAAgG;AAChG,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,MAAM,EAAE,OAAO,4BAA4B,CAAC;IACrD,QAAQ,CAAC,aAAa,EAAE,OAAO,oCAAoC,CAAC;IACpE,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IACnC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAC;IACjC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;CACpC","sourcesContent":["export const FACET_BUNDLE_FORMAT = \"chord.facet-bundle\";\nexport const FACET_BUNDLE_FORMAT_VERSION = 2;\nexport const FACET_BUNDLE_MANIFEST_FILE = \"chord-facets.json\";\nexport const FACET_BUNDLE_ARTIFACT_FORMAT = \"chord.facet-bundle-artifact\";\nexport const FACET_BUNDLE_ARTIFACT_FORMAT_VERSION = 2;\n\nexport interface FacetBundleEntry {\n\t/** Content-addressed CommonJS filename relative to the manifest. */\n\treadonly file: string;\n\t/** SHA-256 subresource-integrity value for the JavaScript file. */\n\treadonly integrity: string;\n\t/** Imports intentionally left for the loading application to resolve. */\n\treadonly externalImports: readonly string[];\n\t/** Source map filename relative to the manifest, when emitted. */\n\treadonly sourceMap?: string;\n}\n\nexport interface FacetBundleManifest {\n\treadonly format: typeof FACET_BUNDLE_FORMAT;\n\treadonly formatVersion: typeof FACET_BUNDLE_FORMAT_VERSION;\n\treadonly plugin: FacetBundlePlugin;\n\treadonly entries: Readonly<Record<string, FacetBundleEntry>>;\n}\n\nexport interface FacetBundlePlugin {\n\treadonly id: string;\n\treadonly version?: string;\n}\n\n/** One self-contained manifest entry suitable for storage or transport to another Node host. */\nexport interface FacetBundleArtifact {\n\treadonly format: typeof FACET_BUNDLE_ARTIFACT_FORMAT;\n\treadonly formatVersion: typeof FACET_BUNDLE_ARTIFACT_FORMAT_VERSION;\n\treadonly plugin: FacetBundlePlugin;\n\treadonly entryName: string;\n\treadonly entry: FacetBundleEntry;\n\treadonly source: string;\n\treadonly sourceMapContents?: string;\n}\n"]}
1
+ {"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../../src/node/manifest.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,mBAAmB,uBAAuB,CAAC;AACxD,eAAO,MAAM,2BAA2B,IAAI,CAAC;AAC7C,eAAO,MAAM,0BAA0B,sBAAsB,CAAC;AAC9D,eAAO,MAAM,4BAA4B,gCAAgC,CAAC;AAC1E,eAAO,MAAM,oCAAoC,IAAI,CAAC;AAEtD,MAAM,WAAW,gBAAgB;IAChC,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,mEAAmE;IACnE,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,yEAAyE;IACzE,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,kEAAkE;IAClE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,MAAM,EAAE,OAAO,mBAAmB,CAAC;IAC5C,QAAQ,CAAC,aAAa,EAAE,OAAO,2BAA2B,CAAC;IAC3D,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IACnC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC;CAC7D;AAED,MAAM,WAAW,iBAAiB;IACjC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,gGAAgG;AAChG,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,MAAM,EAAE,OAAO,4BAA4B,CAAC;IACrD,QAAQ,CAAC,aAAa,EAAE,OAAO,oCAAoC,CAAC;IACpE,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;IACnC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAC;IACjC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;CACpC"}
@@ -1 +1 @@
1
- {"version":3,"file":"package.d.ts","sourceRoot":"","sources":["../../src/node/package.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,kBAAkB,EAAgB,MAAM,aAAa,CAAC;AAEpE,MAAM,WAAW,yBAAyB;IACzC,yDAAyD;IACzD,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,iFAAiF;IACjF,QAAQ,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CAC1D;AAED,MAAM,WAAW,wBAAyB,SAAQ,kBAAkB;IACnE,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;CACjC;AAaD,qGAAqG;AACrG,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAoB9G","sourcesContent":["import { readFile, realpath, stat } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { type BundleFacetsResult, bundleFacets } from \"./bundle.ts\";\n\nexport interface BundleFacetPackageOptions {\n\t/** Plugin package directory or its package.json path. */\n\treadonly packagePath: string;\n\treadonly outdir: string;\n\t/** Application conventions applied when the corresponding source file exists. */\n\treadonly defaultFacets?: Readonly<Record<string, string>>;\n}\n\nexport interface BundleFacetPackageResult extends BundleFacetsResult {\n\treadonly packageDirectory: string;\n\treadonly packageJsonPath: string;\n}\n\ninterface FacetPackageMetadata {\n\treadonly packageDirectory: string;\n\treadonly packageJsonPath: string;\n\treadonly name: string;\n\treadonly version: string;\n\treadonly peerDependencies: readonly string[];\n\treadonly configuredFacets: Readonly<Record<string, string | false>>;\n\treadonly external: readonly string[];\n\treadonly sourceMap: boolean;\n}\n\n/** Build a plugin package using package.json metadata and application-provided facet conventions. */\nexport async function bundleFacetPackage(options: BundleFacetPackageOptions): Promise<BundleFacetPackageResult> {\n\tconst metadata = await readFacetPackageMetadata(options.packagePath);\n\tconst entries = await resolveFacetEntries(metadata, options.defaultFacets ?? {});\n\tconst external = [...metadata.peerDependencies, ...metadata.external].flatMap((specifier) => [\n\t\tspecifier,\n\t\t`${specifier}/*`,\n\t]);\n\tconst result = await bundleFacets({\n\t\tplugin: { id: metadata.name, version: metadata.version },\n\t\tentries,\n\t\toutdir: options.outdir,\n\t\tworkingDirectory: metadata.packageDirectory,\n\t\texternal,\n\t\tsourceMap: metadata.sourceMap,\n\t});\n\treturn Object.freeze({\n\t\t...result,\n\t\tpackageDirectory: metadata.packageDirectory,\n\t\tpackageJsonPath: metadata.packageJsonPath,\n\t});\n}\n\nasync function readFacetPackageMetadata(packagePath: string): Promise<FacetPackageMetadata> {\n\tif (packagePath.length === 0) throw new TypeError(\"Facet package path must not be empty\");\n\tconst candidate = resolve(packagePath);\n\tlet packageDirectory: string;\n\tlet packageJsonPath: string;\n\tlet candidateStats: Awaited<ReturnType<typeof stat>>;\n\ttry {\n\t\tcandidateStats = await stat(candidate);\n\t} catch (error) {\n\t\tthrow new Error(`Could not access facet package ${candidate}`, { cause: error });\n\t}\n\tif (candidateStats.isDirectory()) {\n\t\tpackageDirectory = await realpath(candidate);\n\t\tpackageJsonPath = join(packageDirectory, \"package.json\");\n\t} else if (candidateStats.isFile() && basename(candidate) === \"package.json\") {\n\t\tpackageJsonPath = await realpath(candidate);\n\t\tpackageDirectory = dirname(packageJsonPath);\n\t} else {\n\t\tthrow new Error(`Facet package path must name a directory or package.json: ${candidate}`);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(await readFile(packageJsonPath, \"utf8\"));\n\t} catch (error) {\n\t\tthrow new Error(`Could not read facet package metadata ${packageJsonPath}`, { cause: error });\n\t}\n\tif (!isRecord(parsed)) throw new Error(`Facet package metadata must be an object: ${packageJsonPath}`);\n\tif (typeof parsed.name !== \"string\" || parsed.name.length === 0) {\n\t\tthrow new Error(`Facet package must have a non-empty name: ${packageJsonPath}`);\n\t}\n\tif (typeof parsed.version !== \"string\" || parsed.version.length === 0) {\n\t\tthrow new Error(`Facet package must have a non-empty version: ${packageJsonPath}`);\n\t}\n\tconst peerDependencies = parsePeerDependencies(parsed.peerDependencies, packageJsonPath);\n\tconst chord = parseChordConfiguration(parsed.chord, packageJsonPath);\n\treturn {\n\t\tpackageDirectory,\n\t\tpackageJsonPath,\n\t\tname: parsed.name,\n\t\tversion: parsed.version,\n\t\tpeerDependencies,\n\t\tconfiguredFacets: chord.facets,\n\t\texternal: chord.external,\n\t\tsourceMap: chord.sourceMap,\n\t};\n}\n\nfunction parsePeerDependencies(value: unknown, packageJsonPath: string): readonly string[] {\n\tif (value === undefined) return [];\n\tif (\n\t\t!isRecord(value) ||\n\t\tObject.entries(value).some(([name, version]) => name.length === 0 || typeof version !== \"string\")\n\t) {\n\t\tthrow new Error(`Facet package has invalid peerDependencies: ${packageJsonPath}`);\n\t}\n\treturn Object.freeze(Object.keys(value).sort());\n}\n\nfunction parseChordConfiguration(\n\tvalue: unknown,\n\tpackageJsonPath: string,\n): {\n\treadonly facets: Readonly<Record<string, string | false>>;\n\treadonly external: readonly string[];\n\treadonly sourceMap: boolean;\n} {\n\tif (value === undefined) return { facets: Object.freeze({}), external: Object.freeze([]), sourceMap: true };\n\tif (!isRecord(value)) throw new Error(`Facet package chord configuration must be an object: ${packageJsonPath}`);\n\tif (Object.keys(value).some((key) => key !== \"facets\" && key !== \"external\" && key !== \"sourceMap\")) {\n\t\tthrow new Error(`Facet package chord configuration has an unknown field: ${packageJsonPath}`);\n\t}\n\tconst facets: Record<string, string | false> = {};\n\tif (value.facets !== undefined) {\n\t\tif (!isRecord(value.facets)) {\n\t\t\tthrow new Error(`Facet package chord.facets must be an object: ${packageJsonPath}`);\n\t\t}\n\t\tfor (const [name, source] of Object.entries(value.facets)) {\n\t\t\tif (name.length === 0 || (typeof source !== \"string\" && source !== false) || source === \"\") {\n\t\t\t\tthrow new Error(`Facet package has an invalid chord.facets entry: ${packageJsonPath}`);\n\t\t\t}\n\t\t\tfacets[name] = source;\n\t\t}\n\t}\n\tlet external: readonly string[] = [];\n\tif (value.external !== undefined) {\n\t\tif (\n\t\t\t!Array.isArray(value.external) ||\n\t\t\tvalue.external.some((specifier) => typeof specifier !== \"string\" || specifier.length === 0)\n\t\t) {\n\t\t\tthrow new Error(`Facet package chord.external must contain non-empty strings: ${packageJsonPath}`);\n\t\t}\n\t\texternal = Object.freeze([...new Set(value.external as readonly string[])].sort());\n\t}\n\tif (value.sourceMap !== undefined && typeof value.sourceMap !== \"boolean\") {\n\t\tthrow new Error(`Facet package chord.sourceMap must be a boolean: ${packageJsonPath}`);\n\t}\n\treturn {\n\t\tfacets: Object.freeze(facets),\n\t\texternal,\n\t\tsourceMap: value.sourceMap ?? true,\n\t};\n}\n\nasync function resolveFacetEntries(\n\tmetadata: FacetPackageMetadata,\n\tdefaultFacets: Readonly<Record<string, string>>,\n): Promise<Readonly<Record<string, string>>> {\n\tconst entries: Record<string, string> = {};\n\tfor (const [name, source] of Object.entries(defaultFacets)) {\n\t\tvalidateFacetMapping(name, source, \"default\");\n\t\tconst path = resolvePackageEntry(metadata.packageDirectory, source, name);\n\t\ttry {\n\t\t\tconst entryStats = await stat(path);\n\t\t\tif (!entryStats.isFile()) throw new Error(`Default facet entry ${name} is not a file: ${path}`);\n\t\t\tconst canonicalPath = await realpath(path);\n\t\t\tvalidateCanonicalPackageEntry(metadata.packageDirectory, canonicalPath, name);\n\t\t\tentries[name] = canonicalPath;\n\t\t} catch (error) {\n\t\t\tif (isMissingPath(error)) continue;\n\t\t\tthrow error;\n\t\t}\n\t}\n\tfor (const [name, source] of Object.entries(metadata.configuredFacets)) {\n\t\tif (source === false) {\n\t\t\tdelete entries[name];\n\t\t\tcontinue;\n\t\t}\n\t\tvalidateFacetMapping(name, source, \"configured\");\n\t\tconst path = resolvePackageEntry(metadata.packageDirectory, source, name);\n\t\tlet entryStats: Awaited<ReturnType<typeof stat>>;\n\t\ttry {\n\t\t\tentryStats = await stat(path);\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Could not access configured facet entry ${name}: ${path}`, { cause: error });\n\t\t}\n\t\tif (!entryStats.isFile()) throw new Error(`Configured facet entry ${name} is not a file: ${path}`);\n\t\tconst canonicalPath = await realpath(path);\n\t\tvalidateCanonicalPackageEntry(metadata.packageDirectory, canonicalPath, name);\n\t\tentries[name] = canonicalPath;\n\t}\n\tif (Object.keys(entries).length === 0) {\n\t\tthrow new Error(`Facet package ${metadata.name} has no configured or conventional facet entries`);\n\t}\n\treturn Object.freeze(entries);\n}\n\nfunction validateFacetMapping(name: string, source: string, kind: string): void {\n\tif (name.length === 0) throw new Error(`Facet package ${kind} entry name must not be empty`);\n\tif (source.length === 0) throw new Error(`Facet package ${kind} entry ${name} must have a source path`);\n}\n\nfunction resolvePackageEntry(packageDirectory: string, source: string, name: string): string {\n\tif (isAbsolute(source)) throw new Error(`Facet package entry ${name} must be relative to the package directory`);\n\tconst path = resolve(packageDirectory, source);\n\tconst relativePath = relative(packageDirectory, path);\n\tif (\n\t\trelativePath.length === 0 ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\tthrow new Error(`Facet package entry ${name} escapes the package directory`);\n\t}\n\treturn path;\n}\n\nfunction validateCanonicalPackageEntry(packageDirectory: string, path: string, name: string): void {\n\tconst relativePath = relative(packageDirectory, path);\n\tif (relativePath === \"..\" || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {\n\t\tthrow new Error(`Facet package entry ${name} resolves outside the package directory`);\n\t}\n}\n\nfunction isMissingPath(error: unknown): boolean {\n\treturn isRecord(error) && error.code === \"ENOENT\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
1
+ {"version":3,"file":"package.d.ts","sourceRoot":"","sources":["../../src/node/package.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,kBAAkB,EAAgB,MAAM,aAAa,CAAC;AAEpE,MAAM,WAAW,yBAAyB;IACzC,yDAAyD;IACzD,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,iFAAiF;IACjF,QAAQ,CAAC,aAAa,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CAC1D;AAED,MAAM,WAAW,wBAAyB,SAAQ,kBAAkB;IACnE,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;CACjC;AAaD,qGAAqG;AACrG,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAoB9G"}
@@ -1 +1 @@
1
- {"version":3,"file":"package.js","sourceRoot":"","sources":["../../src/node/package.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACxF,OAAO,EAA2B,YAAY,EAAE,MAAM,aAAa,CAAC;AA0BpE,qGAAqG;AACrG,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,OAAkC,EAAqC;IAC/G,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AAC,gBAAwB,EAAE,IAAY,EAAE,IAAY,EAAQ;IAClG,MAAM,YAAY,GAAG,QAAQ,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAAC;IACtD,IAAI,YAAY,KAAK,IAAI,IAAI,YAAY,CAAC,UAAU,CAAC,KAAK,GAAG,EAAE,CAAC,IAAI,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;QAC9F,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,yCAAyC,CAAC,CAAC;IACvF,CAAC;AAAA,CACD;AAED,SAAS,aAAa,CAAC,KAAc,EAAW;IAC/C,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC;AAAA,CAClD;AAED,SAAS,QAAQ,CAAC,KAAc,EAAoC;IACnE,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAAA,CAC5E","sourcesContent":["import { readFile, realpath, stat } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { type BundleFacetsResult, bundleFacets } from \"./bundle.ts\";\n\nexport interface BundleFacetPackageOptions {\n\t/** Plugin package directory or its package.json path. */\n\treadonly packagePath: string;\n\treadonly outdir: string;\n\t/** Application conventions applied when the corresponding source file exists. */\n\treadonly defaultFacets?: Readonly<Record<string, string>>;\n}\n\nexport interface BundleFacetPackageResult extends BundleFacetsResult {\n\treadonly packageDirectory: string;\n\treadonly packageJsonPath: string;\n}\n\ninterface FacetPackageMetadata {\n\treadonly packageDirectory: string;\n\treadonly packageJsonPath: string;\n\treadonly name: string;\n\treadonly version: string;\n\treadonly peerDependencies: readonly string[];\n\treadonly configuredFacets: Readonly<Record<string, string | false>>;\n\treadonly external: readonly string[];\n\treadonly sourceMap: boolean;\n}\n\n/** Build a plugin package using package.json metadata and application-provided facet conventions. */\nexport async function bundleFacetPackage(options: BundleFacetPackageOptions): Promise<BundleFacetPackageResult> {\n\tconst metadata = await readFacetPackageMetadata(options.packagePath);\n\tconst entries = await resolveFacetEntries(metadata, options.defaultFacets ?? {});\n\tconst external = [...metadata.peerDependencies, ...metadata.external].flatMap((specifier) => [\n\t\tspecifier,\n\t\t`${specifier}/*`,\n\t]);\n\tconst result = await bundleFacets({\n\t\tplugin: { id: metadata.name, version: metadata.version },\n\t\tentries,\n\t\toutdir: options.outdir,\n\t\tworkingDirectory: metadata.packageDirectory,\n\t\texternal,\n\t\tsourceMap: metadata.sourceMap,\n\t});\n\treturn Object.freeze({\n\t\t...result,\n\t\tpackageDirectory: metadata.packageDirectory,\n\t\tpackageJsonPath: metadata.packageJsonPath,\n\t});\n}\n\nasync function readFacetPackageMetadata(packagePath: string): Promise<FacetPackageMetadata> {\n\tif (packagePath.length === 0) throw new TypeError(\"Facet package path must not be empty\");\n\tconst candidate = resolve(packagePath);\n\tlet packageDirectory: string;\n\tlet packageJsonPath: string;\n\tlet candidateStats: Awaited<ReturnType<typeof stat>>;\n\ttry {\n\t\tcandidateStats = await stat(candidate);\n\t} catch (error) {\n\t\tthrow new Error(`Could not access facet package ${candidate}`, { cause: error });\n\t}\n\tif (candidateStats.isDirectory()) {\n\t\tpackageDirectory = await realpath(candidate);\n\t\tpackageJsonPath = join(packageDirectory, \"package.json\");\n\t} else if (candidateStats.isFile() && basename(candidate) === \"package.json\") {\n\t\tpackageJsonPath = await realpath(candidate);\n\t\tpackageDirectory = dirname(packageJsonPath);\n\t} else {\n\t\tthrow new Error(`Facet package path must name a directory or package.json: ${candidate}`);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(await readFile(packageJsonPath, \"utf8\"));\n\t} catch (error) {\n\t\tthrow new Error(`Could not read facet package metadata ${packageJsonPath}`, { cause: error });\n\t}\n\tif (!isRecord(parsed)) throw new Error(`Facet package metadata must be an object: ${packageJsonPath}`);\n\tif (typeof parsed.name !== \"string\" || parsed.name.length === 0) {\n\t\tthrow new Error(`Facet package must have a non-empty name: ${packageJsonPath}`);\n\t}\n\tif (typeof parsed.version !== \"string\" || parsed.version.length === 0) {\n\t\tthrow new Error(`Facet package must have a non-empty version: ${packageJsonPath}`);\n\t}\n\tconst peerDependencies = parsePeerDependencies(parsed.peerDependencies, packageJsonPath);\n\tconst chord = parseChordConfiguration(parsed.chord, packageJsonPath);\n\treturn {\n\t\tpackageDirectory,\n\t\tpackageJsonPath,\n\t\tname: parsed.name,\n\t\tversion: parsed.version,\n\t\tpeerDependencies,\n\t\tconfiguredFacets: chord.facets,\n\t\texternal: chord.external,\n\t\tsourceMap: chord.sourceMap,\n\t};\n}\n\nfunction parsePeerDependencies(value: unknown, packageJsonPath: string): readonly string[] {\n\tif (value === undefined) return [];\n\tif (\n\t\t!isRecord(value) ||\n\t\tObject.entries(value).some(([name, version]) => name.length === 0 || typeof version !== \"string\")\n\t) {\n\t\tthrow new Error(`Facet package has invalid peerDependencies: ${packageJsonPath}`);\n\t}\n\treturn Object.freeze(Object.keys(value).sort());\n}\n\nfunction parseChordConfiguration(\n\tvalue: unknown,\n\tpackageJsonPath: string,\n): {\n\treadonly facets: Readonly<Record<string, string | false>>;\n\treadonly external: readonly string[];\n\treadonly sourceMap: boolean;\n} {\n\tif (value === undefined) return { facets: Object.freeze({}), external: Object.freeze([]), sourceMap: true };\n\tif (!isRecord(value)) throw new Error(`Facet package chord configuration must be an object: ${packageJsonPath}`);\n\tif (Object.keys(value).some((key) => key !== \"facets\" && key !== \"external\" && key !== \"sourceMap\")) {\n\t\tthrow new Error(`Facet package chord configuration has an unknown field: ${packageJsonPath}`);\n\t}\n\tconst facets: Record<string, string | false> = {};\n\tif (value.facets !== undefined) {\n\t\tif (!isRecord(value.facets)) {\n\t\t\tthrow new Error(`Facet package chord.facets must be an object: ${packageJsonPath}`);\n\t\t}\n\t\tfor (const [name, source] of Object.entries(value.facets)) {\n\t\t\tif (name.length === 0 || (typeof source !== \"string\" && source !== false) || source === \"\") {\n\t\t\t\tthrow new Error(`Facet package has an invalid chord.facets entry: ${packageJsonPath}`);\n\t\t\t}\n\t\t\tfacets[name] = source;\n\t\t}\n\t}\n\tlet external: readonly string[] = [];\n\tif (value.external !== undefined) {\n\t\tif (\n\t\t\t!Array.isArray(value.external) ||\n\t\t\tvalue.external.some((specifier) => typeof specifier !== \"string\" || specifier.length === 0)\n\t\t) {\n\t\t\tthrow new Error(`Facet package chord.external must contain non-empty strings: ${packageJsonPath}`);\n\t\t}\n\t\texternal = Object.freeze([...new Set(value.external as readonly string[])].sort());\n\t}\n\tif (value.sourceMap !== undefined && typeof value.sourceMap !== \"boolean\") {\n\t\tthrow new Error(`Facet package chord.sourceMap must be a boolean: ${packageJsonPath}`);\n\t}\n\treturn {\n\t\tfacets: Object.freeze(facets),\n\t\texternal,\n\t\tsourceMap: value.sourceMap ?? true,\n\t};\n}\n\nasync function resolveFacetEntries(\n\tmetadata: FacetPackageMetadata,\n\tdefaultFacets: Readonly<Record<string, string>>,\n): Promise<Readonly<Record<string, string>>> {\n\tconst entries: Record<string, string> = {};\n\tfor (const [name, source] of Object.entries(defaultFacets)) {\n\t\tvalidateFacetMapping(name, source, \"default\");\n\t\tconst path = resolvePackageEntry(metadata.packageDirectory, source, name);\n\t\ttry {\n\t\t\tconst entryStats = await stat(path);\n\t\t\tif (!entryStats.isFile()) throw new Error(`Default facet entry ${name} is not a file: ${path}`);\n\t\t\tconst canonicalPath = await realpath(path);\n\t\t\tvalidateCanonicalPackageEntry(metadata.packageDirectory, canonicalPath, name);\n\t\t\tentries[name] = canonicalPath;\n\t\t} catch (error) {\n\t\t\tif (isMissingPath(error)) continue;\n\t\t\tthrow error;\n\t\t}\n\t}\n\tfor (const [name, source] of Object.entries(metadata.configuredFacets)) {\n\t\tif (source === false) {\n\t\t\tdelete entries[name];\n\t\t\tcontinue;\n\t\t}\n\t\tvalidateFacetMapping(name, source, \"configured\");\n\t\tconst path = resolvePackageEntry(metadata.packageDirectory, source, name);\n\t\tlet entryStats: Awaited<ReturnType<typeof stat>>;\n\t\ttry {\n\t\t\tentryStats = await stat(path);\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Could not access configured facet entry ${name}: ${path}`, { cause: error });\n\t\t}\n\t\tif (!entryStats.isFile()) throw new Error(`Configured facet entry ${name} is not a file: ${path}`);\n\t\tconst canonicalPath = await realpath(path);\n\t\tvalidateCanonicalPackageEntry(metadata.packageDirectory, canonicalPath, name);\n\t\tentries[name] = canonicalPath;\n\t}\n\tif (Object.keys(entries).length === 0) {\n\t\tthrow new Error(`Facet package ${metadata.name} has no configured or conventional facet entries`);\n\t}\n\treturn Object.freeze(entries);\n}\n\nfunction validateFacetMapping(name: string, source: string, kind: string): void {\n\tif (name.length === 0) throw new Error(`Facet package ${kind} entry name must not be empty`);\n\tif (source.length === 0) throw new Error(`Facet package ${kind} entry ${name} must have a source path`);\n}\n\nfunction resolvePackageEntry(packageDirectory: string, source: string, name: string): string {\n\tif (isAbsolute(source)) throw new Error(`Facet package entry ${name} must be relative to the package directory`);\n\tconst path = resolve(packageDirectory, source);\n\tconst relativePath = relative(packageDirectory, path);\n\tif (\n\t\trelativePath.length === 0 ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\tthrow new Error(`Facet package entry ${name} escapes the package directory`);\n\t}\n\treturn path;\n}\n\nfunction validateCanonicalPackageEntry(packageDirectory: string, path: string, name: string): void {\n\tconst relativePath = relative(packageDirectory, path);\n\tif (relativePath === \"..\" || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {\n\t\tthrow new Error(`Facet package entry ${name} resolves outside the package directory`);\n\t}\n}\n\nfunction isMissingPath(error: unknown): boolean {\n\treturn isRecord(error) && error.code === \"ENOENT\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
1
+ {"version":3,"file":"package.js","s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C,gBAAgB,EAAE,IAAI,CAAC,CAAC;IACtD,IACC,YAAY,CAAC,MAAM,KAAK,CAAC;QACzB,YAAY,KAAK,IAAI;QACrB,YAAY,CAAC,UAAU,CAAC,KAAK,GAAG,EAAE,CAAC;QACnC,UAAU,CAAC,YAAY,CAAC,EACvB,CAAC;QACF,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,gCAAgC,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,IAAI,CAAC;AACb,CAAC;AAED,SAAS,6BAA6B,CAAC,gBAAwB,EAAE,IAAY,EAAE,IAAY;IAC1F,MAAM,YAAY,GAAG,QAAQ,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAAC;IACtD,IAAI,YAAY,KAAK,IAAI,IAAI,YAAY,CAAC,UAAU,CAAC,KAAK,GAAG,EAAE,CAAC,IAAI,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;QAC9F,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,yCAAyC,CAAC,CAAC;IACvF,CAAC;AACF,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACpC,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC;AACnD,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import { readFile, realpath, stat } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { type BundleFacetsResult, bundleFacets } from \"./bundle.ts\";\n\nexport interface BundleFacetPackageOptions {\n\t/** Plugin package directory or its package.json path. */\n\treadonly packagePath: string;\n\treadonly outdir: string;\n\t/** Application conventions applied when the corresponding source file exists. */\n\treadonly defaultFacets?: Readonly<Record<string, string>>;\n}\n\nexport interface BundleFacetPackageResult extends BundleFacetsResult {\n\treadonly packageDirectory: string;\n\treadonly packageJsonPath: string;\n}\n\ninterface FacetPackageMetadata {\n\treadonly packageDirectory: string;\n\treadonly packageJsonPath: string;\n\treadonly name: string;\n\treadonly version: string;\n\treadonly peerDependencies: readonly string[];\n\treadonly configuredFacets: Readonly<Record<string, string | false>>;\n\treadonly external: readonly string[];\n\treadonly sourceMap: boolean;\n}\n\n/** Build a plugin package using package.json metadata and application-provided facet conventions. */\nexport async function bundleFacetPackage(options: BundleFacetPackageOptions): Promise<BundleFacetPackageResult> {\n\tconst metadata = await readFacetPackageMetadata(options.packagePath);\n\tconst entries = await resolveFacetEntries(metadata, options.defaultFacets ?? {});\n\tconst external = [...metadata.peerDependencies, ...metadata.external].flatMap((specifier) => [\n\t\tspecifier,\n\t\t`${specifier}/*`,\n\t]);\n\tconst result = await bundleFacets({\n\t\tplugin: { id: metadata.name, version: metadata.version },\n\t\tentries,\n\t\toutdir: options.outdir,\n\t\tworkingDirectory: metadata.packageDirectory,\n\t\texternal,\n\t\tsourceMap: metadata.sourceMap,\n\t});\n\treturn Object.freeze({\n\t\t...result,\n\t\tpackageDirectory: metadata.packageDirectory,\n\t\tpackageJsonPath: metadata.packageJsonPath,\n\t});\n}\n\nasync function readFacetPackageMetadata(packagePath: string): Promise<FacetPackageMetadata> {\n\tif (packagePath.length === 0) throw new TypeError(\"Facet package path must not be empty\");\n\tconst candidate = resolve(packagePath);\n\tlet packageDirectory: string;\n\tlet packageJsonPath: string;\n\tlet candidateStats: Awaited<ReturnType<typeof stat>>;\n\ttry {\n\t\tcandidateStats = await stat(candidate);\n\t} catch (error) {\n\t\tthrow new Error(`Could not access facet package ${candidate}`, { cause: error });\n\t}\n\tif (candidateStats.isDirectory()) {\n\t\tpackageDirectory = await realpath(candidate);\n\t\tpackageJsonPath = join(packageDirectory, \"package.json\");\n\t} else if (candidateStats.isFile() && basename(candidate) === \"package.json\") {\n\t\tpackageJsonPath = await realpath(candidate);\n\t\tpackageDirectory = dirname(packageJsonPath);\n\t} else {\n\t\tthrow new Error(`Facet package path must name a directory or package.json: ${candidate}`);\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(await readFile(packageJsonPath, \"utf8\"));\n\t} catch (error) {\n\t\tthrow new Error(`Could not read facet package metadata ${packageJsonPath}`, { cause: error });\n\t}\n\tif (!isRecord(parsed)) throw new Error(`Facet package metadata must be an object: ${packageJsonPath}`);\n\tif (typeof parsed.name !== \"string\" || parsed.name.length === 0) {\n\t\tthrow new Error(`Facet package must have a non-empty name: ${packageJsonPath}`);\n\t}\n\tif (typeof parsed.version !== \"string\" || parsed.version.length === 0) {\n\t\tthrow new Error(`Facet package must have a non-empty version: ${packageJsonPath}`);\n\t}\n\tconst peerDependencies = parsePeerDependencies(parsed.peerDependencies, packageJsonPath);\n\tconst chord = parseChordConfiguration(parsed.chord, packageJsonPath);\n\treturn {\n\t\tpackageDirectory,\n\t\tpackageJsonPath,\n\t\tname: parsed.name,\n\t\tversion: parsed.version,\n\t\tpeerDependencies,\n\t\tconfiguredFacets: chord.facets,\n\t\texternal: chord.external,\n\t\tsourceMap: chord.sourceMap,\n\t};\n}\n\nfunction parsePeerDependencies(value: unknown, packageJsonPath: string): readonly string[] {\n\tif (value === undefined) return [];\n\tif (\n\t\t!isRecord(value) ||\n\t\tObject.entries(value).some(([name, version]) => name.length === 0 || typeof version !== \"string\")\n\t) {\n\t\tthrow new Error(`Facet package has invalid peerDependencies: ${packageJsonPath}`);\n\t}\n\treturn Object.freeze(Object.keys(value).sort());\n}\n\nfunction parseChordConfiguration(\n\tvalue: unknown,\n\tpackageJsonPath: string,\n): {\n\treadonly facets: Readonly<Record<string, string | false>>;\n\treadonly external: readonly string[];\n\treadonly sourceMap: boolean;\n} {\n\tif (value === undefined) return { facets: Object.freeze({}), external: Object.freeze([]), sourceMap: true };\n\tif (!isRecord(value)) throw new Error(`Facet package chord configuration must be an object: ${packageJsonPath}`);\n\tif (Object.keys(value).some((key) => key !== \"facets\" && key !== \"external\" && key !== \"sourceMap\")) {\n\t\tthrow new Error(`Facet package chord configuration has an unknown field: ${packageJsonPath}`);\n\t}\n\tconst facets: Record<string, string | false> = {};\n\tif (value.facets !== undefined) {\n\t\tif (!isRecord(value.facets)) {\n\t\t\tthrow new Error(`Facet package chord.facets must be an object: ${packageJsonPath}`);\n\t\t}\n\t\tfor (const [name, source] of Object.entries(value.facets)) {\n\t\t\tif (name.length === 0 || (typeof source !== \"string\" && source !== false) || source === \"\") {\n\t\t\t\tthrow new Error(`Facet package has an invalid chord.facets entry: ${packageJsonPath}`);\n\t\t\t}\n\t\t\tfacets[name] = source;\n\t\t}\n\t}\n\tlet external: readonly string[] = [];\n\tif (value.external !== undefined) {\n\t\tif (\n\t\t\t!Array.isArray(value.external) ||\n\t\t\tvalue.external.some((specifier) => typeof specifier !== \"string\" || specifier.length === 0)\n\t\t) {\n\t\t\tthrow new Error(`Facet package chord.external must contain non-empty strings: ${packageJsonPath}`);\n\t\t}\n\t\texternal = Object.freeze([...new Set(value.external as readonly string[])].sort());\n\t}\n\tif (value.sourceMap !== undefined && typeof value.sourceMap !== \"boolean\") {\n\t\tthrow new Error(`Facet package chord.sourceMap must be a boolean: ${packageJsonPath}`);\n\t}\n\treturn {\n\t\tfacets: Object.freeze(facets),\n\t\texternal,\n\t\tsourceMap: value.sourceMap ?? true,\n\t};\n}\n\nasync function resolveFacetEntries(\n\tmetadata: FacetPackageMetadata,\n\tdefaultFacets: Readonly<Record<string, string>>,\n): Promise<Readonly<Record<string, string>>> {\n\tconst entries: Record<string, string> = {};\n\tfor (const [name, source] of Object.entries(defaultFacets)) {\n\t\tvalidateFacetMapping(name, source, \"default\");\n\t\tconst path = resolvePackageEntry(metadata.packageDirectory, source, name);\n\t\ttry {\n\t\t\tconst entryStats = await stat(path);\n\t\t\tif (!entryStats.isFile()) throw new Error(`Default facet entry ${name} is not a file: ${path}`);\n\t\t\tconst canonicalPath = await realpath(path);\n\t\t\tvalidateCanonicalPackageEntry(metadata.packageDirectory, canonicalPath, name);\n\t\t\tentries[name] = canonicalPath;\n\t\t} catch (error) {\n\t\t\tif (isMissingPath(error)) continue;\n\t\t\tthrow error;\n\t\t}\n\t}\n\tfor (const [name, source] of Object.entries(metadata.configuredFacets)) {\n\t\tif (source === false) {\n\t\t\tdelete entries[name];\n\t\t\tcontinue;\n\t\t}\n\t\tvalidateFacetMapping(name, source, \"configured\");\n\t\tconst path = resolvePackageEntry(metadata.packageDirectory, source, name);\n\t\tlet entryStats: Awaited<ReturnType<typeof stat>>;\n\t\ttry {\n\t\t\tentryStats = await stat(path);\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Could not access configured facet entry ${name}: ${path}`, { cause: error });\n\t\t}\n\t\tif (!entryStats.isFile()) throw new Error(`Configured facet entry ${name} is not a file: ${path}`);\n\t\tconst canonicalPath = await realpath(path);\n\t\tvalidateCanonicalPackageEntry(metadata.packageDirectory, canonicalPath, name);\n\t\tentries[name] = canonicalPath;\n\t}\n\tif (Object.keys(entries).length === 0) {\n\t\tthrow new Error(`Facet package ${metadata.name} has no configured or conventional facet entries`);\n\t}\n\treturn Object.freeze(entries);\n}\n\nfunction validateFacetMapping(name: string, source: string, kind: string): void {\n\tif (name.length === 0) throw new Error(`Facet package ${kind} entry name must not be empty`);\n\tif (source.length === 0) throw new Error(`Facet package ${kind} entry ${name} must have a source path`);\n}\n\nfunction resolvePackageEntry(packageDirectory: string, source: string, name: string): string {\n\tif (isAbsolute(source)) throw new Error(`Facet package entry ${name} must be relative to the package directory`);\n\tconst path = resolve(packageDirectory, source);\n\tconst relativePath = relative(packageDirectory, path);\n\tif (\n\t\trelativePath.length === 0 ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\tthrow new Error(`Facet package entry ${name} escapes the package directory`);\n\t}\n\treturn path;\n}\n\nfunction validateCanonicalPackageEntry(packageDirectory: string, path: string, name: string): void {\n\tconst relativePath = relative(packageDirectory, path);\n\tif (relativePath === \"..\" || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {\n\t\tthrow new Error(`Facet package entry ${name} resolves outside the package directory`);\n\t}\n}\n\nfunction isMissingPath(error: unknown): boolean {\n\treturn isRecord(error) && error.code === \"ENOENT\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,YAAY,EACX,gCAAgC,EAChC,2BAA2B,EAC3B,wBAAwB,GACxB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACN,+BAA+B,EAC/B,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,GACvB,MAAM,yBAAyB,CAAC;AACjC,YAAY,EACX,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACN,4BAA4B,EAC5B,oCAAoC,EACpC,mBAAmB,EACnB,2BAA2B,EAC3B,0BAA0B,GAC1B,MAAM,oBAAoB,CAAC","sourcesContent":["export type {\n\tFacetBundleArtifactLoaderOptions,\n\tFacetBundleExternalResolver,\n\tFacetBundleLoaderOptions,\n} from \"./node/bundle-loader.ts\";\nexport {\n\tcreateFacetBundleArtifactLoader,\n\tcreateFacetBundleLoader,\n\treadFacetBundleArtifact,\n\treadFacetBundleManifest,\n} from \"./node/bundle-loader.ts\";\nexport type {\n\tFacetBundleArtifact,\n\tFacetBundleEntry,\n\tFacetBundleManifest,\n\tFacetBundlePlugin,\n} from \"./node/manifest.ts\";\nexport {\n\tFACET_BUNDLE_ARTIFACT_FORMAT,\n\tFACET_BUNDLE_ARTIFACT_FORMAT_VERSION,\n\tFACET_BUNDLE_FORMAT,\n\tFACET_BUNDLE_FORMAT_VERSION,\n\tFACET_BUNDLE_MANIFEST_FILE,\n} from \"./node/manifest.ts\";\n"]}
1
+ {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,YAAY,EACX,gCAAgC,EAChC,2BAA2B,EAC3B,wBAAwB,GACxB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACN,+BAA+B,EAC/B,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,GACvB,MAAM,yBAAyB,CAAC;AACjC,YAAY,EACX,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,EACnB,iBAAiB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACN,4BAA4B,EAC5B,oCAAoC,EACpC,mBAAmB,EACnB,2BAA2B,EAC3B,0BAA0B,GAC1B,MAAM,oBAAoB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"consumer.d.ts","sourceRoot":"","sources":["../../src/services/consumer.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACX,OAAO,EAEP,oBAAoB,EACpB,2BAA2B,EAE3B,OAAO,EAMP,MAAM,aAAa,CAAC;AA0ZrB,qBAAa,wBAAyB,YAAW,oBAAoB;;IAapE,YAAY,OAAO,EAAE,2BAA2B,EAQ/C;IAED,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CA2B7B;IAED,OAAO,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,MAAM,IAAI,CAsB3G;IAEK,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAkB3C;IAEK,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CA8B5D;IAEK,OAAO,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAoB7C;CA6DD","sourcesContent":["import { awaitWithContext, BACKGROUND_CONTEXT } from \"../context/index.ts\";\nimport type { Op } from \"../delta/index.ts\";\nimport type {\n\tContext,\n\tJsonValue,\n\tRemoteServiceBinding,\n\tRemoteServiceBindingOptions,\n\tRemoteServiceTransport,\n\tService,\n\tServiceInstanceAddress,\n\tServiceInstanceSnapshot,\n\tServiceMemberSnapshot,\n\tServiceProviderUpdate,\n\tServiceSubscription,\n} from \"../types.ts\";\nimport { RemoteServiceError } from \"./errors.ts\";\nimport { ServiceSlot } from \"./handle.ts\";\nimport { InstanceDirectory, type InstanceDirectoryEntry } from \"./instances.ts\";\nimport { ReplicatedStateReplica, serviceDeliveryContext } from \"./state.ts\";\n\ntype ErrorReporter = (error: Error) => void;\ntype ServiceMemberKind = ServiceMemberSnapshot[\"kind\"];\n\nclass MemberSlot {\n\treadonly #serviceId: string;\n\treadonly #member: string;\n\treadonly #invoke: (args: readonly JsonValue[], context: Context) => Promise<JsonValue | undefined>;\n\treadonly #state: ReplicatedStateReplica;\n\treadonly #isActive: () => boolean;\n\treadonly #assertAccess: () => void;\n\treadonly value: unknown;\n\t#kind: ServiceMemberKind | undefined;\n\t#expectedKind: ServiceMemberKind | undefined;\n\n\tconstructor(\n\t\tserviceId: string,\n\t\tmember: string,\n\t\tinvoke: (args: readonly JsonValue[], context: Context) => Promise<JsonValue | undefined>,\n\t\tisActive: () => boolean,\n\t\tassertAccess: () => void,\n\t\treportError: ErrorReporter,\n\t) {\n\t\tthis.#serviceId = serviceId;\n\t\tthis.#member = member;\n\t\tthis.#invoke = invoke;\n\t\tthis.#isActive = isActive;\n\t\tthis.#assertAccess = assertAccess;\n\t\tthis.#state = new ReplicatedStateReplica(reportError);\n\t\tconst callable = (): void => {};\n\t\tthis.value = new Proxy(callable, {\n\t\t\tapply: (_target, _thisArg, args) => this.#call(args),\n\t\t\tget: (_target, property) => {\n\t\t\t\tif (property === \"value\") {\n\t\t\t\t\tthis.#assertAccess();\n\t\t\t\t\tthis.#expect(\"state\");\n\t\t\t\t\treturn this.#state.value;\n\t\t\t\t}\n\t\t\t\tif (property === \"subscribe\") return this.#subscribe.bind(this);\n\t\t\t\tif (property === Symbol.toStringTag) return \"RemoteServiceMember\";\n\t\t\t\tif (property === \"then\") return undefined;\n\t\t\t\treturn undefined;\n\t\t\t},\n\t\t});\n\t}\n\n\tsetDescription(kind: ServiceMemberKind): void {\n\t\tif (this.#kind !== undefined && this.#kind !== kind) {\n\t\t\tthrow new Error(`Remote service member ${this.#serviceId}.${this.#member} changed kind`);\n\t\t}\n\t\tthis.#kind = kind;\n\t\tif (this.#expectedKind !== undefined && this.#expectedKind !== kind) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_member_mismatch\",\n\t\t\t\t`Remote service member ${this.#serviceId}.${this.#member} is ${kind}, not ${this.#expectedKind}`,\n\t\t\t);\n\t\t}\n\t}\n\n\thydrate(sequence: number, ops: readonly Op[], context: Context): void {\n\t\tthis.setDescription(\"state\");\n\t\tthis.#state.hydrate(sequence, ops, context);\n\t}\n\n\tupdate(sequence: number, ops: readonly Op[], context: Context): void {\n\t\tthis.setDescription(\"state\");\n\t\tthis.#state.update(sequence, ops, context);\n\t}\n\n\tclear(): void {\n\t\tthis.#state.clear();\n\t}\n\n\t#subscribe(listener: (value: JsonValue, context: Context) => void): () => void {\n\t\tthis.#assertAccess();\n\t\tif (typeof listener !== \"function\") {\n\t\t\tthrow new TypeError(\"Replicated state subscription listener must be a function\");\n\t\t}\n\t\tthis.#expect(\"state\");\n\t\treturn this.#state.subscribe(listener);\n\t}\n\n\t#expect(kind: ServiceMemberKind): void {\n\t\tif (this.#expectedKind !== undefined && this.#expectedKind !== kind) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_member_mismatch\",\n\t\t\t\t`Remote service member ${this.#serviceId}.${this.#member} was used as two different kinds`,\n\t\t\t);\n\t\t}\n\t\tthis.#expectedKind = kind;\n\t\tif (this.#kind !== undefined && this.#kind !== kind) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_member_mismatch\",\n\t\t\t\t`Remote service member ${this.#serviceId}.${this.#member} is ${this.#kind}, not ${kind}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t#call(args: unknown[]): Promise<JsonValue | undefined> {\n\t\tthis.#assertAccess();\n\t\tthis.#expect(\"method\");\n\t\tif (!this.#isActive()) {\n\t\t\treturn Promise.reject(\n\t\t\t\tnew RemoteServiceError(\"service_stale_instance\", `Remote service ${this.#serviceId} binding is closed`),\n\t\t\t);\n\t\t}\n\t\tconst context = args.at(-1);\n\t\tif (!isContext(context)) {\n\t\t\treturn Promise.reject(\n\t\t\t\tnew RemoteServiceError(\n\t\t\t\t\t\"service_invalid_value\",\n\t\t\t\t\t`Remote service method ${this.#serviceId}.${this.#member} requires a trailing Context`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tconst businessArgs = args.slice(0, -1) as JsonValue[];\n\t\treturn this.#invoke(businessArgs, context);\n\t}\n}\n\nclass ServiceFacade {\n\treadonly #serviceId: string;\n\treadonly #address: ServiceInstanceAddress | undefined;\n\treadonly #transport: RemoteServiceTransport;\n\treadonly #reportError: ErrorReporter;\n\treadonly #slots = new Map<string, MemberSlot>();\n\treadonly #descriptions = new Map<string, ServiceMemberKind>();\n\treadonly #isActive: () => boolean;\n\treadonly #assertAccess: () => void;\n\treadonly proxy: object;\n\n\tconstructor(\n\t\tserviceId: string,\n\t\taddress: ServiceInstanceAddress | undefined,\n\t\ttransport: RemoteServiceTransport,\n\t\tisActive: () => boolean,\n\t\tassertAccess: () => void,\n\t\treportError: ErrorReporter,\n\t) {\n\t\tthis.#serviceId = serviceId;\n\t\tthis.#address = address;\n\t\tthis.#transport = transport;\n\t\tthis.#isActive = isActive;\n\t\tthis.#assertAccess = assertAccess;\n\t\tthis.#reportError = reportError;\n\t\tthis.proxy = new Proxy(Object.create(null) as object, {\n\t\t\tget: (_target, property) => {\n\t\t\t\tif (typeof property !== \"string\") return undefined;\n\t\t\t\treturn this.#slot(property).value;\n\t\t\t},\n\t\t});\n\t}\n\n\tinstall(snapshot: ServiceInstanceSnapshot, context: Context): void {\n\t\tif (!sameAddress(snapshot.instance, this.#address))\n\t\t\tthrow new Error(\"Remote service snapshot has the wrong address\");\n\t\tconst members = validateMembers(snapshot.members);\n\t\tfor (const name of this.#slots.keys()) {\n\t\t\tif (!members.has(name)) {\n\t\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\t\"service_member_not_found\",\n\t\t\t\t\t`Unknown remote service member ${this.#serviceId}.${name}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tthis.#descriptions.clear();\n\t\tfor (const [name, member] of members) this.#descriptions.set(name, member.kind);\n\t\tfor (const member of members.values()) {\n\t\t\tconst slot = this.#slots.get(member.name);\n\t\t\tif (member.kind === \"state\") {\n\t\t\t\t(slot ?? this.#slot(member.name)).hydrate(member.sequence, member.ops, context);\n\t\t\t} else {\n\t\t\t\tslot?.setDescription(member.kind);\n\t\t\t}\n\t\t}\n\t}\n\n\tupdate(member: string, sequence: number, ops: readonly Op[], context: Context): void {\n\t\tif (this.#descriptions.get(member) !== \"state\") {\n\t\t\tthrow new Error(`Remote service update targets non-state member ${this.#serviceId}.${member}`);\n\t\t}\n\t\tthis.#slot(member).update(sequence, ops, context);\n\t}\n\n\tclear(): void {\n\t\tfor (const slot of this.#slots.values()) slot.clear();\n\t}\n\n\t#slot(member: string): MemberSlot {\n\t\tlet slot = this.#slots.get(member);\n\t\tif (slot !== undefined) return slot;\n\t\tslot = new MemberSlot(\n\t\t\tthis.#serviceId,\n\t\t\tmember,\n\t\t\t(args, context) =>\n\t\t\t\tthis.#transport.invoke(\n\t\t\t\t\t{\n\t\t\t\t\t\tserviceId: this.#serviceId,\n\t\t\t\t\t\t...(this.#address === undefined ? {} : { instance: this.#address }),\n\t\t\t\t\t\tmember,\n\t\t\t\t\t\targs,\n\t\t\t\t\t},\n\t\t\t\t\tcontext,\n\t\t\t\t),\n\t\t\tthis.#isActive,\n\t\t\tthis.#assertAccess,\n\t\t\tthis.#reportError,\n\t\t);\n\t\tconst kind = this.#descriptions.get(member);\n\t\tif (kind !== undefined) slot.setDescription(kind);\n\t\tthis.#slots.set(member, slot);\n\t\treturn slot;\n\t}\n}\n\ninterface SingletonBinding {\n\tfacade: ServiceFacade;\n\tsubscription?: ServiceSubscription;\n\tstarting?: Promise<void>;\n\tactive: boolean;\n\trevision: number;\n}\n\ninterface KeyedInstance extends InstanceDirectoryEntry {\n\treadonly facade: ServiceFacade;\n}\n\nclass KeyedBinding<T> {\n\treadonly #service: Service<T>;\n\treadonly #transport: RemoteServiceTransport;\n\treadonly #reportError: ErrorReporter;\n\treadonly #assertAccess: () => void;\n\treadonly #onEmpty: () => void;\n\treadonly #instances: InstanceDirectory<KeyedInstance>;\n\t#subscription: ServiceSubscription | undefined;\n\t#starting: Promise<void> | undefined;\n\t#closed = false;\n\t#bound: boolean;\n\t#revision = 0;\n\n\tconstructor(\n\t\tservice: Service<T>,\n\t\ttransport: RemoteServiceTransport,\n\t\treportError: ErrorReporter,\n\t\tassertAccess: () => void,\n\t\tonEmpty: () => void,\n\t\tbound: boolean,\n\t) {\n\t\tthis.#service = service;\n\t\tthis.#transport = transport;\n\t\tthis.#reportError = reportError;\n\t\tthis.#assertAccess = assertAccess;\n\t\tthis.#onEmpty = onEmpty;\n\t\tthis.#bound = bound;\n\t\tthis.#instances = new InstanceDirectory({ ready: false, onError: reportError });\n\t}\n\n\tobserve(handler: (service: T, context: Context) => void | Promise<void>): () => void {\n\t\tif (this.#closed) throw new Error(\"Remote keyed service binding is closed\");\n\t\tlet stopped = false;\n\t\tconst stop = this.#instances.observe<T>((service, context) => {\n\t\t\tconst slot = new ServiceSlot(this.#service.id, true);\n\t\t\tvoid slot.bind(service as object);\n\t\t\treturn handler(\n\t\t\t\tslot.view<T>(() => {\n\t\t\t\t\tthis.#assertAccess();\n\t\t\t\t\tif (stopped || context.abortSignal?.aborted) {\n\t\t\t\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\t\t\t\"service_stale_instance\",\n\t\t\t\t\t\t\t`Remote service ${this.#service.id} observation is closed`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\tcontext,\n\t\t\t);\n\t\t});\n\t\tif (this.#bound && this.#starting === undefined) {\n\t\t\tconst revision = this.#revision;\n\t\t\tconst starting = this.#start(revision);\n\t\t\tthis.#starting = starting;\n\t\t\tvoid starting.catch((error: unknown) => {\n\t\t\t\tif (!this.#closed && this.#revision === revision && this.#bound) this.#reportError(toError(error));\n\t\t\t});\n\t\t}\n\t\treturn () => {\n\t\t\tif (stopped) return;\n\t\t\tstopped = true;\n\t\t\tstop();\n\t\t\tif (this.#instances.observerCount === 0) this.#onEmpty();\n\t\t};\n\t}\n\n\tasync rebind(bound: boolean, context: Context): Promise<void> {\n\t\tif (this.#closed) return;\n\t\tthis.#bound = bound;\n\t\tconst revision = ++this.#revision;\n\t\tawait this.#reset(context, false);\n\t\tif (this.#closed || this.#revision !== revision || this.#bound !== bound) return;\n\t\tif (bound && this.#instances.observerCount > 0) {\n\t\t\tconst starting = this.#start(revision);\n\t\t\tthis.#starting = starting;\n\t\t\tawait starting;\n\t\t}\n\t}\n\n\tready(): Promise<void> {\n\t\treturn this.#starting ?? Promise.resolve();\n\t}\n\n\tasync close(context: Context): Promise<void> {\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tthis.#revision += 1;\n\t\tawait this.#reset(context, true);\n\t\tthis.#instances.dispose();\n\t}\n\n\tasync #reset(context: Context, waitForStarting: boolean): Promise<void> {\n\t\tthis.#instances.reset();\n\t\tconst starting = this.#starting;\n\t\tthis.#starting = undefined;\n\t\tconst subscription = this.#subscription;\n\t\tthis.#subscription = undefined;\n\t\tawait Promise.all([\n\t\t\twaitForStarting ? starting?.catch(() => {}) : undefined,\n\t\t\tsubscription === undefined ? undefined : subscription.close(context),\n\t\t]);\n\t}\n\n\tasync #start(revision: number): Promise<void> {\n\t\tconst subscription = await this.#transport.subscribe(\n\t\t\tthis.#service.id,\n\t\t\t\"keyed\",\n\t\t\t(update, context) => {\n\t\t\t\tif (this.#revision === revision) this.#update(update, context);\n\t\t\t},\n\t\t\tBACKGROUND_CONTEXT,\n\t\t);\n\t\tif (this.#closed || !this.#bound || this.#revision !== revision) {\n\t\t\tawait subscription.close(BACKGROUND_CONTEXT);\n\t\t\treturn;\n\t\t}\n\t\tthis.#subscription = subscription;\n\t\tif (subscription.snapshot.mode !== \"keyed\" || subscription.snapshot.serviceId !== this.#service.id) {\n\t\t\tthrow new Error(`Remote service ${this.#service.id} returned the wrong keyed snapshot`);\n\t\t}\n\t\tfor (const snapshot of subscription.snapshot.instances) this.#spawn(snapshot, serviceDeliveryContext());\n\t\tsubscription.activate();\n\t\tthis.#instances.ready();\n\t}\n\n\t#update(update: ServiceProviderUpdate, context: Context): void {\n\t\tif (this.#closed) return;\n\t\ttry {\n\t\t\tswitch (update.type) {\n\t\t\t\tcase \"unavailable\":\n\t\t\t\tcase \"replaced\":\n\t\t\t\t\tthrow new Error(\"Keyed service received a singleton lifecycle update\");\n\t\t\t\tcase \"spawned\":\n\t\t\t\t\tthis.#spawn(update.instance, context);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"closed\": {\n\t\t\t\t\tconst instance = this.#instances.get(update.instance.key);\n\t\t\t\t\tif (instance?.generation === update.instance.generation) this.#instances.remove(instance);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"state\": {\n\t\t\t\t\tif (update.instance === undefined) throw new Error(\"Keyed state update has no instance address\");\n\t\t\t\t\tconst instance = this.#instances.get(update.instance.key);\n\t\t\t\t\tif (instance?.generation !== update.instance.generation) return;\n\t\t\t\t\tinstance.facade.update(update.member, update.sequence, update.ops, context);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.#reportError(toError(error));\n\t\t}\n\t}\n\n\t#spawn(snapshot: ServiceInstanceSnapshot, context: Context): void {\n\t\tconst address = snapshot.instance;\n\t\tif (address === undefined) throw new Error(\"Keyed service instance snapshot has no address\");\n\t\tlet active = true;\n\t\tconst facade = new ServiceFacade(\n\t\t\tthis.#service.id,\n\t\t\taddress,\n\t\t\tthis.#transport,\n\t\t\t() => active && !this.#closed,\n\t\t\tthis.#assertAccess,\n\t\t\tthis.#reportError,\n\t\t);\n\t\tfacade.install(snapshot, context);\n\t\tthis.#instances.replace({\n\t\t\tkey: address.key,\n\t\t\tgeneration: address.generation,\n\t\t\tservice: facade.proxy,\n\t\t\tfacade,\n\t\t\tdeactivate: () => {\n\t\t\t\tactive = false;\n\t\t\t\tfacade.clear();\n\t\t\t},\n\t\t});\n\t}\n}\n\nexport class RemoteServiceBindingImpl implements RemoteServiceBinding {\n\treadonly #transport: RemoteServiceTransport;\n\treadonly #allowlist = new Set<string>();\n\treadonly #reportError: ErrorReporter;\n\treadonly #modes = new Map<string, \"singleton\" | \"keyed\">();\n\treadonly #assertAccess: () => void;\n\treadonly #singletons = new Map<string, SingletonBinding>();\n\treadonly #keyed = new Map<string, KeyedBinding<unknown>>();\n\t#bound: boolean;\n\t#readinessRevision = 0;\n\t#bindingTransition = Promise.resolve();\n\t#disposed = false;\n\n\tconstructor(options: RemoteServiceBindingOptions) {\n\t\tthis.#transport = options.transport;\n\t\tconst ids = options.services.map(({ id }) => id);\n\t\tif (new Set(ids).size !== ids.length) throw new TypeError(\"Remote service binding has duplicate service IDs\");\n\t\tfor (const id of ids) this.#allowlist.add(id);\n\t\tthis.#reportError = options.onError ?? (() => {});\n\t\tthis.#assertAccess = options.assertAccess ?? (() => {});\n\t\tthis.#bound = options.bound ?? true;\n\t}\n\n\tuse<T>(service: Service<T>): T {\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAvailable(service.id, \"singleton\");\n\t\tlet binding = this.#singletons.get(service.id);\n\t\tif (binding !== undefined) return binding.facade.proxy as T;\n\t\tbinding = { facade: undefined as unknown as ServiceFacade, active: true, revision: 0 };\n\t\tbinding.facade = new ServiceFacade(\n\t\t\tservice.id,\n\t\t\tundefined,\n\t\t\tthis.#transport,\n\t\t\t() => binding!.active && !this.#disposed && this.#bound,\n\t\t\t() => this.#assertHandleAccess(),\n\t\t\tthis.#reportError,\n\t\t);\n\t\tthis.#singletons.set(service.id, binding);\n\t\tthis.#readinessRevision += 1;\n\t\tif (this.#bound) {\n\t\t\tconst revision = binding.revision;\n\t\t\tconst starting = this.#startSingleton(service.id, binding, revision);\n\t\t\tbinding.starting = starting;\n\t\t\tvoid starting.catch((error: unknown) => {\n\t\t\t\tif (binding.active && binding.revision === revision && !this.#disposed && this.#bound) {\n\t\t\t\t\tthis.#reportError(toError(error));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn binding.facade.proxy as T;\n\t}\n\n\tobserve<T>(service: Service<T>, handler: (service: T, context: Context) => void | Promise<void>): () => void {\n\t\tthis.#assertRemotable(service);\n\t\tthis.#assertAvailable(service.id, \"keyed\");\n\t\tlet binding = this.#keyed.get(service.id) as KeyedBinding<T> | undefined;\n\t\tif (binding === undefined) {\n\t\t\tbinding = new KeyedBinding(\n\t\t\t\tservice,\n\t\t\t\tthis.#transport,\n\t\t\t\tthis.#reportError,\n\t\t\t\t() => this.#assertHandleAccess(),\n\t\t\t\t() => {\n\t\t\t\t\tif (this.#keyed.get(service.id) !== binding) return;\n\t\t\t\t\tthis.#keyed.delete(service.id);\n\t\t\t\t\tthis.#readinessRevision += 1;\n\t\t\t\t\tvoid binding!.close(BACKGROUND_CONTEXT).catch(this.#reportError);\n\t\t\t\t},\n\t\t\t\tthis.#bound,\n\t\t\t);\n\t\t\tthis.#keyed.set(service.id, binding as KeyedBinding<unknown>);\n\t\t\tthis.#readinessRevision += 1;\n\t\t}\n\t\treturn binding.observe(handler);\n\t}\n\n\tasync ready(context: Context): Promise<void> {\n\t\tif (this.#disposed) throw new Error(\"Remote service binding is disposed\");\n\t\twhile (true) {\n\t\t\tconst revision = this.#readinessRevision;\n\t\t\tconst starts = [\n\t\t\t\tthis.#bindingTransition,\n\t\t\t\t...[...this.#singletons.values()].flatMap((binding) =>\n\t\t\t\t\tbinding.starting === undefined ? [] : [binding.starting],\n\t\t\t\t),\n\t\t\t\t...[...this.#keyed.values()].map((binding) => binding.ready()),\n\t\t\t];\n\t\t\tawait awaitWithContext(\n\t\t\t\tPromise.all(starts).then(() => undefined),\n\t\t\t\tcontext,\n\t\t\t);\n\t\t\tif (this.#disposed) throw new Error(\"Remote service binding is disposed\");\n\t\t\tif (revision === this.#readinessRevision) return;\n\t\t}\n\t}\n\n\tasync rebind(bound: boolean, context: Context): Promise<void> {\n\t\tif (this.#disposed) throw new Error(\"Remote service binding is disposed\");\n\t\tthis.#bound = bound;\n\t\tthis.#readinessRevision += 1;\n\t\tconst transitions: Promise<void>[] = [];\n\t\tfor (const [serviceId, binding] of this.#singletons) {\n\t\t\tbinding.revision += 1;\n\t\t\tbinding.facade.clear();\n\t\t\tconst subscription = binding.subscription;\n\t\t\tdelete binding.subscription;\n\t\t\tconst revision = binding.revision;\n\t\t\tconst starting = (async () => {\n\t\t\t\tawait subscription?.close(context);\n\t\t\t\tif (bound) await this.#startSingleton(serviceId, binding, revision);\n\t\t\t})();\n\t\t\tbinding.starting = starting;\n\t\t\ttransitions.push(starting);\n\t\t}\n\t\tfor (const binding of this.#keyed.values()) transitions.push(binding.rebind(bound, context));\n\t\tconst completion = (async () => {\n\t\t\tconst results = await Promise.allSettled(transitions);\n\t\t\tconst errors = results.filter((result): result is PromiseRejectedResult => result.status === \"rejected\");\n\t\t\tif (errors.length > 0)\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\terrors.map(({ reason }) => reason),\n\t\t\t\t\t\"Failed to rebind services\",\n\t\t\t\t);\n\t\t})();\n\t\tthis.#bindingTransition = completion;\n\t\tawait completion;\n\t}\n\n\tasync dispose(context: Context): Promise<void> {\n\t\tif (this.#disposed) return;\n\t\tthis.#disposed = true;\n\t\tconst closes: Promise<void>[] = [];\n\t\tfor (const binding of this.#singletons.values()) {\n\t\t\tbinding.active = false;\n\t\t\tbinding.facade.clear();\n\t\t\tif (binding.starting) closes.push(binding.starting.catch(() => {}));\n\t\t\tif (binding.subscription) closes.push(Promise.resolve(binding.subscription.close(context)));\n\t\t}\n\t\tfor (const binding of this.#keyed.values()) closes.push(binding.close(context));\n\t\tthis.#singletons.clear();\n\t\tthis.#keyed.clear();\n\t\tconst results = await Promise.allSettled(closes);\n\t\tconst errors = results.filter((result): result is PromiseRejectedResult => result.status === \"rejected\");\n\t\tif (errors.length > 0)\n\t\t\tthrow new AggregateError(\n\t\t\t\terrors.map(({ reason }) => reason),\n\t\t\t\t\"Failed to dispose services\",\n\t\t\t);\n\t}\n\n\tasync #startSingleton(serviceId: string, binding: SingletonBinding, revision: number): Promise<void> {\n\t\tconst subscription = await this.#transport.subscribe(\n\t\t\tserviceId,\n\t\t\t\"singleton\",\n\t\t\t(update, context) => {\n\t\t\t\tif (!binding.active || binding.revision !== revision) return;\n\t\t\t\ttry {\n\t\t\t\t\tif (update.type === \"unavailable\") {\n\t\t\t\t\t\tbinding.facade.clear();\n\t\t\t\t\t} else if (update.type === \"replaced\") {\n\t\t\t\t\t\tif (update.snapshot.instance !== undefined) {\n\t\t\t\t\t\t\tthrow new Error(\"Singleton replacement has an instance address\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbinding.facade.install(update.snapshot, context);\n\t\t\t\t\t} else if (update.type === \"state\" && update.instance === undefined) {\n\t\t\t\t\t\tbinding.facade.update(update.member, update.sequence, update.ops, context);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.#reportError(toError(error));\n\t\t\t\t}\n\t\t\t},\n\t\t\tBACKGROUND_CONTEXT,\n\t\t);\n\t\tif (!binding.active || this.#disposed || !this.#bound || binding.revision !== revision) {\n\t\t\tawait subscription.close(BACKGROUND_CONTEXT);\n\t\t\treturn;\n\t\t}\n\t\tbinding.subscription = subscription;\n\t\tconst snapshot = subscription.snapshot;\n\t\tif (snapshot.mode !== \"singleton\" || snapshot.serviceId !== serviceId || snapshot.instances.length !== 1) {\n\t\t\tthrow new Error(`Remote service ${serviceId} returned an invalid singleton snapshot`);\n\t\t}\n\t\tbinding.facade.install(snapshot.instances[0]!, serviceDeliveryContext());\n\t\tsubscription.activate();\n\t}\n\n\t#assertHandleAccess(): void {\n\t\tif (this.#disposed) throw new Error(\"Remote service binding is disposed\");\n\t\tthis.#assertAccess();\n\t}\n\n\t#assertRemotable(service: { readonly id: string; readonly local: boolean }): void {\n\t\tif (service.local) throw new RemoteServiceError(\"service_not_allowed\", `Service ${service.id} is process-local`);\n\t}\n\n\t#assertAvailable(serviceId: string, mode: \"singleton\" | \"keyed\"): void {\n\t\tif (this.#disposed) throw new Error(\"Remote service binding is disposed\");\n\t\tif (!this.#allowlist.has(serviceId)) {\n\t\t\tthrow new RemoteServiceError(\"service_not_allowed\", `Remote service ${serviceId} is not allowlisted`);\n\t\t}\n\t\tconst existing = this.#modes.get(serviceId);\n\t\tif (existing !== undefined && existing !== mode) {\n\t\t\tthrow new RemoteServiceError(\n\t\t\t\t\"service_mode_mismatch\",\n\t\t\t\t`Remote service ${serviceId} is already used as ${existing}`,\n\t\t\t);\n\t\t}\n\t\tthis.#modes.set(serviceId, mode);\n\t}\n}\n\nfunction validateMembers(members: readonly ServiceMemberSnapshot[]): ReadonlyMap<string, ServiceMemberSnapshot> {\n\tconst result = new Map<string, ServiceMemberSnapshot>();\n\tfor (const member of members) {\n\t\tif (member.name.length === 0 || result.has(member.name)) {\n\t\t\tthrow new Error(\"Remote service has invalid member descriptions\");\n\t\t}\n\t\tresult.set(member.name, member);\n\t}\n\treturn result;\n}\n\nfunction sameAddress(left: ServiceInstanceAddress | undefined, right: ServiceInstanceAddress | undefined): boolean {\n\tif (left === undefined || right === undefined) return left === right;\n\treturn left.key === right.key && left.generation === right.generation;\n}\n\nfunction isContext(value: unknown): value is Context {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst candidate = value as Partial<Context>;\n\treturn typeof candidate.value === \"function\" && typeof candidate.toString === \"function\";\n}\n\nfunction toError(error: unknown): Error {\n\treturn error instanceof Error ? error : new Error(String(error));\n}\n"]}
1
+ {"version":3,"file":"consumer.d.ts","sourceRoot":"","sources":["../../src/services/consumer.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACX,OAAO,EAEP,oBAAoB,EACpB,2BAA2B,EAG3B,OAAO,EAOP,MAAM,aAAa,CAAC;AA2arB,qBAAa,wBAAyB,YAAW,oBAAoB;;IAapE,YAAY,OAAO,EAAE,2BAA2B,EAQ/C;IAED,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CA2B7B;IAED,OAAO,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,MAAM,IAAI,CAsB3G;IAEK,KAAK,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAkB3C;IAEK,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CA8B5D;IAEK,OAAO,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAoB7C;CAkED"}