@milaboratories/pl-middle-layer 2.10.1 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/dist/block_registry/registry-v2-provider.cjs +8 -1
  2. package/dist/block_registry/registry-v2-provider.cjs.map +1 -1
  3. package/dist/block_registry/registry-v2-provider.d.ts.map +1 -1
  4. package/dist/block_registry/registry-v2-provider.js +8 -1
  5. package/dist/block_registry/registry-v2-provider.js.map +1 -1
  6. package/dist/index.cjs +24 -0
  7. package/dist/index.d.ts +11 -4
  8. package/dist/index.js +4 -2
  9. package/dist/js_render/bundle_bytecode_cache.cjs +6 -1
  10. package/dist/js_render/bundle_bytecode_cache.cjs.map +1 -1
  11. package/dist/js_render/bundle_bytecode_cache.js +6 -1
  12. package/dist/js_render/bundle_bytecode_cache.js.map +1 -1
  13. package/dist/js_render/column_registry.cjs +17 -0
  14. package/dist/js_render/column_registry.cjs.map +1 -1
  15. package/dist/js_render/column_registry.js +16 -1
  16. package/dist/js_render/column_registry.js.map +1 -1
  17. package/dist/js_render/computable_context.cjs +1 -1
  18. package/dist/js_render/computable_context.js +1 -1
  19. package/dist/js_render/context.cjs +3 -2
  20. package/dist/js_render/context.cjs.map +1 -1
  21. package/dist/js_render/context.js +3 -2
  22. package/dist/js_render/context.js.map +1 -1
  23. package/dist/js_render/index.cjs +1 -1
  24. package/dist/js_render/index.cjs.map +1 -1
  25. package/dist/js_render/index.js +1 -1
  26. package/dist/js_render/index.js.map +1 -1
  27. package/dist/js_render/service_injectors.cjs +2 -9
  28. package/dist/js_render/service_injectors.cjs.map +1 -1
  29. package/dist/js_render/service_injectors.js +2 -9
  30. package/dist/js_render/service_injectors.js.map +1 -1
  31. package/dist/middle_layer/block.cjs +48 -0
  32. package/dist/middle_layer/block.cjs.map +1 -1
  33. package/dist/middle_layer/block.js +51 -4
  34. package/dist/middle_layer/block.js.map +1 -1
  35. package/dist/middle_layer/block_pack_description.cjs +80 -0
  36. package/dist/middle_layer/block_pack_description.cjs.map +1 -0
  37. package/dist/middle_layer/block_pack_description.d.ts +36 -0
  38. package/dist/middle_layer/block_pack_description.d.ts.map +1 -0
  39. package/dist/middle_layer/block_pack_description.js +78 -0
  40. package/dist/middle_layer/block_pack_description.js.map +1 -0
  41. package/dist/middle_layer/build_stamp.cjs +1 -1
  42. package/dist/middle_layer/build_stamp.js +1 -1
  43. package/dist/middle_layer/index.cjs +11 -0
  44. package/dist/middle_layer/index.d.ts +8 -2
  45. package/dist/middle_layer/index.js +3 -1
  46. package/dist/middle_layer/legacy_project_holds.cjs +61 -0
  47. package/dist/middle_layer/legacy_project_holds.cjs.map +1 -0
  48. package/dist/middle_layer/legacy_project_holds.js +61 -0
  49. package/dist/middle_layer/legacy_project_holds.js.map +1 -0
  50. package/dist/middle_layer/middle_layer.cjs +18 -21
  51. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  52. package/dist/middle_layer/middle_layer.d.ts +13 -3
  53. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  54. package/dist/middle_layer/middle_layer.js +18 -21
  55. package/dist/middle_layer/middle_layer.js.map +1 -1
  56. package/dist/middle_layer/pool_columns.cjs +160 -0
  57. package/dist/middle_layer/pool_columns.cjs.map +1 -0
  58. package/dist/middle_layer/pool_columns.d.ts +59 -0
  59. package/dist/middle_layer/pool_columns.d.ts.map +1 -0
  60. package/dist/middle_layer/pool_columns.js +157 -0
  61. package/dist/middle_layer/pool_columns.js.map +1 -0
  62. package/dist/middle_layer/pool_frame.cjs +82 -0
  63. package/dist/middle_layer/pool_frame.cjs.map +1 -0
  64. package/dist/middle_layer/pool_frame.d.ts +37 -0
  65. package/dist/middle_layer/pool_frame.d.ts.map +1 -0
  66. package/dist/middle_layer/pool_frame.js +81 -0
  67. package/dist/middle_layer/pool_frame.js.map +1 -0
  68. package/dist/middle_layer/pool_table.cjs +66 -0
  69. package/dist/middle_layer/pool_table.cjs.map +1 -0
  70. package/dist/middle_layer/pool_table.d.ts +27 -0
  71. package/dist/middle_layer/pool_table.d.ts.map +1 -0
  72. package/dist/middle_layer/pool_table.js +66 -0
  73. package/dist/middle_layer/pool_table.js.map +1 -0
  74. package/dist/middle_layer/project.cjs +83 -2
  75. package/dist/middle_layer/project.cjs.map +1 -1
  76. package/dist/middle_layer/project.d.ts +69 -3
  77. package/dist/middle_layer/project.d.ts.map +1 -1
  78. package/dist/middle_layer/project.js +84 -3
  79. package/dist/middle_layer/project.js.map +1 -1
  80. package/dist/middle_layer/rich_column_query.cjs +180 -0
  81. package/dist/middle_layer/rich_column_query.cjs.map +1 -0
  82. package/dist/middle_layer/rich_column_query.d.ts +34 -0
  83. package/dist/middle_layer/rich_column_query.d.ts.map +1 -0
  84. package/dist/middle_layer/rich_column_query.js +176 -0
  85. package/dist/middle_layer/rich_column_query.js.map +1 -0
  86. package/dist/model/args.cjs +23 -0
  87. package/dist/model/args.cjs.map +1 -1
  88. package/dist/model/args.js +24 -2
  89. package/dist/model/args.js.map +1 -1
  90. package/dist/model/args_derivation.cjs +60 -2
  91. package/dist/model/args_derivation.cjs.map +1 -1
  92. package/dist/model/args_derivation.d.ts +73 -3
  93. package/dist/model/args_derivation.d.ts.map +1 -1
  94. package/dist/model/args_derivation.js +60 -3
  95. package/dist/model/args_derivation.js.map +1 -1
  96. package/dist/model/block_params_model.cjs +42 -0
  97. package/dist/model/block_params_model.cjs.map +1 -0
  98. package/dist/model/block_params_model.d.ts +45 -0
  99. package/dist/model/block_params_model.d.ts.map +1 -0
  100. package/dist/model/block_params_model.js +42 -0
  101. package/dist/model/block_params_model.js.map +1 -0
  102. package/dist/model/index.d.ts +3 -1
  103. package/dist/model/project_helper.cjs +50 -6
  104. package/dist/model/project_helper.cjs.map +1 -1
  105. package/dist/model/project_helper.d.ts +25 -1
  106. package/dist/model/project_helper.d.ts.map +1 -1
  107. package/dist/model/project_helper.js +51 -7
  108. package/dist/model/project_helper.js.map +1 -1
  109. package/dist/mutator/block-pack/block_pack.cjs +1 -1
  110. package/dist/mutator/block-pack/block_pack.js +1 -1
  111. package/dist/mutator/project.cjs +4 -0
  112. package/dist/mutator/project.cjs.map +1 -1
  113. package/dist/mutator/project.d.ts +1 -1
  114. package/dist/mutator/project.d.ts.map +1 -1
  115. package/dist/mutator/project.js +4 -0
  116. package/dist/mutator/project.js.map +1 -1
  117. package/package.json +9 -9
  118. package/src/block_registry/registry-v2-provider.test.ts +23 -0
  119. package/src/block_registry/registry-v2-provider.ts +11 -1
  120. package/src/index.ts +2 -0
  121. package/src/js_render/bundle_bytecode_cache.ts +15 -4
  122. package/src/js_render/column_registry.ts +24 -3
  123. package/src/js_render/context.ts +4 -3
  124. package/src/js_render/index.ts +3 -2
  125. package/src/js_render/service_injectors.ts +2 -11
  126. package/src/middle_layer/block.ts +61 -2
  127. package/src/middle_layer/block_pack_description.test.ts +235 -0
  128. package/src/middle_layer/block_pack_description.ts +143 -0
  129. package/src/middle_layer/index.ts +9 -1
  130. package/src/middle_layer/legacy_project_holds.test.ts +133 -0
  131. package/src/middle_layer/legacy_project_holds.ts +73 -0
  132. package/src/middle_layer/middle_layer.ts +23 -26
  133. package/src/middle_layer/pool_columns.test.ts +217 -0
  134. package/src/middle_layer/pool_columns.ts +250 -0
  135. package/src/middle_layer/pool_frame.test.ts +144 -0
  136. package/src/middle_layer/pool_frame.ts +127 -0
  137. package/src/middle_layer/pool_table.test.ts +182 -0
  138. package/src/middle_layer/pool_table.ts +98 -0
  139. package/src/middle_layer/project.ts +128 -5
  140. package/src/middle_layer/rich_column_query.test.ts +311 -0
  141. package/src/middle_layer/rich_column_query.ts +214 -0
  142. package/src/model/args.test.ts +23 -1
  143. package/src/model/args.ts +29 -1
  144. package/src/model/args_derivation.test.ts +129 -12
  145. package/src/model/args_derivation.ts +112 -8
  146. package/src/model/block_params_model.test.ts +194 -0
  147. package/src/model/block_params_model.ts +117 -0
  148. package/src/model/index.ts +6 -0
  149. package/src/model/project_helper.ts +101 -20
  150. package/src/mutator/project.ts +5 -0
  151. package/src/pool/result_pool_markers.test.ts +47 -0
  152. package/src/test/fake_project.ts +33 -6
