@milaboratories/pl-middle-layer 2.9.1 → 2.10.1

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 (66) hide show
  1. package/dist/index.cjs +5 -1
  2. package/dist/index.d.ts +3 -2
  3. package/dist/index.js +3 -2
  4. package/dist/middle_layer/build_stamp.cjs +1 -1
  5. package/dist/middle_layer/build_stamp.js +1 -1
  6. package/dist/middle_layer/index.cjs +4 -0
  7. package/dist/middle_layer/index.d.ts +2 -1
  8. package/dist/middle_layer/index.js +2 -1
  9. package/dist/middle_layer/middle_layer.cjs +100 -31
  10. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  11. package/dist/middle_layer/middle_layer.d.ts +54 -8
  12. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  13. package/dist/middle_layer/middle_layer.js +99 -30
  14. package/dist/middle_layer/middle_layer.js.map +1 -1
  15. package/dist/middle_layer/project.cjs +45 -38
  16. package/dist/middle_layer/project.cjs.map +1 -1
  17. package/dist/middle_layer/project.d.ts +18 -3
  18. package/dist/middle_layer/project.d.ts.map +1 -1
  19. package/dist/middle_layer/project.js +44 -36
  20. package/dist/middle_layer/project.js.map +1 -1
  21. package/dist/middle_layer/project_holds.cjs +266 -0
  22. package/dist/middle_layer/project_holds.cjs.map +1 -0
  23. package/dist/middle_layer/project_holds.d.ts +50 -0
  24. package/dist/middle_layer/project_holds.d.ts.map +1 -0
  25. package/dist/middle_layer/project_holds.js +262 -0
  26. package/dist/middle_layer/project_holds.js.map +1 -0
  27. package/dist/model/block_pack_spec.cjs.map +1 -1
  28. package/dist/model/block_pack_spec.d.ts +3 -3
  29. package/dist/model/block_pack_spec.d.ts.map +1 -1
  30. package/dist/model/block_pack_spec.js.map +1 -1
  31. package/dist/model/template_spec.d.ts +18 -0
  32. package/dist/model/template_spec.d.ts.map +1 -1
  33. package/dist/mutator/block-pack/block_pack.cjs +89 -2
  34. package/dist/mutator/block-pack/block_pack.cjs.map +1 -1
  35. package/dist/mutator/block-pack/block_pack.d.ts +16 -0
  36. package/dist/mutator/block-pack/block_pack.d.ts.map +1 -1
  37. package/dist/mutator/block-pack/block_pack.js +90 -4
  38. package/dist/mutator/block-pack/block_pack.js.map +1 -1
  39. package/dist/mutator/block-pack/required_capabilities.cjs +16 -0
  40. package/dist/mutator/block-pack/required_capabilities.cjs.map +1 -1
  41. package/dist/mutator/block-pack/required_capabilities.js +16 -1
  42. package/dist/mutator/block-pack/required_capabilities.js.map +1 -1
  43. package/dist/mutator/template/template_cache.cjs +8 -1
  44. package/dist/mutator/template/template_cache.cjs.map +1 -1
  45. package/dist/mutator/template/template_cache.d.ts +7 -3
  46. package/dist/mutator/template/template_cache.d.ts.map +1 -1
  47. package/dist/mutator/template/template_cache.js +8 -1
  48. package/dist/mutator/template/template_cache.js.map +1 -1
  49. package/package.json +6 -6
  50. package/src/middle_layer/index.ts +2 -0
  51. package/src/middle_layer/middle_layer.ts +121 -40
  52. package/src/middle_layer/project.ts +47 -42
  53. package/src/middle_layer/project_close_during_write.test.ts +142 -0
  54. package/src/middle_layer/project_handles.test.ts +168 -0
  55. package/src/middle_layer/project_holds.ts +359 -0
  56. package/src/middle_layer/project_slots.test.ts +331 -0
  57. package/src/model/block_pack_spec.ts +3 -2
  58. package/src/model/template_spec.ts +21 -0
  59. package/src/mutator/block-pack/block_pack.test.ts +10 -1
  60. package/src/mutator/block-pack/block_pack.ts +102 -2
  61. package/src/mutator/block-pack/block_pack_load.test.ts +52 -0
  62. package/src/mutator/block-pack/required_capabilities.ts +25 -0
  63. package/src/mutator/project-v3.test.ts +27 -16
  64. package/src/mutator/template/template_cache.ts +26 -3
  65. package/src/test/block_packs.ts +12 -0
  66. package/src/test/write_tx_hooks.ts +75 -0
@@ -1 +1 @@
1
- {"version":3,"file":"required_capabilities.js","names":[],"sources":["../../../src/mutator/block-pack/required_capabilities.ts"],"sourcesContent":["import { gunzipSync } from \"node:zlib\";\nimport type { CompiledTemplateV3, TemplateData } from \"@milaboratories/pl-model-backend\";\n\n/**\n * Reads the capability tokens a template declares it requires via\n * `TemplateDataV3.requiredCapabilities` (populated by `tengo-builder` at\n * compile time).\n *\n * Use this on the install path: `BlockPackPreparer.prepare` parses the\n * workflow off-thread via the worker, and the parsed result feeds\n * straight into this function — no second gunzip+JSON.parse on the main\n * thread, no recursive walk to re-derive what the compiler already wrote\n * down.\n *\n * Returns `undefined` for v2 templates (no compile-time capability\n * field) and for v3 templates that declare no requirements; otherwise\n * the array as the compiler wrote it.\n */\nexport function requiredCapabilitiesFromTemplate(\n parsed: TemplateData | CompiledTemplateV3,\n): string[] | undefined {\n if (parsed.type !== \"pl.tengo-template.v3\") return undefined;\n return parsed.template.requiredCapabilities;\n}\n\n/**\n * Same lookup, starting from raw `main.plj.gz` bytes. Used only at\n * catalog-listing time for local-dev blocks where the worker pipeline\n * isn't in play (`block_registry/registry.ts`). Install paths go through\n * `requiredCapabilitiesFromTemplate` instead to avoid parsing the\n * workflow twice.\n */\nexport function deriveRequiredCapabilities(\n workflowContent: Uint8Array | Buffer,\n): string[] | undefined {\n let parsed: unknown;\n try {\n const json = gunzipSync(workflowContent).toString(\"utf-8\");\n parsed = JSON.parse(json);\n } catch {\n return undefined;\n }\n return requiredCapabilitiesFromTemplate(parsed as TemplateData | CompiledTemplateV3);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,SAAgB,iCACd,QACsB;CACtB,IAAI,OAAO,SAAS,wBAAwB,OAAO,KAAA;CACnD,OAAO,OAAO,SAAS;AACzB;;;;;;;;AASA,SAAgB,2BACd,iBACsB;CACtB,IAAI;CACJ,IAAI;EACF,MAAM,OAAO,WAAW,eAAe,CAAC,CAAC,SAAS,OAAO;EACzD,SAAS,KAAK,MAAM,IAAI;CAC1B,QAAQ;EACN;CACF;CACA,OAAO,iCAAiC,MAA2C;AACrF"}
1
+ {"version":3,"file":"required_capabilities.js","names":[],"sources":["../../../src/mutator/block-pack/required_capabilities.ts"],"sourcesContent":["import { gunzipSync } from \"node:zlib\";\nimport type { CompiledTemplateV3, TemplateData } from \"@milaboratories/pl-model-backend\";\nimport type { PlClient } from \"@milaboratories/pl-client\";\n\n/**\n * Reads the capability tokens a template declares it requires via\n * `TemplateDataV3.requiredCapabilities` (populated by `tengo-builder` at\n * compile time).\n *\n * Use this on the install path: `BlockPackPreparer.prepare` parses the\n * workflow off-thread via the worker, and the parsed result feeds\n * straight into this function — no second gunzip+JSON.parse on the main\n * thread, no recursive walk to re-derive what the compiler already wrote\n * down.\n *\n * Returns `undefined` for v2 templates (no compile-time capability\n * field) and for v3 templates that declare no requirements; otherwise\n * the array as the compiler wrote it.\n */\nexport function requiredCapabilitiesFromTemplate(\n parsed: TemplateData | CompiledTemplateV3,\n): string[] | undefined {\n if (parsed.type !== \"pl.tengo-template.v3\") return undefined;\n return parsed.template.requiredCapabilities;\n}\n\n/**\n * Same lookup, starting from raw `main.plj.gz` bytes. Used only at\n * catalog-listing time for local-dev blocks where the worker pipeline\n * isn't in play (`block_registry/registry.ts`). Install paths go through\n * `requiredCapabilitiesFromTemplate` instead to avoid parsing the\n * workflow twice.\n */\nexport function deriveRequiredCapabilities(\n workflowContent: Uint8Array | Buffer,\n): string[] | undefined {\n let parsed: unknown;\n try {\n const json = gunzipSync(workflowContent).toString(\"utf-8\");\n parsed = JSON.parse(json);\n } catch {\n return undefined;\n }\n return requiredCapabilitiesFromTemplate(parsed as TemplateData | CompiledTemplateV3);\n}\n\n/** Throws when the connected backend doesn't advertise every capability the\n * block-pack requires (as declared in `meta.requiredCapabilities`).\n *\n * The matching set is the desktop's install gate moved server-side so both\n * the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's\n * `add_block` tool, programmatic block installs, tests) reject incompatible\n * blocks consistently. */\nexport function throwIfMissingServerCapabilities(\n pl: PlClient,\n requiredCapabilities: readonly string[] | undefined,\n): void {\n if (!requiredCapabilities || requiredCapabilities.length === 0) return;\n const advertised = (pl.serverInfo.capabilities ?? []) as readonly string[];\n const filterFn = (c: string) => !advertised.includes(c);\n if (!requiredCapabilities.some(filterFn)) return;\n const missing = requiredCapabilities.filter(filterFn);\n throw new Error(\n `Block cannot be added: connected backend does not advertise capabilities ` +\n `${JSON.stringify(missing)}. ` +\n `Backend advertises ${JSON.stringify(advertised)}. ` +\n `Upgrade the backend or remove the requirement from the block manifest.`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,SAAgB,iCACd,QACsB;CACtB,IAAI,OAAO,SAAS,wBAAwB,OAAO,KAAA;CACnD,OAAO,OAAO,SAAS;AACzB;;;;;;;;AASA,SAAgB,2BACd,iBACsB;CACtB,IAAI;CACJ,IAAI;EACF,MAAM,OAAO,WAAW,eAAe,CAAC,CAAC,SAAS,OAAO;EACzD,SAAS,KAAK,MAAM,IAAI;CAC1B,QAAQ;EACN;CACF;CACA,OAAO,iCAAiC,MAA2C;AACrF;;;;;;;;AASA,SAAgB,iCACd,IACA,sBACM;CACN,IAAI,CAAC,wBAAwB,qBAAqB,WAAW,GAAG;CAChE,MAAM,aAAc,GAAG,WAAW,gBAAgB,CAAC;CACnD,MAAM,YAAY,MAAc,CAAC,WAAW,SAAS,CAAC;CACtD,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GAAG;CAC1C,MAAM,UAAU,qBAAqB,OAAO,QAAQ;CACpD,MAAM,IAAI,MACR,4EACK,KAAK,UAAU,OAAO,EAAE,uBACL,KAAK,UAAU,UAAU,EAAE,yEAErD;AACF"}
@@ -1,3 +1,4 @@
1
+ const require_required_capabilities = require("../block-pack/required_capabilities.cjs");
1
2
  const require_index = require("../../debug/index.cjs");
2
3
  let _milaboratories_ts_helpers = require("@milaboratories/ts-helpers");
3
4
  let _milaboratories_pl_client = require("@milaboratories/pl-client");
@@ -512,7 +513,7 @@ async function loadTemplateCached(pl, spec, options) {
512
513
  */
513
514
  async function cacheBlockPackTemplate(pl, spec, options) {
514
515
  if (spec.template.type === "cached") return spec;
515
- const resourceId = await loadTemplateCached(pl, spec.template, options);
516
+ const resourceId = spec.template.type === "registry-pack" || spec.template.type === "local-pack" ? await installPackOnClient(pl, spec.template, options) : await loadTemplateCached(pl, spec.template, options);
516
517
  return {
517
518
  ...spec,
518
519
  template: {
@@ -521,6 +522,12 @@ async function cacheBlockPackTemplate(pl, spec, options) {
521
522
  }
522
523
  };
523
524
  }
525
+ async function installPackOnClient(pl, template, options) {
526
+ if (options?.preparer === void 0) throw new Error("BUG: a pack needs a preparer to load it");
527
+ const loaded = await options.preparer.loadPack(template);
528
+ require_required_capabilities.throwIfMissingServerCapabilities(pl, loaded.requiredCapabilities);
529
+ return await loadTemplateCached(pl, loaded.template, options);
530
+ }
524
531
  exports.ACCESS_COUNT_KEY = ACCESS_COUNT_KEY;
525
532
  exports.ACCESS_KEY_PREFIX = ACCESS_KEY_PREFIX;
526
533
  exports.GC_ACCESS_THRESHOLD = GC_ACCESS_THRESHOLD;
@@ -1 +1 @@
1
- {"version":3,"file":"template_cache.cjs","names":["resourceType","notEmpty","createHash","PlTemplateLibV1","PlTemplateSoftwareV1","PlWasmV1","PlTemplateV1","field","PlTemplateOverrideV1","ensureSignedResourceIdNotNull","toGlobalResourceId","parseTemplate","_","getDebugFlags"],"sources":["../../../src/mutator/template/template_cache.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type {\n AnyResourceRef,\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n} from \"@milaboratories/pl-client\";\nimport {\n ensureSignedResourceIdNotNull,\n field,\n resourceType,\n toGlobalResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n parseTemplate,\n PlTemplateLibV1,\n PlTemplateOverrideV1,\n PlTemplateSoftwareV1,\n PlTemplateV1,\n PlWasmV1,\n} from \"@milaboratories/pl-model-backend\";\nimport type {\n CompiledTemplateV3,\n TemplateData,\n TemplateDataV3,\n TemplateLibData,\n TemplateLibDataV3,\n TemplateSoftwareData,\n TemplateSoftwareDataV3,\n TemplateWasmDataV3,\n} from \"@milaboratories/pl-model-backend\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport type { BlockPackSpecPrepared } from \"../../model\";\nimport type { TemplateSpecPrepared } from \"../../model/template_spec\";\nimport { getDebugFlags } from \"../../debug\";\n\nexport const TemplateCacheType = resourceType(\"TemplateCache\", \"1\");\n\nexport const TemplateCacheFieldName = \"__templateCache\";\nconst BATCH_SIZE = 50;\n/** @internal exported for testing */\nexport const GC_ACCESS_THRESHOLD = 30;\n/** @internal exported for testing */\nexport const GC_MAX_ENTRIES = 3000;\n/** @internal exported for testing */\nexport const ACCESS_COUNT_KEY = \"_accessCount\";\n/** @internal exported for testing */\nexport const ACCESS_KEY_PREFIX = \"access_\";\n\nexport type TemplateCacheStat = {\n totalMs: number;\n flattenMs: number;\n cacheInitMs: number;\n materializeMs: number;\n totalNodes: number;\n cacheHits: number;\n cacheMisses: number;\n batchCount: number;\n happyPath: boolean;\n gcTriggered: boolean;\n retries: number;\n templateFormat: string;\n};\n\nfunction initialStat(): TemplateCacheStat {\n return {\n totalMs: 0,\n flattenMs: 0,\n cacheInitMs: 0,\n materializeMs: 0,\n totalNodes: 0,\n cacheHits: 0,\n cacheMisses: 0,\n batchCount: 0,\n happyPath: false,\n gcTriggered: false,\n retries: 0,\n templateFormat: \"\",\n };\n}\n\ninterface CacheableNode {\n /** SHA-256 content hash (includes all descendant content) */\n hash: string;\n /** Creates this node's resource in a transaction.\n * childRefs maps child hash → already-resolved ResourceRef or SignedResourceId */\n create: (tx: PlTransaction, childRefs: ReadonlyMap<string, AnyResourceRef>) => ResourceRef;\n /** Hashes of direct child nodes this node depends on */\n childHashes: string[];\n}\n\nfunction getSourceCode(name: string, sources: Record<string, string>, sourceHash: string): string {\n return notEmpty(\n sources[sourceHash],\n `trying to get \"${name}\" source: sources map doesn't contain source hash ${sourceHash}`,\n );\n}\n\n/**\n * Bottom-up hash composition: each node hashes its OWN content + child hash STRINGS.\n * This means each unique node is hashed exactly once → O(n) instead of O(n * depth).\n */\n\n// V2 leaf hashes (libs, software — no children)\n\nfunction hashLibV2(lib: TemplateLibData): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.src)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV2(sw: TemplateSoftwareData): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.src)\n .digest(\"hex\");\n}\n\n// V3 leaf hashes — use sourceHash directly instead of resolving source content\n\nfunction hashLibV3(lib: TemplateLibDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV3(sw: TemplateSoftwareDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashWasmV3(wasm: TemplateWasmDataV3): string {\n return createHash(\"sha256\")\n .update(PlWasmV1.type.name)\n .update(PlWasmV1.type.version)\n .update(wasm.name)\n .update(wasm.version)\n .update(wasm.sourceHash)\n .digest(\"hex\");\n}\n\n// ─── Tree flattening ─────────────────────────────────────────────────────────\n\nfunction flattenV2Tree(data: TemplateData): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n\n function processLib(lib: TemplateLibData): string {\n const hash = hashLibV2(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(PlTemplateLibV1.fromV2Data(lib).data),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareData): string {\n const hash = hashSoftwareV2(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV2Data(sw);\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateData): string {\n // Process children first (bottom-up) — their hashes are computed before ours\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content)\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(tpl.version)\n .update(tpl.src);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV2Data(tpl).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV2Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data);\n return nodes;\n}\n\nfunction flattenV3Tree(data: CompiledTemplateV3): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n const sources = data.hashToSource;\n\n function processLib(lib: TemplateLibDataV3): string {\n const hash = hashLibV3(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(\n PlTemplateLibV1.fromV3Data(lib, getSourceCode(lib.name, sources, lib.sourceHash))\n .data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareDataV3): string {\n const hash = hashSoftwareV3(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV3Data(\n sw,\n getSourceCode(sw.name, sources, sw.sourceHash),\n );\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processWasm(wasm: TemplateWasmDataV3): string {\n const hash = hashWasmV3(wasm);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlWasmV1.type,\n JSON.stringify(\n PlWasmV1.fromV3Data(wasm, getSourceCode(wasm.name, sources, wasm.sourceHash)).data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateDataV3): string {\n // Defensive: a template can carry no embedded version at runtime even\n // though the type says `string` — the compiler writes `packageJson.version`\n // unchecked, so a template built from a package with no `version` field\n // yields undefined. Identity is fully covered by name + sourceHash, so the\n // placeholder is safe for both the cache key and the backend resource's\n // required Version field.\n const version = tpl.version ?? \"0.0.0\";\n\n // Process children first (bottom-up)\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n for (const [wasmId, wasm] of Object.entries(tpl.wasm ?? {})) {\n const h = processWasm(wasm);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.wasmPrefix}/${wasmId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content).\n // Uses sourceHash directly — it already uniquely identifies the source.\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(version)\n .update(tpl.sourceHash);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const sourceCode = getSourceCode(tpl.name, sources, tpl.sourceHash);\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV3Data({ ...tpl, version }, sourceCode).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV3Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data.template);\n return nodes;\n}\n\n/** Flatten template tree into a topologically ordered list of cacheable nodes (leaves first). */\nexport function flattenTemplateTree(data: TemplateData | CompiledTemplateV3): CacheableNode[] {\n if (data.type === \"pl.tengo-template.v2\") {\n return flattenV2Tree(data);\n } else {\n return flattenV3Tree(data);\n }\n}\n\n/** In-memory cache for the TemplateCache SignedResourceId per PlClient instance. */\nconst cacheRidMap = new WeakMap<PlClient, SignedResourceId>();\n\n/** Clear the in-memory cacheRid entry (call on errors referencing the cache resource). */\nexport function invalidateTemplateCacheId(pl: PlClient): void {\n cacheRidMap.delete(pl);\n}\n\n/** Find or create the TemplateCache/1 resource on user root. */\nexport async function getOrCreateTemplateCache(pl: PlClient): Promise<SignedResourceId> {\n // Check in-memory cache first (0ms after first call)\n const cached = cacheRidMap.get(pl);\n if (cached !== undefined) return cached;\n\n // Try read-only check\n const existing = await pl.withReadTx(\"templateCache:check\", async (tx) => {\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n return fd ? ensureSignedResourceIdNotNull(fd.value) : undefined;\n });\n if (existing) {\n cacheRidMap.set(pl, existing);\n return existing;\n }\n\n const result = await pl.withWriteTx(\"templateCache:init\", async (tx) => {\n // Double-check inside write tx (another instance may have created it)\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n if (fd) return ensureSignedResourceIdNotNull(fd.value);\n\n const cache = tx.createStruct(TemplateCacheType);\n tx.createField(field(pl.clientRoot, TemplateCacheFieldName), \"Dynamic\", cache);\n tx.lock(cache);\n await tx.commit();\n return await cache.globalId;\n });\n cacheRidMap.set(pl, result);\n return result;\n}\n\n/** Remove the template cache from user root. */\nexport async function dropTemplateCache(pl: PlClient): Promise<void> {\n await pl.withWriteTx(\"templateCache:drop\", async (tx) => {\n const cacheField = field(pl.clientRoot, TemplateCacheFieldName);\n const fd = await tx.getFieldIfExists(cacheField);\n if (fd) {\n tx.removeField(cacheField);\n await tx.commit();\n }\n });\n invalidateTemplateCacheId(pl);\n}\n\n/**\n * Run count-based garbage collection on the template cache.\n * Evicts least-recently-used entries when the cache exceeds maxEntries.\n * Always resets the access counter to 0.\n *\n * @internal exported for testing (maxEntries parameter allows low thresholds in tests)\n * @returns true if entries were evicted\n */\nexport async function runGc(\n pl: PlClient,\n cacheRid: SignedResourceId,\n maxEntries: number = GC_MAX_ENTRIES,\n): Promise<boolean> {\n return await pl.withWriteTx(\"templateCache:gc\", async (tx) => {\n const kvs = await tx.listKeyValuesString(cacheRid);\n const entries: { hash: string; timestamp: number }[] = [];\n for (const { key, value } of kvs) {\n if (!key.startsWith(ACCESS_KEY_PREFIX)) continue;\n entries.push({\n hash: key.slice(ACCESS_KEY_PREFIX.length),\n timestamp: parseInt(value, 10),\n });\n }\n\n // Always reset counter\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, \"0\");\n\n if (entries.length <= maxEntries) {\n await tx.commit();\n return false;\n }\n\n // Sort oldest first, evict until under limit\n entries.sort((a, b) => a.timestamp - b.timestamp);\n const toEvict = entries.length - maxEntries;\n for (let i = 0; i < toEvict; i++) {\n tx.removeField(field(cacheRid, entries[i].hash));\n tx.deleteKValue(cacheRid, ACCESS_KEY_PREFIX + entries[i].hash);\n }\n\n await tx.commit();\n return true;\n });\n}\n\n/** Create a batch of cache nodes in the current transaction. */\nfunction createBatchNodes(\n tx: PlTransaction,\n cacheRid: SignedResourceId,\n batch: CacheableNode[],\n resolvedIds: ReadonlyMap<string, SignedResourceId>,\n newRefs: Map<string, ResourceRef>,\n now: string,\n): void {\n for (const node of batch) {\n const childRefs = new Map<string, AnyResourceRef>();\n for (const ch of node.childHashes) {\n const resolved = resolvedIds.get(ch) ?? newRefs.get(ch);\n if (resolved === undefined) {\n throw new Error(`BUG: child ${ch} not resolved`);\n }\n childRefs.set(ch, resolved);\n }\n const ref = node.create(tx, childRefs);\n newRefs.set(node.hash, ref);\n tx.createField(field(cacheRid, node.hash), \"Dynamic\", ref);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + node.hash, now);\n }\n}\n\n/**\n * Materialize a template tree via the cache using \"probe all + batched creation\".\n *\n * Phase 1 (single write tx):\n * - Check existence of ALL hashes in one roundtrip\n * - Happy path: if root cached, update access tracking and return\n * - Otherwise: fetch ResourceIds for all cache hits, create first batch of missing nodes\n *\n * Phase 2..N (one write tx per batch):\n * - Create remaining missing nodes in BATCH_SIZE chunks\n *\n * @returns root SignedResourceId and current access count (for GC decision)\n */\nasync function materialize(\n pl: PlClient,\n cacheRid: SignedResourceId,\n rootHash: string,\n nodes: CacheableNode[],\n stat: TemplateCacheStat,\n): Promise<{ rootId: SignedResourceId; accessCount: number }> {\n const allHashes = nodes.map((n) => n.hash);\n const resolvedIds = new Map<string, SignedResourceId>();\n\n // Phase 1: probe all + first batch\n const phase1 = await pl.withWriteTx(\"templateCache:materialize\", async (tx) => {\n // 1 roundtrip: check all hashes + read access count\n const [exists, countStr] = await Promise.all([\n Promise.all(allHashes.map((h) => tx.fieldExists(field(cacheRid, h)))),\n tx.getKValueStringIfExists(cacheRid, ACCESS_COUNT_KEY),\n ]);\n\n const prevCount = countStr ? parseInt(countStr, 10) : 0;\n const newCount = prevCount + 1;\n const now = Date.now().toString();\n const rootIdx = allHashes.length - 1;\n\n // Happy path: root already cached\n if (exists[rootIdx]) {\n const rootFd = await tx.getField(field(cacheRid, rootHash));\n const rootRid = ensureSignedResourceIdNotNull(rootFd.value);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + rootHash, now);\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n await tx.commit();\n stat.happyPath = true;\n stat.cacheHits = stat.totalNodes;\n stat.batchCount = 1;\n return { done: true as const, rootId: rootRid, accessCount: newCount };\n }\n\n // Fetch ResourceIds for all cache hits (1 roundtrip)\n const hitIndices: number[] = [];\n for (let i = 0; i < allHashes.length; i++) {\n if (exists[i]) hitIndices.push(i);\n }\n\n if (hitIndices.length > 0) {\n const hitFields = await Promise.all(\n hitIndices.map((i) => tx.getField(field(cacheRid, allHashes[i]))),\n );\n for (let j = 0; j < hitIndices.length; j++) {\n resolvedIds.set(\n allHashes[hitIndices[j]],\n ensureSignedResourceIdNotNull(hitFields[j].value),\n );\n }\n }\n stat.cacheHits = hitIndices.length;\n\n // Missing nodes (topo order preserved from flatten)\n const missing = nodes.filter((n) => !resolvedIds.has(n.hash));\n stat.cacheMisses = missing.length;\n\n // Create first batch of missing nodes\n const firstBatch = missing.slice(0, BATCH_SIZE);\n const newRefs = new Map<string, ResourceRef>();\n createBatchNodes(tx, cacheRid, firstBatch, resolvedIds, newRefs, now);\n\n // Update access tracking for cache hits\n for (const i of hitIndices) {\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + allHashes[i], now);\n }\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n\n await tx.commit();\n\n // Resolve new refs to global IDs (after commit)\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n\n return {\n done: false as const,\n remaining: missing.slice(BATCH_SIZE),\n accessCount: newCount,\n };\n });\n\n if (phase1.done) {\n return { rootId: phase1.rootId, accessCount: phase1.accessCount };\n }\n\n stat.batchCount = 1;\n\n // Phase 2+: remaining batches\n const { remaining } = phase1;\n for (let i = 0; i < remaining.length; i += BATCH_SIZE) {\n const batch = remaining.slice(i, i + BATCH_SIZE);\n stat.batchCount++;\n\n await pl.withWriteTx(\"templateCache:create\", async (tx) => {\n const newRefs = new Map<string, ResourceRef>();\n const now = Date.now().toString();\n createBatchNodes(tx, cacheRid, batch, resolvedIds, newRefs, now);\n await tx.commit();\n\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n });\n }\n\n const rootId = resolvedIds.get(rootHash);\n if (!rootId) throw new Error(\"BUG: root hash not resolved after all batches\");\n return { rootId, accessCount: phase1.accessCount };\n}\n\n/**\n * Materialize a template tree via the cache.\n * Manages its own transactions internally — do NOT call inside an existing tx.\n *\n * @returns concrete SignedResourceId of the root template\n */\nexport async function loadTemplateCached(\n pl: PlClient,\n spec: TemplateSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<SignedResourceId> {\n const stat = initialStat();\n const t0 = performance.now();\n\n try {\n // Parse to data if needed\n let tplData: TemplateData | CompiledTemplateV3;\n switch (spec.type) {\n case \"explicit\":\n tplData = parseTemplate(spec.content);\n break;\n case \"prepared\":\n tplData = spec.data;\n break;\n case \"cached\":\n return spec.resourceId;\n case \"from-registry\":\n throw new Error(\n \"loadTemplateCached does not support from-registry specs; use loadTemplate instead\",\n );\n default: {\n const _: never = spec;\n throw new Error(`unexpected spec type: ${(_ as any).type}`);\n }\n }\n\n stat.templateFormat = tplData.type;\n\n // Flatten to ordered nodes\n const tFlatten = performance.now();\n const nodes = flattenTemplateTree(tplData);\n stat.flattenMs = performance.now() - tFlatten;\n if (nodes.length === 0) throw new Error(\"template tree produced no nodes\");\n\n stat.totalNodes = nodes.length;\n const rootHash = nodes[nodes.length - 1].hash;\n\n // Resolve or create cache resource\n const tCacheInit = performance.now();\n const cacheRid = options?.cacheResourceId ?? (await getOrCreateTemplateCache(pl));\n stat.cacheInitMs = performance.now() - tCacheInit;\n\n // Retry loop: if a write tx fails (e.g. concurrent GC invalidated a cached resource),\n // restart materialization from scratch.\n const MAX_RETRIES = 3;\n for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {\n try {\n const tMat = performance.now();\n const result = await materialize(pl, cacheRid, rootHash, nodes, stat);\n stat.materializeMs = performance.now() - tMat;\n stat.retries = attempt;\n\n // GC in separate tx if access count exceeded threshold\n if (result.accessCount >= GC_ACCESS_THRESHOLD) {\n await runGc(pl, cacheRid);\n stat.gcTriggered = true;\n }\n\n return result.rootId;\n } catch (e) {\n if (attempt === MAX_RETRIES - 1) throw e;\n // Retry from scratch — previous batch results may reference GC'd resources\n stat.cacheHits = 0;\n stat.cacheMisses = 0;\n }\n }\n\n throw new Error(\"BUG: unreachable\");\n } finally {\n stat.totalMs = performance.now() - t0;\n if (getDebugFlags().logTemplateCacheStat) {\n console.log(`[templateCache] ${JSON.stringify(stat)}`);\n }\n }\n}\n\n/**\n * Pre-materialize a block pack's template via cache.\n * Returns a copy of the spec with the template replaced by a cached reference.\n * If the template is already cached, returns the spec unchanged.\n */\nexport async function cacheBlockPackTemplate(\n pl: PlClient,\n spec: BlockPackSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<BlockPackSpecPrepared> {\n if (spec.template.type === \"cached\") return spec;\n\n const resourceId = await loadTemplateCached(pl, spec.template, options);\n return {\n ...spec,\n template: { type: \"cached\", resourceId },\n };\n}\n"],"mappings":";;;;;;AAqCA,MAAa,qBAAA,GAAoBA,0BAAAA,aAAAA,CAAa,iBAAiB,GAAG;AAElE,MAAa,yBAAyB;AACtC,MAAM,aAAa;;AAEnB,MAAa,sBAAsB;;AAEnC,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;AAE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CAAC;EAGzC,MAAM,aAAa,YAAY,IAAI;EACnC,MAAM,WAAW,SAAS,mBAAoB,MAAM,yBAAyB,EAAE;EAC/E,KAAK,cAAc,YAAY,IAAI,IAAI;EAIvC,MAAM,cAAc;EACpB,KAAK,IAAI,UAAU,GAAG,UAAU,aAAa,WAC3C,IAAI;GACF,MAAM,OAAO,YAAY,IAAI;GAC7B,MAAM,SAAS,MAAM,YAAY,IAAI,UAAU,UAAU,OAAO,IAAI;GACpE,KAAK,gBAAgB,YAAY,IAAI,IAAI;GACzC,KAAK,UAAU;GAGf,IAAI,OAAO,eAAA,IAAoC;IAC7C,MAAM,MAAM,IAAI,QAAQ;IACxB,KAAK,cAAc;GACrB;GAEA,OAAO,OAAO;EAChB,SAAS,GAAG;GACV,IAAI,YAAY,GAAiB,MAAM;GAEvC,KAAK,YAAY;GACjB,KAAK,cAAc;EACrB;EAGF,MAAM,IAAI,MAAM,kBAAkB;CACpC,UAAU;EACR,KAAK,UAAU,YAAY,IAAI,IAAI;EACnC,IAAIC,cAAAA,cAAc,CAAC,CAAC,sBAClB,QAAQ,IAAI,mBAAmB,KAAK,UAAU,IAAI,GAAG;CAEzD;AACF;;;;;;AAOA,eAAsB,uBACpB,IACA,MACA,SACgC;CAChC,IAAI,KAAK,SAAS,SAAS,UAAU,OAAO;CAE5C,MAAM,aAAa,MAAM,mBAAmB,IAAI,KAAK,UAAU,OAAO;CACtE,OAAO;EACL,GAAG;EACH,UAAU;GAAE,MAAM;GAAU;EAAW;CACzC;AACF"}
1
+ {"version":3,"file":"template_cache.cjs","names":["resourceType","notEmpty","createHash","PlTemplateLibV1","PlTemplateSoftwareV1","PlWasmV1","PlTemplateV1","field","PlTemplateOverrideV1","ensureSignedResourceIdNotNull","toGlobalResourceId","parseTemplate","_","getDebugFlags"],"sources":["../../../src/mutator/template/template_cache.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type {\n AnyResourceRef,\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n} from \"@milaboratories/pl-client\";\nimport {\n ensureSignedResourceIdNotNull,\n field,\n resourceType,\n toGlobalResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n parseTemplate,\n PlTemplateLibV1,\n PlTemplateOverrideV1,\n PlTemplateSoftwareV1,\n PlTemplateV1,\n PlWasmV1,\n} from \"@milaboratories/pl-model-backend\";\nimport type {\n CompiledTemplateV3,\n TemplateData,\n TemplateDataV3,\n TemplateLibData,\n TemplateLibDataV3,\n TemplateSoftwareData,\n TemplateSoftwareDataV3,\n TemplateWasmDataV3,\n} from \"@milaboratories/pl-model-backend\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport type { BlockPackSpecPrepared } from \"../../model\";\nimport type { InstallablePackTemplate, TemplateSpecPrepared } from \"../../model/template_spec\";\nimport type { BlockPackPreparer } from \"../block-pack/block_pack\";\nimport { throwIfMissingServerCapabilities } from \"../block-pack/required_capabilities\";\nimport { getDebugFlags } from \"../../debug\";\n\nexport const TemplateCacheType = resourceType(\"TemplateCache\", \"1\");\n\nexport const TemplateCacheFieldName = \"__templateCache\";\nconst BATCH_SIZE = 50;\n/** @internal exported for testing */\nexport const GC_ACCESS_THRESHOLD = 30;\n/** @internal exported for testing */\nexport const GC_MAX_ENTRIES = 3000;\n/** @internal exported for testing */\nexport const ACCESS_COUNT_KEY = \"_accessCount\";\n/** @internal exported for testing */\nexport const ACCESS_KEY_PREFIX = \"access_\";\n\nexport type TemplateCacheStat = {\n totalMs: number;\n flattenMs: number;\n cacheInitMs: number;\n materializeMs: number;\n totalNodes: number;\n cacheHits: number;\n cacheMisses: number;\n batchCount: number;\n happyPath: boolean;\n gcTriggered: boolean;\n retries: number;\n templateFormat: string;\n};\n\nfunction initialStat(): TemplateCacheStat {\n return {\n totalMs: 0,\n flattenMs: 0,\n cacheInitMs: 0,\n materializeMs: 0,\n totalNodes: 0,\n cacheHits: 0,\n cacheMisses: 0,\n batchCount: 0,\n happyPath: false,\n gcTriggered: false,\n retries: 0,\n templateFormat: \"\",\n };\n}\n\ninterface CacheableNode {\n /** SHA-256 content hash (includes all descendant content) */\n hash: string;\n /** Creates this node's resource in a transaction.\n * childRefs maps child hash → already-resolved ResourceRef or SignedResourceId */\n create: (tx: PlTransaction, childRefs: ReadonlyMap<string, AnyResourceRef>) => ResourceRef;\n /** Hashes of direct child nodes this node depends on */\n childHashes: string[];\n}\n\nfunction getSourceCode(name: string, sources: Record<string, string>, sourceHash: string): string {\n return notEmpty(\n sources[sourceHash],\n `trying to get \"${name}\" source: sources map doesn't contain source hash ${sourceHash}`,\n );\n}\n\n/**\n * Bottom-up hash composition: each node hashes its OWN content + child hash STRINGS.\n * This means each unique node is hashed exactly once → O(n) instead of O(n * depth).\n */\n\n// V2 leaf hashes (libs, software — no children)\n\nfunction hashLibV2(lib: TemplateLibData): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.src)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV2(sw: TemplateSoftwareData): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.src)\n .digest(\"hex\");\n}\n\n// V3 leaf hashes — use sourceHash directly instead of resolving source content\n\nfunction hashLibV3(lib: TemplateLibDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV3(sw: TemplateSoftwareDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashWasmV3(wasm: TemplateWasmDataV3): string {\n return createHash(\"sha256\")\n .update(PlWasmV1.type.name)\n .update(PlWasmV1.type.version)\n .update(wasm.name)\n .update(wasm.version)\n .update(wasm.sourceHash)\n .digest(\"hex\");\n}\n\n// ─── Tree flattening ─────────────────────────────────────────────────────────\n\nfunction flattenV2Tree(data: TemplateData): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n\n function processLib(lib: TemplateLibData): string {\n const hash = hashLibV2(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(PlTemplateLibV1.fromV2Data(lib).data),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareData): string {\n const hash = hashSoftwareV2(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV2Data(sw);\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateData): string {\n // Process children first (bottom-up) — their hashes are computed before ours\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content)\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(tpl.version)\n .update(tpl.src);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV2Data(tpl).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV2Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data);\n return nodes;\n}\n\nfunction flattenV3Tree(data: CompiledTemplateV3): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n const sources = data.hashToSource;\n\n function processLib(lib: TemplateLibDataV3): string {\n const hash = hashLibV3(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(\n PlTemplateLibV1.fromV3Data(lib, getSourceCode(lib.name, sources, lib.sourceHash))\n .data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareDataV3): string {\n const hash = hashSoftwareV3(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV3Data(\n sw,\n getSourceCode(sw.name, sources, sw.sourceHash),\n );\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processWasm(wasm: TemplateWasmDataV3): string {\n const hash = hashWasmV3(wasm);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlWasmV1.type,\n JSON.stringify(\n PlWasmV1.fromV3Data(wasm, getSourceCode(wasm.name, sources, wasm.sourceHash)).data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateDataV3): string {\n // Defensive: a template can carry no embedded version at runtime even\n // though the type says `string` — the compiler writes `packageJson.version`\n // unchecked, so a template built from a package with no `version` field\n // yields undefined. Identity is fully covered by name + sourceHash, so the\n // placeholder is safe for both the cache key and the backend resource's\n // required Version field.\n const version = tpl.version ?? \"0.0.0\";\n\n // Process children first (bottom-up)\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n for (const [wasmId, wasm] of Object.entries(tpl.wasm ?? {})) {\n const h = processWasm(wasm);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.wasmPrefix}/${wasmId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content).\n // Uses sourceHash directly — it already uniquely identifies the source.\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(version)\n .update(tpl.sourceHash);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const sourceCode = getSourceCode(tpl.name, sources, tpl.sourceHash);\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV3Data({ ...tpl, version }, sourceCode).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV3Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data.template);\n return nodes;\n}\n\n/** Flatten template tree into a topologically ordered list of cacheable nodes (leaves first). */\nexport function flattenTemplateTree(data: TemplateData | CompiledTemplateV3): CacheableNode[] {\n if (data.type === \"pl.tengo-template.v2\") {\n return flattenV2Tree(data);\n } else {\n return flattenV3Tree(data);\n }\n}\n\n/** In-memory cache for the TemplateCache SignedResourceId per PlClient instance. */\nconst cacheRidMap = new WeakMap<PlClient, SignedResourceId>();\n\n/** Clear the in-memory cacheRid entry (call on errors referencing the cache resource). */\nexport function invalidateTemplateCacheId(pl: PlClient): void {\n cacheRidMap.delete(pl);\n}\n\n/** Find or create the TemplateCache/1 resource on user root. */\nexport async function getOrCreateTemplateCache(pl: PlClient): Promise<SignedResourceId> {\n // Check in-memory cache first (0ms after first call)\n const cached = cacheRidMap.get(pl);\n if (cached !== undefined) return cached;\n\n // Try read-only check\n const existing = await pl.withReadTx(\"templateCache:check\", async (tx) => {\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n return fd ? ensureSignedResourceIdNotNull(fd.value) : undefined;\n });\n if (existing) {\n cacheRidMap.set(pl, existing);\n return existing;\n }\n\n const result = await pl.withWriteTx(\"templateCache:init\", async (tx) => {\n // Double-check inside write tx (another instance may have created it)\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n if (fd) return ensureSignedResourceIdNotNull(fd.value);\n\n const cache = tx.createStruct(TemplateCacheType);\n tx.createField(field(pl.clientRoot, TemplateCacheFieldName), \"Dynamic\", cache);\n tx.lock(cache);\n await tx.commit();\n return await cache.globalId;\n });\n cacheRidMap.set(pl, result);\n return result;\n}\n\n/** Remove the template cache from user root. */\nexport async function dropTemplateCache(pl: PlClient): Promise<void> {\n await pl.withWriteTx(\"templateCache:drop\", async (tx) => {\n const cacheField = field(pl.clientRoot, TemplateCacheFieldName);\n const fd = await tx.getFieldIfExists(cacheField);\n if (fd) {\n tx.removeField(cacheField);\n await tx.commit();\n }\n });\n invalidateTemplateCacheId(pl);\n}\n\n/**\n * Run count-based garbage collection on the template cache.\n * Evicts least-recently-used entries when the cache exceeds maxEntries.\n * Always resets the access counter to 0.\n *\n * @internal exported for testing (maxEntries parameter allows low thresholds in tests)\n * @returns true if entries were evicted\n */\nexport async function runGc(\n pl: PlClient,\n cacheRid: SignedResourceId,\n maxEntries: number = GC_MAX_ENTRIES,\n): Promise<boolean> {\n return await pl.withWriteTx(\"templateCache:gc\", async (tx) => {\n const kvs = await tx.listKeyValuesString(cacheRid);\n const entries: { hash: string; timestamp: number }[] = [];\n for (const { key, value } of kvs) {\n if (!key.startsWith(ACCESS_KEY_PREFIX)) continue;\n entries.push({\n hash: key.slice(ACCESS_KEY_PREFIX.length),\n timestamp: parseInt(value, 10),\n });\n }\n\n // Always reset counter\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, \"0\");\n\n if (entries.length <= maxEntries) {\n await tx.commit();\n return false;\n }\n\n // Sort oldest first, evict until under limit\n entries.sort((a, b) => a.timestamp - b.timestamp);\n const toEvict = entries.length - maxEntries;\n for (let i = 0; i < toEvict; i++) {\n tx.removeField(field(cacheRid, entries[i].hash));\n tx.deleteKValue(cacheRid, ACCESS_KEY_PREFIX + entries[i].hash);\n }\n\n await tx.commit();\n return true;\n });\n}\n\n/** Create a batch of cache nodes in the current transaction. */\nfunction createBatchNodes(\n tx: PlTransaction,\n cacheRid: SignedResourceId,\n batch: CacheableNode[],\n resolvedIds: ReadonlyMap<string, SignedResourceId>,\n newRefs: Map<string, ResourceRef>,\n now: string,\n): void {\n for (const node of batch) {\n const childRefs = new Map<string, AnyResourceRef>();\n for (const ch of node.childHashes) {\n const resolved = resolvedIds.get(ch) ?? newRefs.get(ch);\n if (resolved === undefined) {\n throw new Error(`BUG: child ${ch} not resolved`);\n }\n childRefs.set(ch, resolved);\n }\n const ref = node.create(tx, childRefs);\n newRefs.set(node.hash, ref);\n tx.createField(field(cacheRid, node.hash), \"Dynamic\", ref);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + node.hash, now);\n }\n}\n\n/**\n * Materialize a template tree via the cache using \"probe all + batched creation\".\n *\n * Phase 1 (single write tx):\n * - Check existence of ALL hashes in one roundtrip\n * - Happy path: if root cached, update access tracking and return\n * - Otherwise: fetch ResourceIds for all cache hits, create first batch of missing nodes\n *\n * Phase 2..N (one write tx per batch):\n * - Create remaining missing nodes in BATCH_SIZE chunks\n *\n * @returns root SignedResourceId and current access count (for GC decision)\n */\nasync function materialize(\n pl: PlClient,\n cacheRid: SignedResourceId,\n rootHash: string,\n nodes: CacheableNode[],\n stat: TemplateCacheStat,\n): Promise<{ rootId: SignedResourceId; accessCount: number }> {\n const allHashes = nodes.map((n) => n.hash);\n const resolvedIds = new Map<string, SignedResourceId>();\n\n // Phase 1: probe all + first batch\n const phase1 = await pl.withWriteTx(\"templateCache:materialize\", async (tx) => {\n // 1 roundtrip: check all hashes + read access count\n const [exists, countStr] = await Promise.all([\n Promise.all(allHashes.map((h) => tx.fieldExists(field(cacheRid, h)))),\n tx.getKValueStringIfExists(cacheRid, ACCESS_COUNT_KEY),\n ]);\n\n const prevCount = countStr ? parseInt(countStr, 10) : 0;\n const newCount = prevCount + 1;\n const now = Date.now().toString();\n const rootIdx = allHashes.length - 1;\n\n // Happy path: root already cached\n if (exists[rootIdx]) {\n const rootFd = await tx.getField(field(cacheRid, rootHash));\n const rootRid = ensureSignedResourceIdNotNull(rootFd.value);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + rootHash, now);\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n await tx.commit();\n stat.happyPath = true;\n stat.cacheHits = stat.totalNodes;\n stat.batchCount = 1;\n return { done: true as const, rootId: rootRid, accessCount: newCount };\n }\n\n // Fetch ResourceIds for all cache hits (1 roundtrip)\n const hitIndices: number[] = [];\n for (let i = 0; i < allHashes.length; i++) {\n if (exists[i]) hitIndices.push(i);\n }\n\n if (hitIndices.length > 0) {\n const hitFields = await Promise.all(\n hitIndices.map((i) => tx.getField(field(cacheRid, allHashes[i]))),\n );\n for (let j = 0; j < hitIndices.length; j++) {\n resolvedIds.set(\n allHashes[hitIndices[j]],\n ensureSignedResourceIdNotNull(hitFields[j].value),\n );\n }\n }\n stat.cacheHits = hitIndices.length;\n\n // Missing nodes (topo order preserved from flatten)\n const missing = nodes.filter((n) => !resolvedIds.has(n.hash));\n stat.cacheMisses = missing.length;\n\n // Create first batch of missing nodes\n const firstBatch = missing.slice(0, BATCH_SIZE);\n const newRefs = new Map<string, ResourceRef>();\n createBatchNodes(tx, cacheRid, firstBatch, resolvedIds, newRefs, now);\n\n // Update access tracking for cache hits\n for (const i of hitIndices) {\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + allHashes[i], now);\n }\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n\n await tx.commit();\n\n // Resolve new refs to global IDs (after commit)\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n\n return {\n done: false as const,\n remaining: missing.slice(BATCH_SIZE),\n accessCount: newCount,\n };\n });\n\n if (phase1.done) {\n return { rootId: phase1.rootId, accessCount: phase1.accessCount };\n }\n\n stat.batchCount = 1;\n\n // Phase 2+: remaining batches\n const { remaining } = phase1;\n for (let i = 0; i < remaining.length; i += BATCH_SIZE) {\n const batch = remaining.slice(i, i + BATCH_SIZE);\n stat.batchCount++;\n\n await pl.withWriteTx(\"templateCache:create\", async (tx) => {\n const newRefs = new Map<string, ResourceRef>();\n const now = Date.now().toString();\n createBatchNodes(tx, cacheRid, batch, resolvedIds, newRefs, now);\n await tx.commit();\n\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n });\n }\n\n const rootId = resolvedIds.get(rootHash);\n if (!rootId) throw new Error(\"BUG: root hash not resolved after all batches\");\n return { rootId, accessCount: phase1.accessCount };\n}\n\n/**\n * Materialize a template tree via the cache.\n * Manages its own transactions internally — do NOT call inside an existing tx.\n *\n * @returns concrete SignedResourceId of the root template\n */\nexport async function loadTemplateCached(\n pl: PlClient,\n spec: TemplateSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<SignedResourceId> {\n const stat = initialStat();\n const t0 = performance.now();\n\n try {\n // Parse to data if needed\n let tplData: TemplateData | CompiledTemplateV3;\n switch (spec.type) {\n case \"explicit\":\n tplData = parseTemplate(spec.content);\n break;\n case \"prepared\":\n tplData = spec.data;\n break;\n case \"cached\":\n return spec.resourceId;\n case \"from-registry\":\n throw new Error(\n \"loadTemplateCached does not support from-registry specs; use loadTemplate instead\",\n );\n default: {\n const _: never = spec;\n throw new Error(`unexpected spec type: ${(_ as any).type}`);\n }\n }\n\n stat.templateFormat = tplData.type;\n\n // Flatten to ordered nodes\n const tFlatten = performance.now();\n const nodes = flattenTemplateTree(tplData);\n stat.flattenMs = performance.now() - tFlatten;\n if (nodes.length === 0) throw new Error(\"template tree produced no nodes\");\n\n stat.totalNodes = nodes.length;\n const rootHash = nodes[nodes.length - 1].hash;\n\n // Resolve or create cache resource\n const tCacheInit = performance.now();\n const cacheRid = options?.cacheResourceId ?? (await getOrCreateTemplateCache(pl));\n stat.cacheInitMs = performance.now() - tCacheInit;\n\n // Retry loop: if a write tx fails (e.g. concurrent GC invalidated a cached resource),\n // restart materialization from scratch.\n const MAX_RETRIES = 3;\n for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {\n try {\n const tMat = performance.now();\n const result = await materialize(pl, cacheRid, rootHash, nodes, stat);\n stat.materializeMs = performance.now() - tMat;\n stat.retries = attempt;\n\n // GC in separate tx if access count exceeded threshold\n if (result.accessCount >= GC_ACCESS_THRESHOLD) {\n await runGc(pl, cacheRid);\n stat.gcTriggered = true;\n }\n\n return result.rootId;\n } catch (e) {\n if (attempt === MAX_RETRIES - 1) throw e;\n // Retry from scratch — previous batch results may reference GC'd resources\n stat.cacheHits = 0;\n stat.cacheMisses = 0;\n }\n }\n\n throw new Error(\"BUG: unreachable\");\n } finally {\n stat.totalMs = performance.now() - t0;\n if (getDebugFlags().logTemplateCacheStat) {\n console.log(`[templateCache] ${JSON.stringify(stat)}`);\n }\n }\n}\n\ntype CacheBlockPackOptions = {\n cacheResourceId?: SignedResourceId;\n /** Loads registry and local packs. */\n preparer?: BlockPackPreparer;\n};\n\n/**\n * Pre-materialize a block pack's template via cache.\n * Returns a copy of the spec with the template replaced by a cached reference.\n * If the template is already cached, returns the spec unchanged.\n */\nexport async function cacheBlockPackTemplate(\n pl: PlClient,\n spec: BlockPackSpecPrepared,\n options?: CacheBlockPackOptions,\n): Promise<BlockPackSpecPrepared> {\n if (spec.template.type === \"cached\") return spec;\n\n const resourceId =\n spec.template.type === \"registry-pack\" || spec.template.type === \"local-pack\"\n ? await installPackOnClient(pl, spec.template, options)\n : await loadTemplateCached(pl, spec.template, options);\n return {\n ...spec,\n template: { type: \"cached\", resourceId },\n };\n}\n\nasync function installPackOnClient(\n pl: PlClient,\n template: InstallablePackTemplate,\n options?: CacheBlockPackOptions,\n): Promise<SignedResourceId> {\n if (options?.preparer === undefined) throw new Error(\"BUG: a pack needs a preparer to load it\");\n const loaded = await options.preparer.loadPack(template);\n // The manifest may predate the requiredCapabilities field: check what the pack declares.\n throwIfMissingServerCapabilities(pl, loaded.requiredCapabilities);\n return await loadTemplateCached(pl, loaded.template, options);\n}\n"],"mappings":";;;;;;;AAuCA,MAAa,qBAAA,GAAoBA,0BAAAA,aAAAA,CAAa,iBAAiB,GAAG;AAElE,MAAa,yBAAyB;AACtC,MAAM,aAAa;;AAEnB,MAAa,sBAAsB;;AAEnC,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;AAEhC,MAAa,oBAAoB;AAiBjC,SAAS,cAAiC;CACxC,OAAO;EACL,SAAS;EACT,WAAW;EACX,aAAa;EACb,eAAe;EACf,YAAY;EACZ,WAAW;EACX,aAAa;EACb,YAAY;EACZ,WAAW;EACX,aAAa;EACb,SAAS;EACT,gBAAgB;CAClB;AACF;AAYA,SAAS,cAAc,MAAc,SAAiC,YAA4B;CAChG,QAAA,GAAOC,2BAAAA,SAAAA,CACL,QAAQ,aACR,kBAAkB,KAAK,oDAAoD,YAC7E;AACF;;;;;AASA,SAAS,UAA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,UAAU;GAGf,IAAI,OAAO,eAAA,IAAoC;IAC7C,MAAM,MAAM,IAAI,QAAQ;IACxB,KAAK,cAAc;GACrB;GAEA,OAAO,OAAO;EAChB,SAAS,GAAG;GACV,IAAI,YAAY,GAAiB,MAAM;GAEvC,KAAK,YAAY;GACjB,KAAK,cAAc;EACrB;EAGF,MAAM,IAAI,MAAM,kBAAkB;CACpC,UAAU;EACR,KAAK,UAAU,YAAY,IAAI,IAAI;EACnC,IAAIC,cAAAA,cAAc,CAAC,CAAC,sBAClB,QAAQ,IAAI,mBAAmB,KAAK,UAAU,IAAI,GAAG;CAEzD;AACF;;;;;;AAaA,eAAsB,uBACpB,IACA,MACA,SACgC;CAChC,IAAI,KAAK,SAAS,SAAS,UAAU,OAAO;CAE5C,MAAM,aACJ,KAAK,SAAS,SAAS,mBAAmB,KAAK,SAAS,SAAS,eAC7D,MAAM,oBAAoB,IAAI,KAAK,UAAU,OAAO,IACpD,MAAM,mBAAmB,IAAI,KAAK,UAAU,OAAO;CACzD,OAAO;EACL,GAAG;EACH,UAAU;GAAE,MAAM;GAAU;EAAW;CACzC;AACF;AAEA,eAAe,oBACb,IACA,UACA,SAC2B;CAC3B,IAAI,SAAS,aAAa,KAAA,GAAW,MAAM,IAAI,MAAM,yCAAyC;CAC9F,MAAM,SAAS,MAAM,QAAQ,SAAS,SAAS,QAAQ;CAEvD,8BAAA,iCAAiC,IAAI,OAAO,oBAAoB;CAChE,OAAO,MAAM,mBAAmB,IAAI,OAAO,UAAU,OAAO;AAC9D"}
@@ -1,6 +1,7 @@
1
1
  import { TemplateSpecPrepared } from "../../model/template_spec.js";
2
2
  import { BlockPackSpecPrepared } from "../../model/block_pack_spec.js";
3
3
  import "../../model/index.js";
4
+ import { BlockPackPreparer } from "../block-pack/block_pack.js";
4
5
  import { AnyResourceRef, PlClient, PlTransaction, ResourceRef, SignedResourceId } from "@milaboratories/pl-client";
5
6
  import { CompiledTemplateV3, TemplateData } from "@milaboratories/pl-model-backend";
6
7
  export declare const TemplateCacheType: import("@milaboratories/pl-client").ResourceType;
@@ -62,13 +63,16 @@ export declare function runGc(pl: PlClient, cacheRid: SignedResourceId, maxEntri
62
63
  export declare function loadTemplateCached(pl: PlClient, spec: TemplateSpecPrepared, options?: {
63
64
  cacheResourceId?: SignedResourceId;
64
65
  }): Promise<SignedResourceId>;
66
+ type CacheBlockPackOptions = {
67
+ cacheResourceId?: SignedResourceId;
68
+ /** Loads registry and local packs. */
69
+ preparer?: BlockPackPreparer;
70
+ };
65
71
  /**
66
72
  * Pre-materialize a block pack's template via cache.
67
73
  * Returns a copy of the spec with the template replaced by a cached reference.
68
74
  * If the template is already cached, returns the spec unchanged.
69
75
  */
70
- export declare function cacheBlockPackTemplate(pl: PlClient, spec: BlockPackSpecPrepared, options?: {
71
- cacheResourceId?: SignedResourceId;
72
- }): Promise<BlockPackSpecPrepared>;
76
+ export declare function cacheBlockPackTemplate(pl: PlClient, spec: BlockPackSpecPrepared, options?: CacheBlockPackOptions): Promise<BlockPackSpecPrepared>;
73
77
  export {};
74
78
  //# sourceMappingURL=template_cache.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"template_cache.d.ts","names":[],"sources":["../../../src/mutator/template/template_cache.ts"],"mappings":";;;;;qBAqCa,uDAAiB;qBAEjB;;qBAGA;;qBAEA;;qBAEA;;qBAEA;YAED;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAoBQ;;EAER;;;EAGA,SAAS,IAAI,eAAe,WAAW,oBAAoB,oBAAoB;;EAE/E;;;wBA2Vc,oBAAoB,MAAM,eAAe,qBAAqB;;wBAY9D,0BAA0B,IAAI;;wBAKxB,yBAAyB,IAAI,WAAW,QAAQ;;wBA+BhD,kBAAkB,IAAI,WAAW;;;;;;;;;wBAoBjC,MACpB,IAAI,UACJ,UAAU,kBACV,sBACC;;;;;;;wBA8LmB,mBACpB,IAAI,UACJ,MAAM,sBACN;EAAY,kBAAkB;IAC7B,QAAQ;;;;;;wBAiFW,uBACpB,IAAI,UACJ,MAAM,uBACN;EAAY,kBAAkB;IAC7B,QAAQ"}
1
+ {"version":3,"file":"template_cache.d.ts","names":[],"sources":["../../../src/mutator/template/template_cache.ts"],"mappings":";;;;;;qBAuCa,uDAAiB;qBAEjB;;qBAGA;;qBAEA;;qBAEA;;qBAEA;YAED;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAoBQ;;EAER;;;EAGA,SAAS,IAAI,eAAe,WAAW,oBAAoB,oBAAoB;;EAE/E;;;wBA2Vc,oBAAoB,MAAM,eAAe,qBAAqB;;wBAY9D,0BAA0B,IAAI;;wBAKxB,yBAAyB,IAAI,WAAW,QAAQ;;wBA+BhD,kBAAkB,IAAI,WAAW;;;;;;;;;wBAoBjC,MACpB,IAAI,UACJ,UAAU,kBACV,sBACC;;;;;;;wBA8LmB,mBACpB,IAAI,UACJ,MAAM,sBACN;EAAY,kBAAkB;IAC7B,QAAQ;KA4EN;EACH,kBAAkB;;EAElB,WAAW;;;;;;;wBAQS,uBACpB,IAAI,UACJ,MAAM,uBACN,UAAU,wBACT,QAAQ"}
@@ -1,3 +1,4 @@
1
+ import { throwIfMissingServerCapabilities } from "../block-pack/required_capabilities.js";
1
2
  import { getDebugFlags } from "../../debug/index.js";
2
3
  import { notEmpty } from "@milaboratories/ts-helpers";
3
4
  import { ensureSignedResourceIdNotNull, field, resourceType, toGlobalResourceId } from "@milaboratories/pl-client";
@@ -512,7 +513,7 @@ async function loadTemplateCached(pl, spec, options) {
512
513
  */
513
514
  async function cacheBlockPackTemplate(pl, spec, options) {
514
515
  if (spec.template.type === "cached") return spec;
515
- const resourceId = await loadTemplateCached(pl, spec.template, options);
516
+ const resourceId = spec.template.type === "registry-pack" || spec.template.type === "local-pack" ? await installPackOnClient(pl, spec.template, options) : await loadTemplateCached(pl, spec.template, options);
516
517
  return {
517
518
  ...spec,
518
519
  template: {
@@ -521,6 +522,12 @@ async function cacheBlockPackTemplate(pl, spec, options) {
521
522
  }
522
523
  };
523
524
  }
525
+ async function installPackOnClient(pl, template, options) {
526
+ if (options?.preparer === void 0) throw new Error("BUG: a pack needs a preparer to load it");
527
+ const loaded = await options.preparer.loadPack(template);
528
+ throwIfMissingServerCapabilities(pl, loaded.requiredCapabilities);
529
+ return await loadTemplateCached(pl, loaded.template, options);
530
+ }
524
531
  export { ACCESS_COUNT_KEY, ACCESS_KEY_PREFIX, GC_ACCESS_THRESHOLD, GC_MAX_ENTRIES, TemplateCacheFieldName, TemplateCacheType, cacheBlockPackTemplate, dropTemplateCache, flattenTemplateTree, getOrCreateTemplateCache, invalidateTemplateCacheId, loadTemplateCached, runGc };
525
532
 
526
533
  //# sourceMappingURL=template_cache.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"template_cache.js","names":["_"],"sources":["../../../src/mutator/template/template_cache.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type {\n AnyResourceRef,\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n} from \"@milaboratories/pl-client\";\nimport {\n ensureSignedResourceIdNotNull,\n field,\n resourceType,\n toGlobalResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n parseTemplate,\n PlTemplateLibV1,\n PlTemplateOverrideV1,\n PlTemplateSoftwareV1,\n PlTemplateV1,\n PlWasmV1,\n} from \"@milaboratories/pl-model-backend\";\nimport type {\n CompiledTemplateV3,\n TemplateData,\n TemplateDataV3,\n TemplateLibData,\n TemplateLibDataV3,\n TemplateSoftwareData,\n TemplateSoftwareDataV3,\n TemplateWasmDataV3,\n} from \"@milaboratories/pl-model-backend\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport type { BlockPackSpecPrepared } from \"../../model\";\nimport type { TemplateSpecPrepared } from \"../../model/template_spec\";\nimport { getDebugFlags } from \"../../debug\";\n\nexport const TemplateCacheType = resourceType(\"TemplateCache\", \"1\");\n\nexport const TemplateCacheFieldName = \"__templateCache\";\nconst BATCH_SIZE = 50;\n/** @internal exported for testing */\nexport const GC_ACCESS_THRESHOLD = 30;\n/** @internal exported for testing */\nexport const GC_MAX_ENTRIES = 3000;\n/** @internal exported for testing */\nexport const ACCESS_COUNT_KEY = \"_accessCount\";\n/** @internal exported for testing */\nexport const ACCESS_KEY_PREFIX = \"access_\";\n\nexport type TemplateCacheStat = {\n totalMs: number;\n flattenMs: number;\n cacheInitMs: number;\n materializeMs: number;\n totalNodes: number;\n cacheHits: number;\n cacheMisses: number;\n batchCount: number;\n happyPath: boolean;\n gcTriggered: boolean;\n retries: number;\n templateFormat: string;\n};\n\nfunction initialStat(): TemplateCacheStat {\n return {\n totalMs: 0,\n flattenMs: 0,\n cacheInitMs: 0,\n materializeMs: 0,\n totalNodes: 0,\n cacheHits: 0,\n cacheMisses: 0,\n batchCount: 0,\n happyPath: false,\n gcTriggered: false,\n retries: 0,\n templateFormat: \"\",\n };\n}\n\ninterface CacheableNode {\n /** SHA-256 content hash (includes all descendant content) */\n hash: string;\n /** Creates this node's resource in a transaction.\n * childRefs maps child hash → already-resolved ResourceRef or SignedResourceId */\n create: (tx: PlTransaction, childRefs: ReadonlyMap<string, AnyResourceRef>) => ResourceRef;\n /** Hashes of direct child nodes this node depends on */\n childHashes: string[];\n}\n\nfunction getSourceCode(name: string, sources: Record<string, string>, sourceHash: string): string {\n return notEmpty(\n sources[sourceHash],\n `trying to get \"${name}\" source: sources map doesn't contain source hash ${sourceHash}`,\n );\n}\n\n/**\n * Bottom-up hash composition: each node hashes its OWN content + child hash STRINGS.\n * This means each unique node is hashed exactly once → O(n) instead of O(n * depth).\n */\n\n// V2 leaf hashes (libs, software — no children)\n\nfunction hashLibV2(lib: TemplateLibData): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.src)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV2(sw: TemplateSoftwareData): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.src)\n .digest(\"hex\");\n}\n\n// V3 leaf hashes — use sourceHash directly instead of resolving source content\n\nfunction hashLibV3(lib: TemplateLibDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV3(sw: TemplateSoftwareDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashWasmV3(wasm: TemplateWasmDataV3): string {\n return createHash(\"sha256\")\n .update(PlWasmV1.type.name)\n .update(PlWasmV1.type.version)\n .update(wasm.name)\n .update(wasm.version)\n .update(wasm.sourceHash)\n .digest(\"hex\");\n}\n\n// ─── Tree flattening ─────────────────────────────────────────────────────────\n\nfunction flattenV2Tree(data: TemplateData): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n\n function processLib(lib: TemplateLibData): string {\n const hash = hashLibV2(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(PlTemplateLibV1.fromV2Data(lib).data),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareData): string {\n const hash = hashSoftwareV2(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV2Data(sw);\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateData): string {\n // Process children first (bottom-up) — their hashes are computed before ours\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content)\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(tpl.version)\n .update(tpl.src);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV2Data(tpl).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV2Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data);\n return nodes;\n}\n\nfunction flattenV3Tree(data: CompiledTemplateV3): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n const sources = data.hashToSource;\n\n function processLib(lib: TemplateLibDataV3): string {\n const hash = hashLibV3(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(\n PlTemplateLibV1.fromV3Data(lib, getSourceCode(lib.name, sources, lib.sourceHash))\n .data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareDataV3): string {\n const hash = hashSoftwareV3(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV3Data(\n sw,\n getSourceCode(sw.name, sources, sw.sourceHash),\n );\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processWasm(wasm: TemplateWasmDataV3): string {\n const hash = hashWasmV3(wasm);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlWasmV1.type,\n JSON.stringify(\n PlWasmV1.fromV3Data(wasm, getSourceCode(wasm.name, sources, wasm.sourceHash)).data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateDataV3): string {\n // Defensive: a template can carry no embedded version at runtime even\n // though the type says `string` — the compiler writes `packageJson.version`\n // unchecked, so a template built from a package with no `version` field\n // yields undefined. Identity is fully covered by name + sourceHash, so the\n // placeholder is safe for both the cache key and the backend resource's\n // required Version field.\n const version = tpl.version ?? \"0.0.0\";\n\n // Process children first (bottom-up)\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n for (const [wasmId, wasm] of Object.entries(tpl.wasm ?? {})) {\n const h = processWasm(wasm);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.wasmPrefix}/${wasmId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content).\n // Uses sourceHash directly — it already uniquely identifies the source.\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(version)\n .update(tpl.sourceHash);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const sourceCode = getSourceCode(tpl.name, sources, tpl.sourceHash);\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV3Data({ ...tpl, version }, sourceCode).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV3Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data.template);\n return nodes;\n}\n\n/** Flatten template tree into a topologically ordered list of cacheable nodes (leaves first). */\nexport function flattenTemplateTree(data: TemplateData | CompiledTemplateV3): CacheableNode[] {\n if (data.type === \"pl.tengo-template.v2\") {\n return flattenV2Tree(data);\n } else {\n return flattenV3Tree(data);\n }\n}\n\n/** In-memory cache for the TemplateCache SignedResourceId per PlClient instance. */\nconst cacheRidMap = new WeakMap<PlClient, SignedResourceId>();\n\n/** Clear the in-memory cacheRid entry (call on errors referencing the cache resource). */\nexport function invalidateTemplateCacheId(pl: PlClient): void {\n cacheRidMap.delete(pl);\n}\n\n/** Find or create the TemplateCache/1 resource on user root. */\nexport async function getOrCreateTemplateCache(pl: PlClient): Promise<SignedResourceId> {\n // Check in-memory cache first (0ms after first call)\n const cached = cacheRidMap.get(pl);\n if (cached !== undefined) return cached;\n\n // Try read-only check\n const existing = await pl.withReadTx(\"templateCache:check\", async (tx) => {\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n return fd ? ensureSignedResourceIdNotNull(fd.value) : undefined;\n });\n if (existing) {\n cacheRidMap.set(pl, existing);\n return existing;\n }\n\n const result = await pl.withWriteTx(\"templateCache:init\", async (tx) => {\n // Double-check inside write tx (another instance may have created it)\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n if (fd) return ensureSignedResourceIdNotNull(fd.value);\n\n const cache = tx.createStruct(TemplateCacheType);\n tx.createField(field(pl.clientRoot, TemplateCacheFieldName), \"Dynamic\", cache);\n tx.lock(cache);\n await tx.commit();\n return await cache.globalId;\n });\n cacheRidMap.set(pl, result);\n return result;\n}\n\n/** Remove the template cache from user root. */\nexport async function dropTemplateCache(pl: PlClient): Promise<void> {\n await pl.withWriteTx(\"templateCache:drop\", async (tx) => {\n const cacheField = field(pl.clientRoot, TemplateCacheFieldName);\n const fd = await tx.getFieldIfExists(cacheField);\n if (fd) {\n tx.removeField(cacheField);\n await tx.commit();\n }\n });\n invalidateTemplateCacheId(pl);\n}\n\n/**\n * Run count-based garbage collection on the template cache.\n * Evicts least-recently-used entries when the cache exceeds maxEntries.\n * Always resets the access counter to 0.\n *\n * @internal exported for testing (maxEntries parameter allows low thresholds in tests)\n * @returns true if entries were evicted\n */\nexport async function runGc(\n pl: PlClient,\n cacheRid: SignedResourceId,\n maxEntries: number = GC_MAX_ENTRIES,\n): Promise<boolean> {\n return await pl.withWriteTx(\"templateCache:gc\", async (tx) => {\n const kvs = await tx.listKeyValuesString(cacheRid);\n const entries: { hash: string; timestamp: number }[] = [];\n for (const { key, value } of kvs) {\n if (!key.startsWith(ACCESS_KEY_PREFIX)) continue;\n entries.push({\n hash: key.slice(ACCESS_KEY_PREFIX.length),\n timestamp: parseInt(value, 10),\n });\n }\n\n // Always reset counter\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, \"0\");\n\n if (entries.length <= maxEntries) {\n await tx.commit();\n return false;\n }\n\n // Sort oldest first, evict until under limit\n entries.sort((a, b) => a.timestamp - b.timestamp);\n const toEvict = entries.length - maxEntries;\n for (let i = 0; i < toEvict; i++) {\n tx.removeField(field(cacheRid, entries[i].hash));\n tx.deleteKValue(cacheRid, ACCESS_KEY_PREFIX + entries[i].hash);\n }\n\n await tx.commit();\n return true;\n });\n}\n\n/** Create a batch of cache nodes in the current transaction. */\nfunction createBatchNodes(\n tx: PlTransaction,\n cacheRid: SignedResourceId,\n batch: CacheableNode[],\n resolvedIds: ReadonlyMap<string, SignedResourceId>,\n newRefs: Map<string, ResourceRef>,\n now: string,\n): void {\n for (const node of batch) {\n const childRefs = new Map<string, AnyResourceRef>();\n for (const ch of node.childHashes) {\n const resolved = resolvedIds.get(ch) ?? newRefs.get(ch);\n if (resolved === undefined) {\n throw new Error(`BUG: child ${ch} not resolved`);\n }\n childRefs.set(ch, resolved);\n }\n const ref = node.create(tx, childRefs);\n newRefs.set(node.hash, ref);\n tx.createField(field(cacheRid, node.hash), \"Dynamic\", ref);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + node.hash, now);\n }\n}\n\n/**\n * Materialize a template tree via the cache using \"probe all + batched creation\".\n *\n * Phase 1 (single write tx):\n * - Check existence of ALL hashes in one roundtrip\n * - Happy path: if root cached, update access tracking and return\n * - Otherwise: fetch ResourceIds for all cache hits, create first batch of missing nodes\n *\n * Phase 2..N (one write tx per batch):\n * - Create remaining missing nodes in BATCH_SIZE chunks\n *\n * @returns root SignedResourceId and current access count (for GC decision)\n */\nasync function materialize(\n pl: PlClient,\n cacheRid: SignedResourceId,\n rootHash: string,\n nodes: CacheableNode[],\n stat: TemplateCacheStat,\n): Promise<{ rootId: SignedResourceId; accessCount: number }> {\n const allHashes = nodes.map((n) => n.hash);\n const resolvedIds = new Map<string, SignedResourceId>();\n\n // Phase 1: probe all + first batch\n const phase1 = await pl.withWriteTx(\"templateCache:materialize\", async (tx) => {\n // 1 roundtrip: check all hashes + read access count\n const [exists, countStr] = await Promise.all([\n Promise.all(allHashes.map((h) => tx.fieldExists(field(cacheRid, h)))),\n tx.getKValueStringIfExists(cacheRid, ACCESS_COUNT_KEY),\n ]);\n\n const prevCount = countStr ? parseInt(countStr, 10) : 0;\n const newCount = prevCount + 1;\n const now = Date.now().toString();\n const rootIdx = allHashes.length - 1;\n\n // Happy path: root already cached\n if (exists[rootIdx]) {\n const rootFd = await tx.getField(field(cacheRid, rootHash));\n const rootRid = ensureSignedResourceIdNotNull(rootFd.value);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + rootHash, now);\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n await tx.commit();\n stat.happyPath = true;\n stat.cacheHits = stat.totalNodes;\n stat.batchCount = 1;\n return { done: true as const, rootId: rootRid, accessCount: newCount };\n }\n\n // Fetch ResourceIds for all cache hits (1 roundtrip)\n const hitIndices: number[] = [];\n for (let i = 0; i < allHashes.length; i++) {\n if (exists[i]) hitIndices.push(i);\n }\n\n if (hitIndices.length > 0) {\n const hitFields = await Promise.all(\n hitIndices.map((i) => tx.getField(field(cacheRid, allHashes[i]))),\n );\n for (let j = 0; j < hitIndices.length; j++) {\n resolvedIds.set(\n allHashes[hitIndices[j]],\n ensureSignedResourceIdNotNull(hitFields[j].value),\n );\n }\n }\n stat.cacheHits = hitIndices.length;\n\n // Missing nodes (topo order preserved from flatten)\n const missing = nodes.filter((n) => !resolvedIds.has(n.hash));\n stat.cacheMisses = missing.length;\n\n // Create first batch of missing nodes\n const firstBatch = missing.slice(0, BATCH_SIZE);\n const newRefs = new Map<string, ResourceRef>();\n createBatchNodes(tx, cacheRid, firstBatch, resolvedIds, newRefs, now);\n\n // Update access tracking for cache hits\n for (const i of hitIndices) {\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + allHashes[i], now);\n }\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n\n await tx.commit();\n\n // Resolve new refs to global IDs (after commit)\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n\n return {\n done: false as const,\n remaining: missing.slice(BATCH_SIZE),\n accessCount: newCount,\n };\n });\n\n if (phase1.done) {\n return { rootId: phase1.rootId, accessCount: phase1.accessCount };\n }\n\n stat.batchCount = 1;\n\n // Phase 2+: remaining batches\n const { remaining } = phase1;\n for (let i = 0; i < remaining.length; i += BATCH_SIZE) {\n const batch = remaining.slice(i, i + BATCH_SIZE);\n stat.batchCount++;\n\n await pl.withWriteTx(\"templateCache:create\", async (tx) => {\n const newRefs = new Map<string, ResourceRef>();\n const now = Date.now().toString();\n createBatchNodes(tx, cacheRid, batch, resolvedIds, newRefs, now);\n await tx.commit();\n\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n });\n }\n\n const rootId = resolvedIds.get(rootHash);\n if (!rootId) throw new Error(\"BUG: root hash not resolved after all batches\");\n return { rootId, accessCount: phase1.accessCount };\n}\n\n/**\n * Materialize a template tree via the cache.\n * Manages its own transactions internally — do NOT call inside an existing tx.\n *\n * @returns concrete SignedResourceId of the root template\n */\nexport async function loadTemplateCached(\n pl: PlClient,\n spec: TemplateSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<SignedResourceId> {\n const stat = initialStat();\n const t0 = performance.now();\n\n try {\n // Parse to data if needed\n let tplData: TemplateData | CompiledTemplateV3;\n switch (spec.type) {\n case \"explicit\":\n tplData = parseTemplate(spec.content);\n break;\n case \"prepared\":\n tplData = spec.data;\n break;\n case \"cached\":\n return spec.resourceId;\n case \"from-registry\":\n throw new Error(\n \"loadTemplateCached does not support from-registry specs; use loadTemplate instead\",\n );\n default: {\n const _: never = spec;\n throw new Error(`unexpected spec type: ${(_ as any).type}`);\n }\n }\n\n stat.templateFormat = tplData.type;\n\n // Flatten to ordered nodes\n const tFlatten = performance.now();\n const nodes = flattenTemplateTree(tplData);\n stat.flattenMs = performance.now() - tFlatten;\n if (nodes.length === 0) throw new Error(\"template tree produced no nodes\");\n\n stat.totalNodes = nodes.length;\n const rootHash = nodes[nodes.length - 1].hash;\n\n // Resolve or create cache resource\n const tCacheInit = performance.now();\n const cacheRid = options?.cacheResourceId ?? (await getOrCreateTemplateCache(pl));\n stat.cacheInitMs = performance.now() - tCacheInit;\n\n // Retry loop: if a write tx fails (e.g. concurrent GC invalidated a cached resource),\n // restart materialization from scratch.\n const MAX_RETRIES = 3;\n for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {\n try {\n const tMat = performance.now();\n const result = await materialize(pl, cacheRid, rootHash, nodes, stat);\n stat.materializeMs = performance.now() - tMat;\n stat.retries = attempt;\n\n // GC in separate tx if access count exceeded threshold\n if (result.accessCount >= GC_ACCESS_THRESHOLD) {\n await runGc(pl, cacheRid);\n stat.gcTriggered = true;\n }\n\n return result.rootId;\n } catch (e) {\n if (attempt === MAX_RETRIES - 1) throw e;\n // Retry from scratch — previous batch results may reference GC'd resources\n stat.cacheHits = 0;\n stat.cacheMisses = 0;\n }\n }\n\n throw new Error(\"BUG: unreachable\");\n } finally {\n stat.totalMs = performance.now() - t0;\n if (getDebugFlags().logTemplateCacheStat) {\n console.log(`[templateCache] ${JSON.stringify(stat)}`);\n }\n }\n}\n\n/**\n * Pre-materialize a block pack's template via cache.\n * Returns a copy of the spec with the template replaced by a cached reference.\n * If the template is already cached, returns the spec unchanged.\n */\nexport async function cacheBlockPackTemplate(\n pl: PlClient,\n spec: BlockPackSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<BlockPackSpecPrepared> {\n if (spec.template.type === \"cached\") return spec;\n\n const resourceId = await loadTemplateCached(pl, spec.template, options);\n return {\n ...spec,\n template: { type: \"cached\", resourceId },\n };\n}\n"],"mappings":";;;;;;AAqCA,MAAa,oBAAoB,aAAa,iBAAiB,GAAG;AAElE,MAAa,yBAAyB;AACtC,MAAM,aAAa;;AAEnB,MAAa,sBAAsB;;AAEnC,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;AAEhC,MAAa,oBAAoB;AAiBjC,SAAS,cAAiC;CACxC,OAAO;EACL,SAAS;EACT,WAAW;EACX,aAAa;EACb,eAAe;EACf,YAAY;EACZ,WAAW;EACX,aAAa;EACb,YAAY;EACZ,WAAW;EACX,aAAa;EACb,SAAS;EACT,gBAAgB;CAClB;AACF;AAYA,SAAS,cAAc,MAAc,SAAiC,YAA4B;CAChG,OAAO,SACL,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,EAAE;EAC/E,KAAK,cAAc,YAAY,IAAI,IAAI;EAIvC,MAAM,cAAc;EACpB,KAAK,IAAI,UAAU,GAAG,UAAU,aAAa,WAC3C,IAAI;GACF,MAAM,OAAO,YAAY,IAAI;GAC7B,MAAM,SAAS,MAAM,YAAY,IAAI,UAAU,UAAU,OAAO,IAAI;GACpE,KAAK,gBAAgB,YAAY,IAAI,IAAI;GACzC,KAAK,UAAU;GAGf,IAAI,OAAO,eAAA,IAAoC;IAC7C,MAAM,MAAM,IAAI,QAAQ;IACxB,KAAK,cAAc;GACrB;GAEA,OAAO,OAAO;EAChB,SAAS,GAAG;GACV,IAAI,YAAY,GAAiB,MAAM;GAEvC,KAAK,YAAY;GACjB,KAAK,cAAc;EACrB;EAGF,MAAM,IAAI,MAAM,kBAAkB;CACpC,UAAU;EACR,KAAK,UAAU,YAAY,IAAI,IAAI;EACnC,IAAI,cAAc,CAAC,CAAC,sBAClB,QAAQ,IAAI,mBAAmB,KAAK,UAAU,IAAI,GAAG;CAEzD;AACF;;;;;;AAOA,eAAsB,uBACpB,IACA,MACA,SACgC;CAChC,IAAI,KAAK,SAAS,SAAS,UAAU,OAAO;CAE5C,MAAM,aAAa,MAAM,mBAAmB,IAAI,KAAK,UAAU,OAAO;CACtE,OAAO;EACL,GAAG;EACH,UAAU;GAAE,MAAM;GAAU;EAAW;CACzC;AACF"}
1
+ {"version":3,"file":"template_cache.js","names":["_"],"sources":["../../../src/mutator/template/template_cache.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type {\n AnyResourceRef,\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n} from \"@milaboratories/pl-client\";\nimport {\n ensureSignedResourceIdNotNull,\n field,\n resourceType,\n toGlobalResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n parseTemplate,\n PlTemplateLibV1,\n PlTemplateOverrideV1,\n PlTemplateSoftwareV1,\n PlTemplateV1,\n PlWasmV1,\n} from \"@milaboratories/pl-model-backend\";\nimport type {\n CompiledTemplateV3,\n TemplateData,\n TemplateDataV3,\n TemplateLibData,\n TemplateLibDataV3,\n TemplateSoftwareData,\n TemplateSoftwareDataV3,\n TemplateWasmDataV3,\n} from \"@milaboratories/pl-model-backend\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport type { BlockPackSpecPrepared } from \"../../model\";\nimport type { InstallablePackTemplate, TemplateSpecPrepared } from \"../../model/template_spec\";\nimport type { BlockPackPreparer } from \"../block-pack/block_pack\";\nimport { throwIfMissingServerCapabilities } from \"../block-pack/required_capabilities\";\nimport { getDebugFlags } from \"../../debug\";\n\nexport const TemplateCacheType = resourceType(\"TemplateCache\", \"1\");\n\nexport const TemplateCacheFieldName = \"__templateCache\";\nconst BATCH_SIZE = 50;\n/** @internal exported for testing */\nexport const GC_ACCESS_THRESHOLD = 30;\n/** @internal exported for testing */\nexport const GC_MAX_ENTRIES = 3000;\n/** @internal exported for testing */\nexport const ACCESS_COUNT_KEY = \"_accessCount\";\n/** @internal exported for testing */\nexport const ACCESS_KEY_PREFIX = \"access_\";\n\nexport type TemplateCacheStat = {\n totalMs: number;\n flattenMs: number;\n cacheInitMs: number;\n materializeMs: number;\n totalNodes: number;\n cacheHits: number;\n cacheMisses: number;\n batchCount: number;\n happyPath: boolean;\n gcTriggered: boolean;\n retries: number;\n templateFormat: string;\n};\n\nfunction initialStat(): TemplateCacheStat {\n return {\n totalMs: 0,\n flattenMs: 0,\n cacheInitMs: 0,\n materializeMs: 0,\n totalNodes: 0,\n cacheHits: 0,\n cacheMisses: 0,\n batchCount: 0,\n happyPath: false,\n gcTriggered: false,\n retries: 0,\n templateFormat: \"\",\n };\n}\n\ninterface CacheableNode {\n /** SHA-256 content hash (includes all descendant content) */\n hash: string;\n /** Creates this node's resource in a transaction.\n * childRefs maps child hash → already-resolved ResourceRef or SignedResourceId */\n create: (tx: PlTransaction, childRefs: ReadonlyMap<string, AnyResourceRef>) => ResourceRef;\n /** Hashes of direct child nodes this node depends on */\n childHashes: string[];\n}\n\nfunction getSourceCode(name: string, sources: Record<string, string>, sourceHash: string): string {\n return notEmpty(\n sources[sourceHash],\n `trying to get \"${name}\" source: sources map doesn't contain source hash ${sourceHash}`,\n );\n}\n\n/**\n * Bottom-up hash composition: each node hashes its OWN content + child hash STRINGS.\n * This means each unique node is hashed exactly once → O(n) instead of O(n * depth).\n */\n\n// V2 leaf hashes (libs, software — no children)\n\nfunction hashLibV2(lib: TemplateLibData): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.src)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV2(sw: TemplateSoftwareData): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.src)\n .digest(\"hex\");\n}\n\n// V3 leaf hashes — use sourceHash directly instead of resolving source content\n\nfunction hashLibV3(lib: TemplateLibDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV3(sw: TemplateSoftwareDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashWasmV3(wasm: TemplateWasmDataV3): string {\n return createHash(\"sha256\")\n .update(PlWasmV1.type.name)\n .update(PlWasmV1.type.version)\n .update(wasm.name)\n .update(wasm.version)\n .update(wasm.sourceHash)\n .digest(\"hex\");\n}\n\n// ─── Tree flattening ─────────────────────────────────────────────────────────\n\nfunction flattenV2Tree(data: TemplateData): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n\n function processLib(lib: TemplateLibData): string {\n const hash = hashLibV2(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(PlTemplateLibV1.fromV2Data(lib).data),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareData): string {\n const hash = hashSoftwareV2(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV2Data(sw);\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateData): string {\n // Process children first (bottom-up) — their hashes are computed before ours\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content)\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(tpl.version)\n .update(tpl.src);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV2Data(tpl).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV2Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data);\n return nodes;\n}\n\nfunction flattenV3Tree(data: CompiledTemplateV3): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n const sources = data.hashToSource;\n\n function processLib(lib: TemplateLibDataV3): string {\n const hash = hashLibV3(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(\n PlTemplateLibV1.fromV3Data(lib, getSourceCode(lib.name, sources, lib.sourceHash))\n .data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareDataV3): string {\n const hash = hashSoftwareV3(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV3Data(\n sw,\n getSourceCode(sw.name, sources, sw.sourceHash),\n );\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processWasm(wasm: TemplateWasmDataV3): string {\n const hash = hashWasmV3(wasm);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlWasmV1.type,\n JSON.stringify(\n PlWasmV1.fromV3Data(wasm, getSourceCode(wasm.name, sources, wasm.sourceHash)).data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateDataV3): string {\n // Defensive: a template can carry no embedded version at runtime even\n // though the type says `string` — the compiler writes `packageJson.version`\n // unchecked, so a template built from a package with no `version` field\n // yields undefined. Identity is fully covered by name + sourceHash, so the\n // placeholder is safe for both the cache key and the backend resource's\n // required Version field.\n const version = tpl.version ?? \"0.0.0\";\n\n // Process children first (bottom-up)\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n for (const [wasmId, wasm] of Object.entries(tpl.wasm ?? {})) {\n const h = processWasm(wasm);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.wasmPrefix}/${wasmId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content).\n // Uses sourceHash directly — it already uniquely identifies the source.\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(version)\n .update(tpl.sourceHash);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const sourceCode = getSourceCode(tpl.name, sources, tpl.sourceHash);\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV3Data({ ...tpl, version }, sourceCode).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV3Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data.template);\n return nodes;\n}\n\n/** Flatten template tree into a topologically ordered list of cacheable nodes (leaves first). */\nexport function flattenTemplateTree(data: TemplateData | CompiledTemplateV3): CacheableNode[] {\n if (data.type === \"pl.tengo-template.v2\") {\n return flattenV2Tree(data);\n } else {\n return flattenV3Tree(data);\n }\n}\n\n/** In-memory cache for the TemplateCache SignedResourceId per PlClient instance. */\nconst cacheRidMap = new WeakMap<PlClient, SignedResourceId>();\n\n/** Clear the in-memory cacheRid entry (call on errors referencing the cache resource). */\nexport function invalidateTemplateCacheId(pl: PlClient): void {\n cacheRidMap.delete(pl);\n}\n\n/** Find or create the TemplateCache/1 resource on user root. */\nexport async function getOrCreateTemplateCache(pl: PlClient): Promise<SignedResourceId> {\n // Check in-memory cache first (0ms after first call)\n const cached = cacheRidMap.get(pl);\n if (cached !== undefined) return cached;\n\n // Try read-only check\n const existing = await pl.withReadTx(\"templateCache:check\", async (tx) => {\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n return fd ? ensureSignedResourceIdNotNull(fd.value) : undefined;\n });\n if (existing) {\n cacheRidMap.set(pl, existing);\n return existing;\n }\n\n const result = await pl.withWriteTx(\"templateCache:init\", async (tx) => {\n // Double-check inside write tx (another instance may have created it)\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n if (fd) return ensureSignedResourceIdNotNull(fd.value);\n\n const cache = tx.createStruct(TemplateCacheType);\n tx.createField(field(pl.clientRoot, TemplateCacheFieldName), \"Dynamic\", cache);\n tx.lock(cache);\n await tx.commit();\n return await cache.globalId;\n });\n cacheRidMap.set(pl, result);\n return result;\n}\n\n/** Remove the template cache from user root. */\nexport async function dropTemplateCache(pl: PlClient): Promise<void> {\n await pl.withWriteTx(\"templateCache:drop\", async (tx) => {\n const cacheField = field(pl.clientRoot, TemplateCacheFieldName);\n const fd = await tx.getFieldIfExists(cacheField);\n if (fd) {\n tx.removeField(cacheField);\n await tx.commit();\n }\n });\n invalidateTemplateCacheId(pl);\n}\n\n/**\n * Run count-based garbage collection on the template cache.\n * Evicts least-recently-used entries when the cache exceeds maxEntries.\n * Always resets the access counter to 0.\n *\n * @internal exported for testing (maxEntries parameter allows low thresholds in tests)\n * @returns true if entries were evicted\n */\nexport async function runGc(\n pl: PlClient,\n cacheRid: SignedResourceId,\n maxEntries: number = GC_MAX_ENTRIES,\n): Promise<boolean> {\n return await pl.withWriteTx(\"templateCache:gc\", async (tx) => {\n const kvs = await tx.listKeyValuesString(cacheRid);\n const entries: { hash: string; timestamp: number }[] = [];\n for (const { key, value } of kvs) {\n if (!key.startsWith(ACCESS_KEY_PREFIX)) continue;\n entries.push({\n hash: key.slice(ACCESS_KEY_PREFIX.length),\n timestamp: parseInt(value, 10),\n });\n }\n\n // Always reset counter\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, \"0\");\n\n if (entries.length <= maxEntries) {\n await tx.commit();\n return false;\n }\n\n // Sort oldest first, evict until under limit\n entries.sort((a, b) => a.timestamp - b.timestamp);\n const toEvict = entries.length - maxEntries;\n for (let i = 0; i < toEvict; i++) {\n tx.removeField(field(cacheRid, entries[i].hash));\n tx.deleteKValue(cacheRid, ACCESS_KEY_PREFIX + entries[i].hash);\n }\n\n await tx.commit();\n return true;\n });\n}\n\n/** Create a batch of cache nodes in the current transaction. */\nfunction createBatchNodes(\n tx: PlTransaction,\n cacheRid: SignedResourceId,\n batch: CacheableNode[],\n resolvedIds: ReadonlyMap<string, SignedResourceId>,\n newRefs: Map<string, ResourceRef>,\n now: string,\n): void {\n for (const node of batch) {\n const childRefs = new Map<string, AnyResourceRef>();\n for (const ch of node.childHashes) {\n const resolved = resolvedIds.get(ch) ?? newRefs.get(ch);\n if (resolved === undefined) {\n throw new Error(`BUG: child ${ch} not resolved`);\n }\n childRefs.set(ch, resolved);\n }\n const ref = node.create(tx, childRefs);\n newRefs.set(node.hash, ref);\n tx.createField(field(cacheRid, node.hash), \"Dynamic\", ref);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + node.hash, now);\n }\n}\n\n/**\n * Materialize a template tree via the cache using \"probe all + batched creation\".\n *\n * Phase 1 (single write tx):\n * - Check existence of ALL hashes in one roundtrip\n * - Happy path: if root cached, update access tracking and return\n * - Otherwise: fetch ResourceIds for all cache hits, create first batch of missing nodes\n *\n * Phase 2..N (one write tx per batch):\n * - Create remaining missing nodes in BATCH_SIZE chunks\n *\n * @returns root SignedResourceId and current access count (for GC decision)\n */\nasync function materialize(\n pl: PlClient,\n cacheRid: SignedResourceId,\n rootHash: string,\n nodes: CacheableNode[],\n stat: TemplateCacheStat,\n): Promise<{ rootId: SignedResourceId; accessCount: number }> {\n const allHashes = nodes.map((n) => n.hash);\n const resolvedIds = new Map<string, SignedResourceId>();\n\n // Phase 1: probe all + first batch\n const phase1 = await pl.withWriteTx(\"templateCache:materialize\", async (tx) => {\n // 1 roundtrip: check all hashes + read access count\n const [exists, countStr] = await Promise.all([\n Promise.all(allHashes.map((h) => tx.fieldExists(field(cacheRid, h)))),\n tx.getKValueStringIfExists(cacheRid, ACCESS_COUNT_KEY),\n ]);\n\n const prevCount = countStr ? parseInt(countStr, 10) : 0;\n const newCount = prevCount + 1;\n const now = Date.now().toString();\n const rootIdx = allHashes.length - 1;\n\n // Happy path: root already cached\n if (exists[rootIdx]) {\n const rootFd = await tx.getField(field(cacheRid, rootHash));\n const rootRid = ensureSignedResourceIdNotNull(rootFd.value);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + rootHash, now);\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n await tx.commit();\n stat.happyPath = true;\n stat.cacheHits = stat.totalNodes;\n stat.batchCount = 1;\n return { done: true as const, rootId: rootRid, accessCount: newCount };\n }\n\n // Fetch ResourceIds for all cache hits (1 roundtrip)\n const hitIndices: number[] = [];\n for (let i = 0; i < allHashes.length; i++) {\n if (exists[i]) hitIndices.push(i);\n }\n\n if (hitIndices.length > 0) {\n const hitFields = await Promise.all(\n hitIndices.map((i) => tx.getField(field(cacheRid, allHashes[i]))),\n );\n for (let j = 0; j < hitIndices.length; j++) {\n resolvedIds.set(\n allHashes[hitIndices[j]],\n ensureSignedResourceIdNotNull(hitFields[j].value),\n );\n }\n }\n stat.cacheHits = hitIndices.length;\n\n // Missing nodes (topo order preserved from flatten)\n const missing = nodes.filter((n) => !resolvedIds.has(n.hash));\n stat.cacheMisses = missing.length;\n\n // Create first batch of missing nodes\n const firstBatch = missing.slice(0, BATCH_SIZE);\n const newRefs = new Map<string, ResourceRef>();\n createBatchNodes(tx, cacheRid, firstBatch, resolvedIds, newRefs, now);\n\n // Update access tracking for cache hits\n for (const i of hitIndices) {\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + allHashes[i], now);\n }\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n\n await tx.commit();\n\n // Resolve new refs to global IDs (after commit)\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n\n return {\n done: false as const,\n remaining: missing.slice(BATCH_SIZE),\n accessCount: newCount,\n };\n });\n\n if (phase1.done) {\n return { rootId: phase1.rootId, accessCount: phase1.accessCount };\n }\n\n stat.batchCount = 1;\n\n // Phase 2+: remaining batches\n const { remaining } = phase1;\n for (let i = 0; i < remaining.length; i += BATCH_SIZE) {\n const batch = remaining.slice(i, i + BATCH_SIZE);\n stat.batchCount++;\n\n await pl.withWriteTx(\"templateCache:create\", async (tx) => {\n const newRefs = new Map<string, ResourceRef>();\n const now = Date.now().toString();\n createBatchNodes(tx, cacheRid, batch, resolvedIds, newRefs, now);\n await tx.commit();\n\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n });\n }\n\n const rootId = resolvedIds.get(rootHash);\n if (!rootId) throw new Error(\"BUG: root hash not resolved after all batches\");\n return { rootId, accessCount: phase1.accessCount };\n}\n\n/**\n * Materialize a template tree via the cache.\n * Manages its own transactions internally — do NOT call inside an existing tx.\n *\n * @returns concrete SignedResourceId of the root template\n */\nexport async function loadTemplateCached(\n pl: PlClient,\n spec: TemplateSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<SignedResourceId> {\n const stat = initialStat();\n const t0 = performance.now();\n\n try {\n // Parse to data if needed\n let tplData: TemplateData | CompiledTemplateV3;\n switch (spec.type) {\n case \"explicit\":\n tplData = parseTemplate(spec.content);\n break;\n case \"prepared\":\n tplData = spec.data;\n break;\n case \"cached\":\n return spec.resourceId;\n case \"from-registry\":\n throw new Error(\n \"loadTemplateCached does not support from-registry specs; use loadTemplate instead\",\n );\n default: {\n const _: never = spec;\n throw new Error(`unexpected spec type: ${(_ as any).type}`);\n }\n }\n\n stat.templateFormat = tplData.type;\n\n // Flatten to ordered nodes\n const tFlatten = performance.now();\n const nodes = flattenTemplateTree(tplData);\n stat.flattenMs = performance.now() - tFlatten;\n if (nodes.length === 0) throw new Error(\"template tree produced no nodes\");\n\n stat.totalNodes = nodes.length;\n const rootHash = nodes[nodes.length - 1].hash;\n\n // Resolve or create cache resource\n const tCacheInit = performance.now();\n const cacheRid = options?.cacheResourceId ?? (await getOrCreateTemplateCache(pl));\n stat.cacheInitMs = performance.now() - tCacheInit;\n\n // Retry loop: if a write tx fails (e.g. concurrent GC invalidated a cached resource),\n // restart materialization from scratch.\n const MAX_RETRIES = 3;\n for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {\n try {\n const tMat = performance.now();\n const result = await materialize(pl, cacheRid, rootHash, nodes, stat);\n stat.materializeMs = performance.now() - tMat;\n stat.retries = attempt;\n\n // GC in separate tx if access count exceeded threshold\n if (result.accessCount >= GC_ACCESS_THRESHOLD) {\n await runGc(pl, cacheRid);\n stat.gcTriggered = true;\n }\n\n return result.rootId;\n } catch (e) {\n if (attempt === MAX_RETRIES - 1) throw e;\n // Retry from scratch — previous batch results may reference GC'd resources\n stat.cacheHits = 0;\n stat.cacheMisses = 0;\n }\n }\n\n throw new Error(\"BUG: unreachable\");\n } finally {\n stat.totalMs = performance.now() - t0;\n if (getDebugFlags().logTemplateCacheStat) {\n console.log(`[templateCache] ${JSON.stringify(stat)}`);\n }\n }\n}\n\ntype CacheBlockPackOptions = {\n cacheResourceId?: SignedResourceId;\n /** Loads registry and local packs. */\n preparer?: BlockPackPreparer;\n};\n\n/**\n * Pre-materialize a block pack's template via cache.\n * Returns a copy of the spec with the template replaced by a cached reference.\n * If the template is already cached, returns the spec unchanged.\n */\nexport async function cacheBlockPackTemplate(\n pl: PlClient,\n spec: BlockPackSpecPrepared,\n options?: CacheBlockPackOptions,\n): Promise<BlockPackSpecPrepared> {\n if (spec.template.type === \"cached\") return spec;\n\n const resourceId =\n spec.template.type === \"registry-pack\" || spec.template.type === \"local-pack\"\n ? await installPackOnClient(pl, spec.template, options)\n : await loadTemplateCached(pl, spec.template, options);\n return {\n ...spec,\n template: { type: \"cached\", resourceId },\n };\n}\n\nasync function installPackOnClient(\n pl: PlClient,\n template: InstallablePackTemplate,\n options?: CacheBlockPackOptions,\n): Promise<SignedResourceId> {\n if (options?.preparer === undefined) throw new Error(\"BUG: a pack needs a preparer to load it\");\n const loaded = await options.preparer.loadPack(template);\n // The manifest may predate the requiredCapabilities field: check what the pack declares.\n throwIfMissingServerCapabilities(pl, loaded.requiredCapabilities);\n return await loadTemplateCached(pl, loaded.template, options);\n}\n"],"mappings":";;;;;;;AAuCA,MAAa,oBAAoB,aAAa,iBAAiB,GAAG;AAElE,MAAa,yBAAyB;AACtC,MAAM,aAAa;;AAEnB,MAAa,sBAAsB;;AAEnC,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;AAEhC,MAAa,oBAAoB;AAiBjC,SAAS,cAAiC;CACxC,OAAO;EACL,SAAS;EACT,WAAW;EACX,aAAa;EACb,eAAe;EACf,YAAY;EACZ,WAAW;EACX,aAAa;EACb,YAAY;EACZ,WAAW;EACX,aAAa;EACb,SAAS;EACT,gBAAgB;CAClB;AACF;AAYA,SAAS,cAAc,MAAc,SAAiC,YAA4B;CAChG,OAAO,SACL,QAAQ,aACR,kBAAkB,KAAK,oDAAoD,YAC7E;AACF;;;;;AASA,SAAS,UAAU,KAA8B;CAC/C,OAAO,WAAW,QAAQ,CAAC,CACxB,OAAO,gBAAgB,KAAK,IAAI,CAAC,CACjC,OAAO,gBAAgB,KAAK,OAAO,CAAC,CACpC,OAAO,IAAI,IAAI,CAAC,CAChB,OAAO,IAAI,OAAO,CAAC,CACnB,OAAO,IAAI,GAAG,CAAC,CACf,OAAO,KAAK;AACjB;AAEA,SAAS,eAAe,IAAkC;CACxD,OAAO,WAAW,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cAAc;GACrB;GAEA,OAAO,OAAO;EAChB,SAAS,GAAG;GACV,IAAI,YAAY,GAAiB,MAAM;GAEvC,KAAK,YAAY;GACjB,KAAK,cAAc;EACrB;EAGF,MAAM,IAAI,MAAM,kBAAkB;CACpC,UAAU;EACR,KAAK,UAAU,YAAY,IAAI,IAAI;EACnC,IAAI,cAAc,CAAC,CAAC,sBAClB,QAAQ,IAAI,mBAAmB,KAAK,UAAU,IAAI,GAAG;CAEzD;AACF;;;;;;AAaA,eAAsB,uBACpB,IACA,MACA,SACgC;CAChC,IAAI,KAAK,SAAS,SAAS,UAAU,OAAO;CAE5C,MAAM,aACJ,KAAK,SAAS,SAAS,mBAAmB,KAAK,SAAS,SAAS,eAC7D,MAAM,oBAAoB,IAAI,KAAK,UAAU,OAAO,IACpD,MAAM,mBAAmB,IAAI,KAAK,UAAU,OAAO;CACzD,OAAO;EACL,GAAG;EACH,UAAU;GAAE,MAAM;GAAU;EAAW;CACzC;AACF;AAEA,eAAe,oBACb,IACA,UACA,SAC2B;CAC3B,IAAI,SAAS,aAAa,KAAA,GAAW,MAAM,IAAI,MAAM,yCAAyC;CAC9F,MAAM,SAAS,MAAM,QAAQ,SAAS,SAAS,QAAQ;CAEvD,iCAAiC,IAAI,OAAO,oBAAoB;CAChE,OAAO,MAAM,mBAAmB,IAAI,OAAO,UAAU,OAAO;AAC9D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milaboratories/pl-middle-layer",
3
- "version": "2.9.1",
3
+ "version": "2.10.1",
4
4
  "description": "Pl Middle Layer",
5
5
  "keywords": [],
6
6
  "license": "UNLICENSED",
@@ -22,8 +22,8 @@
22
22
  "@milaboratories/columns-collection-driver": "0.3.4",
23
23
  "@milaboratories/computable": "2.9.10",
24
24
  "@milaboratories/helpers": "1.14.7",
25
- "@milaboratories/pf-driver": "1.9.24",
26
- "@milaboratories/pf-spec-driver": "1.6.6",
25
+ "@milaboratories/pf-driver": "1.9.25",
26
+ "@milaboratories/pf-spec-driver": "1.6.7",
27
27
  "@milaboratories/pframes-rs-node": "1.3.1",
28
28
  "@milaboratories/pl-client": "3.28.2",
29
29
  "@milaboratories/pl-crash-recorder": "0.3.16",
@@ -32,12 +32,12 @@
32
32
  "@milaboratories/pl-http": "1.2.7",
33
33
  "@milaboratories/pl-model-backend": "1.4.58",
34
34
  "@milaboratories/pl-model-common": "1.60.0",
35
- "@milaboratories/pl-model-middle-layer": "1.41.4",
35
+ "@milaboratories/pl-model-middle-layer": "1.41.5",
36
36
  "@milaboratories/pl-tree": "1.18.13",
37
37
  "@milaboratories/resolve-helper": "1.1.3",
38
38
  "@milaboratories/ts-helpers": "1.9.1",
39
- "@platforma-sdk/block-tools": "2.22.5",
40
- "@platforma-sdk/model": "1.96.1",
39
+ "@platforma-sdk/block-tools": "2.23.0",
40
+ "@platforma-sdk/model": "1.96.4",
41
41
  "@platforma-sdk/workflow-tengo": "7.2.0",
42
42
  "canonicalize": "~2.1.0",
43
43
  "denque": "^2.1.0",
@@ -1,6 +1,8 @@
1
1
  export { MiddleLayer } from "./middle_layer";
2
2
  export { Project } from "./project";
3
3
  export type { AddBlockOps } from "./project";
4
+ export type { ProjectHandle, ProjectHandleEnd, ProjectHolder } from "./project_holds";
5
+ export { asProjectHolder, isProjectInUseError, ProjectInUseError } from "./project_holds";
4
6
  export * from "./driver_kit";
5
7
  export * from "./ops";
6
8
  export type { TreeSnapshotMiss, TreeSnapshotStat } from "./tree_snapshot_store";