@@ -1 +1 @@
1
- {"version":3,"file":"context.cjs","names":["ComputableContextHelper","Scope","JsRenderInternal","randomUUID","errors","stringifyWithResourceId","PlQuickJSError"],"sources":["../../src/js_render/context.ts"],"sourcesContent":["import type { ComputableCtx } from \"@milaboratories/computable\";\nimport type { BlockCodeKnownFeatureFlags } from \"@platforma-sdk/model\";\nimport { JsRenderInternal } from \"@platforma-sdk/model\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { randomUUID } from \"node:crypto\";\nimport type { QuickJSContext, QuickJSHandle } from \"quickjs-emscripten\";\nimport { Scope, errors } from \"quickjs-emscripten\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport { stringifyWithResourceId } from \"@milaboratories/pl-client\";\nimport { PlQuickJSError } from \"@milaboratories/pl-errors\";\nimport { ComputableContextHelper } from \"./computable_context\";\n\nimport { evaluateBundleCached } from \"./bundle_bytecode_cache\";\nexport type DeadlineSettings = {\n currentExecutionTarget: string;\n deadline: number;\n};\n\n/**\n * Communicates a deadline to the quickjs runtime, that if passed, will interrupt the execution.\n * Undefined can be used to reset the deadline.\n * */\nexport type DeadlineSetter = (settings: DeadlineSettings | undefined) => void;\n\nfunction isArrayBufferOrView(obj: unknown): obj is ArrayBufferLike {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\n\n/**\n * Contains references to objects needed to execute lambda within computable,\n * providing access to:\n * - block context\n * - computable context\n * - middle layer environment\n * */\nexport type ComputableEnv = {\n readonly blockCtx: BlockContextAny;\n readonly mlEnv: MiddleLayerEnvironment;\n computableCtx: ComputableCtx;\n};\n\n/** Execution stats accumulated during the lifetime of a JsExecutionContext. */\nexport type JsExecStats = {\n bundleEvalMs: number;\n bundleBytes: number;\n\n callbackMs: number;\n callbackCount: number;\n\n serInMs: number;\n serInBytes: number;\n serInCalls: number;\n\n serOutMs: number;\n serOutBytes: number;\n serOutCalls: number;\n\n ctxMethodCalls: number;\n ctxMethodMs: number;\n};\n\nexport class JsExecutionContext {\n private readonly callbackRegistry: QuickJSHandle;\n private readonly fnJSONStringify: QuickJSHandle;\n private readonly fnJSONParse: QuickJSHandle;\n\n public readonly errorRepo = new ErrorRepository();\n\n public readonly computableHelper: ComputableContextHelper | undefined;\n\n public readonly stats: JsExecStats = {\n bundleEvalMs: 0,\n bundleBytes: 0,\n callbackMs: 0,\n callbackCount: 0,\n serInMs: 0,\n serInBytes: 0,\n serInCalls: 0,\n serOutMs: 0,\n serOutBytes: 0,\n serOutCalls: 0,\n ctxMethodCalls: 0,\n ctxMethodMs: 0,\n };\n\n /**\n * Creates a new JS execution context.\n *\n * @param scope - QuickJS scope for memory management\n * @param vm - QuickJS VM context\n * @param deadlineSetter - Function to set execution deadline\n * @param featureFlags - Block feature flags\n * @param computableEnv - Optional reactive computable environment (for outputs, inputsValid, etc.)\n */\n constructor(\n public readonly scope: Scope,\n public readonly vm: QuickJSContext,\n private readonly deadlineSetter: DeadlineSetter,\n featureFlags: BlockCodeKnownFeatureFlags | undefined,\n computableEnv?: ComputableEnv,\n ) {\n this.callbackRegistry = this.scope.manage(this.vm.newObject());\n\n this.fnJSONStringify = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"stringify\")),\n );\n if (vm.typeof(this.fnJSONStringify) !== \"function\")\n throw new Error(`JSON.stringify() not found.`);\n\n this.fnJSONParse = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"parse\")),\n );\n if (vm.typeof(this.fnJSONParse) !== \"function\") throw new Error(`JSON.parse() not found.`);\n\n if (computableEnv !== undefined)\n this.computableHelper = new ComputableContextHelper(\n this,\n computableEnv.blockCtx,\n computableEnv.mlEnv,\n featureFlags,\n computableEnv.computableCtx,\n );\n\n this.injectCtx();\n }\n\n public resetComputableCtx() {\n notEmpty(\n this.computableHelper,\n \"Computable context helper is not initialized\",\n ).resetComputableCtx();\n }\n\n private static cleanErrorContext(error: unknown): void {\n if (typeof error === \"object\" && error !== null && \"context\" in error) delete error[\"context\"];\n }\n\n // private static cleanError(error: unknown): unknown {\n // if (error instanceof errors.QuickJSUnwrapError) {\n // const { cause, context: _, name, message, stack, ...rest } = error;\n // const clean = new errors.QuickJSUnwrapError(cause);\n // Object.assign(clean, { ...rest, name, message, stack });\n // return clean;\n // }\n // return error;\n // }\n\n public evaluateBundle(code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n this.vm.unwrapResult(this.vm.evalCode(code, \"bundle.js\", { type: \"global\" })).dispose();\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n /**\n * {@link evaluateBundle}, reusing bytecode compiled for an earlier context with the same\n * `cacheKey`. Every lambda gets its own context and needs the whole bundle in scope, so\n * parsing per context was the dominant cost of rendering a block.\n */\n public evaluateBundleCached(cacheKey: string, code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n evaluateBundleCached(this.vm, cacheKey, code);\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n public runCallback(cbName: string, ...args: unknown[]): QuickJSHandle {\n const t0 = performance.now();\n try {\n this.deadlineSetter({ currentExecutionTarget: cbName, deadline: Date.now() + 10000 });\n return Scope.withScope((localScope) => {\n const targetCallback = localScope.manage(this.vm.getProp(this.callbackRegistry, cbName));\n\n if (this.vm.typeof(targetCallback) !== \"function\")\n throw new Error(`No such callback: ${cbName}`);\n\n return this.scope.manage(\n this.vm.unwrapResult(\n this.vm.callFunction(\n targetCallback,\n this.vm.undefined,\n ...args.map((arg) => this.exportObjectUniversal(arg, localScope)),\n ),\n ),\n );\n });\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n const original = this.errorRepo.getOriginal(err);\n throw original;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.callbackMs += performance.now() - t0;\n this.stats.callbackCount++;\n }\n }\n\n //\n // QuickJS Helpers\n //\n\n public exportSingleValue(\n obj: boolean | number | string | null | ArrayBuffer | undefined,\n scope?: Scope,\n ): QuickJSHandle {\n const result = this.tryExportSingleValue(obj, scope);\n if (result === undefined) {\n throw new Error(\n `Can't export value: ${obj === undefined ? \"undefined\" : JSON.stringify(obj)}`,\n );\n }\n return result;\n }\n\n public tryExportSingleValue(obj: unknown, scope?: Scope): QuickJSHandle | undefined {\n let handle: QuickJSHandle;\n let manage = false;\n switch (typeof obj) {\n case \"string\":\n handle = this.vm.newString(obj);\n manage = true;\n break;\n case \"number\":\n handle = this.vm.newNumber(obj);\n manage = true;\n break;\n case \"undefined\":\n handle = this.vm.undefined;\n break;\n case \"boolean\":\n handle = obj ? this.vm.true : this.vm.false;\n break;\n default:\n if (obj === null) {\n handle = this.vm.null;\n break;\n }\n if (isArrayBufferOrView(obj)) {\n handle = this.vm.newArrayBuffer(obj);\n manage = true;\n break;\n }\n return undefined;\n }\n return manage && scope != undefined ? scope.manage(handle) : handle;\n }\n\n public exportObjectUniversal(obj: unknown, scope?: Scope): QuickJSHandle {\n const simpleHandle = this.tryExportSingleValue(obj, scope);\n if (simpleHandle !== undefined) return simpleHandle;\n return this.exportObjectViaJson(obj, scope);\n }\n\n public exportObjectViaJson(obj: unknown, scope?: Scope): QuickJSHandle {\n const t0 = performance.now();\n const json = JSON.stringify(obj);\n this.stats.serInBytes += json.length;\n this.stats.serInCalls++;\n const result = this.vm\n .newString(json)\n .consume((jsonHandle) =>\n this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse, this.vm.undefined, jsonHandle)),\n );\n this.stats.serInMs += performance.now() - t0;\n return scope !== undefined ? scope.manage(result) : result;\n }\n\n public importObjectUniversal(handle: QuickJSHandle | undefined): unknown {\n if (handle === undefined) return undefined;\n switch (this.vm.typeof(handle)) {\n case \"undefined\":\n return undefined;\n case \"boolean\":\n case \"number\":\n case \"string\":\n return this.vm.dump(handle);\n default:\n return this.importObjectViaJson(handle);\n }\n }\n\n public importObjectViaJson(handle: QuickJSHandle): unknown {\n const t0 = performance.now();\n const text = this.vm\n .unwrapResult(this.vm.callFunction(this.fnJSONStringify, this.vm.undefined, handle))\n .consume((strHandle) => this.vm.getString(strHandle));\n this.stats.serOutBytes += text.length;\n this.stats.serOutCalls++;\n if (text === \"undefined\") {\n // special case with futures\n this.stats.serOutMs += performance.now() - t0;\n return undefined;\n }\n const result = JSON.parse(text);\n this.stats.serOutMs += performance.now() - t0;\n return result;\n }\n\n private injectCtx() {\n Scope.withScope((localScope) => {\n const configCtx = localScope.manage(this.vm.newObject());\n\n //\n // Core props\n //\n\n this.vm.setProp(configCtx, \"callbackRegistry\", this.callbackRegistry);\n this.vm.setProp(\n configCtx,\n \"featureFlags\",\n this.exportObjectUniversal(JsRenderInternal.GlobalCfgRenderCtxFeatureFlags, localScope),\n );\n\n // Inject context values from computableHelper (reactive context for outputs, inputsValid, etc.)\n if (this.computableHelper !== undefined) {\n this.computableHelper.injectCtx(configCtx);\n }\n\n //\n // Creating global variable inside the vm\n //\n\n this.vm.setProp(this.vm.global, \"cfgRenderCtx\", configCtx);\n });\n }\n}\n\n/** Holds errors that happened in the host code (like in middle-layer's drivers)\n * and then throws it where the error from quick JS is needed.\n * QuickJS couldn't throw custom errors, so we store them here, and rethrow them when we exit QuickJS side. */\nexport class ErrorRepository {\n private readonly errorIdToError = new Map<string, unknown>();\n\n /** Sets the error to the repository and returns a mimicrated error that also has uuid key of the original error. */\n public setAndRecreateForQuickJS(error: unknown): {\n name: string;\n message: string;\n } {\n const errorId = randomUUID();\n this.errorIdToError.set(errorId, error);\n\n if (error instanceof Error) {\n return {\n name: `${error.name}/uuid:${errorId}`,\n message: error.message,\n };\n }\n\n return {\n name: `UnknownErrorQuickJS/uuid:${errorId}`,\n message: `${error as any}`,\n };\n }\n\n /** Returns the original error that was stored by parsing uuid of mimicrated error. */\n public getOriginal(quickJSError: unknown): unknown {\n if (!(quickJSError instanceof errors.QuickJSUnwrapError)) {\n console.warn(\n \"ErrorRepo: quickJSError is not a QuickJSUnwrapError\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const cause = quickJSError.cause;\n if (\n !(\n typeof cause === \"object\" &&\n cause !== null &&\n \"name\" in cause &&\n typeof cause.name === \"string\"\n )\n ) {\n console.warn(\n \"ErrorRepo: quickJSError.cause is not an Error (can be stack limit exceeded)\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const causeName = cause.name;\n const uuidIdx = causeName.indexOf(\"/uuid:\");\n if (uuidIdx === -1) {\n const causeMsg = \"message\" in cause && typeof cause.message === \"string\" ? cause.message : \"\";\n throw new Error(\n `QuickJS native error: ${causeName}: ${causeMsg}, ${stringifyWithResourceId(quickJSError)}`,\n { cause: quickJSError },\n );\n }\n const errorId = causeName.slice(uuidIdx + \"/uuid:\".length);\n if (!errorId) {\n throw new Error(\n `ErrorRepo: quickJSError.cause.name does not contain errorId: ${causeName}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n const error = this.errorIdToError.get(errorId);\n if (error === undefined) {\n throw new Error(\n `ErrorRepo: errorId not found: ${errorId}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n return new PlQuickJSError(quickJSError, error as Error);\n }\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAS,oBAAoB,KAAsC;CACjE,OAAO,eAAe,eAAe,YAAY,OAAO,GAAG;AAC7D;AAmCA,IAAa,qBAAb,MAAa,mBAAmB;CAkCZ;CACA;CACC;CAnCnB;CACA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QAAQ,KAAA,GAAIA,0BAAAA,wBAAAA,CAAwB,YAAY,GACnF;EAGF,OAAO,IAAIC,0BAAAA,eAAe,cAAc,KAAc;CACxD;AACF"}
1
+ {"version":3,"file":"context.cjs","names":["ComputableContextHelper","Scope","JsRenderInternal","randomUUID","errors","stringifyWithResourceId","PlQuickJSError"],"sources":["../../src/js_render/context.ts"],"sourcesContent":["import type { ComputableCtx } from \"@milaboratories/computable\";\nimport type { BlockCodeKnownFeatureFlags } from \"@platforma-sdk/model\";\nimport { JsRenderInternal } from \"@platforma-sdk/model\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { randomUUID } from \"node:crypto\";\nimport type { QuickJSContext, QuickJSHandle } from \"quickjs-emscripten\";\nimport { Scope, errors } from \"quickjs-emscripten\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport { stringifyWithResourceId } from \"@milaboratories/pl-client\";\nimport { PlQuickJSError } from \"@milaboratories/pl-errors\";\nimport { ComputableContextHelper } from \"./computable_context\";\n\nimport { evaluateBundleCached } from \"./bundle_bytecode_cache\";\nexport type DeadlineSettings = {\n currentExecutionTarget: string;\n deadline: number;\n};\n\n/**\n * Communicates a deadline to the quickjs runtime, that if passed, will interrupt the execution.\n * Undefined can be used to reset the deadline.\n * */\nexport type DeadlineSetter = (settings: DeadlineSettings | undefined) => void;\n\nfunction isArrayBufferOrView(obj: unknown): obj is ArrayBufferLike {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\n\n/**\n * Contains references to objects needed to execute lambda within computable,\n * providing access to:\n * - block context\n * - computable context\n * - middle layer environment\n * */\nexport type ComputableEnv = {\n readonly blockCtx: BlockContextAny;\n readonly mlEnv: MiddleLayerEnvironment;\n computableCtx: ComputableCtx;\n};\n\n/** Execution stats accumulated during the lifetime of a JsExecutionContext. */\nexport type JsExecStats = {\n bundleEvalMs: number;\n bundleBytes: number;\n\n callbackMs: number;\n callbackCount: number;\n\n serInMs: number;\n serInBytes: number;\n serInCalls: number;\n\n serOutMs: number;\n serOutBytes: number;\n serOutCalls: number;\n\n ctxMethodCalls: number;\n ctxMethodMs: number;\n};\n\nexport class JsExecutionContext {\n private readonly callbackRegistry: QuickJSHandle;\n private readonly fnJSONStringify: QuickJSHandle;\n private readonly fnJSONParse: QuickJSHandle;\n\n public readonly errorRepo = new ErrorRepository();\n\n public readonly computableHelper: ComputableContextHelper | undefined;\n\n public readonly stats: JsExecStats = {\n bundleEvalMs: 0,\n bundleBytes: 0,\n callbackMs: 0,\n callbackCount: 0,\n serInMs: 0,\n serInBytes: 0,\n serInCalls: 0,\n serOutMs: 0,\n serOutBytes: 0,\n serOutCalls: 0,\n ctxMethodCalls: 0,\n ctxMethodMs: 0,\n };\n\n /**\n * Creates a new JS execution context.\n *\n * @param scope - QuickJS scope for memory management\n * @param vm - QuickJS VM context\n * @param deadlineSetter - Function to set execution deadline\n * @param featureFlags - Block feature flags\n * @param computableEnv - Optional reactive computable environment (for outputs, inputsValid, etc.)\n */\n constructor(\n public readonly scope: Scope,\n public readonly vm: QuickJSContext,\n private readonly deadlineSetter: DeadlineSetter,\n featureFlags: BlockCodeKnownFeatureFlags | undefined,\n computableEnv?: ComputableEnv,\n ) {\n this.callbackRegistry = this.scope.manage(this.vm.newObject());\n\n this.fnJSONStringify = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"stringify\")),\n );\n if (vm.typeof(this.fnJSONStringify) !== \"function\")\n throw new Error(`JSON.stringify() not found.`);\n\n this.fnJSONParse = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"parse\")),\n );\n if (vm.typeof(this.fnJSONParse) !== \"function\") throw new Error(`JSON.parse() not found.`);\n\n if (computableEnv !== undefined)\n this.computableHelper = new ComputableContextHelper(\n this,\n computableEnv.blockCtx,\n computableEnv.mlEnv,\n featureFlags,\n computableEnv.computableCtx,\n );\n\n this.injectCtx();\n }\n\n public resetComputableCtx() {\n notEmpty(\n this.computableHelper,\n \"Computable context helper is not initialized\",\n ).resetComputableCtx();\n }\n\n private static cleanErrorContext(error: unknown): void {\n if (typeof error === \"object\" && error !== null && \"context\" in error) delete error[\"context\"];\n }\n\n // private static cleanError(error: unknown): unknown {\n // if (error instanceof errors.QuickJSUnwrapError) {\n // const { cause, context: _, name, message, stack, ...rest } = error;\n // const clean = new errors.QuickJSUnwrapError(cause);\n // Object.assign(clean, { ...rest, name, message, stack });\n // return clean;\n // }\n // return error;\n // }\n\n public evaluateBundle(code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n this.vm.unwrapResult(this.vm.evalCode(code, \"bundle.js\", { type: \"global\" })).dispose();\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n /**\n * {@link evaluateBundle}, reusing bytecode compiled for an earlier context with the same\n * code (identified by `cacheKey` when given, by its hash otherwise). Every lambda gets its own\n * context and needs the whole bundle in scope, so parsing per context was the dominant cost of\n * rendering a block.\n */\n public evaluateBundleCached(cacheKey: string | undefined, code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n evaluateBundleCached(this.vm, cacheKey, code);\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n public runCallback(cbName: string, ...args: unknown[]): QuickJSHandle {\n const t0 = performance.now();\n try {\n this.deadlineSetter({ currentExecutionTarget: cbName, deadline: Date.now() + 10000 });\n return Scope.withScope((localScope) => {\n const targetCallback = localScope.manage(this.vm.getProp(this.callbackRegistry, cbName));\n\n if (this.vm.typeof(targetCallback) !== \"function\")\n throw new Error(`No such callback: ${cbName}`);\n\n return this.scope.manage(\n this.vm.unwrapResult(\n this.vm.callFunction(\n targetCallback,\n this.vm.undefined,\n ...args.map((arg) => this.exportObjectUniversal(arg, localScope)),\n ),\n ),\n );\n });\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n const original = this.errorRepo.getOriginal(err);\n throw original;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.callbackMs += performance.now() - t0;\n this.stats.callbackCount++;\n }\n }\n\n //\n // QuickJS Helpers\n //\n\n public exportSingleValue(\n obj: boolean | number | string | null | ArrayBuffer | undefined,\n scope?: Scope,\n ): QuickJSHandle {\n const result = this.tryExportSingleValue(obj, scope);\n if (result === undefined) {\n throw new Error(\n `Can't export value: ${obj === undefined ? \"undefined\" : JSON.stringify(obj)}`,\n );\n }\n return result;\n }\n\n public tryExportSingleValue(obj: unknown, scope?: Scope): QuickJSHandle | undefined {\n let handle: QuickJSHandle;\n let manage = false;\n switch (typeof obj) {\n case \"string\":\n handle = this.vm.newString(obj);\n manage = true;\n break;\n case \"number\":\n handle = this.vm.newNumber(obj);\n manage = true;\n break;\n case \"undefined\":\n handle = this.vm.undefined;\n break;\n case \"boolean\":\n handle = obj ? this.vm.true : this.vm.false;\n break;\n default:\n if (obj === null) {\n handle = this.vm.null;\n break;\n }\n if (isArrayBufferOrView(obj)) {\n handle = this.vm.newArrayBuffer(obj);\n manage = true;\n break;\n }\n return undefined;\n }\n return manage && scope != undefined ? scope.manage(handle) : handle;\n }\n\n public exportObjectUniversal(obj: unknown, scope?: Scope): QuickJSHandle {\n const simpleHandle = this.tryExportSingleValue(obj, scope);\n if (simpleHandle !== undefined) return simpleHandle;\n return this.exportObjectViaJson(obj, scope);\n }\n\n public exportObjectViaJson(obj: unknown, scope?: Scope): QuickJSHandle {\n const t0 = performance.now();\n const json = JSON.stringify(obj);\n this.stats.serInBytes += json.length;\n this.stats.serInCalls++;\n const result = this.vm\n .newString(json)\n .consume((jsonHandle) =>\n this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse, this.vm.undefined, jsonHandle)),\n );\n this.stats.serInMs += performance.now() - t0;\n return scope !== undefined ? scope.manage(result) : result;\n }\n\n public importObjectUniversal(handle: QuickJSHandle | undefined): unknown {\n if (handle === undefined) return undefined;\n switch (this.vm.typeof(handle)) {\n case \"undefined\":\n return undefined;\n case \"boolean\":\n case \"number\":\n case \"string\":\n return this.vm.dump(handle);\n default:\n return this.importObjectViaJson(handle);\n }\n }\n\n public importObjectViaJson(handle: QuickJSHandle): unknown {\n const t0 = performance.now();\n const text = this.vm\n .unwrapResult(this.vm.callFunction(this.fnJSONStringify, this.vm.undefined, handle))\n .consume((strHandle) => this.vm.getString(strHandle));\n this.stats.serOutBytes += text.length;\n this.stats.serOutCalls++;\n if (text === \"undefined\") {\n // special case with futures\n this.stats.serOutMs += performance.now() - t0;\n return undefined;\n }\n const result = JSON.parse(text);\n this.stats.serOutMs += performance.now() - t0;\n return result;\n }\n\n private injectCtx() {\n Scope.withScope((localScope) => {\n const configCtx = localScope.manage(this.vm.newObject());\n\n //\n // Core props\n //\n\n this.vm.setProp(configCtx, \"callbackRegistry\", this.callbackRegistry);\n this.vm.setProp(\n configCtx,\n \"featureFlags\",\n this.exportObjectUniversal(JsRenderInternal.GlobalCfgRenderCtxFeatureFlags, localScope),\n );\n\n // Inject context values from computableHelper (reactive context for outputs, inputsValid, etc.)\n if (this.computableHelper !== undefined) {\n this.computableHelper.injectCtx(configCtx);\n }\n\n //\n // Creating global variable inside the vm\n //\n\n this.vm.setProp(this.vm.global, \"cfgRenderCtx\", configCtx);\n });\n }\n}\n\n/** Holds errors that happened in the host code (like in middle-layer's drivers)\n * and then throws it where the error from quick JS is needed.\n * QuickJS couldn't throw custom errors, so we store them here, and rethrow them when we exit QuickJS side. */\nexport class ErrorRepository {\n private readonly errorIdToError = new Map<string, unknown>();\n\n /** Sets the error to the repository and returns a mimicrated error that also has uuid key of the original error. */\n public setAndRecreateForQuickJS(error: unknown): {\n name: string;\n message: string;\n } {\n const errorId = randomUUID();\n this.errorIdToError.set(errorId, error);\n\n if (error instanceof Error) {\n return {\n name: `${error.name}/uuid:${errorId}`,\n message: error.message,\n };\n }\n\n return {\n name: `UnknownErrorQuickJS/uuid:${errorId}`,\n message: `${error as any}`,\n };\n }\n\n /** Returns the original error that was stored by parsing uuid of mimicrated error. */\n public getOriginal(quickJSError: unknown): unknown {\n if (!(quickJSError instanceof errors.QuickJSUnwrapError)) {\n console.warn(\n \"ErrorRepo: quickJSError is not a QuickJSUnwrapError\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const cause = quickJSError.cause;\n if (\n !(\n typeof cause === \"object\" &&\n cause !== null &&\n \"name\" in cause &&\n typeof cause.name === \"string\"\n )\n ) {\n console.warn(\n \"ErrorRepo: quickJSError.cause is not an Error (can be stack limit exceeded)\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const causeName = cause.name;\n const uuidIdx = causeName.indexOf(\"/uuid:\");\n if (uuidIdx === -1) {\n const causeMsg = \"message\" in cause && typeof cause.message === \"string\" ? cause.message : \"\";\n throw new Error(\n `QuickJS native error: ${causeName}: ${causeMsg}, ${stringifyWithResourceId(quickJSError)}`,\n { cause: quickJSError },\n );\n }\n const errorId = causeName.slice(uuidIdx + \"/uuid:\".length);\n if (!errorId) {\n throw new Error(\n `ErrorRepo: quickJSError.cause.name does not contain errorId: ${causeName}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n const error = this.errorIdToError.get(errorId);\n if (error === undefined) {\n throw new Error(\n `ErrorRepo: errorId not found: ${errorId}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n return new PlQuickJSError(quickJSError, error as Error);\n }\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAS,oBAAoB,KAAsC;CACjE,OAAO,eAAe,eAAe,YAAY,OAAO,GAAG;AAC7D;AAm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AAO;EAC7C,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MACR,iCAAiC,QAAQ,KAAA,GAAIA,0BAAAA,wBAAAA,CAAwB,YAAY,GACnF;EAGF,OAAO,IAAIC,0BAAAA,eAAe,cAAc,KAAc;CACxD;AACF"}
@@ -79,8 +79,9 @@ var JsExecutionContext = class JsExecutionContext {
79
79
  }
80
80
  /**
81
81
  * {@link evaluateBundle}, reusing bytecode compiled for an earlier context with the same
82
- * `cacheKey`. Every lambda gets its own context and needs the whole bundle in scope, so
83
- * parsing per context was the dominant cost of rendering a block.
82
+ * code (identified by `cacheKey` when given, by its hash otherwise). Every lambda gets its own
83
+ * context and needs the whole bundle in scope, so parsing per context was the dominant cost of
84
+ * rendering a block.
84
85
  */
85
86
  evaluateBundleCached(cacheKey, code) {
86
87
  const t0 = performance.now();
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../../src/js_render/context.ts"],"sourcesContent":["import type { ComputableCtx } from \"@milaboratories/computable\";\nimport type { BlockCodeKnownFeatureFlags } from \"@platforma-sdk/model\";\nimport { JsRenderInternal } from \"@platforma-sdk/model\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { randomUUID } from \"node:crypto\";\nimport type { QuickJSContext, QuickJSHandle } from \"quickjs-emscripten\";\nimport { Scope, errors } from \"quickjs-emscripten\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport { stringifyWithResourceId } from \"@milaboratories/pl-client\";\nimport { PlQuickJSError } from \"@milaboratories/pl-errors\";\nimport { ComputableContextHelper } from \"./computable_context\";\n\nimport { evaluateBundleCached } from \"./bundle_bytecode_cache\";\nexport type DeadlineSettings = {\n currentExecutionTarget: string;\n deadline: number;\n};\n\n/**\n * Communicates a deadline to the quickjs runtime, that if passed, will interrupt the execution.\n * Undefined can be used to reset the deadline.\n * */\nexport type DeadlineSetter = (settings: DeadlineSettings | undefined) => void;\n\nfunction isArrayBufferOrView(obj: unknown): obj is ArrayBufferLike {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\n\n/**\n * Contains references to objects needed to execute lambda within computable,\n * providing access to:\n * - block context\n * - computable context\n * - middle layer environment\n * */\nexport type ComputableEnv = {\n readonly blockCtx: BlockContextAny;\n readonly mlEnv: MiddleLayerEnvironment;\n computableCtx: ComputableCtx;\n};\n\n/** Execution stats accumulated during the lifetime of a JsExecutionContext. */\nexport type JsExecStats = {\n bundleEvalMs: number;\n bundleBytes: number;\n\n callbackMs: number;\n callbackCount: number;\n\n serInMs: number;\n serInBytes: number;\n serInCalls: number;\n\n serOutMs: number;\n serOutBytes: number;\n serOutCalls: number;\n\n ctxMethodCalls: number;\n ctxMethodMs: number;\n};\n\nexport class JsExecutionContext {\n private readonly callbackRegistry: QuickJSHandle;\n private readonly fnJSONStringify: QuickJSHandle;\n private readonly fnJSONParse: QuickJSHandle;\n\n public readonly errorRepo = new ErrorRepository();\n\n public readonly computableHelper: ComputableContextHelper | undefined;\n\n public readonly stats: JsExecStats = {\n bundleEvalMs: 0,\n bundleBytes: 0,\n callbackMs: 0,\n callbackCount: 0,\n serInMs: 0,\n serInBytes: 0,\n serInCalls: 0,\n serOutMs: 0,\n serOutBytes: 0,\n serOutCalls: 0,\n ctxMethodCalls: 0,\n ctxMethodMs: 0,\n };\n\n /**\n * Creates a new JS execution context.\n *\n * @param scope - QuickJS scope for memory management\n * @param vm - QuickJS VM context\n * @param deadlineSetter - Function to set execution deadline\n * @param featureFlags - Block feature flags\n * @param computableEnv - Optional reactive computable environment (for outputs, inputsValid, etc.)\n */\n constructor(\n public readonly scope: Scope,\n public readonly vm: QuickJSContext,\n private readonly deadlineSetter: DeadlineSetter,\n featureFlags: BlockCodeKnownFeatureFlags | undefined,\n computableEnv?: ComputableEnv,\n ) {\n this.callbackRegistry = this.scope.manage(this.vm.newObject());\n\n this.fnJSONStringify = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"stringify\")),\n );\n if (vm.typeof(this.fnJSONStringify) !== \"function\")\n throw new Error(`JSON.stringify() not found.`);\n\n this.fnJSONParse = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"parse\")),\n );\n if (vm.typeof(this.fnJSONParse) !== \"function\") throw new Error(`JSON.parse() not found.`);\n\n if (computableEnv !== undefined)\n this.computableHelper = new ComputableContextHelper(\n this,\n computableEnv.blockCtx,\n computableEnv.mlEnv,\n featureFlags,\n computableEnv.computableCtx,\n );\n\n this.injectCtx();\n }\n\n public resetComputableCtx() {\n notEmpty(\n this.computableHelper,\n \"Computable context helper is not initialized\",\n ).resetComputableCtx();\n }\n\n private static cleanErrorContext(error: unknown): void {\n if (typeof error === \"object\" && error !== null && \"context\" in error) delete error[\"context\"];\n }\n\n // private static cleanError(error: unknown): unknown {\n // if (error instanceof errors.QuickJSUnwrapError) {\n // const { cause, context: _, name, message, stack, ...rest } = error;\n // const clean = new errors.QuickJSUnwrapError(cause);\n // Object.assign(clean, { ...rest, name, message, stack });\n // return clean;\n // }\n // return error;\n // }\n\n public evaluateBundle(code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n this.vm.unwrapResult(this.vm.evalCode(code, \"bundle.js\", { type: \"global\" })).dispose();\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n /**\n * {@link evaluateBundle}, reusing bytecode compiled for an earlier context with the same\n * `cacheKey`. Every lambda gets its own context and needs the whole bundle in scope, so\n * parsing per context was the dominant cost of rendering a block.\n */\n public evaluateBundleCached(cacheKey: string, code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n evaluateBundleCached(this.vm, cacheKey, code);\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n public runCallback(cbName: string, ...args: unknown[]): QuickJSHandle {\n const t0 = performance.now();\n try {\n this.deadlineSetter({ currentExecutionTarget: cbName, deadline: Date.now() + 10000 });\n return Scope.withScope((localScope) => {\n const targetCallback = localScope.manage(this.vm.getProp(this.callbackRegistry, cbName));\n\n if (this.vm.typeof(targetCallback) !== \"function\")\n throw new Error(`No such callback: ${cbName}`);\n\n return this.scope.manage(\n this.vm.unwrapResult(\n this.vm.callFunction(\n targetCallback,\n this.vm.undefined,\n ...args.map((arg) => this.exportObjectUniversal(arg, localScope)),\n ),\n ),\n );\n });\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n const original = this.errorRepo.getOriginal(err);\n throw original;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.callbackMs += performance.now() - t0;\n this.stats.callbackCount++;\n }\n }\n\n //\n // QuickJS Helpers\n //\n\n public exportSingleValue(\n obj: boolean | number | string | null | ArrayBuffer | undefined,\n scope?: Scope,\n ): QuickJSHandle {\n const result = this.tryExportSingleValue(obj, scope);\n if (result === undefined) {\n throw new Error(\n `Can't export value: ${obj === undefined ? \"undefined\" : JSON.stringify(obj)}`,\n );\n }\n return result;\n }\n\n public tryExportSingleValue(obj: unknown, scope?: Scope): QuickJSHandle | undefined {\n let handle: QuickJSHandle;\n let manage = false;\n switch (typeof obj) {\n case \"string\":\n handle = this.vm.newString(obj);\n manage = true;\n break;\n case \"number\":\n handle = this.vm.newNumber(obj);\n manage = true;\n break;\n case \"undefined\":\n handle = this.vm.undefined;\n break;\n case \"boolean\":\n handle = obj ? this.vm.true : this.vm.false;\n break;\n default:\n if (obj === null) {\n handle = this.vm.null;\n break;\n }\n if (isArrayBufferOrView(obj)) {\n handle = this.vm.newArrayBuffer(obj);\n manage = true;\n break;\n }\n return undefined;\n }\n return manage && scope != undefined ? scope.manage(handle) : handle;\n }\n\n public exportObjectUniversal(obj: unknown, scope?: Scope): QuickJSHandle {\n const simpleHandle = this.tryExportSingleValue(obj, scope);\n if (simpleHandle !== undefined) return simpleHandle;\n return this.exportObjectViaJson(obj, scope);\n }\n\n public exportObjectViaJson(obj: unknown, scope?: Scope): QuickJSHandle {\n const t0 = performance.now();\n const json = JSON.stringify(obj);\n this.stats.serInBytes += json.length;\n this.stats.serInCalls++;\n const result = this.vm\n .newString(json)\n .consume((jsonHandle) =>\n this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse, this.vm.undefined, jsonHandle)),\n );\n this.stats.serInMs += performance.now() - t0;\n return scope !== undefined ? scope.manage(result) : result;\n }\n\n public importObjectUniversal(handle: QuickJSHandle | undefined): unknown {\n if (handle === undefined) return undefined;\n switch (this.vm.typeof(handle)) {\n case \"undefined\":\n return undefined;\n case \"boolean\":\n case \"number\":\n case \"string\":\n return this.vm.dump(handle);\n default:\n return this.importObjectViaJson(handle);\n }\n }\n\n public importObjectViaJson(handle: QuickJSHandle): unknown {\n const t0 = performance.now();\n const text = this.vm\n .unwrapResult(this.vm.callFunction(this.fnJSONStringify, this.vm.undefined, handle))\n .consume((strHandle) => this.vm.getString(strHandle));\n this.stats.serOutBytes += text.length;\n this.stats.serOutCalls++;\n if (text === \"undefined\") {\n // special case with futures\n this.stats.serOutMs += performance.now() - t0;\n return undefined;\n }\n const result = JSON.parse(text);\n this.stats.serOutMs += performance.now() - t0;\n return result;\n }\n\n private injectCtx() {\n Scope.withScope((localScope) => {\n const configCtx = localScope.manage(this.vm.newObject());\n\n //\n // Core props\n //\n\n this.vm.setProp(configCtx, \"callbackRegistry\", this.callbackRegistry);\n this.vm.setProp(\n configCtx,\n \"featureFlags\",\n this.exportObjectUniversal(JsRenderInternal.GlobalCfgRenderCtxFeatureFlags, localScope),\n );\n\n // Inject context values from computableHelper (reactive context for outputs, inputsValid, etc.)\n if (this.computableHelper !== undefined) {\n this.computableHelper.injectCtx(configCtx);\n }\n\n //\n // Creating global variable inside the vm\n //\n\n this.vm.setProp(this.vm.global, \"cfgRenderCtx\", configCtx);\n });\n }\n}\n\n/** Holds errors that happened in the host code (like in middle-layer's drivers)\n * and then throws it where the error from quick JS is needed.\n * QuickJS couldn't throw custom errors, so we store them here, and rethrow them when we exit QuickJS side. */\nexport class ErrorRepository {\n private readonly errorIdToError = new Map<string, unknown>();\n\n /** Sets the error to the repository and returns a mimicrated error that also has uuid key of the original error. */\n public setAndRecreateForQuickJS(error: unknown): {\n name: string;\n message: string;\n } {\n const errorId = randomUUID();\n this.errorIdToError.set(errorId, error);\n\n if (error instanceof Error) {\n return {\n name: `${error.name}/uuid:${errorId}`,\n message: error.message,\n };\n }\n\n return {\n name: `UnknownErrorQuickJS/uuid:${errorId}`,\n message: `${error as any}`,\n };\n }\n\n /** Returns the original error that was stored by parsing uuid of mimicrated error. */\n public getOriginal(quickJSError: unknown): unknown {\n if (!(quickJSError instanceof errors.QuickJSUnwrapError)) {\n console.warn(\n \"ErrorRepo: quickJSError is not a QuickJSUnwrapError\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const cause = quickJSError.cause;\n if (\n !(\n typeof cause === \"object\" &&\n cause !== null &&\n \"name\" in cause &&\n typeof cause.name === \"string\"\n )\n ) {\n console.warn(\n \"ErrorRepo: quickJSError.cause is not an Error (can be stack limit exceeded)\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const causeName = cause.name;\n const uuidIdx = causeName.indexOf(\"/uuid:\");\n if (uuidIdx === -1) {\n const causeMsg = \"message\" in cause && typeof cause.message === \"string\" ? cause.message : \"\";\n throw new Error(\n `QuickJS native error: ${causeName}: ${causeMsg}, ${stringifyWithResourceId(quickJSError)}`,\n { cause: quickJSError },\n );\n }\n const errorId = causeName.slice(uuidIdx + \"/uuid:\".length);\n if (!errorId) {\n throw new Error(\n `ErrorRepo: quickJSError.cause.name does not contain errorId: ${causeName}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n const error = this.errorIdToError.get(errorId);\n if (error === undefined) {\n throw new Error(\n `ErrorRepo: errorId not found: ${errorId}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n return new PlQuickJSError(quickJSError, error as Error);\n }\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAS,oBAAoB,KAAsC;CACjE,OAAO,eAAe,eAAe,YAAY,OAAO,GAAG;AAC7D;AAmCA,IAAa,qBAAb,MAAa,mBAAmB;CAkCZ;CACA;CACC;CAnCnB;CACA;CACA;CAEA,YAA4B,IAAI,gBAAgB;CAEhD;CAEA,QAAqC;EACnC,cAAc;EACd,aAAa;EACb,YAAY;EACZ,eAAe;EACf,SAAS;EACT,YAAY;EACZ,YAAY;EACZ,UAAU;EACV,aAAa;EACb,aAAa;EACb,gBAAgB;EAChB,aAAa;CACf;;;;;;;;;;CAWA,YACE,OACA,IACA,gBACA,cACA,eACA;EALgB,KAAA,QAAA;EACA,KAAA,KAAA;EACC,KAAA,iBAAA;EAIjB,KAAK,mBAAmB,KAAK,MAAM,OAAO,KAAK,GAAG,UAAU,CAAC;EAE7D,KAAK,kBAAkB,MAAM,OAC3B,GAAG,QAAQ,GAAG,QAAQ,MAAM,CAAC,CAAC,SAAS,SAAS,GAAG,QAAQ,MAAM,WAAW,CAAC,CAC/E;EACA,IAAI,GAAG,OAAO,KAAK,eAAe,MAAM,YACtC,MAAM,IAAI,MAAM,6BAA6B;EAE/C,KAAK,cAAc,MAAM,OACvB,GAAG,QAAQ,GAAG,QAAQ,MAAM,CAAC,CAAC,SAAS,SAAS,GAAG,QAAQ,MAAM,OAAO,CAAC,CAC3E;EACA,IAAI,GAAG,OAAO,KAAK,WAAW,MAAM,YAAY,MAAM,IAAI,MAAM,yBAAyB;EAEzF,IAAI,kBAAkB,KAAA,GACpB,KAAK,mBAAmB,IAAI,wBAC1B,MACA,cAAc,UACd,cAAc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,UAAU,CAAe;EACzD,IAAI,CAAC,SACH,MAAM,IAAI,MACR,gEAAgE,UAAU,IAAI,wBAAwB,YAAY,GACpH;EAGF,MAAM,QAAQ,KAAK,eAAe,IAAI,OAAO;EAC7C,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MACR,iCAAiC,QAAQ,IAAI,wBAAwB,YAAY,GACnF;EAGF,OAAO,IAAI,eAAe,cAAc,KAAc;CACxD;AACF"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../../src/js_render/context.ts"],"sourcesContent":["import type { ComputableCtx } from \"@milaboratories/computable\";\nimport type { BlockCodeKnownFeatureFlags } from \"@platforma-sdk/model\";\nimport { JsRenderInternal } from \"@platforma-sdk/model\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { randomUUID } from \"node:crypto\";\nimport type { QuickJSContext, QuickJSHandle } from \"quickjs-emscripten\";\nimport { Scope, errors } from \"quickjs-emscripten\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport { stringifyWithResourceId } from \"@milaboratories/pl-client\";\nimport { PlQuickJSError } from \"@milaboratories/pl-errors\";\nimport { ComputableContextHelper } from \"./computable_context\";\n\nimport { evaluateBundleCached } from \"./bundle_bytecode_cache\";\nexport type DeadlineSettings = {\n currentExecutionTarget: string;\n deadline: number;\n};\n\n/**\n * Communicates a deadline to the quickjs runtime, that if passed, will interrupt the execution.\n * Undefined can be used to reset the deadline.\n * */\nexport type DeadlineSetter = (settings: DeadlineSettings | undefined) => void;\n\nfunction isArrayBufferOrView(obj: unknown): obj is ArrayBufferLike {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\n\n/**\n * Contains references to objects needed to execute lambda within computable,\n * providing access to:\n * - block context\n * - computable context\n * - middle layer environment\n * */\nexport type ComputableEnv = {\n readonly blockCtx: BlockContextAny;\n readonly mlEnv: MiddleLayerEnvironment;\n computableCtx: ComputableCtx;\n};\n\n/** Execution stats accumulated during the lifetime of a JsExecutionContext. */\nexport type JsExecStats = {\n bundleEvalMs: number;\n bundleBytes: number;\n\n callbackMs: number;\n callbackCount: number;\n\n serInMs: number;\n serInBytes: number;\n serInCalls: number;\n\n serOutMs: number;\n serOutBytes: number;\n serOutCalls: number;\n\n ctxMethodCalls: number;\n ctxMethodMs: number;\n};\n\nexport class JsExecutionContext {\n private readonly callbackRegistry: QuickJSHandle;\n private readonly fnJSONStringify: QuickJSHandle;\n private readonly fnJSONParse: QuickJSHandle;\n\n public readonly errorRepo = new ErrorRepository();\n\n public readonly computableHelper: ComputableContextHelper | undefined;\n\n public readonly stats: JsExecStats = {\n bundleEvalMs: 0,\n bundleBytes: 0,\n callbackMs: 0,\n callbackCount: 0,\n serInMs: 0,\n serInBytes: 0,\n serInCalls: 0,\n serOutMs: 0,\n serOutBytes: 0,\n serOutCalls: 0,\n ctxMethodCalls: 0,\n ctxMethodMs: 0,\n };\n\n /**\n * Creates a new JS execution context.\n *\n * @param scope - QuickJS scope for memory management\n * @param vm - QuickJS VM context\n * @param deadlineSetter - Function to set execution deadline\n * @param featureFlags - Block feature flags\n * @param computableEnv - Optional reactive computable environment (for outputs, inputsValid, etc.)\n */\n constructor(\n public readonly scope: Scope,\n public readonly vm: QuickJSContext,\n private readonly deadlineSetter: DeadlineSetter,\n featureFlags: BlockCodeKnownFeatureFlags | undefined,\n computableEnv?: ComputableEnv,\n ) {\n this.callbackRegistry = this.scope.manage(this.vm.newObject());\n\n this.fnJSONStringify = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"stringify\")),\n );\n if (vm.typeof(this.fnJSONStringify) !== \"function\")\n throw new Error(`JSON.stringify() not found.`);\n\n this.fnJSONParse = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"parse\")),\n );\n if (vm.typeof(this.fnJSONParse) !== \"function\") throw new Error(`JSON.parse() not found.`);\n\n if (computableEnv !== undefined)\n this.computableHelper = new ComputableContextHelper(\n this,\n computableEnv.blockCtx,\n computableEnv.mlEnv,\n featureFlags,\n computableEnv.computableCtx,\n );\n\n this.injectCtx();\n }\n\n public resetComputableCtx() {\n notEmpty(\n this.computableHelper,\n \"Computable context helper is not initialized\",\n ).resetComputableCtx();\n }\n\n private static cleanErrorContext(error: unknown): void {\n if (typeof error === \"object\" && error !== null && \"context\" in error) delete error[\"context\"];\n }\n\n // private static cleanError(error: unknown): unknown {\n // if (error instanceof errors.QuickJSUnwrapError) {\n // const { cause, context: _, name, message, stack, ...rest } = error;\n // const clean = new errors.QuickJSUnwrapError(cause);\n // Object.assign(clean, { ...rest, name, message, stack });\n // return clean;\n // }\n // return error;\n // }\n\n public evaluateBundle(code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n this.vm.unwrapResult(this.vm.evalCode(code, \"bundle.js\", { type: \"global\" })).dispose();\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n /**\n * {@link evaluateBundle}, reusing bytecode compiled for an earlier context with the same\n * code (identified by `cacheKey` when given, by its hash otherwise). Every lambda gets its own\n * context and needs the whole bundle in scope, so parsing per context was the dominant cost of\n * rendering a block.\n */\n public evaluateBundleCached(cacheKey: string | undefined, code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n evaluateBundleCached(this.vm, cacheKey, code);\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n public runCallback(cbName: string, ...args: unknown[]): QuickJSHandle {\n const t0 = performance.now();\n try {\n this.deadlineSetter({ currentExecutionTarget: cbName, deadline: Date.now() + 10000 });\n return Scope.withScope((localScope) => {\n const targetCallback = localScope.manage(this.vm.getProp(this.callbackRegistry, cbName));\n\n if (this.vm.typeof(targetCallback) !== \"function\")\n throw new Error(`No such callback: ${cbName}`);\n\n return this.scope.manage(\n this.vm.unwrapResult(\n this.vm.callFunction(\n targetCallback,\n this.vm.undefined,\n ...args.map((arg) => this.exportObjectUniversal(arg, localScope)),\n ),\n ),\n );\n });\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n const original = this.errorRepo.getOriginal(err);\n throw original;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.callbackMs += performance.now() - t0;\n this.stats.callbackCount++;\n }\n }\n\n //\n // QuickJS Helpers\n //\n\n public exportSingleValue(\n obj: boolean | number | string | null | ArrayBuffer | undefined,\n scope?: Scope,\n ): QuickJSHandle {\n const result = this.tryExportSingleValue(obj, scope);\n if (result === undefined) {\n throw new Error(\n `Can't export value: ${obj === undefined ? \"undefined\" : JSON.stringify(obj)}`,\n );\n }\n return result;\n }\n\n public tryExportSingleValue(obj: unknown, scope?: Scope): QuickJSHandle | undefined {\n let handle: QuickJSHandle;\n let manage = false;\n switch (typeof obj) {\n case \"string\":\n handle = this.vm.newString(obj);\n manage = true;\n break;\n case \"number\":\n handle = this.vm.newNumber(obj);\n manage = true;\n break;\n case \"undefined\":\n handle = this.vm.undefined;\n break;\n case \"boolean\":\n handle = obj ? this.vm.true : this.vm.false;\n break;\n default:\n if (obj === null) {\n handle = this.vm.null;\n break;\n }\n if (isArrayBufferOrView(obj)) {\n handle = this.vm.newArrayBuffer(obj);\n manage = true;\n break;\n }\n return undefined;\n }\n return manage && scope != undefined ? scope.manage(handle) : handle;\n }\n\n public exportObjectUniversal(obj: unknown, scope?: Scope): QuickJSHandle {\n const simpleHandle = this.tryExportSingleValue(obj, scope);\n if (simpleHandle !== undefined) return simpleHandle;\n return this.exportObjectViaJson(obj, scope);\n }\n\n public exportObjectViaJson(obj: unknown, scope?: Scope): QuickJSHandle {\n const t0 = performance.now();\n const json = JSON.stringify(obj);\n this.stats.serInBytes += json.length;\n this.stats.serInCalls++;\n const result = this.vm\n .newString(json)\n .consume((jsonHandle) =>\n this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse, this.vm.undefined, jsonHandle)),\n );\n this.stats.serInMs += performance.now() - t0;\n return scope !== undefined ? scope.manage(result) : result;\n }\n\n public importObjectUniversal(handle: QuickJSHandle | undefined): unknown {\n if (handle === undefined) return undefined;\n switch (this.vm.typeof(handle)) {\n case \"undefined\":\n return undefined;\n case \"boolean\":\n case \"number\":\n case \"string\":\n return this.vm.dump(handle);\n default:\n return this.importObjectViaJson(handle);\n }\n }\n\n public importObjectViaJson(handle: QuickJSHandle): unknown {\n const t0 = performance.now();\n const text = this.vm\n .unwrapResult(this.vm.callFunction(this.fnJSONStringify, this.vm.undefined, handle))\n .consume((strHandle) => this.vm.getString(strHandle));\n this.stats.serOutBytes += text.length;\n this.stats.serOutCalls++;\n if (text === \"undefined\") {\n // special case with futures\n this.stats.serOutMs += performance.now() - t0;\n return undefined;\n }\n const result = JSON.parse(text);\n this.stats.serOutMs += performance.now() - t0;\n return result;\n }\n\n private injectCtx() {\n Scope.withScope((localScope) => {\n const configCtx = localScope.manage(this.vm.newObject());\n\n //\n // Core props\n //\n\n this.vm.setProp(configCtx, \"callbackRegistry\", this.callbackRegistry);\n this.vm.setProp(\n configCtx,\n \"featureFlags\",\n this.exportObjectUniversal(JsRenderInternal.GlobalCfgRenderCtxFeatureFlags, localScope),\n );\n\n // Inject context values from computableHelper (reactive context for outputs, inputsValid, etc.)\n if (this.computableHelper !== undefined) {\n this.computableHelper.injectCtx(configCtx);\n }\n\n //\n // Creating global variable inside the vm\n //\n\n this.vm.setProp(this.vm.global, \"cfgRenderCtx\", configCtx);\n });\n }\n}\n\n/** Holds errors that happened in the host code (like in middle-layer's drivers)\n * and then throws it where the error from quick JS is needed.\n * QuickJS couldn't throw custom errors, so we store them here, and rethrow them when we exit QuickJS side. */\nexport class ErrorRepository {\n private readonly errorIdToError = new Map<string, unknown>();\n\n /** Sets the error to the repository and returns a mimicrated error that also has uuid key of the original error. */\n public setAndRecreateForQuickJS(error: unknown): {\n name: string;\n message: string;\n } {\n const errorId = randomUUID();\n this.errorIdToError.set(errorId, error);\n\n if (error instanceof Error) {\n return {\n name: `${error.name}/uuid:${errorId}`,\n message: error.message,\n };\n }\n\n return {\n name: `UnknownErrorQuickJS/uuid:${errorId}`,\n message: `${error as any}`,\n };\n }\n\n /** Returns the original error that was stored by parsing uuid of mimicrated error. */\n public getOriginal(quickJSError: unknown): unknown {\n if (!(quickJSError instanceof errors.QuickJSUnwrapError)) {\n console.warn(\n \"ErrorRepo: quickJSError is not a QuickJSUnwrapError\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const cause = quickJSError.cause;\n if (\n !(\n typeof cause === \"object\" &&\n cause !== null &&\n \"name\" in cause &&\n typeof cause.name === \"string\"\n )\n ) {\n console.warn(\n \"ErrorRepo: quickJSError.cause is not an Error (can be stack limit exceeded)\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const causeName = cause.name;\n const uuidIdx = causeName.indexOf(\"/uuid:\");\n if (uuidIdx === -1) {\n const causeMsg = \"message\" in cause && typeof cause.message === \"string\" ? cause.message : \"\";\n throw new Error(\n `QuickJS native error: ${causeName}: ${causeMsg}, ${stringifyWithResourceId(quickJSError)}`,\n { cause: quickJSError },\n );\n }\n const errorId = causeName.slice(uuidIdx + \"/uuid:\".length);\n if (!errorId) {\n throw new Error(\n `ErrorRepo: quickJSError.cause.name does not contain errorId: ${causeName}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n const error = this.errorIdToError.get(errorId);\n if (error === undefined) {\n throw new Error(\n `ErrorRepo: errorId not found: ${errorId}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n return new PlQuickJSError(quickJSError, error as Error);\n }\n}\n"],"m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EAGF,OAAO,IAAI,eAAe,cAAc,KAAc;CACxD;AACF"}
@@ -159,7 +159,7 @@ function executeSingleLambda(quickJs, fh, codeWithInfo, ...args) {
159
159
  const rCtx = new require_context.JsExecutionContext(scope, vm, (s) => {
160
160
  deadlineSettings = s;
161
161
  }, featureFlags);
162
- rCtx.evaluateBundle(code.content);
162
+ rCtx.evaluateBundleCached(void 0, code.content);
163
163
  const importedResult = rCtx.importObjectUniversal(rCtx.runCallback(fh.handle, ...args));
164
164
  if (require_index.getDebugFlags().logJsExecStat) console.log(`[jsExec] ${fh.handle}: ${JSON.stringify(rCtx.stats)}`);
165
165
  return importedResult;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["getDebugFlags","Computable","Scope","JsExecutionContext","recordModelRenderSync"],"sources":["../../src/js_render/index.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport type { BlockCodeWithInfo, ConfigRenderLambda } from \"@platforma-sdk/model\";\nimport type { BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport type { ComputableRenderingOps } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { Scope } from \"quickjs-emscripten\";\nimport type { DeadlineSettings } from \"./context\";\nimport { JsExecutionContext } from \"./context\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport { getDebugFlags } from \"../debug\";\nimport { recordModelRenderSync } from \"@milaboratories/pl-crash-recorder\";\n\n/** Memory ceiling applied to every QuickJS runtime that evaluates model code. */\nconst QUICK_JS_MEMORY_LIMIT = 1024 * 1024 * 8;\n\nfunction logOutputStatus(\n handle: string,\n renderedResult: unknown,\n stable: boolean,\n recalculationCounter: number,\n unstableMarker?: string,\n) {\n if (getDebugFlags().logOutputStatus && (getDebugFlags().logOutputStatus === \"any\" || !stable)) {\n if (stable)\n console.log(\n `Stable output ${handle} calculated ${renderedResult !== undefined ? \"defined\" : \"undefined\"}; (#${recalculationCounter})`,\n );\n else\n console.log(\n `Unstable output ${handle}; marker = ${unstableMarker}; ${renderedResult !== undefined ? \"defined\" : \"undefined\"} (#${recalculationCounter})`,\n );\n }\n}\n\n/**\n * Creates a Computable that executes a render function (`fh`) from a block's code in a QuickJS virtual machine.\n * This function handles both synchronous and asynchronous execution patterns of the sandboxed JS code.\n *\n * The overall data flow is as follows:\n * 1. A QuickJS VM is initialized.\n * 2. A `JsExecutionContext` is created to bridge the host (TypeScript) and guest (QuickJS) environments. It injects a\n * context object (`cfgRenderCtx`) into the VM, providing helper methods for the sandboxed code to interact with the\n * platform (e.g., to request data).\n * 3. The block's Javascript bundle is evaluated in the VM.\n * 4. The specified render function (`fh.handle`) is executed.\n *\n * Two execution paths are possible depending on the behavior of the render function:\n *\n * ### Synchronous Path\n * If the render function computes its result without requesting any external data requiring asynchronous calculations,\n * it executes synchronously.\n * - The `computablesToResolve` map in `JsExecutionContext` remains empty.\n * - The function returns an object with an `ir` field holding the result (`{ ir: importedResult }`).\n * Since `postprocessValue` is not specified, `ir` is treated as the final resolved value of the Computable.\n * - The QuickJS VM is disposed of immediately as it's no longer needed.\n *\n * ### Asynchronous Path (with `postprocessValue`)\n * If the render function needs external data requiring asynchronous calculations (e.g., fetching a file), it calls\n * one of the injected helper methods. These methods don't return data directly. Instead, they:\n * a. Create a new `Computable` for the data request (e.g., to fetch a blob).\n * b. Register this new `Computable` in the `computablesToResolve` map.\n * c. Return a handle (string) to the sandboxed code.\n *\n * In this case:\n * - The initial execution of the render function returns a scaffold of the final result, which depends on the pending\n * computables.\n * - The `computablesToResolve` map is passed as the `ir` (initial result) to `Computable.makeRaw`.\n * - The `postprocessValue` function is provided to handle the results once the computables are resolved.\n * - The QuickJS VM is kept alive (`keepVmAlive = true`) because its state is needed in `postprocessValue`.\n * - Once the `computable` framework resolves all dependencies, it calls `postprocessValue` with the resolved data.\n * - `postprocessValue` feeds the resolved data back into the VM, allowing the sandboxed code to compute the final\n * result.\n * - The VM is eventually disposed of when the host Computable is destroyed.\n *\n * @param env The middle layer environment.\n * @param ctx The block context.\n * @param fh The config render lambda to execute.\n * @param codeWithInfo The block's code and feature flags.\n * @param configKey A key for the configuration, used for cache busting.\n * @param ops Options for the computable.\n * @returns A `Computable` that will resolve to the result of the lambda execution.\n */\nexport function computableFromRF(\n env: MiddleLayerEnvironment,\n ctx: BlockContextAny,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n configKey: string,\n ops: Partial<ComputableRenderingOps> = {},\n blockPack?: BlockPackSpec,\n): Computable<unknown> {\n // adding configKey to reload all outputs on block-pack update\n const key = `${ctx.blockId}#lambda#${configKey}#${fh.handle}`;\n ops = { ...ops, key };\n if (ops.mode === undefined && fh.retentive === true) ops.mode = \"StableOnlyRetentive\";\n return Computable.makeRaw((cCtx) => {\n const { code, featureFlags } = codeWithInfo;\n\n if (getDebugFlags().logOutputRecalculations)\n console.log(\n `Block lambda recalculation : ${key} (${cCtx.changeSourceMarker}; ${cCtx.bodyInvocations} invocations)`,\n );\n\n const scope = new Scope();\n let keepVmAlive = false;\n cCtx.addOnDestroy(() => {\n // If keepVmAlive is false, the scope will be disposed by the finally block,\n // no need to dispose it here.\n if (keepVmAlive) scope.dispose();\n });\n\n try {\n const runtime = scope.manage(env.quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n { computableCtx: cCtx, blockCtx: ctx, mlEnv: env },\n );\n\n const crashRecorder = env.driverKit.crashRecorder;\n const renderInfo = {\n blockId: ctx.blockId,\n // A block id is unique to one project; these say which code it is, so a\n // log can be read against the right version without the project.\n ...describeBlockPack(blockPack),\n sdkVersion: codeWithInfo.sdkVersion,\n key,\n lambda: fh.handle,\n // The sandbox has its own 8 MB ceiling, so the model's own objects can\n // never exhaust the host heap. What can is the volume crossing out of\n // it, which `stats` counts.\n sandboxMemoryLimit: QUICK_JS_MEMORY_LIMIT,\n getStats: () => ({ ...rCtx.stats }),\n };\n\n return recordModelRenderSync(crashRecorder, renderInfo, () => {\n // configKey already identifies this block pack's config, and exists to invalidate\n // rendered outputs when the pack changes, so it keys the compiled bundle too.\n rCtx.evaluateBundleCached(configKey, code.content);\n const result = rCtx.runCallback(fh.handle);\n\n rCtx.resetComputableCtx();\n\n const toBeResolved = rCtx.computableHelper!.computablesToResolve;\n\n if (Object.keys(toBeResolved).length === 0) {\n const importedResult = rCtx.importObjectUniversal(result);\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${key}: ${JSON.stringify(rCtx.stats)}`);\n logOutputStatus(\n fh.handle,\n importedResult,\n cCtx.unstableMarker === undefined,\n -1,\n cCtx.unstableMarker,\n );\n return { ir: importedResult };\n }\n\n let recalculationCounter = 0;\n if (getDebugFlags().logOutputStatus)\n console.log(\n `Output ${fh.handle} scaffold calculated (not all computables resolved yet).`,\n );\n keepVmAlive = true;\n\n return {\n ir: toBeResolved,\n postprocessValue: (resolved: Record<string, unknown>, { unstableMarker, stable }) => {\n recalculationCounter++;\n // A deferred render resumes here, potentially many times, and each\n // resumption can build joins of its own, so each gets its own span.\n return recordModelRenderSync(\n crashRecorder,\n { ...renderInfo, recalculation: recalculationCounter },\n () => {\n // resolving futures\n for (const [handle, value] of Object.entries(resolved))\n rCtx.runCallback(handle, value);\n\n // rendering result\n const renderedResult = rCtx.importObjectUniversal(result);\n\n // logging\n if (getDebugFlags().logJsExecStat)\n console.log(\n `[jsExec] ${key} #${recalculationCounter}: ${JSON.stringify(rCtx.stats)}`,\n );\n logOutputStatus(\n fh.handle,\n renderedResult,\n stable,\n recalculationCounter,\n unstableMarker,\n );\n\n return renderedResult;\n },\n );\n },\n };\n });\n } catch (e) {\n keepVmAlive = false;\n throw e;\n } finally {\n if (!keepVmAlive) scope.dispose();\n }\n }, ops);\n}\n\nexport function executeSingleLambda(\n quickJs: QuickJSWASMModule,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n ...args: unknown[]\n): unknown {\n const { code, featureFlags } = codeWithInfo;\n const scope = new Scope();\n try {\n const runtime = scope.manage(quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n );\n\n // Initializing the model\n rCtx.evaluateBundle(code.content);\n\n // Running the lambda with arguments (e.g., state for args(), args for enrichmentTargets())\n const importedResult = rCtx.importObjectUniversal(rCtx.runCallback(fh.handle, ...args));\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${fh.handle}: ${JSON.stringify(rCtx.stats)}`);\n return importedResult;\n } finally {\n scope.dispose();\n }\n}\n\n/**\n * The part of a block pack that names the code, and nothing else.\n *\n * Registry packs carry an organization, name and version, which is what a reader\n * needs to open the right source. Local and development packs carry a filesystem\n * path instead; the path is deliberately not recorded — it identifies the\n * machine rather than the code, and its `type` already says that no published\n * version exists to look up.\n */\nfunction describeBlockPack(spec: BlockPackSpec | undefined): {\n block?: string;\n blockVersion?: string;\n blockSource?: string;\n} {\n if (spec === undefined) return {};\n if (spec.type === \"from-registry-v1\" || spec.type === \"from-registry-v2\") {\n return {\n block: `${spec.id.organization}:${spec.id.name}`,\n blockVersion: spec.id.version,\n blockSource: spec.type,\n };\n }\n return { block: \"(unpublished)\", blockSource: spec.type };\n}\n"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,kBAAkB,MAIzB;CACA,IAAI,SAAS,KAAA,GAAW,OAAO,CAAC;CAChC,IAAI,KAAK,SAAS,sBAAsB,KAAK,SAAS,oBACpD,OAAO;EACL,OAAO,GAAG,KAAK,GAAG,aAAa,GAAG,KAAK,GAAG;EAC1C,cAAc,KAAK,GAAG;EACtB,aAAa,KAAK;CACpB;CAEF,OAAO;EAAE,OAAO;EAAiB,aAAa,KAAK;CAAK;AAC1D"}
1
+ {"version":3,"file":"index.cjs","names":["getDebugFlags","Computable","Scope","JsExecutionContext","recordModelRenderSync"],"sources":["../../src/js_render/index.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport type { BlockCodeWithInfo, ConfigRenderLambda } from \"@platforma-sdk/model\";\nimport type { BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport type { ComputableRenderingOps } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { Scope } from \"quickjs-emscripten\";\nimport type { DeadlineSettings } from \"./context\";\nimport { JsExecutionContext } from \"./context\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport { getDebugFlags } from \"../debug\";\nimport { recordModelRenderSync } from \"@milaboratories/pl-crash-recorder\";\n\n/** Memory ceiling applied to every QuickJS runtime that evaluates model code. */\nconst QUICK_JS_MEMORY_LIMIT = 1024 * 1024 * 8;\n\nfunction logOutputStatus(\n handle: string,\n renderedResult: unknown,\n stable: boolean,\n recalculationCounter: number,\n unstableMarker?: string,\n) {\n if (getDebugFlags().logOutputStatus && (getDebugFlags().logOutputStatus === \"any\" || !stable)) {\n if (stable)\n console.log(\n `Stable output ${handle} calculated ${renderedResult !== undefined ? \"defined\" : \"undefined\"}; (#${recalculationCounter})`,\n );\n else\n console.log(\n `Unstable output ${handle}; marker = ${unstableMarker}; ${renderedResult !== undefined ? \"defined\" : \"undefined\"} (#${recalculationCounter})`,\n );\n }\n}\n\n/**\n * Creates a Computable that executes a render function (`fh`) from a block's code in a QuickJS virtual machine.\n * This function handles both synchronous and asynchronous execution patterns of the sandboxed JS code.\n *\n * The overall data flow is as follows:\n * 1. A QuickJS VM is initialized.\n * 2. A `JsExecutionContext` is created to bridge the host (TypeScript) and guest (QuickJS) environments. It injects a\n * context object (`cfgRenderCtx`) into the VM, providing helper methods for the sandboxed code to interact with the\n * platform (e.g., to request data).\n * 3. The block's Javascript bundle is evaluated in the VM.\n * 4. The specified render function (`fh.handle`) is executed.\n *\n * Two execution paths are possible depending on the behavior of the render function:\n *\n * ### Synchronous Path\n * If the render function computes its result without requesting any external data requiring asynchronous calculations,\n * it executes synchronously.\n * - The `computablesToResolve` map in `JsExecutionContext` remains empty.\n * - The function returns an object with an `ir` field holding the result (`{ ir: importedResult }`).\n * Since `postprocessValue` is not specified, `ir` is treated as the final resolved value of the Computable.\n * - The QuickJS VM is disposed of immediately as it's no longer needed.\n *\n * ### Asynchronous Path (with `postprocessValue`)\n * If the render function needs external data requiring asynchronous calculations (e.g., fetching a file), it calls\n * one of the injected helper methods. These methods don't return data directly. Instead, they:\n * a. Create a new `Computable` for the data request (e.g., to fetch a blob).\n * b. Register this new `Computable` in the `computablesToResolve` map.\n * c. Return a handle (string) to the sandboxed code.\n *\n * In this case:\n * - The initial execution of the render function returns a scaffold of the final result, which depends on the pending\n * computables.\n * - The `computablesToResolve` map is passed as the `ir` (initial result) to `Computable.makeRaw`.\n * - The `postprocessValue` function is provided to handle the results once the computables are resolved.\n * - The QuickJS VM is kept alive (`keepVmAlive = true`) because its state is needed in `postprocessValue`.\n * - Once the `computable` framework resolves all dependencies, it calls `postprocessValue` with the resolved data.\n * - `postprocessValue` feeds the resolved data back into the VM, allowing the sandboxed code to compute the final\n * result.\n * - The VM is eventually disposed of when the host Computable is destroyed.\n *\n * @param env The middle layer environment.\n * @param ctx The block context.\n * @param fh The config render lambda to execute.\n * @param codeWithInfo The block's code and feature flags.\n * @param configKey A key for the configuration, used for cache busting.\n * @param ops Options for the computable.\n * @returns A `Computable` that will resolve to the result of the lambda execution.\n */\nexport function computableFromRF(\n env: MiddleLayerEnvironment,\n ctx: BlockContextAny,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n configKey: string,\n ops: Partial<ComputableRenderingOps> = {},\n blockPack?: BlockPackSpec,\n): Computable<unknown> {\n // adding configKey to reload all outputs on block-pack update\n const key = `${ctx.blockId}#lambda#${configKey}#${fh.handle}`;\n ops = { ...ops, key };\n if (ops.mode === undefined && fh.retentive === true) ops.mode = \"StableOnlyRetentive\";\n return Computable.makeRaw((cCtx) => {\n const { code, featureFlags } = codeWithInfo;\n\n if (getDebugFlags().logOutputRecalculations)\n console.log(\n `Block lambda recalculation : ${key} (${cCtx.changeSourceMarker}; ${cCtx.bodyInvocations} invocations)`,\n );\n\n const scope = new Scope();\n let keepVmAlive = false;\n cCtx.addOnDestroy(() => {\n // If keepVmAlive is false, the scope will be disposed by the finally block,\n // no need to dispose it here.\n if (keepVmAlive) scope.dispose();\n });\n\n try {\n const runtime = scope.manage(env.quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n { computableCtx: cCtx, blockCtx: ctx, mlEnv: env },\n );\n\n const crashRecorder = env.driverKit.crashRecorder;\n const renderInfo = {\n blockId: ctx.blockId,\n // A block id is unique to one project; these say which code it is, so a\n // log can be read against the right version without the project.\n ...describeBlockPack(blockPack),\n sdkVersion: codeWithInfo.sdkVersion,\n key,\n lambda: fh.handle,\n // The sandbox has its own 8 MB ceiling, so the model's own objects can\n // never exhaust the host heap. What can is the volume crossing out of\n // it, which `stats` counts.\n sandboxMemoryLimit: QUICK_JS_MEMORY_LIMIT,\n getStats: () => ({ ...rCtx.stats }),\n };\n\n return recordModelRenderSync(crashRecorder, renderInfo, () => {\n // configKey already identifies this block pack's config, and exists to invalidate\n // rendered outputs when the pack changes, so it keys the compiled bundle too.\n rCtx.evaluateBundleCached(configKey, code.content);\n const result = rCtx.runCallback(fh.handle);\n\n rCtx.resetComputableCtx();\n\n const toBeResolved = rCtx.computableHelper!.computablesToResolve;\n\n if (Object.keys(toBeResolved).length === 0) {\n const importedResult = rCtx.importObjectUniversal(result);\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${key}: ${JSON.stringify(rCtx.stats)}`);\n logOutputStatus(\n fh.handle,\n importedResult,\n cCtx.unstableMarker === undefined,\n -1,\n cCtx.unstableMarker,\n );\n return { ir: importedResult };\n }\n\n let recalculationCounter = 0;\n if (getDebugFlags().logOutputStatus)\n console.log(\n `Output ${fh.handle} scaffold calculated (not all computables resolved yet).`,\n );\n keepVmAlive = true;\n\n return {\n ir: toBeResolved,\n postprocessValue: (resolved: Record<string, unknown>, { unstableMarker, stable }) => {\n recalculationCounter++;\n // A deferred render resumes here, potentially many times, and each\n // resumption can build joins of its own, so each gets its own span.\n return recordModelRenderSync(\n crashRecorder,\n { ...renderInfo, recalculation: recalculationCounter },\n () => {\n // resolving futures\n for (const [handle, value] of Object.entries(resolved))\n rCtx.runCallback(handle, value);\n\n // rendering result\n const renderedResult = rCtx.importObjectUniversal(result);\n\n // logging\n if (getDebugFlags().logJsExecStat)\n console.log(\n `[jsExec] ${key} #${recalculationCounter}: ${JSON.stringify(rCtx.stats)}`,\n );\n logOutputStatus(\n fh.handle,\n renderedResult,\n stable,\n recalculationCounter,\n unstableMarker,\n );\n\n return renderedResult;\n },\n );\n },\n };\n });\n } catch (e) {\n keepVmAlive = false;\n throw e;\n } finally {\n if (!keepVmAlive) scope.dispose();\n }\n }, ops);\n}\n\nexport function executeSingleLambda(\n quickJs: QuickJSWASMModule,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n ...args: unknown[]\n): unknown {\n const { code, featureFlags } = codeWithInfo;\n const scope = new Scope();\n try {\n const runtime = scope.manage(quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n );\n\n // Initializing the model. The bytecode cache spares compiling the bundle on every call: the\n // args derivations of each write and readiness check run here.\n rCtx.evaluateBundleCached(undefined, code.content);\n\n // Running the lambda with arguments (e.g., state for args(), args for enrichmentTargets())\n const importedResult = rCtx.importObjectUniversal(rCtx.runCallback(fh.handle, ...args));\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${fh.handle}: ${JSON.stringify(rCtx.stats)}`);\n return importedResult;\n } finally {\n scope.dispose();\n }\n}\n\n/**\n * The part of a block pack that names the code, and nothing else.\n *\n * Registry packs carry an organization, name and version, which is what a reader\n * needs to open the right source. Local and development packs carry a filesystem\n * path instead; the path is deliberately not recorded — it identifies the\n * machine rather than the code, and its `type` already says that no published\n * version exists to look up.\n */\nfunction describeBlockPack(spec: BlockPackSpec | undefined): {\n block?: string;\n blockVersion?: string;\n blockSource?: string;\n} {\n if (spec === undefined) return {};\n if (spec.type === \"from-registry-v1\" || spec.type === \"from-registry-v2\") {\n return {\n block: `${spec.id.organization}:${spec.id.name}`,\n blockVersion: spec.id.version,\n blockSource: spec.type,\n };\n }\n return { block: \"(unpublished)\", blockSource: spec.type };\n}\n"],"mappings":";;;;;;;AAcA,MAAM,wBAAwB;AAE9B,SAAS,gBACP,QACA,gBACA,QACA,sBACA,gBAC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AI,KAAK,SAAS,sBAAsB,KAAK,SAAS,oBACpD,OAAO;EACL,OAAO,GAAG,KAAK,GAAG,aAAa,GAAG,KAAK,GAAG;EAC1C,cAAc,KAAK,GAAG;EACtB,aAAa,KAAK;CACpB;CAEF,OAAO;EAAE,OAAO;EAAiB,aAAa,KAAK;CAAK;AAC1D"}
@@ -159,7 +159,7 @@ function executeSingleLambda(quickJs, fh, codeWithInfo, ...args) {
159
159
  const rCtx = new JsExecutionContext(scope, vm, (s) => {
160
160
  deadlineSettings = s;
161
161
  }, featureFlags);
162
- rCtx.evaluateBundle(code.content);
162
+ rCtx.evaluateBundleCached(void 0, code.content);
163
163
  const importedResult = rCtx.importObjectUniversal(rCtx.runCallback(fh.handle, ...args));
164
164
  if (getDebugFlags().logJsExecStat) console.log(`[jsExec] ${fh.handle}: ${JSON.stringify(rCtx.stats)}`);
165
165
  return importedResult;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/js_render/index.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport type { BlockCodeWithInfo, ConfigRenderLambda } from \"@platforma-sdk/model\";\nimport type { BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport type { ComputableRenderingOps } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { Scope } from \"quickjs-emscripten\";\nimport type { DeadlineSettings } from \"./context\";\nimport { JsExecutionContext } from \"./context\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport { getDebugFlags } from \"../debug\";\nimport { recordModelRenderSync } from \"@milaboratories/pl-crash-recorder\";\n\n/** Memory ceiling applied to every QuickJS runtime that evaluates model code. */\nconst QUICK_JS_MEMORY_LIMIT = 1024 * 1024 * 8;\n\nfunction logOutputStatus(\n handle: string,\n renderedResult: unknown,\n stable: boolean,\n recalculationCounter: number,\n unstableMarker?: string,\n) {\n if (getDebugFlags().logOutputStatus && (getDebugFlags().logOutputStatus === \"any\" || !stable)) {\n if (stable)\n console.log(\n `Stable output ${handle} calculated ${renderedResult !== undefined ? \"defined\" : \"undefined\"}; (#${recalculationCounter})`,\n );\n else\n console.log(\n `Unstable output ${handle}; marker = ${unstableMarker}; ${renderedResult !== undefined ? \"defined\" : \"undefined\"} (#${recalculationCounter})`,\n );\n }\n}\n\n/**\n * Creates a Computable that executes a render function (`fh`) from a block's code in a QuickJS virtual machine.\n * This function handles both synchronous and asynchronous execution patterns of the sandboxed JS code.\n *\n * The overall data flow is as follows:\n * 1. A QuickJS VM is initialized.\n * 2. A `JsExecutionContext` is created to bridge the host (TypeScript) and guest (QuickJS) environments. It injects a\n * context object (`cfgRenderCtx`) into the VM, providing helper methods for the sandboxed code to interact with the\n * platform (e.g., to request data).\n * 3. The block's Javascript bundle is evaluated in the VM.\n * 4. The specified render function (`fh.handle`) is executed.\n *\n * Two execution paths are possible depending on the behavior of the render function:\n *\n * ### Synchronous Path\n * If the render function computes its result without requesting any external data requiring asynchronous calculations,\n * it executes synchronously.\n * - The `computablesToResolve` map in `JsExecutionContext` remains empty.\n * - The function returns an object with an `ir` field holding the result (`{ ir: importedResult }`).\n * Since `postprocessValue` is not specified, `ir` is treated as the final resolved value of the Computable.\n * - The QuickJS VM is disposed of immediately as it's no longer needed.\n *\n * ### Asynchronous Path (with `postprocessValue`)\n * If the render function needs external data requiring asynchronous calculations (e.g., fetching a file), it calls\n * one of the injected helper methods. These methods don't return data directly. Instead, they:\n * a. Create a new `Computable` for the data request (e.g., to fetch a blob).\n * b. Register this new `Computable` in the `computablesToResolve` map.\n * c. Return a handle (string) to the sandboxed code.\n *\n * In this case:\n * - The initial execution of the render function returns a scaffold of the final result, which depends on the pending\n * computables.\n * - The `computablesToResolve` map is passed as the `ir` (initial result) to `Computable.makeRaw`.\n * - The `postprocessValue` function is provided to handle the results once the computables are resolved.\n * - The QuickJS VM is kept alive (`keepVmAlive = true`) because its state is needed in `postprocessValue`.\n * - Once the `computable` framework resolves all dependencies, it calls `postprocessValue` with the resolved data.\n * - `postprocessValue` feeds the resolved data back into the VM, allowing the sandboxed code to compute the final\n * result.\n * - The VM is eventually disposed of when the host Computable is destroyed.\n *\n * @param env The middle layer environment.\n * @param ctx The block context.\n * @param fh The config render lambda to execute.\n * @param codeWithInfo The block's code and feature flags.\n * @param configKey A key for the configuration, used for cache busting.\n * @param ops Options for the computable.\n * @returns A `Computable` that will resolve to the result of the lambda execution.\n */\nexport function computableFromRF(\n env: MiddleLayerEnvironment,\n ctx: BlockContextAny,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n configKey: string,\n ops: Partial<ComputableRenderingOps> = {},\n blockPack?: BlockPackSpec,\n): Computable<unknown> {\n // adding configKey to reload all outputs on block-pack update\n const key = `${ctx.blockId}#lambda#${configKey}#${fh.handle}`;\n ops = { ...ops, key };\n if (ops.mode === undefined && fh.retentive === true) ops.mode = \"StableOnlyRetentive\";\n return Computable.makeRaw((cCtx) => {\n const { code, featureFlags } = codeWithInfo;\n\n if (getDebugFlags().logOutputRecalculations)\n console.log(\n `Block lambda recalculation : ${key} (${cCtx.changeSourceMarker}; ${cCtx.bodyInvocations} invocations)`,\n );\n\n const scope = new Scope();\n let keepVmAlive = false;\n cCtx.addOnDestroy(() => {\n // If keepVmAlive is false, the scope will be disposed by the finally block,\n // no need to dispose it here.\n if (keepVmAlive) scope.dispose();\n });\n\n try {\n const runtime = scope.manage(env.quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n { computableCtx: cCtx, blockCtx: ctx, mlEnv: env },\n );\n\n const crashRecorder = env.driverKit.crashRecorder;\n const renderInfo = {\n blockId: ctx.blockId,\n // A block id is unique to one project; these say which code it is, so a\n // log can be read against the right version without the project.\n ...describeBlockPack(blockPack),\n sdkVersion: codeWithInfo.sdkVersion,\n key,\n lambda: fh.handle,\n // The sandbox has its own 8 MB ceiling, so the model's own objects can\n // never exhaust the host heap. What can is the volume crossing out of\n // it, which `stats` counts.\n sandboxMemoryLimit: QUICK_JS_MEMORY_LIMIT,\n getStats: () => ({ ...rCtx.stats }),\n };\n\n return recordModelRenderSync(crashRecorder, renderInfo, () => {\n // configKey already identifies this block pack's config, and exists to invalidate\n // rendered outputs when the pack changes, so it keys the compiled bundle too.\n rCtx.evaluateBundleCached(configKey, code.content);\n const result = rCtx.runCallback(fh.handle);\n\n rCtx.resetComputableCtx();\n\n const toBeResolved = rCtx.computableHelper!.computablesToResolve;\n\n if (Object.keys(toBeResolved).length === 0) {\n const importedResult = rCtx.importObjectUniversal(result);\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${key}: ${JSON.stringify(rCtx.stats)}`);\n logOutputStatus(\n fh.handle,\n importedResult,\n cCtx.unstableMarker === undefined,\n -1,\n cCtx.unstableMarker,\n );\n return { ir: importedResult };\n }\n\n let recalculationCounter = 0;\n if (getDebugFlags().logOutputStatus)\n console.log(\n `Output ${fh.handle} scaffold calculated (not all computables resolved yet).`,\n );\n keepVmAlive = true;\n\n return {\n ir: toBeResolved,\n postprocessValue: (resolved: Record<string, unknown>, { unstableMarker, stable }) => {\n recalculationCounter++;\n // A deferred render resumes here, potentially many times, and each\n // resumption can build joins of its own, so each gets its own span.\n return recordModelRenderSync(\n crashRecorder,\n { ...renderInfo, recalculation: recalculationCounter },\n () => {\n // resolving futures\n for (const [handle, value] of Object.entries(resolved))\n rCtx.runCallback(handle, value);\n\n // rendering result\n const renderedResult = rCtx.importObjectUniversal(result);\n\n // logging\n if (getDebugFlags().logJsExecStat)\n console.log(\n `[jsExec] ${key} #${recalculationCounter}: ${JSON.stringify(rCtx.stats)}`,\n );\n logOutputStatus(\n fh.handle,\n renderedResult,\n stable,\n recalculationCounter,\n unstableMarker,\n );\n\n return renderedResult;\n },\n );\n },\n };\n });\n } catch (e) {\n keepVmAlive = false;\n throw e;\n } finally {\n if (!keepVmAlive) scope.dispose();\n }\n }, ops);\n}\n\nexport function executeSingleLambda(\n quickJs: QuickJSWASMModule,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n ...args: unknown[]\n): unknown {\n const { code, featureFlags } = codeWithInfo;\n const scope = new Scope();\n try {\n const runtime = scope.manage(quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n );\n\n // Initializing the model\n rCtx.evaluateBundle(code.content);\n\n // Running the lambda with arguments (e.g., state for args(), args for enrichmentTargets())\n const importedResult = rCtx.importObjectUniversal(rCtx.runCallback(fh.handle, ...args));\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${fh.handle}: ${JSON.stringify(rCtx.stats)}`);\n return importedResult;\n } finally {\n scope.dispose();\n }\n}\n\n/**\n * The part of a block pack that names the code, and nothing else.\n *\n * Registry packs carry an organization, name and version, which is what a reader\n * needs to open the right source. Local and development packs carry a filesystem\n * path instead; the path is deliberately not recorded — it identifies the\n * machine rather than the code, and its `type` already says that no published\n * version exists to look up.\n */\nfunction describeBlockPack(spec: BlockPackSpec | undefined): {\n block?: string;\n blockVersion?: string;\n blockSource?: string;\n} {\n if (spec === undefined) return {};\n if (spec.type === \"from-registry-v1\" || spec.type === \"from-registry-v2\") {\n return {\n block: `${spec.id.organization}:${spec.id.name}`,\n blockVersion: spec.id.version,\n blockSource: spec.type,\n };\n }\n return { block: \"(unpublished)\", blockSource: spec.type };\n}\n"],"mappings":";;;;;;;AAcA,MAAM,wBAAwB;AAE9B,SAAS,gBACP,QACA,gBACA,QACA,sBACA,gBACA;CACA,IAAI,cAAc,CAAC,CAAC,oBAAoB,cAAc,CAAC,CAAC,oBAAoB,SAAS,CAAC,SAAS;EAC7F,IAAI,QACF,QAAQ,IACN,iBAAiB,OAAO,cAAc,mBAAmB,KAAA,IAAY,YAAY,YAAY,MAAM,qBAAqB,EAC1H;OAEA,QAAQ,IACN,mBAAmB,OAAO,aAAa,eAAe,IAAI,mBAAmB,KAAA,IAAY,YAAY,YAAY,KAAK,qBAAqB,EAC7I;CACJ;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,iBACd,KACA,KACA,IACA,cACA,WACA,MAAuC,CAAC,GACxC,WACqB;CAErB,MAAM,MAAM,GAAG,IAAI,QAAQ,UAAU,UAAU,GAAG,GAAG;CACrD,MAAM;EAAE,GAAG;EAAK;CAAI;CACpB,IAAI,IAAI,SAAS,KAAA,KAAa,GAAG,cAAc,MAAM,IAAI,OAAO;CAChE,OAAO,WAAW,SAAS,SAAS;EAClC,MAAM,EAAE,MAAM,iBAAiB;EAE/B,IAAI,cAAc,CAAC,CAAC,yBAClB,QAAQ,IACN,gCAAgC,IAAI,IAAI,KAAK,mBAAmB,IAAI,KAAK,gBAAgB,cAC3F;EAEF,MAAM,QAAQ,IAAI,MAAM;EACxB,IAAI,cAAc;EAClB,KAAK,mBAAmB;GAGtB,IAAI,aAAa,MAAM,QAAQ;EACjC,CAAC;EAED,IAAI;GACF,MAAM,UAAU,MAAM,OAAO,IAAI,QAAQ,WAAW,CAAC;GACrD,QAAQ,eAAe,qBAAqB;GAC5C,QAAQ,gBAAgB,MAAU;GAElC,IAAI;GACJ,QAAQ,0BAA0B;IACh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AAO,CAAC;CAChC,IAAI,KAAK,SAAS,sBAAsB,KAAK,SAAS,oBACpD,OAAO;EACL,OAAO,GAAG,KAAK,GAAG,aAAa,GAAG,KAAK,GAAG;EAC1C,cAAc,KAAK,GAAG;EACtB,aAAa,KAAK;CACpB;CAEF,OAAO;EAAE,OAAO;EAAiB,aAAa,KAAK;CAAK;AAC1D"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/js_render/index.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport type { BlockCodeWithInfo, ConfigRenderLambda } from \"@platforma-sdk/model\";\nimport type { BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport type { ComputableRenderingOps } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { Scope } from \"quickjs-emscripten\";\nimport type { DeadlineSettings } from \"./context\";\nimport { JsExecutionContext } from \"./context\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport { getDebugFlags } from \"../debug\";\nimport { recordModelRenderSync } from \"@milaboratories/pl-crash-recorder\";\n\n/** Memory ceiling applied to every QuickJS runtime that evaluates model code. */\nconst QUICK_JS_MEMORY_LIMIT = 1024 * 1024 * 8;\n\nfunction logOutputStatus(\n handle: string,\n renderedResult: unknown,\n stable: boolean,\n recalculationCounter: number,\n unstableMarker?: string,\n) {\n if (getDebugFlags().logOutputStatus && (getDebugFlags().logOutputStatus === \"any\" || !stable)) {\n if (stable)\n console.log(\n `Stable output ${handle} calculated ${renderedResult !== undefined ? \"defined\" : \"undefined\"}; (#${recalculationCounter})`,\n );\n else\n console.log(\n `Unstable output ${handle}; marker = ${unstableMarker}; ${renderedResult !== undefined ? \"defined\" : \"undefined\"} (#${recalculationCounter})`,\n );\n }\n}\n\n/**\n * Creates a Computable that executes a render function (`fh`) from a block's code in a QuickJS virtual machine.\n * This function handles both synchronous and asynchronous execution patterns of the sandboxed JS code.\n *\n * The overall data flow is as follows:\n * 1. A QuickJS VM is initialized.\n * 2. A `JsExecutionContext` is created to bridge the host (TypeScript) and guest (QuickJS) environments. It injects a\n * context object (`cfgRenderCtx`) into the VM, providing helper methods for the sandboxed code to interact with the\n * platform (e.g., to request data).\n * 3. The block's Javascript bundle is evaluated in the VM.\n * 4. The specified render function (`fh.handle`) is executed.\n *\n * Two execution paths are possible depending on the behavior of the render function:\n *\n * ### Synchronous Path\n * If the render function computes its result without requesting any external data requiring asynchronous calculations,\n * it executes synchronously.\n * - The `computablesToResolve` map in `JsExecutionContext` remains empty.\n * - The function returns an object with an `ir` field holding the result (`{ ir: importedResult }`).\n * Since `postprocessValue` is not specified, `ir` is treated as the final resolved value of the Computable.\n * - The QuickJS VM is disposed of immediately as it's no longer needed.\n *\n * ### Asynchronous Path (with `postprocessValue`)\n * If the render function needs external data requiring asynchronous calculations (e.g., fetching a file), it calls\n * one of the injected helper methods. These methods don't return data directly. Instead, they:\n * a. Create a new `Computable` for the data request (e.g., to fetch a blob).\n * b. Register this new `Computable` in the `computablesToResolve` map.\n * c. Return a handle (string) to the sandboxed code.\n *\n * In this case:\n * - The initial execution of the render function returns a scaffold of the final result, which depends on the pending\n * computables.\n * - The `computablesToResolve` map is passed as the `ir` (initial result) to `Computable.makeRaw`.\n * - The `postprocessValue` function is provided to handle the results once the computables are resolved.\n * - The QuickJS VM is kept alive (`keepVmAlive = true`) because its state is needed in `postprocessValue`.\n * - Once the `computable` framework resolves all dependencies, it calls `postprocessValue` with the resolved data.\n * - `postprocessValue` feeds the resolved data back into the VM, allowing the sandboxed code to compute the final\n * result.\n * - The VM is eventually disposed of when the host Computable is destroyed.\n *\n * @param env The middle layer environment.\n * @param ctx The block context.\n * @param fh The config render lambda to execute.\n * @param codeWithInfo The block's code and feature flags.\n * @param configKey A key for the configuration, used for cache busting.\n * @param ops Options for the computable.\n * @returns A `Computable` that will resolve to the result of the lambda execution.\n */\nexport function computableFromRF(\n env: MiddleLayerEnvironment,\n ctx: BlockContextAny,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n configKey: string,\n ops: Partial<ComputableRenderingOps> = {},\n blockPack?: BlockPackSpec,\n): Computable<unknown> {\n // adding configKey to reload all outputs on block-pack update\n const key = `${ctx.blockId}#lambda#${configKey}#${fh.handle}`;\n ops = { ...ops, key };\n if (ops.mode === undefined && fh.retentive === true) ops.mode = \"StableOnlyRetentive\";\n return Computable.makeRaw((cCtx) => {\n const { code, featureFlags } = codeWithInfo;\n\n if (getDebugFlags().logOutputRecalculations)\n console.log(\n `Block lambda recalculation : ${key} (${cCtx.changeSourceMarker}; ${cCtx.bodyInvocations} invocations)`,\n );\n\n const scope = new Scope();\n let keepVmAlive = false;\n cCtx.addOnDestroy(() => {\n // If keepVmAlive is false, the scope will be disposed by the finally block,\n // no need to dispose it here.\n if (keepVmAlive) scope.dispose();\n });\n\n try {\n const runtime = scope.manage(env.quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n { computableCtx: cCtx, blockCtx: ctx, mlEnv: env },\n );\n\n const crashRecorder = env.driverKit.crashRecorder;\n const renderInfo = {\n blockId: ctx.blockId,\n // A block id is unique to one project; these say which code it is, so a\n // log can be read against the right version without the project.\n ...describeBlockPack(blockPack),\n sdkVersion: codeWithInfo.sdkVersion,\n key,\n lambda: fh.handle,\n // The sandbox has its own 8 MB ceiling, so the model's own objects can\n // never exhaust the host heap. What can is the volume crossing out of\n // it, which `stats` counts.\n sandboxMemoryLimit: QUICK_JS_MEMORY_LIMIT,\n getStats: () => ({ ...rCtx.stats }),\n };\n\n return recordModelRenderSync(crashRecorder, renderInfo, () => {\n // configKey already identifies this block pack's config, and exists to invalidate\n // rendered outputs when the pack changes, so it keys the compiled bundle too.\n rCtx.evaluateBundleCached(configKey, code.content);\n const result = rCtx.runCallback(fh.handle);\n\n rCtx.resetComputableCtx();\n\n const toBeResolved = rCtx.computableHelper!.computablesToResolve;\n\n if (Object.keys(toBeResolved).length === 0) {\n const importedResult = rCtx.importObjectUniversal(result);\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${key}: ${JSON.stringify(rCtx.stats)}`);\n logOutputStatus(\n fh.handle,\n importedResult,\n cCtx.unstableMarker === undefined,\n -1,\n cCtx.unstableMarker,\n );\n return { ir: importedResult };\n }\n\n let recalculationCounter = 0;\n if (getDebugFlags().logOutputStatus)\n console.log(\n `Output ${fh.handle} scaffold calculated (not all computables resolved yet).`,\n );\n keepVmAlive = true;\n\n return {\n ir: toBeResolved,\n postprocessValue: (resolved: Record<string, unknown>, { unstableMarker, stable }) => {\n recalculationCounter++;\n // A deferred render resumes here, potentially many times, and each\n // resumption can build joins of its own, so each gets its own span.\n return recordModelRenderSync(\n crashRecorder,\n { ...renderInfo, recalculation: recalculationCounter },\n () => {\n // resolving futures\n for (const [handle, value] of Object.entries(resolved))\n rCtx.runCallback(handle, value);\n\n // rendering result\n const renderedResult = rCtx.importObjectUniversal(result);\n\n // logging\n if (getDebugFlags().logJsExecStat)\n console.log(\n `[jsExec] ${key} #${recalculationCounter}: ${JSON.stringify(rCtx.stats)}`,\n );\n logOutputStatus(\n fh.handle,\n renderedResult,\n stable,\n recalculationCounter,\n unstableMarker,\n );\n\n return renderedResult;\n },\n );\n },\n };\n });\n } catch (e) {\n keepVmAlive = false;\n throw e;\n } finally {\n if (!keepVmAlive) scope.dispose();\n }\n }, ops);\n}\n\nexport function executeSingleLambda(\n quickJs: QuickJSWASMModule,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n ...args: unknown[]\n): unknown {\n const { code, featureFlags } = codeWithInfo;\n const scope = new Scope();\n try {\n const runtime = scope.manage(quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n );\n\n // Initializing the model. The bytecode cache spares compiling the bundle on every call: the\n // args derivations of each write and readiness check run here.\n rCtx.evaluateBundleCached(undefined, code.content);\n\n // Running the lambda with arguments (e.g., state for args(), args for enrichmentTargets())\n const importedResult = rCtx.importObjectUniversal(rCtx.runCallback(fh.handle, ...args));\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${fh.handle}: ${JSON.stringify(rCtx.stats)}`);\n return importedResult;\n } finally {\n scope.dispose();\n }\n}\n\n/**\n * The part of a block pack that names the code, and nothing else.\n *\n * Registry packs carry an organization, name and version, which is what a reader\n * needs to open the right source. Local and development packs carry a filesystem\n * path instead; the path is deliberately not recorded — it identifies the\n * machine rather than the code, and its `type` already says that no published\n * version exists to look up.\n */\nfunction describeBlockPack(spec: BlockPackSpec | undefined): {\n block?: string;\n blockVersion?: string;\n blockSource?: string;\n} {\n if (spec === undefined) return {};\n if (spec.type === \"from-registry-v1\" || spec.type === \"from-registry-v2\") {\n return {\n block: `${spec.id.organization}:${spec.id.name}`,\n blockVersion: spec.id.version,\n blockSource: spec.type,\n };\n }\n return { block: \"(unpublished)\", blockSource: spec.type };\n}\n"],"mappings":";;;;;;;AAcA,MAAM,wBAAwB;AAE9B,SAAS,gBACP,QACA,gBACA,QACA,sBACA,gBACA;CACA,IAAI,cAAc,CAAC,CAAC,oBAAoB,cAAc,CAAC,CAAC,oBAAoB,SAAS,CAAC,SAAS;EAC7F,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= require("../_virtual/_@oxc-project_runtime@0.155.0/helpers/esm/usingCtx.cjs");
2
+ const require_column_registry = require("./column_registry.cjs");
2
3
  let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
3
4
  // src/js_render/service_injectors.ts
4
5
  function getServiceInjectors() {
@@ -53,15 +54,7 @@ function getServiceInjectors() {
53
54
  resolveAccessor: (h) => host.getAccessor(h),
54
55
  getUpstreamBlockCtxes: () => host.getRawUpstreamBlockCtx(),
55
56
  getSpecDriver: () => specDriver,
56
- resolveSpec: (id) => {
57
- const leaf = host.getColumnRegistry().resolve(id);
58
- if (leaf === void 0) return void 0;
59
- return leaf.accessor.traverse({
60
- field: `${leaf.name}.spec`,
61
- assertFieldType: "Input",
62
- ignoreError: true
63
- })?.getDataAsJson();
64
- }
57
+ resolveSpec: (id) => require_column_registry.resolveColumnSpec(host.getColumnRegistry(), id)
65
58
  };
66
59
  const pinHandle = (entry) => {
67
60
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"service_injectors.cjs","names":["Services","ServiceNotRegisteredError","PoolEntryGuard"],"sources":["../../src/js_render/service_injectors.ts"],"sourcesContent":["import type { QuickJSHandle, VmFunctionImplementation } from \"quickjs-emscripten\";\nimport type {\n CollectionHandle,\n ColumnsCollectionDriverHost,\n DiscoverColumnsOptions,\n DiscoverRootsOptions,\n InferServiceModel,\n PoolEntry,\n SerializedColumnsSource,\n ServiceBrand,\n} from \"@milaboratories/pl-model-common\";\nimport { Services, ServiceNotRegisteredError } from \"@milaboratories/pl-model-common\";\nimport type { PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport type {\n AxesId,\n AxesSpec,\n DataInfo,\n PColumn,\n PColumnSpec,\n PColumnValues,\n PObjectId,\n PObjectSpec,\n PTableColumnId,\n PTableColumnSpec,\n PTableRecordFilter,\n SingleAxisSelector,\n BuildQueryInput,\n DeleteColumnRequest,\n DiscoverColumnsRequest,\n DiscoverRootsRequest,\n PFrameDef,\n SpecQuery,\n PTableDef,\n PTableDefV2,\n SpecFrameHandle,\n} from \"@milaboratories/pl-model-common\";\nimport { PoolEntryGuard } from \"@milaboratories/pl-model-common\";\nimport type { JsExecutionContext } from \"./context\";\nimport type { ComputableContextHelper } from \"./computable_context\";\n\ntype VmMethod = VmFunctionImplementation<QuickJSHandle>;\n\nexport type ServiceInjectorContext = {\n host: ComputableContextHelper;\n vm: JsExecutionContext;\n};\n\n// Each injector returns a record of method name -> VM function implementation.\n// The framework automatically registers them with serviceFnKey(serviceId, methodName).\nexport type ServiceInjector<Methods extends string = string> = (\n ctx: ServiceInjectorContext,\n) => Record<Methods, VmMethod>;\n\n// Type-safe injector for a specific service — must return all methods from the model interface.\ntype ServiceInjectorFor<S extends keyof typeof Services> = ServiceInjector<\n string & keyof InferServiceModel<ServiceBrand<(typeof Services)[S]>>\n>;\n\n// Complete, type-checked injector map.\n// Adding a service to Services without an entry here is a compile-time error.\n// Missing a method from the interface is also a compile-time error.\ntype ServiceInjectorMap = { [K in keyof typeof Services]: ServiceInjectorFor<K> };\n\nexport function getServiceInjectors(): ServiceInjectorMap {\n return {\n PFrameSpec: ({ host, vm }: ServiceInjectorContext) => {\n const driver = host.serviceRegistry.get(Services.PFrameSpec);\n if (!driver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.PFrameSpec}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n\n return {\n createSpecFrame: (specs: QuickJSHandle) => {\n using guard = new PoolEntryGuard(\n driver.createSpecFrame(vm.importObjectViaJson(specs) as Record<string, PColumnSpec>),\n );\n host.addOnDestroy(guard.entry.unref);\n const entry = guard.keep();\n // TODO: add [Symbol.dispose] once QuickJS supports ES2024 explicit resource management\n const obj = vm.vm.newObject();\n vm.vm.newString(entry.key).consume((k) => vm.vm.setProp(obj, \"key\", k));\n vm.vm\n .newFunction(\"unref\", () => {\n entry.unref();\n })\n .consume((fn) => vm.vm.setProp(obj, \"unref\", fn));\n return obj;\n },\n\n listColumns: (handle: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.listColumns(vm.vm.getString(handle) as SpecFrameHandle)),\n\n discoverColumns: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverColumns(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DiscoverColumnsRequest,\n ),\n ),\n\n discoverRoots: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverRoots(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DiscoverRootsRequest,\n ),\n ),\n\n buildQuery: (input: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.buildQuery(vm.importObjectViaJson(input) as BuildQueryInput),\n ),\n\n deleteColumn: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.deleteColumn(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DeleteColumnRequest,\n ),\n ),\n\n evaluateQuery: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.evaluateQuery(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as SpecQuery,\n ),\n ),\n\n expandAxes: (spec: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.expandAxes(vm.importObjectViaJson(spec) as AxesSpec)),\n\n collapseAxes: (ids: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.collapseAxes(vm.importObjectViaJson(ids) as AxesId)),\n\n findAxis: (spec: QuickJSHandle, selector: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.findAxis(\n vm.importObjectViaJson(spec) as AxesSpec,\n vm.importObjectViaJson(selector) as SingleAxisSelector,\n ),\n ),\n\n findTableColumn: (tableSpec: QuickJSHandle, selector: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.findTableColumn(\n vm.importObjectViaJson(tableSpec) as PTableColumnSpec[],\n vm.importObjectViaJson(selector) as PTableColumnId,\n ),\n ),\n\n rewriteLegacyFilters: (request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.rewriteLegacyFilters(\n vm.importObjectViaJson(request) as {\n tableSpec: PTableColumnSpec[];\n filters: PTableRecordFilter[];\n },\n ),\n ),\n };\n },\n\n PFrame: ({ host, vm }: ServiceInjectorContext) => ({\n createPFrame: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPFrame(\n vm.importObjectViaJson(def) as PFrameDef<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n\n createPTable: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPTable(\n vm.importObjectViaJson(def) as PTableDef<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n\n createPTableV2: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPTableV2(\n vm.importObjectViaJson(def) as PTableDefV2<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n }),\n\n // Dialog has no model-side surface — workflow scripts cannot open save dialogs.\n // Declared as an empty injector to satisfy the exhaustive ServiceInjectorMap.\n Dialog: () => ({}) as Record<never, VmMethod>,\n\n ColumnsCollection: ({ host, vm }: ServiceInjectorContext) => {\n const driver = host.serviceRegistry.get(Services.ColumnsCollection);\n if (!driver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.ColumnsCollection}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n const specDriver = host.serviceRegistry.get(Services.PFrameSpec);\n if (!specDriver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.PFrameSpec}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n\n const bindings: ColumnsCollectionDriverHost<PlTreeNodeAccessor> = {\n resolveAccessor: (h) => host.getAccessor(h),\n getUpstreamBlockCtxes: () => host.getRawUpstreamBlockCtx(),\n getSpecDriver: () => specDriver,\n resolveSpec: (id: PObjectId) => {\n const leaf = host.getColumnRegistry().resolve(id);\n if (leaf === undefined) return undefined;\n const specNode = leaf.accessor.traverse({\n field: `${leaf.name}.spec`,\n assertFieldType: \"Input\",\n ignoreError: true,\n });\n return specNode?.getDataAsJson<PObjectSpec>();\n },\n };\n\n const pinHandle = (entry: PoolEntry<CollectionHandle>): CollectionHandle => {\n using guard = new PoolEntryGuard(entry);\n host.addOnDestroy(guard.entry.unref);\n return guard.keep().key;\n };\n\n return {\n create: (sources: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.create(vm.importObjectViaJson(sources) as SerializedColumnsSource[], bindings),\n ),\n ),\n\n isEmpty: (handle: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.isEmpty(vm.vm.getString(handle) as CollectionHandle, bindings),\n ),\n\n isFinal: (handle: QuickJSHandle) =>\n vm.exportSingleValue(driver.isFinal(vm.vm.getString(handle) as CollectionHandle)),\n\n getColumns: (handle: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.getColumns(vm.vm.getString(handle) as CollectionHandle, bindings),\n ),\n\n addSource: (handle: QuickJSHandle, sources: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.addSource(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(sources) as SerializedColumnsSource[],\n bindings,\n ),\n ),\n ),\n\n discover: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.discover(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as DiscoverColumnsOptions,\n bindings,\n ),\n ),\n ),\n\n filter: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.filter(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as DiscoverColumnsOptions,\n bindings,\n ),\n ),\n ),\n\n discoverRoots: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverRoots(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as Disc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,CACF;IAEF,gBAAgB,QAAuB,SACrC,GAAG,oBACD,OAAO,cACL,GAAG,GAAG,UAAU,MAAM,GACtB,GAAG,oBAAoB,IAAI,GAC3B,QACF,CACF;GACJ;EACF;CACF;AACF"}
1
+ {"version":3,"file":"service_injectors.cjs","names":["Services","ServiceNotRegisteredError","PoolEntryGuard","resolveColumnSpec"],"sources":["../../src/js_render/service_injectors.ts"],"sourcesContent":["import type { QuickJSHandle, VmFunctionImplementation } from \"quickjs-emscripten\";\nimport type {\n CollectionHandle,\n ColumnsCollectionDriverHost,\n DiscoverColumnsOptions,\n DiscoverRootsOptions,\n InferServiceModel,\n PoolEntry,\n SerializedColumnsSource,\n ServiceBrand,\n} from \"@milaboratories/pl-model-common\";\nimport { Services, ServiceNotRegisteredError } from \"@milaboratories/pl-model-common\";\nimport type { PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport type {\n AxesId,\n AxesSpec,\n DataInfo,\n PColumn,\n PColumnSpec,\n PColumnValues,\n PObjectId,\n PTableColumnId,\n PTableColumnSpec,\n PTableRecordFilter,\n SingleAxisSelector,\n BuildQueryInput,\n DeleteColumnRequest,\n DiscoverColumnsRequest,\n DiscoverRootsRequest,\n PFrameDef,\n SpecQuery,\n PTableDef,\n PTableDefV2,\n SpecFrameHandle,\n} from \"@milaboratories/pl-model-common\";\nimport { PoolEntryGuard } from \"@milaboratories/pl-model-common\";\nimport type { JsExecutionContext } from \"./context\";\nimport type { ComputableContextHelper } from \"./computable_context\";\nimport { resolveColumnSpec } from \"./column_registry\";\n\ntype VmMethod = VmFunctionImplementation<QuickJSHandle>;\n\nexport type ServiceInjectorContext = {\n host: ComputableContextHelper;\n vm: JsExecutionContext;\n};\n\n// Each injector returns a record of method name -> VM function implementation.\n// The framework automatically registers them with serviceFnKey(serviceId, methodName).\nexport type ServiceInjector<Methods extends string = string> = (\n ctx: ServiceInjectorContext,\n) => Record<Methods, VmMethod>;\n\n// Type-safe injector for a specific service — must return all methods from the model interface.\ntype ServiceInjectorFor<S extends keyof typeof Services> = ServiceInjector<\n string & keyof InferServiceModel<ServiceBrand<(typeof Services)[S]>>\n>;\n\n// Complete, type-checked injector map.\n// Adding a service to Services without an entry here is a compile-time error.\n// Missing a method from the interface is also a compile-time error.\ntype ServiceInjectorMap = { [K in keyof typeof Services]: ServiceInjectorFor<K> };\n\nexport function getServiceInjectors(): ServiceInjectorMap {\n return {\n PFrameSpec: ({ host, vm }: ServiceInjectorContext) => {\n const driver = host.serviceRegistry.get(Services.PFrameSpec);\n if (!driver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.PFrameSpec}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n\n return {\n createSpecFrame: (specs: QuickJSHandle) => {\n using guard = new PoolEntryGuard(\n driver.createSpecFrame(vm.importObjectViaJson(specs) as Record<string, PColumnSpec>),\n );\n host.addOnDestroy(guard.entry.unref);\n const entry = guard.keep();\n // TODO: add [Symbol.dispose] once QuickJS supports ES2024 explicit resource management\n const obj = vm.vm.newObject();\n vm.vm.newString(entry.key).consume((k) => vm.vm.setProp(obj, \"key\", k));\n vm.vm\n .newFunction(\"unref\", () => {\n entry.unref();\n })\n .consume((fn) => vm.vm.setProp(obj, \"unref\", fn));\n return obj;\n },\n\n listColumns: (handle: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.listColumns(vm.vm.getString(handle) as SpecFrameHandle)),\n\n discoverColumns: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverColumns(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DiscoverColumnsRequest,\n ),\n ),\n\n discoverRoots: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverRoots(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DiscoverRootsRequest,\n ),\n ),\n\n buildQuery: (input: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.buildQuery(vm.importObjectViaJson(input) as BuildQueryInput),\n ),\n\n deleteColumn: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.deleteColumn(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DeleteColumnRequest,\n ),\n ),\n\n evaluateQuery: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.evaluateQuery(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as SpecQuery,\n ),\n ),\n\n expandAxes: (spec: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.expandAxes(vm.importObjectViaJson(spec) as AxesSpec)),\n\n collapseAxes: (ids: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.collapseAxes(vm.importObjectViaJson(ids) as AxesId)),\n\n findAxis: (spec: QuickJSHandle, selector: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.findAxis(\n vm.importObjectViaJson(spec) as AxesSpec,\n vm.importObjectViaJson(selector) as SingleAxisSelector,\n ),\n ),\n\n findTableColumn: (tableSpec: QuickJSHandle, selector: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.findTableColumn(\n vm.importObjectViaJson(tableSpec) as PTableColumnSpec[],\n vm.importObjectViaJson(selector) as PTableColumnId,\n ),\n ),\n\n rewriteLegacyFilters: (request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.rewriteLegacyFilters(\n vm.importObjectViaJson(request) as {\n tableSpec: PTableColumnSpec[];\n filters: PTableRecordFilter[];\n },\n ),\n ),\n };\n },\n\n PFrame: ({ host, vm }: ServiceInjectorContext) => ({\n createPFrame: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPFrame(\n vm.importObjectViaJson(def) as PFrameDef<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n\n createPTable: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPTable(\n vm.importObjectViaJson(def) as PTableDef<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n\n createPTableV2: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPTableV2(\n vm.importObjectViaJson(def) as PTableDefV2<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n }),\n\n // Dialog has no model-side surface — workflow scripts cannot open save dialogs.\n // Declared as an empty injector to satisfy the exhaustive ServiceInjectorMap.\n Dialog: () => ({}) as Record<never, VmMethod>,\n\n ColumnsCollection: ({ host, vm }: ServiceInjectorContext) => {\n const driver = host.serviceRegistry.get(Services.ColumnsCollection);\n if (!driver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.ColumnsCollection}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n const specDriver = host.serviceRegistry.get(Services.PFrameSpec);\n if (!specDriver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.PFrameSpec}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n\n const bindings: ColumnsCollectionDriverHost<PlTreeNodeAccessor> = {\n resolveAccessor: (h) => host.getAccessor(h),\n getUpstreamBlockCtxes: () => host.getRawUpstreamBlockCtx(),\n getSpecDriver: () => specDriver,\n resolveSpec: (id: PObjectId) => resolveColumnSpec(host.getColumnRegistry(), id),\n };\n\n const pinHandle = (entry: PoolEntry<CollectionHandle>): CollectionHandle => {\n using guard = new PoolEntryGuard(entry);\n host.addOnDestroy(guard.entry.unref);\n return guard.keep().key;\n };\n\n return {\n create: (sources: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.create(vm.importObjectViaJson(sources) as SerializedColumnsSource[], bindings),\n ),\n ),\n\n isEmpty: (handle: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.isEmpty(vm.vm.getString(handle) as CollectionHandle, bindings),\n ),\n\n isFinal: (handle: QuickJSHandle) =>\n vm.exportSingleValue(driver.isFinal(vm.vm.getString(handle) as CollectionHandle)),\n\n getColumns: (handle: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.getColumns(vm.vm.getString(handle) as CollectionHandle, bindings),\n ),\n\n addSource: (handle: QuickJSHandle, sources: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.addSource(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(sources) as SerializedColumnsSource[],\n bindings,\n ),\n ),\n ),\n\n discover: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.discover(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as DiscoverColumnsOptions,\n bindings,\n ),\n ),\n ),\n\n filter: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.filter(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as DiscoverColumnsOptions,\n bindings,\n ),\n ),\n ),\n\n discoverRoots: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverRoots(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as DiscoverRootsOptions,\n bindings,\n ),\n ),\n };\n },\n };\n}\n"],"mappings":";;;;AA+DA,SAAgB,sBAA0C;CACxD,OAAO;EACL,aAAa,EAAE,MAAM,SAAiC;GACpD,MAAM,SAAS,KAAK,gBAAgB,IAAIA,gCAAAA,SAAS,UAAU;GAC3D,IAAI,CAAC,QACH,MAAM,IAAIC,gCAAAA,0BACR,YAAYD,gCAAAA,SAAS,WAAW,sEAClC;GAEF,OAAO;IACL,kBAAkB,UAAyB;;;MACzC,MAAM,QAAA,YAAA,EAAQ,IAAIE,gCAAAA,eAChB,OAAO,gBAAgB,GAAG,oBAAoB,KAAK,CAAgC,CACrF,CAAA;MACA,KAAK,aAAa,MAAM,MAAM,KAAK;MACnC,MAAM,QAAQ,MAAM,KAAK;MAEzB,MAAM,MAAM,GAAG,GAAG,UAAU;MAC5B,GAAG,GAAG,UAAU,MAAM,GAAG,C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AAQ,GAAG,GAAG,UAAU,MAAM,CAAqB,CAAC;IAElF,aAAa,WACX,GAAG,oBACD,OAAO,WAAW,GAAG,GAAG,UAAU,MAAM,GAAuB,QAAQ,CACzE;IAEF,YAAY,QAAuB,YACjC,GAAG,kBACD,UACE,OAAO,UACL,GAAG,GAAG,UAAU,MAAM,GACtB,GAAG,oBAAoB,OAAO,GAC9B,QACF,CACF,CACF;IAEF,WAAW,QAAuB,SAChC,GAAG,kBACD,UACE,OAAO,SACL,GAAG,GAAG,UAAU,MAAM,GACtB,GAAG,oBAAoB,IAAI,GAC3B,QACF,CACF,CACF;IAEF,SAAS,QAAuB,SAC9B,GAAG,kBACD,UACE,OAAO,OACL,GAAG,GAAG,UAAU,MAAM,GACtB,GAAG,oBAAoB,IAAI,GAC3B,QACF,CACF,CACF;IAEF,gBAAgB,QAAuB,SACrC,GAAG,oBACD,OAAO,cACL,GAAG,GAAG,UAAU,MAAM,GACtB,GAAG,oBAAoB,IAAI,GAC3B,QACF,CACF;GACJ;EACF;CACF;AACF"}
@@ -1,4 +1,5 @@
1
1
  import _usingCtx from "../_virtual/_@oxc-project_runtime@0.155.0/helpers/esm/usingCtx.js";
2
+ import { resolveColumnSpec } from "./column_registry.js";
2
3
  import { PoolEntryGuard, ServiceNotRegisteredError, Services } from "@milaboratories/pl-model-common";
3
4
  // src/js_render/service_injectors.ts
4
5
  function getServiceInjectors() {
@@ -53,15 +54,7 @@ function getServiceInjectors() {
53
54
  resolveAccessor: (h) => host.getAccessor(h),
54
55
  getUpstreamBlockCtxes: () => host.getRawUpstreamBlockCtx(),
55
56
  getSpecDriver: () => specDriver,
56
- resolveSpec: (id) => {
57
- const leaf = host.getColumnRegistry().resolve(id);
58
- if (leaf === void 0) return void 0;
59
- return leaf.accessor.traverse({
60
- field: `${leaf.name}.spec`,
61
- assertFieldType: "Input",
62
- ignoreError: true
63
- })?.getDataAsJson();
64
- }
57
+ resolveSpec: (id) => resolveColumnSpec(host.getColumnRegistry(), id)
65
58
  };
66
59
  const pinHandle = (entry) => {
67
60
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"service_injectors.js","names":[],"sources":["../../src/js_render/service_injectors.ts"],"sourcesContent":["import type { QuickJSHandle, VmFunctionImplementation } from \"quickjs-emscripten\";\nimport type {\n CollectionHandle,\n ColumnsCollectionDriverHost,\n DiscoverColumnsOptions,\n DiscoverRootsOptions,\n InferServiceModel,\n PoolEntry,\n SerializedColumnsSource,\n ServiceBrand,\n} from \"@milaboratories/pl-model-common\";\nimport { Services, ServiceNotRegisteredError } from \"@milaboratories/pl-model-common\";\nimport type { PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport type {\n AxesId,\n AxesSpec,\n DataInfo,\n PColumn,\n PColumnSpec,\n PColumnValues,\n PObjectId,\n PObjectSpec,\n PTableColumnId,\n PTableColumnSpec,\n PTableRecordFilter,\n SingleAxisSelector,\n BuildQueryInput,\n DeleteColumnRequest,\n DiscoverColumnsRequest,\n DiscoverRootsRequest,\n PFrameDef,\n SpecQuery,\n PTableDef,\n PTableDefV2,\n SpecFrameHandle,\n} from \"@milaboratories/pl-model-common\";\nimport { PoolEntryGuard } from \"@milaboratories/pl-model-common\";\nimport type { JsExecutionContext } from \"./context\";\nimport type { ComputableContextHelper } from \"./computable_context\";\n\ntype VmMethod = VmFunctionImplementation<QuickJSHandle>;\n\nexport type ServiceInjectorContext = {\n host: ComputableContextHelper;\n vm: JsExecutionContext;\n};\n\n// Each injector returns a record of method name -> VM function implementation.\n// The framework automatically registers them with serviceFnKey(serviceId, methodName).\nexport type ServiceInjector<Methods extends string = string> = (\n ctx: ServiceInjectorContext,\n) => Record<Methods, VmMethod>;\n\n// Type-safe injector for a specific service — must return all methods from the model interface.\ntype ServiceInjectorFor<S extends keyof typeof Services> = ServiceInjector<\n string & keyof InferServiceModel<ServiceBrand<(typeof Services)[S]>>\n>;\n\n// Complete, type-checked injector map.\n// Adding a service to Services without an entry here is a compile-time error.\n// Missing a method from the interface is also a compile-time error.\ntype ServiceInjectorMap = { [K in keyof typeof Services]: ServiceInjectorFor<K> };\n\nexport function getServiceInjectors(): ServiceInjectorMap {\n return {\n PFrameSpec: ({ host, vm }: ServiceInjectorContext) => {\n const driver = host.serviceRegistry.get(Services.PFrameSpec);\n if (!driver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.PFrameSpec}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n\n return {\n createSpecFrame: (specs: QuickJSHandle) => {\n using guard = new PoolEntryGuard(\n driver.createSpecFrame(vm.importObjectViaJson(specs) as Record<string, PColumnSpec>),\n );\n host.addOnDestroy(guard.entry.unref);\n const entry = guard.keep();\n // TODO: add [Symbol.dispose] once QuickJS supports ES2024 explicit resource management\n const obj = vm.vm.newObject();\n vm.vm.newString(entry.key).consume((k) => vm.vm.setProp(obj, \"key\", k));\n vm.vm\n .newFunction(\"unref\", () => {\n entry.unref();\n })\n .consume((fn) => vm.vm.setProp(obj, \"unref\", fn));\n return obj;\n },\n\n listColumns: (handle: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.listColumns(vm.vm.getString(handle) as SpecFrameHandle)),\n\n discoverColumns: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverColumns(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DiscoverColumnsRequest,\n ),\n ),\n\n discoverRoots: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverRoots(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DiscoverRootsRequest,\n ),\n ),\n\n buildQuery: (input: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.buildQuery(vm.importObjectViaJson(input) as BuildQueryInput),\n ),\n\n deleteColumn: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.deleteColumn(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DeleteColumnRequest,\n ),\n ),\n\n evaluateQuery: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.evaluateQuery(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as SpecQuery,\n ),\n ),\n\n expandAxes: (spec: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.expandAxes(vm.importObjectViaJson(spec) as AxesSpec)),\n\n collapseAxes: (ids: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.collapseAxes(vm.importObjectViaJson(ids) as AxesId)),\n\n findAxis: (spec: QuickJSHandle, selector: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.findAxis(\n vm.importObjectViaJson(spec) as AxesSpec,\n vm.importObjectViaJson(selector) as SingleAxisSelector,\n ),\n ),\n\n findTableColumn: (tableSpec: QuickJSHandle, selector: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.findTableColumn(\n vm.importObjectViaJson(tableSpec) as PTableColumnSpec[],\n vm.importObjectViaJson(selector) as PTableColumnId,\n ),\n ),\n\n rewriteLegacyFilters: (request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.rewriteLegacyFilters(\n vm.importObjectViaJson(request) as {\n tableSpec: PTableColumnSpec[];\n filters: PTableRecordFilter[];\n },\n ),\n ),\n };\n },\n\n PFrame: ({ host, vm }: ServiceInjectorContext) => ({\n createPFrame: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPFrame(\n vm.importObjectViaJson(def) as PFrameDef<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n\n createPTable: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPTable(\n vm.importObjectViaJson(def) as PTableDef<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n\n createPTableV2: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPTableV2(\n vm.importObjectViaJson(def) as PTableDefV2<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n }),\n\n // Dialog has no model-side surface — workflow scripts cannot open save dialogs.\n // Declared as an empty injector to satisfy the exhaustive ServiceInjectorMap.\n Dialog: () => ({}) as Record<never, VmMethod>,\n\n ColumnsCollection: ({ host, vm }: ServiceInjectorContext) => {\n const driver = host.serviceRegistry.get(Services.ColumnsCollection);\n if (!driver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.ColumnsCollection}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n const specDriver = host.serviceRegistry.get(Services.PFrameSpec);\n if (!specDriver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.PFrameSpec}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n\n const bindings: ColumnsCollectionDriverHost<PlTreeNodeAccessor> = {\n resolveAccessor: (h) => host.getAccessor(h),\n getUpstreamBlockCtxes: () => host.getRawUpstreamBlockCtx(),\n getSpecDriver: () => specDriver,\n resolveSpec: (id: PObjectId) => {\n const leaf = host.getColumnRegistry().resolve(id);\n if (leaf === undefined) return undefined;\n const specNode = leaf.accessor.traverse({\n field: `${leaf.name}.spec`,\n assertFieldType: \"Input\",\n ignoreError: true,\n });\n return specNode?.getDataAsJson<PObjectSpec>();\n },\n };\n\n const pinHandle = (entry: PoolEntry<CollectionHandle>): CollectionHandle => {\n using guard = new PoolEntryGuard(entry);\n host.addOnDestroy(guard.entry.unref);\n return guard.keep().key;\n };\n\n return {\n create: (sources: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.create(vm.importObjectViaJson(sources) as SerializedColumnsSource[], bindings),\n ),\n ),\n\n isEmpty: (handle: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.isEmpty(vm.vm.getString(handle) as CollectionHandle, bindings),\n ),\n\n isFinal: (handle: QuickJSHandle) =>\n vm.exportSingleValue(driver.isFinal(vm.vm.getString(handle) as CollectionHandle)),\n\n getColumns: (handle: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.getColumns(vm.vm.getString(handle) as CollectionHandle, bindings),\n ),\n\n addSource: (handle: QuickJSHandle, sources: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.addSource(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(sources) as SerializedColumnsSource[],\n bindings,\n ),\n ),\n ),\n\n discover: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.discover(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as DiscoverColumnsOptions,\n bindings,\n ),\n ),\n ),\n\n filter: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.filter(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as DiscoverColumnsOptions,\n bindings,\n ),\n ),\n ),\n\n discoverRoots: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverRoots(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as DiscoverRootsOptions,\n bindings,\n ),\n ),\n };\n },\n };\n}\n"],"mappings":";;;AA+DA,SAAgB,sBAA0C;CACxD,OAAO;EACL,aAAa,EAAE,MAAM,SAAiC;GACpD,MAAM,SAAS,KAAK,gBAAgB,IAAI,SAAS,UAAU;GAC3D,IAAI,CAAC,QACH,MAAM,IAAI,0BACR,YAAY,SAAS,WAAW,sEAClC;GAEF,OAAO;IACL,kBAAkB,UAAyB;;;MACzC,MAAM,QAAA,YAAA,EAAQ,IAAI,eAChB,OAAO,gBAAgB,GAAG,oBAAoB,KAAK,CAAgC,CACrF,CAAA;MACA,KAAK,aAAa,MAAM,MAAM,KAAK;MACnC,MAAM,QAAQ,MAAM,KAAK;MAEzB,MAAM,MAAM,GAAG,GAAG,UAAU;MAC5B,GAAG,GAAG,UAAU,MAAM,GAAG,CAAC,CAAC,SAAS,MAAM,GAAG,GAAG,QAAQ,KAAK,OAAO,CAAC,CAAC;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,CACtE;IAEF,UAAU,WACR,GAAG,kBAAkB,OAAO,QAAQ,GAAG,GAAG,UAAU,MAAM,CAAqB,CAAC;IAElF,aAAa,WACX,GAAG,oBACD,OAAO,WAAW,GAAG,GAAG,UAAU,MAAM,GAAuB,QAAQ,CACzE;IAEF,YAAY,QAAuB,YACjC,GAAG,kBACD,UACE,OAAO,UACL,GAAG,GAAG,UAAU,MAAM,GACtB,GAAG,oBAAoB,OAAO,GAC9B,QACF,CACF,CACF;IAEF,WAAW,QAAuB,SAChC,GAAG,kBACD,UACE,OAAO,SACL,GAAG,GAAG,UAAU,MAAM,GACtB,GAAG,oBAAoB,IAAI,GAC3B,QACF,CACF,CACF;IAEF,SAAS,QAAuB,SAC9B,GAAG,kBACD,UACE,OAAO,OACL,GAAG,GAAG,UAAU,MAAM,GACtB,GAAG,oBAAoB,IAAI,GAC3B,QACF,CACF,CACF;IAEF,gBAAgB,QAAuB,SACrC,GAAG,oBACD,OAAO,cACL,GAAG,GAAG,UAAU,MAAM,GACtB,GAAG,oBAAoB,IAAI,GAC3B,QACF,CACF;GACJ;EACF;CACF;AACF"}
1
+ {"version":3,"file":"service_injectors.js","names":[],"sources":["../../src/js_render/service_injectors.ts"],"sourcesContent":["import type { QuickJSHandle, VmFunctionImplementation } from \"quickjs-emscripten\";\nimport type {\n CollectionHandle,\n ColumnsCollectionDriverHost,\n DiscoverColumnsOptions,\n DiscoverRootsOptions,\n InferServiceModel,\n PoolEntry,\n SerializedColumnsSource,\n ServiceBrand,\n} from \"@milaboratories/pl-model-common\";\nimport { Services, ServiceNotRegisteredError } from \"@milaboratories/pl-model-common\";\nimport type { PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport type {\n AxesId,\n AxesSpec,\n DataInfo,\n PColumn,\n PColumnSpec,\n PColumnValues,\n PObjectId,\n PTableColumnId,\n PTableColumnSpec,\n PTableRecordFilter,\n SingleAxisSelector,\n BuildQueryInput,\n DeleteColumnRequest,\n DiscoverColumnsRequest,\n DiscoverRootsRequest,\n PFrameDef,\n SpecQuery,\n PTableDef,\n PTableDefV2,\n SpecFrameHandle,\n} from \"@milaboratories/pl-model-common\";\nimport { PoolEntryGuard } from \"@milaboratories/pl-model-common\";\nimport type { JsExecutionContext } from \"./context\";\nimport type { ComputableContextHelper } from \"./computable_context\";\nimport { resolveColumnSpec } from \"./column_registry\";\n\ntype VmMethod = VmFunctionImplementation<QuickJSHandle>;\n\nexport type ServiceInjectorContext = {\n host: ComputableContextHelper;\n vm: JsExecutionContext;\n};\n\n// Each injector returns a record of method name -> VM function implementation.\n// The framework automatically registers them with serviceFnKey(serviceId, methodName).\nexport type ServiceInjector<Methods extends string = string> = (\n ctx: ServiceInjectorContext,\n) => Record<Methods, VmMethod>;\n\n// Type-safe injector for a specific service — must return all methods from the model interface.\ntype ServiceInjectorFor<S extends keyof typeof Services> = ServiceInjector<\n string & keyof InferServiceModel<ServiceBrand<(typeof Services)[S]>>\n>;\n\n// Complete, type-checked injector map.\n// Adding a service to Services without an entry here is a compile-time error.\n// Missing a method from the interface is also a compile-time error.\ntype ServiceInjectorMap = { [K in keyof typeof Services]: ServiceInjectorFor<K> };\n\nexport function getServiceInjectors(): ServiceInjectorMap {\n return {\n PFrameSpec: ({ host, vm }: ServiceInjectorContext) => {\n const driver = host.serviceRegistry.get(Services.PFrameSpec);\n if (!driver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.PFrameSpec}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n\n return {\n createSpecFrame: (specs: QuickJSHandle) => {\n using guard = new PoolEntryGuard(\n driver.createSpecFrame(vm.importObjectViaJson(specs) as Record<string, PColumnSpec>),\n );\n host.addOnDestroy(guard.entry.unref);\n const entry = guard.keep();\n // TODO: add [Symbol.dispose] once QuickJS supports ES2024 explicit resource management\n const obj = vm.vm.newObject();\n vm.vm.newString(entry.key).consume((k) => vm.vm.setProp(obj, \"key\", k));\n vm.vm\n .newFunction(\"unref\", () => {\n entry.unref();\n })\n .consume((fn) => vm.vm.setProp(obj, \"unref\", fn));\n return obj;\n },\n\n listColumns: (handle: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.listColumns(vm.vm.getString(handle) as SpecFrameHandle)),\n\n discoverColumns: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverColumns(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DiscoverColumnsRequest,\n ),\n ),\n\n discoverRoots: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverRoots(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DiscoverRootsRequest,\n ),\n ),\n\n buildQuery: (input: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.buildQuery(vm.importObjectViaJson(input) as BuildQueryInput),\n ),\n\n deleteColumn: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.deleteColumn(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as DeleteColumnRequest,\n ),\n ),\n\n evaluateQuery: (handle: QuickJSHandle, request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.evaluateQuery(\n vm.vm.getString(handle) as SpecFrameHandle,\n vm.importObjectViaJson(request) as SpecQuery,\n ),\n ),\n\n expandAxes: (spec: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.expandAxes(vm.importObjectViaJson(spec) as AxesSpec)),\n\n collapseAxes: (ids: QuickJSHandle) =>\n vm.exportObjectViaJson(driver.collapseAxes(vm.importObjectViaJson(ids) as AxesId)),\n\n findAxis: (spec: QuickJSHandle, selector: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.findAxis(\n vm.importObjectViaJson(spec) as AxesSpec,\n vm.importObjectViaJson(selector) as SingleAxisSelector,\n ),\n ),\n\n findTableColumn: (tableSpec: QuickJSHandle, selector: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.findTableColumn(\n vm.importObjectViaJson(tableSpec) as PTableColumnSpec[],\n vm.importObjectViaJson(selector) as PTableColumnId,\n ),\n ),\n\n rewriteLegacyFilters: (request: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.rewriteLegacyFilters(\n vm.importObjectViaJson(request) as {\n tableSpec: PTableColumnSpec[];\n filters: PTableRecordFilter[];\n },\n ),\n ),\n };\n },\n\n PFrame: ({ host, vm }: ServiceInjectorContext) => ({\n createPFrame: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPFrame(\n vm.importObjectViaJson(def) as PFrameDef<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n\n createPTable: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPTable(\n vm.importObjectViaJson(def) as PTableDef<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n\n createPTableV2: (def: QuickJSHandle) =>\n vm.exportSingleValue(\n host.createPTableV2(\n vm.importObjectViaJson(def) as PTableDefV2<\n PObjectId | PColumn<string | PColumnValues | DataInfo<string>>\n >,\n ),\n ),\n }),\n\n // Dialog has no model-side surface — workflow scripts cannot open save dialogs.\n // Declared as an empty injector to satisfy the exhaustive ServiceInjectorMap.\n Dialog: () => ({}) as Record<never, VmMethod>,\n\n ColumnsCollection: ({ host, vm }: ServiceInjectorContext) => {\n const driver = host.serviceRegistry.get(Services.ColumnsCollection);\n if (!driver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.ColumnsCollection}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n const specDriver = host.serviceRegistry.get(Services.PFrameSpec);\n if (!specDriver)\n throw new ServiceNotRegisteredError(\n `Service \"${Services.PFrameSpec}\" has no factory in ModelServiceRegistry. Provide a non-null factory.`,\n );\n\n const bindings: ColumnsCollectionDriverHost<PlTreeNodeAccessor> = {\n resolveAccessor: (h) => host.getAccessor(h),\n getUpstreamBlockCtxes: () => host.getRawUpstreamBlockCtx(),\n getSpecDriver: () => specDriver,\n resolveSpec: (id: PObjectId) => resolveColumnSpec(host.getColumnRegistry(), id),\n };\n\n const pinHandle = (entry: PoolEntry<CollectionHandle>): CollectionHandle => {\n using guard = new PoolEntryGuard(entry);\n host.addOnDestroy(guard.entry.unref);\n return guard.keep().key;\n };\n\n return {\n create: (sources: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.create(vm.importObjectViaJson(sources) as SerializedColumnsSource[], bindings),\n ),\n ),\n\n isEmpty: (handle: QuickJSHandle) =>\n vm.exportSingleValue(\n driver.isEmpty(vm.vm.getString(handle) as CollectionHandle, bindings),\n ),\n\n isFinal: (handle: QuickJSHandle) =>\n vm.exportSingleValue(driver.isFinal(vm.vm.getString(handle) as CollectionHandle)),\n\n getColumns: (handle: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.getColumns(vm.vm.getString(handle) as CollectionHandle, bindings),\n ),\n\n addSource: (handle: QuickJSHandle, sources: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.addSource(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(sources) as SerializedColumnsSource[],\n bindings,\n ),\n ),\n ),\n\n discover: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.discover(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as DiscoverColumnsOptions,\n bindings,\n ),\n ),\n ),\n\n filter: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportSingleValue(\n pinHandle(\n driver.filter(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as DiscoverColumnsOptions,\n bindings,\n ),\n ),\n ),\n\n discoverRoots: (handle: QuickJSHandle, opts: QuickJSHandle) =>\n vm.exportObjectViaJson(\n driver.discoverRoots(\n vm.vm.getString(handle) as CollectionHandle,\n vm.importObjectViaJson(opts) as DiscoverRootsOptions,\n bindings,\n ),\n ),\n };\n },\n };\n}\n"],"mappings":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