@milaboratories/pl-middle-layer 1.53.3 → 1.54.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/js_render/computable_context.cjs +92 -85
- package/dist/js_render/computable_context.cjs.map +1 -1
- package/dist/js_render/computable_context.js +92 -84
- package/dist/js_render/computable_context.js.map +1 -1
- package/dist/js_render/context.cjs.map +1 -1
- package/dist/js_render/context.js.map +1 -1
- package/dist/js_render/service_injectors.cjs +49 -0
- package/dist/js_render/service_injectors.cjs.map +1 -0
- package/dist/js_render/service_injectors.js +48 -0
- package/dist/js_render/service_injectors.js.map +1 -0
- package/dist/middle_layer/middle_layer.cjs +10 -0
- package/dist/middle_layer/middle_layer.cjs.map +1 -1
- package/dist/middle_layer/middle_layer.d.ts +4 -0
- package/dist/middle_layer/middle_layer.js +10 -0
- package/dist/middle_layer/middle_layer.js.map +1 -1
- package/dist/pool/driver.cjs +1 -0
- package/dist/pool/driver.cjs.map +1 -1
- package/dist/pool/driver.js +1 -0
- package/dist/pool/driver.js.map +1 -1
- package/dist/service_factories.cjs +22 -0
- package/dist/service_factories.cjs.map +1 -0
- package/dist/service_factories.js +21 -0
- package/dist/service_factories.js.map +1 -0
- package/package.json +20 -20
- package/src/js_render/computable_context.ts +105 -171
- package/src/js_render/context.ts +4 -4
- package/src/js_render/service_injectors.ts +153 -0
- package/src/middle_layer/middle_layer.ts +18 -0
- package/src/pool/driver.ts +1 -1
- package/src/service_factories.ts +22 -0
- package/dist/js_render/spec_driver.cjs +0 -2
- package/dist/js_render/spec_driver.js +0 -3
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import { _usingCtx } from "../_virtual/_@oxc-project_runtime@0.114.0/helpers/usingCtx.js";
|
|
1
2
|
import { parseFinalPObjectCollection } from "../pool/p_object_collection.js";
|
|
2
|
-
import {
|
|
3
|
+
import { getServiceInjectors } from "./service_injectors.js";
|
|
3
4
|
import { checkBlockFlag, isDataInfo, mapDataInfo, mapPObjectData, mapPTableDef, mapPTableDefV2, mapValueInVOE } from "@platforma-sdk/model";
|
|
4
5
|
import { notEmpty } from "@milaboratories/ts-helpers";
|
|
5
6
|
import { Computable } from "@milaboratories/computable";
|
|
6
7
|
import { randomUUID } from "node:crypto";
|
|
7
8
|
import { Scope } from "quickjs-emscripten";
|
|
9
|
+
import { PoolEntryGuard, ServiceInjectionError, ServiceMethodNotFoundError, Services, resolveRequiredServices, serviceFnKey } from "@milaboratories/pl-model-common";
|
|
8
10
|
|
|
9
11
|
//#region src/js_render/computable_context.ts
|
|
10
12
|
function bytesToBase64(data) {
|
|
@@ -14,15 +16,14 @@ var ComputableContextHelper = class {
|
|
|
14
16
|
computablesToResolve = {};
|
|
15
17
|
computableCtx;
|
|
16
18
|
accessors = /* @__PURE__ */ new Map();
|
|
17
|
-
specDriver = new SpecDriver();
|
|
18
19
|
_meta;
|
|
19
20
|
get meta() {
|
|
20
|
-
if (this._meta === void 0)
|
|
21
|
-
if (this.computableCtx === void 0) throw new Error("blockMeta can't be resolved in this context");
|
|
22
|
-
this._meta = this.blockCtx.blockMeta(this.computableCtx);
|
|
23
|
-
}
|
|
21
|
+
if (this._meta === void 0) this._meta = this.blockCtx.blockMeta(this.requireComputableCtx);
|
|
24
22
|
return this._meta;
|
|
25
23
|
}
|
|
24
|
+
get serviceRegistry() {
|
|
25
|
+
return this.env.serviceRegistry;
|
|
26
|
+
}
|
|
26
27
|
constructor(parent, blockCtx, env, featureFlags, computableCtx) {
|
|
27
28
|
this.parent = parent;
|
|
28
29
|
this.blockCtx = blockCtx;
|
|
@@ -34,15 +35,22 @@ var ComputableContextHelper = class {
|
|
|
34
35
|
this.computableCtx = void 0;
|
|
35
36
|
this.accessors.clear();
|
|
36
37
|
}
|
|
38
|
+
get requireComputableCtx() {
|
|
39
|
+
if (this.computableCtx === void 0) throw new Error("computableCtx not available (called from future mapper?)");
|
|
40
|
+
return this.computableCtx;
|
|
41
|
+
}
|
|
42
|
+
addOnDestroy(callback) {
|
|
43
|
+
this.requireComputableCtx.addOnDestroy(callback);
|
|
44
|
+
}
|
|
37
45
|
getAccessorHandleByName(name) {
|
|
38
|
-
|
|
46
|
+
const cCtx = this.requireComputableCtx;
|
|
39
47
|
const wellKnownAccessor = (name, ctxKey) => {
|
|
40
48
|
if (!this.accessors.has(name)) {
|
|
41
49
|
const lambda = this.blockCtx[ctxKey];
|
|
42
50
|
if (lambda === void 0) throw new Error("Staging context not available");
|
|
43
|
-
const entry = lambda(
|
|
51
|
+
const entry = lambda(cCtx);
|
|
44
52
|
if (!entry) this.accessors.set(name, void 0);
|
|
45
|
-
else this.accessors.set(name,
|
|
53
|
+
else this.accessors.set(name, cCtx.accessor(entry).node({ ignoreError: true }));
|
|
46
54
|
}
|
|
47
55
|
return this.accessors.get(name) ? name : void 0;
|
|
48
56
|
};
|
|
@@ -157,10 +165,7 @@ var ComputableContextHelper = class {
|
|
|
157
165
|
}
|
|
158
166
|
_resultPool = void 0;
|
|
159
167
|
get resultPool() {
|
|
160
|
-
if (this._resultPool === void 0)
|
|
161
|
-
if (this.computableCtx === void 0) throw new Error("can't use result pool in this context (most porbably called from the future mapper)");
|
|
162
|
-
this._resultPool = notEmpty(this.blockCtx.getResultsPool, "getResultsPool")(this.computableCtx);
|
|
163
|
-
}
|
|
168
|
+
if (this._resultPool === void 0) this._resultPool = notEmpty(this.blockCtx.getResultsPool, "getResultsPool")(this.requireComputableCtx);
|
|
164
169
|
return this._resultPool;
|
|
165
170
|
}
|
|
166
171
|
calculateOptions(predicate) {
|
|
@@ -168,7 +173,7 @@ var ComputableContextHelper = class {
|
|
|
168
173
|
}
|
|
169
174
|
getDataFromResultPool() {
|
|
170
175
|
const collection = this.resultPool.getData();
|
|
171
|
-
if (collection.instabilityMarker !== void 0) this.
|
|
176
|
+
if (collection.instabilityMarker !== void 0) this.requireComputableCtx.markUnstable(`incomplete_result_pool:${collection.instabilityMarker}`);
|
|
172
177
|
return {
|
|
173
178
|
isComplete: collection.isComplete,
|
|
174
179
|
entries: collection.entries.map((e) => ({
|
|
@@ -179,7 +184,7 @@ var ComputableContextHelper = class {
|
|
|
179
184
|
}
|
|
180
185
|
getDataWithErrorsFromResultPool() {
|
|
181
186
|
const collection = this.resultPool.getDataWithErrors();
|
|
182
|
-
if (collection.instabilityMarker !== void 0) this.
|
|
187
|
+
if (collection.instabilityMarker !== void 0) this.requireComputableCtx.markUnstable(`incomplete_result_pool:${collection.instabilityMarker}`);
|
|
183
188
|
return {
|
|
184
189
|
isComplete: collection.isComplete,
|
|
185
190
|
entries: collection.entries.map((e) => ({
|
|
@@ -194,7 +199,7 @@ var ComputableContextHelper = class {
|
|
|
194
199
|
}
|
|
195
200
|
getSpecsFromResultPool() {
|
|
196
201
|
const specs = this.resultPool.getSpecs();
|
|
197
|
-
if (specs.instabilityMarker !== void 0) this.
|
|
202
|
+
if (specs.instabilityMarker !== void 0) this.requireComputableCtx.markUnstable(`specs_from_pool_incomplete:${specs.instabilityMarker}`);
|
|
198
203
|
return specs;
|
|
199
204
|
}
|
|
200
205
|
getSpecFromResultPoolByRef(blockId, exportName) {
|
|
@@ -204,45 +209,40 @@ var ComputableContextHelper = class {
|
|
|
204
209
|
return mapPObjectData(this.resultPool.getDataByRef(blockId, exportName), (acc) => this.wrapAccessor(acc));
|
|
205
210
|
}
|
|
206
211
|
createPFrame(def) {
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
212
|
+
try {
|
|
213
|
+
var _usingCtx$1 = _usingCtx();
|
|
214
|
+
const guard = _usingCtx$1.u(new PoolEntryGuard(this.env.driverKit.pFrameDriver.createPFrame(def.map((c) => mapPObjectData(c, (d) => this.transformInputPData(d))))));
|
|
215
|
+
this.requireComputableCtx.addOnDestroy(guard.entry.unref);
|
|
216
|
+
return guard.keep().key;
|
|
217
|
+
} catch (_) {
|
|
218
|
+
_usingCtx$1.e = _;
|
|
219
|
+
} finally {
|
|
220
|
+
_usingCtx$1.d();
|
|
221
|
+
}
|
|
211
222
|
}
|
|
212
223
|
createPTable(def) {
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
224
|
+
try {
|
|
225
|
+
var _usingCtx3 = _usingCtx();
|
|
226
|
+
const guard = _usingCtx3.u(new PoolEntryGuard(this.env.driverKit.pFrameDriver.createPTable(mapPTableDef(def, (c) => mapPObjectData(c, (d) => this.transformInputPData(d))))));
|
|
227
|
+
this.requireComputableCtx.addOnDestroy(guard.entry.unref);
|
|
228
|
+
return guard.keep().key;
|
|
229
|
+
} catch (_) {
|
|
230
|
+
_usingCtx3.e = _;
|
|
231
|
+
} finally {
|
|
232
|
+
_usingCtx3.d();
|
|
233
|
+
}
|
|
217
234
|
}
|
|
218
235
|
createPTableV2(def) {
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
specFrameDiscoverColumns(handle, request) {
|
|
230
|
-
return this.specDriver.specFrameDiscoverColumns(handle, request);
|
|
231
|
-
}
|
|
232
|
-
disposeSpecFrame(handle) {
|
|
233
|
-
this.specDriver.disposeSpecFrame(handle);
|
|
234
|
-
}
|
|
235
|
-
expandAxes(spec) {
|
|
236
|
-
return this.specDriver.expandAxes(spec);
|
|
237
|
-
}
|
|
238
|
-
collapseAxes(ids) {
|
|
239
|
-
return this.specDriver.collapseAxes(ids);
|
|
240
|
-
}
|
|
241
|
-
findAxis(spec, selector) {
|
|
242
|
-
return this.specDriver.findAxis(spec, selector);
|
|
243
|
-
}
|
|
244
|
-
findTableColumn(tableSpec, selector) {
|
|
245
|
-
return this.specDriver.findTableColumn(tableSpec, selector);
|
|
236
|
+
try {
|
|
237
|
+
var _usingCtx4 = _usingCtx();
|
|
238
|
+
const guard = _usingCtx4.u(new PoolEntryGuard(this.env.driverKit.pFrameDriver.createPTableV2(mapPTableDefV2(def, (c) => mapPObjectData(c, (d) => this.transformInputPData(d))))));
|
|
239
|
+
this.requireComputableCtx.addOnDestroy(guard.entry.unref);
|
|
240
|
+
return guard.keep().key;
|
|
241
|
+
} catch (_) {
|
|
242
|
+
_usingCtx4.e = _;
|
|
243
|
+
} finally {
|
|
244
|
+
_usingCtx4.d();
|
|
245
|
+
}
|
|
246
246
|
}
|
|
247
247
|
/**
|
|
248
248
|
* Transforms input data for PFrame/PTable creation
|
|
@@ -312,31 +312,29 @@ var ComputableContextHelper = class {
|
|
|
312
312
|
};
|
|
313
313
|
if (checkBlockFlag(this.featureFlags, "supportsLazyState")) {
|
|
314
314
|
exportCtxFunction("args", () => {
|
|
315
|
-
|
|
316
|
-
const args = this.blockCtx.args(
|
|
315
|
+
const cCtx = this.requireComputableCtx;
|
|
316
|
+
const args = this.blockCtx.args(cCtx);
|
|
317
317
|
return args === void 0 ? vm.undefined : vm.newString(args);
|
|
318
318
|
});
|
|
319
319
|
exportCtxFunction("blockStorage", () => {
|
|
320
|
-
|
|
321
|
-
return vm.newString(this.blockCtx.blockStorage(this.computableCtx) ?? "{}");
|
|
320
|
+
return vm.newString(this.blockCtx.blockStorage(this.requireComputableCtx) ?? "{}");
|
|
322
321
|
});
|
|
323
322
|
exportCtxFunction("data", () => {
|
|
324
|
-
|
|
325
|
-
return vm.newString(this.blockCtx.data(this.computableCtx) ?? "{}");
|
|
323
|
+
return vm.newString(this.blockCtx.data(this.requireComputableCtx) ?? "{}");
|
|
326
324
|
});
|
|
327
325
|
exportCtxFunction("activeArgs", () => {
|
|
328
|
-
|
|
329
|
-
const res = this.blockCtx.activeArgs(
|
|
326
|
+
const cCtx = this.requireComputableCtx;
|
|
327
|
+
const res = this.blockCtx.activeArgs(cCtx);
|
|
330
328
|
return res === void 0 ? vm.undefined : vm.newString(res);
|
|
331
329
|
});
|
|
332
330
|
if (isLegacyBlock) exportCtxFunction("uiState", () => {
|
|
333
|
-
|
|
334
|
-
return vm.newString(extractUiState(this.blockCtx.data(this.computableCtx)));
|
|
331
|
+
return vm.newString(extractUiState(this.blockCtx.data(this.requireComputableCtx)));
|
|
335
332
|
});
|
|
336
333
|
} else {
|
|
337
|
-
const
|
|
338
|
-
const
|
|
339
|
-
const
|
|
334
|
+
const cCtx = this.requireComputableCtx;
|
|
335
|
+
const args = this.blockCtx.args(cCtx);
|
|
336
|
+
const activeArgs = this.blockCtx.activeArgs(cCtx);
|
|
337
|
+
const data = this.blockCtx.data(cCtx);
|
|
340
338
|
if (args !== void 0) vm.setProp(configCtx, "args", localScope.manage(vm.newString(args)));
|
|
341
339
|
vm.setProp(configCtx, "data", localScope.manage(vm.newString(data ?? "{}")));
|
|
342
340
|
if (activeArgs !== void 0) vm.setProp(configCtx, "activeArgs", localScope.manage(vm.newString(activeArgs)));
|
|
@@ -450,26 +448,36 @@ var ComputableContextHelper = class {
|
|
|
450
448
|
exportCtxFunction("createPTableV2", (def) => {
|
|
451
449
|
return parent.exportSingleValue(this.createPTableV2(parent.importObjectViaJson(def)), void 0);
|
|
452
450
|
});
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
451
|
+
const requiredServiceNames = new Set(resolveRequiredServices(this.featureFlags));
|
|
452
|
+
const serviceFunctions = /* @__PURE__ */ new Map();
|
|
453
|
+
const injectors = getServiceInjectors();
|
|
454
|
+
for (const [key, serviceId] of Object.entries(Services)) {
|
|
455
|
+
if (!requiredServiceNames.has(serviceId)) continue;
|
|
456
|
+
const injector = injectors[key];
|
|
457
|
+
try {
|
|
458
|
+
const methods = injector({
|
|
459
|
+
host: this,
|
|
460
|
+
vm: parent
|
|
461
|
+
});
|
|
462
|
+
for (const [method, fn] of Object.entries(methods)) serviceFunctions.set(serviceFnKey(serviceId, method), fn);
|
|
463
|
+
} catch (e) {
|
|
464
|
+
throw new ServiceInjectionError(`Failed to inject service "${serviceId}"`, { cause: e });
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
exportCtxFunction("getServiceNames", () => {
|
|
468
|
+
return parent.exportObjectViaJson([...requiredServiceNames]);
|
|
469
|
+
});
|
|
470
|
+
exportCtxFunction("getServiceMethods", (serviceIdHandle) => {
|
|
471
|
+
const pfx = serviceFnKey(vm.getString(serviceIdHandle));
|
|
472
|
+
const methods = [...serviceFunctions.keys()].filter((k) => k.startsWith(pfx)).map((k) => k.slice(pfx.length));
|
|
473
|
+
return parent.exportObjectViaJson(methods, void 0);
|
|
474
|
+
});
|
|
475
|
+
exportCtxFunction("callServiceMethod", function(serviceIdHandle, methodHandle, ...argHandles) {
|
|
476
|
+
const serviceId = vm.getString(serviceIdHandle);
|
|
477
|
+
const method = vm.getString(methodHandle);
|
|
478
|
+
const fn = serviceFunctions.get(serviceFnKey(serviceId, method));
|
|
479
|
+
if (!fn) throw new ServiceMethodNotFoundError(`Method "${method}" not found on service "${serviceId}"`);
|
|
480
|
+
return fn.call(this, ...argHandles);
|
|
473
481
|
});
|
|
474
482
|
exportCtxFunction("getCurrentUnstableMarker", () => {
|
|
475
483
|
return parent.exportSingleValue(this.getCurrentUnstableMarker(), void 0);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"computable_context.js","names":[],"sources":["../../src/js_render/computable_context.ts"],"sourcesContent":["import type { ComputableCtx } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport type { PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport { checkBlockFlag } from \"@platforma-sdk/model\";\nimport type {\n ArchiveFormat,\n CommonFieldTraverseOps as CommonFieldTraverseOpsFromSDK,\n DataInfo,\n FieldTraversalStep as FieldTraversalStepFromSDK,\n Option,\n PColumn,\n PColumnValues,\n PFrameDef,\n PFrameHandle,\n PObject,\n PObjectSpec,\n PSpecPredicate,\n PTableDef,\n PTableDefV2,\n PTableHandle,\n ResourceType as ResourceTypeFromSDK,\n ResultCollection,\n ValueOrError,\n RangeBytes,\n BlockCodeKnownFeatureFlags,\n JsRenderInternal,\n} from \"@platforma-sdk/model\";\nimport {\n isDataInfo,\n mapDataInfo,\n mapPObjectData,\n mapPTableDef,\n mapPTableDefV2,\n mapValueInVOE,\n} from \"@platforma-sdk/model\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { randomUUID } from \"node:crypto\";\nimport type { Optional } from \"utility-types\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport type { Block } from \"../model/project_model\";\nimport { parseFinalPObjectCollection } from \"../pool/p_object_collection\";\nimport type { ResultPool } from \"../pool/result_pool\";\nimport type { JsExecutionContext } from \"./context\";\nimport type { VmFunctionImplementation } from \"quickjs-emscripten\";\nimport { Scope, type QuickJSHandle } from \"quickjs-emscripten\";\nimport type {\n AxesId,\n AxesSpec,\n DiscoverColumnsRequest,\n DiscoverColumnsResponse,\n PColumnSpec,\n PTableColumnId,\n PTableColumnSpec,\n SingleAxisSelector,\n SpecFrameHandle,\n} from \"@milaboratories/pl-model-common\";\nimport { SpecDriver } from \"./spec_driver\";\n\nfunction bytesToBase64(data: Uint8Array | undefined): string | undefined {\n return data !== undefined ? Buffer.from(data).toString(\"base64\") : undefined;\n}\n\nexport class ComputableContextHelper implements JsRenderInternal.GlobalCfgRenderCtxMethods<\n string,\n string\n> {\n public readonly computablesToResolve: Record<string, Computable<unknown>> = {};\n\n private computableCtx: ComputableCtx | undefined;\n private readonly accessors = new Map<string, PlTreeNodeAccessor | undefined>();\n private readonly specDriver = new SpecDriver();\n\n private _meta: Map<string, Block> | undefined;\n private get meta(): Map<string, Block> {\n if (this._meta === undefined) {\n if (this.computableCtx === undefined)\n throw new Error(\"blockMeta can't be resolved in this context\");\n this._meta = this.blockCtx.blockMeta(this.computableCtx);\n }\n return this._meta;\n }\n\n constructor(\n private readonly parent: JsExecutionContext,\n private readonly blockCtx: BlockContextAny,\n private readonly env: MiddleLayerEnvironment,\n private readonly featureFlags: BlockCodeKnownFeatureFlags | undefined,\n computableCtx: ComputableCtx,\n ) {\n this.computableCtx = computableCtx;\n }\n\n public resetComputableCtx() {\n this.computableCtx = undefined;\n this.accessors.clear();\n }\n\n //\n // Methods for injected ctx object\n //\n\n getAccessorHandleByName(name: string): string | undefined {\n if (this.computableCtx === undefined)\n throw new Error(\"Accessors can't be used in this context\");\n const wellKnownAccessor = (name: string, ctxKey: \"staging\" | \"prod\"): string | undefined => {\n if (!this.accessors.has(name)) {\n const lambda = this.blockCtx[ctxKey];\n if (lambda === undefined) throw new Error(\"Staging context not available\");\n const entry = lambda(this.computableCtx!);\n if (!entry) this.accessors.set(name, undefined);\n else\n this.accessors.set(name, this.computableCtx!.accessor(entry).node({ ignoreError: true }));\n }\n return this.accessors.get(name) ? name : undefined;\n };\n if (name === \"staging\") return wellKnownAccessor(\"staging\", \"staging\");\n else if (name === \"main\") return wellKnownAccessor(\"main\", \"prod\");\n return undefined;\n }\n\n //\n // Accessors\n //\n\n resolveWithCommon(\n handle: string,\n commonOptions: CommonFieldTraverseOpsFromSDK,\n ...steps: (FieldTraversalStepFromSDK | string)[]\n ): string | undefined {\n return this.wrapAccessor(this.getAccessor(handle).traverseWithCommon(commonOptions, ...steps));\n }\n\n getResourceType(handle: string): ResourceTypeFromSDK {\n return this.getAccessor(handle).resourceType;\n }\n\n getInputsLocked(handle: string): boolean {\n return this.getAccessor(handle).getInputsLocked();\n }\n\n getOutputsLocked(handle: string): boolean {\n return this.getAccessor(handle).getOutputsLocked();\n }\n\n getIsReadyOrError(handle: string): boolean {\n return this.getAccessor(handle).getIsReadyOrError();\n }\n\n getIsFinal(handle: string): boolean {\n return this.getAccessor(handle).getIsFinal();\n }\n\n getError(handle: string): string | undefined {\n return this.wrapAccessor(this.getAccessor(handle).getError());\n }\n\n listInputFields(handle: string): string[] {\n return this.getAccessor(handle).listInputFields();\n }\n\n listOutputFields(handle: string): string[] {\n return this.getAccessor(handle).listOutputFields();\n }\n\n listDynamicFields(handle: string): string[] {\n return this.getAccessor(handle).listDynamicFields();\n }\n\n getKeyValueBase64(handle: string, key: string): string | undefined {\n return bytesToBase64(this.getAccessor(handle).getKeyValue(key));\n }\n\n getKeyValueAsString(handle: string, key: string): string | undefined {\n return this.getAccessor(handle).getKeyValueAsString(key);\n }\n\n getDataBase64(handle: string): string | undefined {\n return bytesToBase64(this.getAccessor(handle).getData());\n }\n\n getDataAsString(handle: string): string | undefined {\n return this.getAccessor(handle).getDataAsString();\n }\n\n //\n // Accessor helpers\n //\n\n parsePObjectCollection(\n handle: string,\n errorOnUnknownField: boolean,\n prefix: string,\n ...resolveSteps: string[]\n ): Record<string, PObject<string>> | undefined {\n const acc = this.getAccessor(handle);\n if (!acc.getIsReadyOrError()) return undefined;\n const accResult = parseFinalPObjectCollection(acc, errorOnUnknownField, prefix, resolveSteps);\n const result: Record<string, PObject<string>> = {};\n for (const [key, obj] of Object.entries(accResult)) {\n result[key] = mapPObjectData(obj, (d) => this.wrapAccessor(d));\n }\n return result;\n }\n\n //\n // Blobs\n //\n\n private registerComputable(hPrefix: string, computable: Computable<unknown>): string {\n const fHandle = `${hPrefix}_${randomUUID()}`;\n this.computablesToResolve[fHandle] = computable;\n return fHandle;\n }\n\n public getBlobContentAsString(handle: string, range?: RangeBytes): string {\n const resourceInfo = this.getAccessor(handle).resourceInfo;\n return this.registerComputable(\n \"getBlobContentAsString\",\n Computable.make((ctx) => this.env.driverKit.blobDriver.getDownloadedBlob(resourceInfo, ctx), {\n postprocessValue: async (value) => {\n if (value === undefined) return undefined;\n return Buffer.from(\n await this.env.driverKit.blobDriver.getContent(value.handle, range),\n ).toString(\"utf-8\");\n },\n }),\n );\n }\n\n public getBlobContentAsBase64(handle: string, range?: RangeBytes): string {\n const resourceInfo = this.getAccessor(handle).resourceInfo;\n return this.registerComputable(\n \"getBlobContentAsBase64\",\n Computable.make((ctx) => this.env.driverKit.blobDriver.getDownloadedBlob(resourceInfo, ctx), {\n postprocessValue: async (value) => {\n if (value === undefined) return undefined;\n return Buffer.from(\n await this.env.driverKit.blobDriver.getContent(value.handle, range),\n ).toString(\"base64\");\n },\n }),\n );\n }\n\n public getDownloadedBlobContentHandle(handle: string): string {\n const resourceInfo = this.getAccessor(handle).resourceInfo;\n return this.registerComputable(\n \"getDownloadedBlobContentHandle\",\n this.env.driverKit.blobDriver.getDownloadedBlob(resourceInfo),\n );\n }\n\n public getOnDemandBlobContentHandle(handle: string): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getOnDemandBlobContentHandle\",\n this.env.driverKit.blobDriver.getOnDemandBlob(resource),\n );\n }\n\n //\n // Blobs to URLs\n //\n\n public extractArchiveAndGetURL(handle: string, format: ArchiveFormat): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"extractArchiveAndGetURL\",\n this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(resource, format),\n );\n }\n\n //\n // Import progress\n //\n\n getImportProgress(handle: string): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getImportProgress\",\n this.env.driverKit.uploadDriver.getProgressId(resource),\n );\n }\n\n //\n // Logs\n //\n\n getLastLogs(handle: string, nLines: number): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getLastLogs\",\n this.env.driverKit.logDriver.getLastLogs(resource, nLines),\n );\n }\n\n getProgressLog(handle: string, patternToSearch: string): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getProgressLog\",\n this.env.driverKit.logDriver.getProgressLog(resource, patternToSearch),\n );\n }\n\n getProgressLogWithInfo(handle: string, patternToSearch: string): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getProgressLogWithInfo\",\n this.env.driverKit.logDriver.getProgressLogWithInfo(resource, patternToSearch),\n );\n }\n\n getLogHandle(handle: string): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getLogHandle\",\n this.env.driverKit.logDriver.getLogHandle(resource),\n );\n }\n\n //\n // Blocks\n //\n\n public getBlockLabel(blockId: string): string {\n const b = this.meta.get(blockId);\n if (b === undefined) throw new Error(`Block ${blockId} not found.`);\n return b.label;\n }\n\n //\n // Result Pool\n //\n\n private _resultPool: ResultPool | undefined = undefined;\n private get resultPool(): ResultPool {\n if (this._resultPool === undefined) {\n if (this.computableCtx === undefined)\n throw new Error(\n \"can't use result pool in this context (most porbably called from the future mapper)\",\n );\n this._resultPool = notEmpty(\n this.blockCtx.getResultsPool,\n \"getResultsPool\",\n )(this.computableCtx);\n }\n return this._resultPool;\n }\n\n public calculateOptions(predicate: PSpecPredicate): Option[] {\n return this.resultPool.calculateOptions(predicate);\n }\n\n public getDataFromResultPool(): ResultCollection<PObject<string>> {\n const collection = this.resultPool.getData();\n if (collection.instabilityMarker !== undefined)\n this.computableCtx!.markUnstable(`incomplete_result_pool:${collection.instabilityMarker}`);\n return {\n isComplete: collection.isComplete,\n entries: collection.entries.map((e) => ({\n ref: e.ref,\n obj: mapPObjectData(e.obj, (d) => this.wrapAccessor(d)),\n })),\n };\n }\n\n public getDataWithErrorsFromResultPool(): ResultCollection<\n Optional<PObject<ValueOrError<string, Error>>, \"id\">\n > {\n const collection = this.resultPool.getDataWithErrors();\n if (collection.instabilityMarker !== undefined)\n this.computableCtx!.markUnstable(`incomplete_result_pool:${collection.instabilityMarker}`);\n return {\n isComplete: collection.isComplete,\n entries: collection.entries.map((e) => ({\n ref: e.ref,\n obj: {\n id: e.obj.id,\n spec: e.obj.spec,\n data: mapValueInVOE(e.obj.data, (d) => this.wrapAccessor(d)),\n },\n })),\n };\n }\n\n public getSpecsFromResultPool(): ResultCollection<PObjectSpec> {\n const specs = this.resultPool.getSpecs();\n if (specs.instabilityMarker !== undefined)\n this.computableCtx!.markUnstable(`specs_from_pool_incomplete:${specs.instabilityMarker}`);\n return specs;\n }\n\n getSpecFromResultPoolByRef(blockId: string, exportName: string): PObjectSpec | undefined {\n return this.resultPool.getSpecByRef(blockId, exportName);\n }\n\n getDataFromResultPoolByRef(blockId: string, exportName: string): PObject<string> | undefined {\n return mapPObjectData(this.resultPool.getDataByRef(blockId, exportName), (acc) =>\n this.wrapAccessor(acc),\n );\n }\n\n //\n // PFrames / PTables\n //\n\n public createPFrame(\n def: PFrameDef<PColumn<string | PColumnValues | DataInfo<string>>>,\n ): PFrameHandle {\n if (this.computableCtx === undefined)\n throw new Error(\n \"can't instantiate PFrames from this context (most porbably called from the future mapper)\",\n );\n const { key, unref } = this.env.driverKit.pFrameDriver.createPFrame(\n def.map((c) => mapPObjectData(c, (d) => this.transformInputPData(d))),\n );\n this.computableCtx.addOnDestroy(unref);\n return key;\n }\n\n public createPTable(\n def: PTableDef<PColumn<string | PColumnValues | DataInfo<string>>>,\n ): PTableHandle {\n if (this.computableCtx === undefined)\n throw new Error(\n \"can't instantiate PTable from this context (most porbably called from the future mapper)\",\n );\n const { key, unref } = this.env.driverKit.pFrameDriver.createPTable(\n mapPTableDef(def, (c) => mapPObjectData(c, (d) => this.transformInputPData(d))),\n );\n this.computableCtx.addOnDestroy(unref);\n return key;\n }\n public createPTableV2(\n def: PTableDefV2<PColumn<string | PColumnValues | DataInfo<string>>>,\n ): PTableHandle {\n if (this.computableCtx === undefined)\n throw new Error(\n \"can't instantiate PTable from this context (most porbably called from the future mapper)\",\n );\n const { key, unref } = this.env.driverKit.pFrameDriver.createPTableV2(\n mapPTableDefV2(def, (c) => mapPObjectData(c, (d) => this.transformInputPData(d))),\n );\n this.computableCtx.addOnDestroy(unref);\n return key;\n }\n\n //\n // Spec Frames\n //\n\n public createSpecFrame(specs: Record<string, PColumnSpec>): SpecFrameHandle {\n const handle = this.specDriver.createSpecFrame(specs);\n this.computableCtx?.addOnDestroy(() => this.specDriver.disposeSpecFrame(handle));\n return handle;\n }\n\n public specFrameDiscoverColumns(\n handle: SpecFrameHandle,\n request: DiscoverColumnsRequest,\n ): DiscoverColumnsResponse {\n return this.specDriver.specFrameDiscoverColumns(handle as SpecFrameHandle, request);\n }\n\n public disposeSpecFrame(handle: SpecFrameHandle): void {\n this.specDriver.disposeSpecFrame(handle as SpecFrameHandle);\n }\n\n public expandAxes(spec: AxesSpec): AxesId {\n return this.specDriver.expandAxes(spec);\n }\n\n public collapseAxes(ids: AxesId): AxesSpec {\n return this.specDriver.collapseAxes(ids);\n }\n\n public findAxis(spec: AxesSpec, selector: SingleAxisSelector): number {\n return this.specDriver.findAxis(spec, selector);\n }\n\n public findTableColumn(tableSpec: PTableColumnSpec[], selector: PTableColumnId): number {\n return this.specDriver.findTableColumn(tableSpec, selector);\n }\n\n /**\n * Transforms input data for PFrame/PTable creation\n * - Converts string handles to accessors\n * - Maps accessors in DataInfo objects\n * - Passes through other values\n */\n private transformInputPData(\n d: string | PColumnValues | DataInfo<string>,\n ): PlTreeNodeAccessor | PColumnValues | DataInfo<PlTreeNodeAccessor> {\n if (typeof d === \"string\") {\n return this.getAccessor(d);\n } else if (isDataInfo(d)) {\n return mapDataInfo(d, (a) => this.getAccessor(a));\n } else {\n return d;\n }\n }\n\n //\n // Computable\n //\n\n public getCurrentUnstableMarker(): string | undefined {\n return this.computableCtx?.unstableMarker;\n }\n\n //\n // Logging\n //\n\n public logInfo(message: string): void {\n this.env.blockEventDispatcher.logInfo(this.blockCtx.blockId, message);\n }\n\n public logWarn(message: string): void {\n this.env.blockEventDispatcher.logWarn(this.blockCtx.blockId, message);\n }\n\n public logError(message: string): void {\n this.env.blockEventDispatcher.logError(this.blockCtx.blockId, message);\n }\n\n //\n // Helpers\n //\n\n private getAccessor(handle: string): PlTreeNodeAccessor {\n const accessor = this.accessors.get(handle);\n if (accessor === undefined) throw new Error(\"No such accessor\");\n return accessor;\n }\n\n private wrapAccessor(accessor: PlTreeNodeAccessor): string;\n private wrapAccessor(accessor: PlTreeNodeAccessor | undefined): string | undefined;\n private wrapAccessor(accessor: PlTreeNodeAccessor | undefined): string | undefined {\n if (accessor === undefined) return undefined;\n else {\n const nextHandle = randomUUID();\n this.accessors.set(nextHandle, accessor);\n return nextHandle;\n }\n }\n\n public injectCtx(configCtx: QuickJSHandle): void {\n const parent = this.parent;\n const vm = parent.vm;\n\n Scope.withScope((localScope) => {\n // Exporting methods\n\n const exportCtxFunction = (\n name: string,\n fn: VmFunctionImplementation<QuickJSHandle>,\n ): void => {\n const withCachedError: VmFunctionImplementation<QuickJSHandle> = (...args) => {\n // QuickJS strips all fields from errors apart from 'name' and 'message'.\n // That's why here we need to store them, and rethrow them when we exit\n // from QuickJS code.\n const t0 = performance.now();\n try {\n return (fn as any)(...args);\n } catch (e: unknown) {\n const newErr = parent.errorRepo.setAndRecreateForQuickJS(e);\n throw vm.newError(newErr);\n } finally {\n parent.stats.ctxMethodCalls++;\n parent.stats.ctxMethodMs += performance.now() - t0;\n }\n };\n\n vm.newFunction(name, withCachedError).consume((fnh) => vm.setProp(configCtx, name, fnh));\n vm.newFunction(name, fn).consume((fnh) =>\n vm.setProp(configCtx, name + \"__internal__\", fnh),\n );\n };\n\n // Check if this is a v1/v2 block (requiresModelAPIVersion !== 2)\n // For v1/v2 blocks, state is {args, uiState} and we need to inject uiState separately\n const isLegacyBlock = !checkBlockFlag(this.featureFlags, \"requiresModelAPIVersion\", 2);\n\n // Helper to extract uiState from legacy state format {args, uiState}\n const extractUiState = (stateJson: string | undefined): string => {\n if (!stateJson) return \"{}\";\n try {\n const parsed = JSON.parse(stateJson);\n return JSON.stringify(parsed?.uiState ?? {});\n } catch {\n return \"{}\";\n }\n };\n\n if (checkBlockFlag(this.featureFlags, \"supportsLazyState\")) {\n // injecting lazy state functions\n exportCtxFunction(\"args\", () => {\n if (this.computableCtx === undefined)\n throw new Error(\n `Add dummy call to ctx.args outside the future lambda. Can't be directly used in this context.`,\n );\n const args = this.blockCtx.args(this.computableCtx);\n return args === undefined ? vm.undefined : vm.newString(args);\n });\n exportCtxFunction(\"blockStorage\", () => {\n if (this.computableCtx === undefined)\n throw new Error(\n `Add dummy call to ctx.blockStorage outside the future lambda. Can't be directly used in this context.`,\n );\n return vm.newString(this.blockCtx.blockStorage(this.computableCtx) ?? \"{}\");\n });\n exportCtxFunction(\"data\", () => {\n if (this.computableCtx === undefined)\n throw new Error(\n `Add dummy call to ctx.data outside the future lambda. Can't be directly used in this context.`,\n );\n return vm.newString(this.blockCtx.data(this.computableCtx) ?? \"{}\");\n });\n exportCtxFunction(\"activeArgs\", () => {\n if (this.computableCtx === undefined)\n throw new Error(\n `Add dummy call to ctx.activeArgs outside the future lambda. Can't be directly used in this context.`,\n );\n const res = this.blockCtx.activeArgs(this.computableCtx);\n return res === undefined ? vm.undefined : vm.newString(res);\n });\n // For v1/v2 blocks, also inject uiState (extracted from state.uiState)\n if (isLegacyBlock) {\n exportCtxFunction(\"uiState\", () => {\n if (this.computableCtx === undefined)\n throw new Error(\n `Add dummy call to ctx.uiState outside the future lambda. Can't be directly used in this context.`,\n );\n return vm.newString(extractUiState(this.blockCtx.data(this.computableCtx)));\n });\n }\n } else {\n const args = this.blockCtx.args(this.computableCtx!);\n const activeArgs = this.blockCtx.activeArgs(this.computableCtx!);\n const data = this.blockCtx.data(this.computableCtx!);\n if (args !== undefined) {\n vm.setProp(configCtx, \"args\", localScope.manage(vm.newString(args)));\n }\n vm.setProp(configCtx, \"data\", localScope.manage(vm.newString(data ?? \"{}\")));\n if (activeArgs !== undefined)\n vm.setProp(configCtx, \"activeArgs\", localScope.manage(vm.newString(activeArgs)));\n // For v1/v2 blocks, also inject uiState (extracted from state.uiState)\n if (isLegacyBlock) {\n vm.setProp(configCtx, \"uiState\", localScope.manage(vm.newString(extractUiState(data))));\n }\n }\n\n //\n // Methods for injected ctx object\n //\n\n exportCtxFunction(\"getAccessorHandleByName\", (name) => {\n return parent.exportSingleValue(\n this.getAccessorHandleByName(vm.getString(name)),\n undefined,\n );\n });\n\n //\n // Accessors\n //\n\n exportCtxFunction(\"resolveWithCommon\", (handle, commonOptions, ...steps) => {\n return parent.exportSingleValue(\n this.resolveWithCommon(\n vm.getString(handle),\n parent.importObjectViaJson(commonOptions) as CommonFieldTraverseOpsFromSDK,\n ...steps.map(\n (step) => parent.importObjectViaJson(step) as FieldTraversalStepFromSDK | string,\n ),\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"getResourceType\", (handle) => {\n return parent.exportObjectViaJson(this.getResourceType(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getInputsLocked\", (handle) => {\n return parent.exportSingleValue(this.getInputsLocked(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getOutputsLocked\", (handle) => {\n return parent.exportSingleValue(this.getOutputsLocked(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getIsReadyOrError\", (handle) => {\n return parent.exportSingleValue(this.getIsReadyOrError(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getIsFinal\", (handle) => {\n return parent.exportSingleValue(this.getIsFinal(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getError\", (handle) => {\n return parent.exportSingleValue(this.getError(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"listInputFields\", (handle) => {\n return parent.exportObjectViaJson(this.listInputFields(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"listOutputFields\", (handle) => {\n return parent.exportObjectViaJson(this.listOutputFields(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"listDynamicFields\", (handle) => {\n return parent.exportObjectViaJson(this.listDynamicFields(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getKeyValueBase64\", (handle, key) => {\n return parent.exportSingleValue(\n this.getKeyValueBase64(vm.getString(handle), vm.getString(key)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getKeyValueAsString\", (handle, key) => {\n return parent.exportSingleValue(\n this.getKeyValueAsString(vm.getString(handle), vm.getString(key)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getDataBase64\", (handle) => {\n return parent.exportSingleValue(this.getDataBase64(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getDataAsString\", (handle) => {\n return parent.exportSingleValue(this.getDataAsString(vm.getString(handle)), undefined);\n });\n\n //\n // Accessor helpers\n //\n\n exportCtxFunction(\n \"parsePObjectCollection\",\n (handle, errorOnUnknownField, prefix, ...resolveSteps) => {\n return parent.exportObjectUniversal(\n this.parsePObjectCollection(\n vm.getString(handle),\n vm.dump(errorOnUnknownField) as boolean,\n vm.getString(prefix),\n ...resolveSteps.map((stepHandle) => vm.getString(stepHandle)),\n ),\n undefined,\n );\n },\n );\n\n //\n // Blobs\n //\n\n exportCtxFunction(\"getBlobContentAsBase64\", (handle, range) => {\n return parent.exportSingleValue(\n this.getBlobContentAsBase64(\n vm.getString(handle),\n parent.importObjectUniversal(range) as RangeBytes | undefined,\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"getBlobContentAsString\", (handle, range) => {\n return parent.exportSingleValue(\n this.getBlobContentAsString(\n vm.getString(handle),\n parent.importObjectUniversal(range) as RangeBytes | undefined,\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"getDownloadedBlobContentHandle\", (handle) => {\n return parent.exportSingleValue(\n this.getDownloadedBlobContentHandle(vm.getString(handle)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getOnDemandBlobContentHandle\", (handle) => {\n return parent.exportSingleValue(\n this.getOnDemandBlobContentHandle(vm.getString(handle)),\n undefined,\n );\n });\n\n //\n // Blobs to URLs\n //\n\n exportCtxFunction(\"extractArchiveAndGetURL\", (handle, format) => {\n return parent.exportSingleValue(\n this.extractArchiveAndGetURL(vm.getString(handle), vm.getString(format) as ArchiveFormat),\n undefined,\n );\n });\n\n //\n // ImportProgress\n //\n\n exportCtxFunction(\"getImportProgress\", (handle) => {\n return parent.exportSingleValue(this.getImportProgress(vm.getString(handle)), undefined);\n });\n\n //\n // Logs\n //\n\n exportCtxFunction(\"getLastLogs\", (handle, nLines) => {\n return parent.exportSingleValue(\n this.getLastLogs(vm.getString(handle), vm.getNumber(nLines)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getProgressLog\", (handle, patternToSearch) => {\n return parent.exportSingleValue(\n this.getProgressLog(vm.getString(handle), vm.getString(patternToSearch)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getProgressLogWithInfo\", (handle, patternToSearch) => {\n return parent.exportSingleValue(\n this.getProgressLogWithInfo(vm.getString(handle), vm.getString(patternToSearch)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getLogHandle\", (handle) => {\n return parent.exportSingleValue(this.getLogHandle(vm.getString(handle)), undefined);\n });\n\n //\n // Blocks\n //\n\n exportCtxFunction(\"getBlockLabel\", (blockId) => {\n return parent.exportSingleValue(this.getBlockLabel(vm.getString(blockId)), undefined);\n });\n\n //\n // Result pool\n //\n\n exportCtxFunction(\"getDataFromResultPool\", () => {\n return parent.exportObjectUniversal(this.getDataFromResultPool(), undefined);\n });\n\n exportCtxFunction(\"getDataWithErrorsFromResultPool\", () => {\n return parent.exportObjectUniversal(this.getDataWithErrorsFromResultPool(), undefined);\n });\n\n exportCtxFunction(\"getSpecsFromResultPool\", () => {\n return parent.exportObjectUniversal(this.getSpecsFromResultPool(), undefined);\n });\n\n exportCtxFunction(\"calculateOptions\", (predicate) => {\n return parent.exportObjectUniversal(\n this.calculateOptions(parent.importObjectViaJson(predicate) as PSpecPredicate),\n undefined,\n );\n });\n\n exportCtxFunction(\"getSpecFromResultPoolByRef\", (blockId, exportName) => {\n return parent.exportObjectUniversal(\n this.getSpecFromResultPoolByRef(vm.getString(blockId), vm.getString(exportName)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getDataFromResultPoolByRef\", (blockId, exportName) => {\n return parent.exportObjectUniversal(\n this.getDataFromResultPoolByRef(vm.getString(blockId), vm.getString(exportName)),\n undefined,\n );\n });\n\n //\n // PFrames / PTables\n //\n\n exportCtxFunction(\"createPFrame\", (def) => {\n return parent.exportSingleValue(\n this.createPFrame(\n parent.importObjectViaJson(def) as PFrameDef<PColumn<string | PColumnValues>>,\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"createPTable\", (def) => {\n return parent.exportSingleValue(\n this.createPTable(\n parent.importObjectViaJson(def) as PTableDef<PColumn<string | PColumnValues>>,\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"createPTableV2\", (def) => {\n return parent.exportSingleValue(\n this.createPTableV2(\n parent.importObjectViaJson(def) as PTableDefV2<PColumn<string | PColumnValues>>,\n ),\n undefined,\n );\n });\n\n //\n // Spec Frames\n //\n\n exportCtxFunction(\"createSpecFrame\", (specs) => {\n return parent.exportSingleValue(\n this.createSpecFrame(parent.importObjectViaJson(specs) as Record<string, PColumnSpec>),\n undefined,\n );\n });\n\n exportCtxFunction(\"specFrameDiscoverColumns\", (handle, request) => {\n return parent.exportObjectViaJson(\n this.specFrameDiscoverColumns(\n vm.getString(handle) as SpecFrameHandle,\n parent.importObjectViaJson(request) as DiscoverColumnsRequest,\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"disposeSpecFrame\", (handle) => {\n this.disposeSpecFrame(vm.getString(handle) as SpecFrameHandle);\n });\n\n exportCtxFunction(\"expandAxes\", (spec) => {\n return parent.exportObjectViaJson(\n this.expandAxes(parent.importObjectViaJson(spec) as AxesSpec),\n undefined,\n );\n });\n\n exportCtxFunction(\"collapseAxes\", (ids) => {\n return parent.exportObjectViaJson(\n this.collapseAxes(parent.importObjectViaJson(ids) as AxesId),\n undefined,\n );\n });\n\n exportCtxFunction(\"findAxis\", (spec, selector) => {\n return parent.exportSingleValue(\n this.findAxis(\n parent.importObjectViaJson(spec) as AxesSpec,\n parent.importObjectViaJson(selector) as SingleAxisSelector,\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"findTableColumn\", (tableSpec, selector) => {\n return parent.exportSingleValue(\n this.findTableColumn(\n parent.importObjectViaJson(tableSpec) as PTableColumnSpec[],\n parent.importObjectViaJson(selector) as PTableColumnId,\n ),\n undefined,\n );\n });\n\n //\n // Computable\n //\n\n exportCtxFunction(\"getCurrentUnstableMarker\", () => {\n return parent.exportSingleValue(this.getCurrentUnstableMarker(), undefined);\n });\n\n //\n // Logging\n //\n\n exportCtxFunction(\"logInfo\", (message) => {\n this.logInfo(vm.getString(message));\n });\n\n exportCtxFunction(\"logWarn\", (message) => {\n this.logWarn(vm.getString(message));\n });\n\n exportCtxFunction(\"logError\", (message) => {\n this.logError(vm.getString(message));\n });\n });\n }\n}\n"],"mappings":";;;;;;;;;AA2DA,SAAS,cAAc,MAAkD;AACvE,QAAO,SAAS,SAAY,OAAO,KAAK,KAAK,CAAC,SAAS,SAAS,GAAG;;AAGrE,IAAa,0BAAb,MAGE;CACA,AAAgB,uBAA4D,EAAE;CAE9E,AAAQ;CACR,AAAiB,4BAAY,IAAI,KAA6C;CAC9E,AAAiB,aAAa,IAAI,YAAY;CAE9C,AAAQ;CACR,IAAY,OAA2B;AACrC,MAAI,KAAK,UAAU,QAAW;AAC5B,OAAI,KAAK,kBAAkB,OACzB,OAAM,IAAI,MAAM,8CAA8C;AAChE,QAAK,QAAQ,KAAK,SAAS,UAAU,KAAK,cAAc;;AAE1D,SAAO,KAAK;;CAGd,YACE,AAAiB,QACjB,AAAiB,UACjB,AAAiB,KACjB,AAAiB,cACjB,eACA;EALiB;EACA;EACA;EACA;AAGjB,OAAK,gBAAgB;;CAGvB,AAAO,qBAAqB;AAC1B,OAAK,gBAAgB;AACrB,OAAK,UAAU,OAAO;;CAOxB,wBAAwB,MAAkC;AACxD,MAAI,KAAK,kBAAkB,OACzB,OAAM,IAAI,MAAM,0CAA0C;EAC5D,MAAM,qBAAqB,MAAc,WAAmD;AAC1F,OAAI,CAAC,KAAK,UAAU,IAAI,KAAK,EAAE;IAC7B,MAAM,SAAS,KAAK,SAAS;AAC7B,QAAI,WAAW,OAAW,OAAM,IAAI,MAAM,gCAAgC;IAC1E,MAAM,QAAQ,OAAO,KAAK,cAAe;AACzC,QAAI,CAAC,MAAO,MAAK,UAAU,IAAI,MAAM,OAAU;QAE7C,M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Y;AACxC,SAAK,QAAQ,GAAG,UAAU,QAAQ,CAAC;KACnC;AAEF,qBAAkB,YAAY,YAAY;AACxC,SAAK,QAAQ,GAAG,UAAU,QAAQ,CAAC;KACnC;AAEF,qBAAkB,aAAa,YAAY;AACzC,SAAK,SAAS,GAAG,UAAU,QAAQ,CAAC;KACpC;IACF"}
|
|
1
|
+
{"version":3,"file":"computable_context.js","names":[],"sources":["../../src/js_render/computable_context.ts"],"sourcesContent":["import type { ComputableCtx } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport type { PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport { checkBlockFlag } from \"@platforma-sdk/model\";\nimport type {\n ArchiveFormat,\n CommonFieldTraverseOps as CommonFieldTraverseOpsFromSDK,\n DataInfo,\n FieldTraversalStep as FieldTraversalStepFromSDK,\n Option,\n PColumn,\n PColumnValues,\n PFrameDef,\n PFrameHandle,\n PObject,\n PObjectSpec,\n PSpecPredicate,\n PTableDef,\n PTableDefV2,\n PTableHandle,\n ResourceType as ResourceTypeFromSDK,\n ResultCollection,\n ValueOrError,\n RangeBytes,\n BlockCodeKnownFeatureFlags,\n JsRenderInternal,\n} from \"@platforma-sdk/model\";\nimport {\n isDataInfo,\n mapDataInfo,\n mapPObjectData,\n mapPTableDef,\n mapPTableDefV2,\n mapValueInVOE,\n} from \"@platforma-sdk/model\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { PoolEntryGuard } from \"@milaboratories/pl-model-common\";\nimport { randomUUID } from \"node:crypto\";\nimport type { Optional } from \"utility-types\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport type { Block } from \"../model/project_model\";\nimport { parseFinalPObjectCollection } from \"../pool/p_object_collection\";\nimport type { ResultPool } from \"../pool/result_pool\";\nimport type { JsExecutionContext } from \"./context\";\nimport type { VmFunctionImplementation } from \"quickjs-emscripten\";\nimport { Scope, type QuickJSHandle } from \"quickjs-emscripten\";\nimport {\n resolveRequiredServices,\n serviceFnKey,\n Services,\n ModelServiceRegistry,\n ServiceInjectionError,\n ServiceMethodNotFoundError,\n} from \"@milaboratories/pl-model-common\";\nimport { getServiceInjectors } from \"./service_injectors\";\n\nfunction bytesToBase64(data: Uint8Array | undefined): string | undefined {\n return data !== undefined ? Buffer.from(data).toString(\"base64\") : undefined;\n}\n\nexport class ComputableContextHelper implements JsRenderInternal.GlobalCfgRenderCtxMethods<\n string,\n string\n> {\n public readonly computablesToResolve: Record<string, Computable<unknown>> = {};\n\n private computableCtx: ComputableCtx | undefined;\n private readonly accessors = new Map<string, PlTreeNodeAccessor | undefined>();\n private _meta: Map<string, Block> | undefined;\n private get meta(): Map<string, Block> {\n if (this._meta === undefined) {\n this._meta = this.blockCtx.blockMeta(this.requireComputableCtx);\n }\n return this._meta;\n }\n\n public get serviceRegistry(): ModelServiceRegistry {\n return this.env.serviceRegistry;\n }\n\n constructor(\n private readonly parent: JsExecutionContext,\n private readonly blockCtx: BlockContextAny,\n private readonly env: MiddleLayerEnvironment,\n private readonly featureFlags: BlockCodeKnownFeatureFlags | undefined,\n computableCtx: ComputableCtx,\n ) {\n this.computableCtx = computableCtx;\n }\n\n public resetComputableCtx() {\n this.computableCtx = undefined;\n this.accessors.clear();\n }\n\n private get requireComputableCtx(): ComputableCtx {\n if (this.computableCtx === undefined)\n throw new Error(\"computableCtx not available (called from future mapper?)\");\n return this.computableCtx;\n }\n\n public addOnDestroy(callback: () => void): void {\n this.requireComputableCtx.addOnDestroy(callback);\n }\n\n //\n // Methods for injected ctx object\n //\n\n getAccessorHandleByName(name: string): string | undefined {\n const cCtx = this.requireComputableCtx;\n const wellKnownAccessor = (name: string, ctxKey: \"staging\" | \"prod\"): string | undefined => {\n if (!this.accessors.has(name)) {\n const lambda = this.blockCtx[ctxKey];\n if (lambda === undefined) throw new Error(\"Staging context not available\");\n const entry = lambda(cCtx);\n if (!entry) this.accessors.set(name, undefined);\n else this.accessors.set(name, cCtx.accessor(entry).node({ ignoreError: true }));\n }\n return this.accessors.get(name) ? name : undefined;\n };\n if (name === \"staging\") return wellKnownAccessor(\"staging\", \"staging\");\n else if (name === \"main\") return wellKnownAccessor(\"main\", \"prod\");\n return undefined;\n }\n\n //\n // Accessors\n //\n\n resolveWithCommon(\n handle: string,\n commonOptions: CommonFieldTraverseOpsFromSDK,\n ...steps: (FieldTraversalStepFromSDK | string)[]\n ): string | undefined {\n return this.wrapAccessor(this.getAccessor(handle).traverseWithCommon(commonOptions, ...steps));\n }\n\n getResourceType(handle: string): ResourceTypeFromSDK {\n return this.getAccessor(handle).resourceType;\n }\n\n getInputsLocked(handle: string): boolean {\n return this.getAccessor(handle).getInputsLocked();\n }\n\n getOutputsLocked(handle: string): boolean {\n return this.getAccessor(handle).getOutputsLocked();\n }\n\n getIsReadyOrError(handle: string): boolean {\n return this.getAccessor(handle).getIsReadyOrError();\n }\n\n getIsFinal(handle: string): boolean {\n return this.getAccessor(handle).getIsFinal();\n }\n\n getError(handle: string): string | undefined {\n return this.wrapAccessor(this.getAccessor(handle).getError());\n }\n\n listInputFields(handle: string): string[] {\n return this.getAccessor(handle).listInputFields();\n }\n\n listOutputFields(handle: string): string[] {\n return this.getAccessor(handle).listOutputFields();\n }\n\n listDynamicFields(handle: string): string[] {\n return this.getAccessor(handle).listDynamicFields();\n }\n\n getKeyValueBase64(handle: string, key: string): string | undefined {\n return bytesToBase64(this.getAccessor(handle).getKeyValue(key));\n }\n\n getKeyValueAsString(handle: string, key: string): string | undefined {\n return this.getAccessor(handle).getKeyValueAsString(key);\n }\n\n getDataBase64(handle: string): string | undefined {\n return bytesToBase64(this.getAccessor(handle).getData());\n }\n\n getDataAsString(handle: string): string | undefined {\n return this.getAccessor(handle).getDataAsString();\n }\n\n //\n // Accessor helpers\n //\n\n parsePObjectCollection(\n handle: string,\n errorOnUnknownField: boolean,\n prefix: string,\n ...resolveSteps: string[]\n ): Record<string, PObject<string>> | undefined {\n const acc = this.getAccessor(handle);\n if (!acc.getIsReadyOrError()) return undefined;\n const accResult = parseFinalPObjectCollection(acc, errorOnUnknownField, prefix, resolveSteps);\n const result: Record<string, PObject<string>> = {};\n for (const [key, obj] of Object.entries(accResult)) {\n result[key] = mapPObjectData(obj, (d) => this.wrapAccessor(d));\n }\n return result;\n }\n\n //\n // Blobs\n //\n\n private registerComputable(hPrefix: string, computable: Computable<unknown>): string {\n const fHandle = `${hPrefix}_${randomUUID()}`;\n this.computablesToResolve[fHandle] = computable;\n return fHandle;\n }\n\n public getBlobContentAsString(handle: string, range?: RangeBytes): string {\n const resourceInfo = this.getAccessor(handle).resourceInfo;\n return this.registerComputable(\n \"getBlobContentAsString\",\n Computable.make((ctx) => this.env.driverKit.blobDriver.getDownloadedBlob(resourceInfo, ctx), {\n postprocessValue: async (value) => {\n if (value === undefined) return undefined;\n return Buffer.from(\n await this.env.driverKit.blobDriver.getContent(value.handle, range),\n ).toString(\"utf-8\");\n },\n }),\n );\n }\n\n public getBlobContentAsBase64(handle: string, range?: RangeBytes): string {\n const resourceInfo = this.getAccessor(handle).resourceInfo;\n return this.registerComputable(\n \"getBlobContentAsBase64\",\n Computable.make((ctx) => this.env.driverKit.blobDriver.getDownloadedBlob(resourceInfo, ctx), {\n postprocessValue: async (value) => {\n if (value === undefined) return undefined;\n return Buffer.from(\n await this.env.driverKit.blobDriver.getContent(value.handle, range),\n ).toString(\"base64\");\n },\n }),\n );\n }\n\n public getDownloadedBlobContentHandle(handle: string): string {\n const resourceInfo = this.getAccessor(handle).resourceInfo;\n return this.registerComputable(\n \"getDownloadedBlobContentHandle\",\n this.env.driverKit.blobDriver.getDownloadedBlob(resourceInfo),\n );\n }\n\n public getOnDemandBlobContentHandle(handle: string): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getOnDemandBlobContentHandle\",\n this.env.driverKit.blobDriver.getOnDemandBlob(resource),\n );\n }\n\n //\n // Blobs to URLs\n //\n\n public extractArchiveAndGetURL(handle: string, format: ArchiveFormat): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"extractArchiveAndGetURL\",\n this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(resource, format),\n );\n }\n\n //\n // Import progress\n //\n\n getImportProgress(handle: string): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getImportProgress\",\n this.env.driverKit.uploadDriver.getProgressId(resource),\n );\n }\n\n //\n // Logs\n //\n\n getLastLogs(handle: string, nLines: number): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getLastLogs\",\n this.env.driverKit.logDriver.getLastLogs(resource, nLines),\n );\n }\n\n getProgressLog(handle: string, patternToSearch: string): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getProgressLog\",\n this.env.driverKit.logDriver.getProgressLog(resource, patternToSearch),\n );\n }\n\n getProgressLogWithInfo(handle: string, patternToSearch: string): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getProgressLogWithInfo\",\n this.env.driverKit.logDriver.getProgressLogWithInfo(resource, patternToSearch),\n );\n }\n\n getLogHandle(handle: string): string {\n const resource = this.getAccessor(handle).persist();\n return this.registerComputable(\n \"getLogHandle\",\n this.env.driverKit.logDriver.getLogHandle(resource),\n );\n }\n\n //\n // Blocks\n //\n\n public getBlockLabel(blockId: string): string {\n const b = this.meta.get(blockId);\n if (b === undefined) throw new Error(`Block ${blockId} not found.`);\n return b.label;\n }\n\n //\n // Result Pool\n //\n\n private _resultPool: ResultPool | undefined = undefined;\n private get resultPool(): ResultPool {\n if (this._resultPool === undefined) {\n this._resultPool = notEmpty(\n this.blockCtx.getResultsPool,\n \"getResultsPool\",\n )(this.requireComputableCtx);\n }\n return this._resultPool;\n }\n\n public calculateOptions(predicate: PSpecPredicate): Option[] {\n return this.resultPool.calculateOptions(predicate);\n }\n\n public getDataFromResultPool(): ResultCollection<PObject<string>> {\n const collection = this.resultPool.getData();\n if (collection.instabilityMarker !== undefined)\n this.requireComputableCtx.markUnstable(\n `incomplete_result_pool:${collection.instabilityMarker}`,\n );\n return {\n isComplete: collection.isComplete,\n entries: collection.entries.map((e) => ({\n ref: e.ref,\n obj: mapPObjectData(e.obj, (d) => this.wrapAccessor(d)),\n })),\n };\n }\n\n public getDataWithErrorsFromResultPool(): ResultCollection<\n Optional<PObject<ValueOrError<string, Error>>, \"id\">\n > {\n const collection = this.resultPool.getDataWithErrors();\n if (collection.instabilityMarker !== undefined)\n this.requireComputableCtx.markUnstable(\n `incomplete_result_pool:${collection.instabilityMarker}`,\n );\n return {\n isComplete: collection.isComplete,\n entries: collection.entries.map((e) => ({\n ref: e.ref,\n obj: {\n id: e.obj.id,\n spec: e.obj.spec,\n data: mapValueInVOE(e.obj.data, (d) => this.wrapAccessor(d)),\n },\n })),\n };\n }\n\n public getSpecsFromResultPool(): ResultCollection<PObjectSpec> {\n const specs = this.resultPool.getSpecs();\n if (specs.instabilityMarker !== undefined)\n this.requireComputableCtx.markUnstable(\n `specs_from_pool_incomplete:${specs.instabilityMarker}`,\n );\n return specs;\n }\n\n getSpecFromResultPoolByRef(blockId: string, exportName: string): PObjectSpec | undefined {\n return this.resultPool.getSpecByRef(blockId, exportName);\n }\n\n getDataFromResultPoolByRef(blockId: string, exportName: string): PObject<string> | undefined {\n return mapPObjectData(this.resultPool.getDataByRef(blockId, exportName), (acc) =>\n this.wrapAccessor(acc),\n );\n }\n\n //\n // PFrames / PTables\n //\n\n public createPFrame(\n def: PFrameDef<PColumn<string | PColumnValues | DataInfo<string>>>,\n ): PFrameHandle {\n using guard = new PoolEntryGuard(\n this.env.driverKit.pFrameDriver.createPFrame(\n def.map((c) => mapPObjectData(c, (d) => this.transformInputPData(d))),\n ),\n );\n this.requireComputableCtx.addOnDestroy(guard.entry.unref);\n return guard.keep().key;\n }\n\n public createPTable(\n def: PTableDef<PColumn<string | PColumnValues | DataInfo<string>>>,\n ): PTableHandle {\n using guard = new PoolEntryGuard(\n this.env.driverKit.pFrameDriver.createPTable(\n mapPTableDef(def, (c) => mapPObjectData(c, (d) => this.transformInputPData(d))),\n ),\n );\n this.requireComputableCtx.addOnDestroy(guard.entry.unref);\n return guard.keep().key;\n }\n\n public createPTableV2(\n def: PTableDefV2<PColumn<string | PColumnValues | DataInfo<string>>>,\n ): PTableHandle {\n using guard = new PoolEntryGuard(\n this.env.driverKit.pFrameDriver.createPTableV2(\n mapPTableDefV2(def, (c) => mapPObjectData(c, (d) => this.transformInputPData(d))),\n ),\n );\n this.requireComputableCtx.addOnDestroy(guard.entry.unref);\n return guard.keep().key;\n }\n\n /**\n * Transforms input data for PFrame/PTable creation\n * - Converts string handles to accessors\n * - Maps accessors in DataInfo objects\n * - Passes through other values\n */\n private transformInputPData(\n d: string | PColumnValues | DataInfo<string>,\n ): PlTreeNodeAccessor | PColumnValues | DataInfo<PlTreeNodeAccessor> {\n if (typeof d === \"string\") {\n return this.getAccessor(d);\n } else if (isDataInfo(d)) {\n return mapDataInfo(d, (a) => this.getAccessor(a));\n } else {\n return d;\n }\n }\n\n //\n // Computable\n //\n\n public getCurrentUnstableMarker(): string | undefined {\n return this.computableCtx?.unstableMarker;\n }\n\n //\n // Logging\n //\n\n public logInfo(message: string): void {\n this.env.blockEventDispatcher.logInfo(this.blockCtx.blockId, message);\n }\n\n public logWarn(message: string): void {\n this.env.blockEventDispatcher.logWarn(this.blockCtx.blockId, message);\n }\n\n public logError(message: string): void {\n this.env.blockEventDispatcher.logError(this.blockCtx.blockId, message);\n }\n\n //\n // Helpers\n //\n\n private getAccessor(handle: string): PlTreeNodeAccessor {\n const accessor = this.accessors.get(handle);\n if (accessor === undefined) throw new Error(\"No such accessor\");\n return accessor;\n }\n\n private wrapAccessor(accessor: PlTreeNodeAccessor): string;\n private wrapAccessor(accessor: PlTreeNodeAccessor | undefined): string | undefined;\n private wrapAccessor(accessor: PlTreeNodeAccessor | undefined): string | undefined {\n if (accessor === undefined) return undefined;\n else {\n const nextHandle = randomUUID();\n this.accessors.set(nextHandle, accessor);\n return nextHandle;\n }\n }\n\n public injectCtx(configCtx: QuickJSHandle): void {\n const parent = this.parent;\n const vm = parent.vm;\n\n Scope.withScope((localScope) => {\n // Exporting methods\n\n const exportCtxFunction = (\n name: string,\n fn: VmFunctionImplementation<QuickJSHandle>,\n ): void => {\n const withCachedError: VmFunctionImplementation<QuickJSHandle> = (...args) => {\n // QuickJS strips all fields from errors apart from 'name' and 'message'.\n // That's why here we need to store them, and rethrow them when we exit\n // from QuickJS code.\n const t0 = performance.now();\n try {\n return (fn as any)(...args);\n } catch (e: unknown) {\n const newErr = parent.errorRepo.setAndRecreateForQuickJS(e);\n throw vm.newError(newErr);\n } finally {\n parent.stats.ctxMethodCalls++;\n parent.stats.ctxMethodMs += performance.now() - t0;\n }\n };\n\n vm.newFunction(name, withCachedError).consume((fnh) => vm.setProp(configCtx, name, fnh));\n vm.newFunction(name, fn).consume((fnh) =>\n vm.setProp(configCtx, name + \"__internal__\", fnh),\n );\n };\n\n // Check if this is a v1/v2 block (requiresModelAPIVersion !== 2)\n // For v1/v2 blocks, state is {args, uiState} and we need to inject uiState separately\n const isLegacyBlock = !checkBlockFlag(this.featureFlags, \"requiresModelAPIVersion\", 2);\n\n // Helper to extract uiState from legacy state format {args, uiState}\n const extractUiState = (stateJson: string | undefined): string => {\n if (!stateJson) return \"{}\";\n try {\n const parsed = JSON.parse(stateJson);\n return JSON.stringify(parsed?.uiState ?? {});\n } catch {\n return \"{}\";\n }\n };\n\n if (checkBlockFlag(this.featureFlags, \"supportsLazyState\")) {\n // injecting lazy state functions\n exportCtxFunction(\"args\", () => {\n const cCtx = this.requireComputableCtx;\n const args = this.blockCtx.args(cCtx);\n return args === undefined ? vm.undefined : vm.newString(args);\n });\n exportCtxFunction(\"blockStorage\", () => {\n return vm.newString(this.blockCtx.blockStorage(this.requireComputableCtx) ?? \"{}\");\n });\n exportCtxFunction(\"data\", () => {\n return vm.newString(this.blockCtx.data(this.requireComputableCtx) ?? \"{}\");\n });\n exportCtxFunction(\"activeArgs\", () => {\n const cCtx = this.requireComputableCtx;\n const res = this.blockCtx.activeArgs(cCtx);\n return res === undefined ? vm.undefined : vm.newString(res);\n });\n // For v1/v2 blocks, also inject uiState (extracted from state.uiState)\n if (isLegacyBlock) {\n exportCtxFunction(\"uiState\", () => {\n return vm.newString(extractUiState(this.blockCtx.data(this.requireComputableCtx)));\n });\n }\n } else {\n const cCtx = this.requireComputableCtx;\n const args = this.blockCtx.args(cCtx);\n const activeArgs = this.blockCtx.activeArgs(cCtx);\n const data = this.blockCtx.data(cCtx);\n if (args !== undefined) {\n vm.setProp(configCtx, \"args\", localScope.manage(vm.newString(args)));\n }\n vm.setProp(configCtx, \"data\", localScope.manage(vm.newString(data ?? \"{}\")));\n if (activeArgs !== undefined)\n vm.setProp(configCtx, \"activeArgs\", localScope.manage(vm.newString(activeArgs)));\n // For v1/v2 blocks, also inject uiState (extracted from state.uiState)\n if (isLegacyBlock) {\n vm.setProp(configCtx, \"uiState\", localScope.manage(vm.newString(extractUiState(data))));\n }\n }\n\n //\n // Methods for injected ctx object\n //\n\n exportCtxFunction(\"getAccessorHandleByName\", (name) => {\n return parent.exportSingleValue(\n this.getAccessorHandleByName(vm.getString(name)),\n undefined,\n );\n });\n\n //\n // Accessors\n //\n\n exportCtxFunction(\"resolveWithCommon\", (handle, commonOptions, ...steps) => {\n return parent.exportSingleValue(\n this.resolveWithCommon(\n vm.getString(handle),\n parent.importObjectViaJson(commonOptions) as CommonFieldTraverseOpsFromSDK,\n ...steps.map(\n (step) => parent.importObjectViaJson(step) as FieldTraversalStepFromSDK | string,\n ),\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"getResourceType\", (handle) => {\n return parent.exportObjectViaJson(this.getResourceType(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getInputsLocked\", (handle) => {\n return parent.exportSingleValue(this.getInputsLocked(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getOutputsLocked\", (handle) => {\n return parent.exportSingleValue(this.getOutputsLocked(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getIsReadyOrError\", (handle) => {\n return parent.exportSingleValue(this.getIsReadyOrError(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getIsFinal\", (handle) => {\n return parent.exportSingleValue(this.getIsFinal(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getError\", (handle) => {\n return parent.exportSingleValue(this.getError(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"listInputFields\", (handle) => {\n return parent.exportObjectViaJson(this.listInputFields(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"listOutputFields\", (handle) => {\n return parent.exportObjectViaJson(this.listOutputFields(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"listDynamicFields\", (handle) => {\n return parent.exportObjectViaJson(this.listDynamicFields(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getKeyValueBase64\", (handle, key) => {\n return parent.exportSingleValue(\n this.getKeyValueBase64(vm.getString(handle), vm.getString(key)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getKeyValueAsString\", (handle, key) => {\n return parent.exportSingleValue(\n this.getKeyValueAsString(vm.getString(handle), vm.getString(key)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getDataBase64\", (handle) => {\n return parent.exportSingleValue(this.getDataBase64(vm.getString(handle)), undefined);\n });\n\n exportCtxFunction(\"getDataAsString\", (handle) => {\n return parent.exportSingleValue(this.getDataAsString(vm.getString(handle)), undefined);\n });\n\n //\n // Accessor helpers\n //\n\n exportCtxFunction(\n \"parsePObjectCollection\",\n (handle, errorOnUnknownField, prefix, ...resolveSteps) => {\n return parent.exportObjectUniversal(\n this.parsePObjectCollection(\n vm.getString(handle),\n vm.dump(errorOnUnknownField) as boolean,\n vm.getString(prefix),\n ...resolveSteps.map((stepHandle) => vm.getString(stepHandle)),\n ),\n undefined,\n );\n },\n );\n\n //\n // Blobs\n //\n\n exportCtxFunction(\"getBlobContentAsBase64\", (handle, range) => {\n return parent.exportSingleValue(\n this.getBlobContentAsBase64(\n vm.getString(handle),\n parent.importObjectUniversal(range) as RangeBytes | undefined,\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"getBlobContentAsString\", (handle, range) => {\n return parent.exportSingleValue(\n this.getBlobContentAsString(\n vm.getString(handle),\n parent.importObjectUniversal(range) as RangeBytes | undefined,\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"getDownloadedBlobContentHandle\", (handle) => {\n return parent.exportSingleValue(\n this.getDownloadedBlobContentHandle(vm.getString(handle)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getOnDemandBlobContentHandle\", (handle) => {\n return parent.exportSingleValue(\n this.getOnDemandBlobContentHandle(vm.getString(handle)),\n undefined,\n );\n });\n\n //\n // Blobs to URLs\n //\n\n exportCtxFunction(\"extractArchiveAndGetURL\", (handle, format) => {\n return parent.exportSingleValue(\n this.extractArchiveAndGetURL(vm.getString(handle), vm.getString(format) as ArchiveFormat),\n undefined,\n );\n });\n\n //\n // ImportProgress\n //\n\n exportCtxFunction(\"getImportProgress\", (handle) => {\n return parent.exportSingleValue(this.getImportProgress(vm.getString(handle)), undefined);\n });\n\n //\n // Logs\n //\n\n exportCtxFunction(\"getLastLogs\", (handle, nLines) => {\n return parent.exportSingleValue(\n this.getLastLogs(vm.getString(handle), vm.getNumber(nLines)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getProgressLog\", (handle, patternToSearch) => {\n return parent.exportSingleValue(\n this.getProgressLog(vm.getString(handle), vm.getString(patternToSearch)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getProgressLogWithInfo\", (handle, patternToSearch) => {\n return parent.exportSingleValue(\n this.getProgressLogWithInfo(vm.getString(handle), vm.getString(patternToSearch)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getLogHandle\", (handle) => {\n return parent.exportSingleValue(this.getLogHandle(vm.getString(handle)), undefined);\n });\n\n //\n // Blocks\n //\n\n exportCtxFunction(\"getBlockLabel\", (blockId) => {\n return parent.exportSingleValue(this.getBlockLabel(vm.getString(blockId)), undefined);\n });\n\n //\n // Result pool\n //\n\n exportCtxFunction(\"getDataFromResultPool\", () => {\n return parent.exportObjectUniversal(this.getDataFromResultPool(), undefined);\n });\n\n exportCtxFunction(\"getDataWithErrorsFromResultPool\", () => {\n return parent.exportObjectUniversal(this.getDataWithErrorsFromResultPool(), undefined);\n });\n\n exportCtxFunction(\"getSpecsFromResultPool\", () => {\n return parent.exportObjectUniversal(this.getSpecsFromResultPool(), undefined);\n });\n\n exportCtxFunction(\"calculateOptions\", (predicate) => {\n return parent.exportObjectUniversal(\n this.calculateOptions(parent.importObjectViaJson(predicate) as PSpecPredicate),\n undefined,\n );\n });\n\n exportCtxFunction(\"getSpecFromResultPoolByRef\", (blockId, exportName) => {\n return parent.exportObjectUniversal(\n this.getSpecFromResultPoolByRef(vm.getString(blockId), vm.getString(exportName)),\n undefined,\n );\n });\n\n exportCtxFunction(\"getDataFromResultPoolByRef\", (blockId, exportName) => {\n return parent.exportObjectUniversal(\n this.getDataFromResultPoolByRef(vm.getString(blockId), vm.getString(exportName)),\n undefined,\n );\n });\n\n exportCtxFunction(\"createPFrame\", (def) => {\n return parent.exportSingleValue(\n this.createPFrame(\n parent.importObjectViaJson(def) as PFrameDef<PColumn<string | PColumnValues>>,\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"createPTable\", (def) => {\n return parent.exportSingleValue(\n this.createPTable(\n parent.importObjectViaJson(def) as PTableDef<PColumn<string | PColumnValues>>,\n ),\n undefined,\n );\n });\n\n exportCtxFunction(\"createPTableV2\", (def) => {\n return parent.exportSingleValue(\n this.createPTableV2(\n parent.importObjectViaJson(def) as PTableDefV2<PColumn<string | PColumnValues>>,\n ),\n undefined,\n );\n });\n\n //\n // Services\n //\n\n const requiredServiceNames = new Set(resolveRequiredServices(this.featureFlags) as string[]);\n const serviceFunctions = new Map<string, VmFunctionImplementation<QuickJSHandle>>();\n const injectors = getServiceInjectors();\n\n for (const [key, serviceId] of Object.entries(Services)) {\n if (!requiredServiceNames.has(serviceId)) continue;\n const injector = injectors[key as keyof typeof injectors];\n try {\n const methods = injector({ host: this, vm: parent });\n for (const [method, fn] of Object.entries(methods)) {\n serviceFunctions.set(serviceFnKey(serviceId, method), fn);\n }\n } catch (e) {\n throw new ServiceInjectionError(`Failed to inject service \"${serviceId}\"`, { cause: e });\n }\n }\n\n exportCtxFunction(\"getServiceNames\", () => {\n return parent.exportObjectViaJson([...requiredServiceNames]);\n });\n\n exportCtxFunction(\"getServiceMethods\", (serviceIdHandle) => {\n const serviceId = vm.getString(serviceIdHandle);\n const pfx = serviceFnKey(serviceId);\n const methods = [...serviceFunctions.keys()]\n .filter((k) => k.startsWith(pfx))\n .map((k) => k.slice(pfx.length));\n return parent.exportObjectViaJson(methods, undefined);\n });\n\n exportCtxFunction(\n \"callServiceMethod\",\n function (this: QuickJSHandle, serviceIdHandle, methodHandle, ...argHandles) {\n const serviceId = vm.getString(serviceIdHandle);\n const method = vm.getString(methodHandle);\n const fn = serviceFunctions.get(serviceFnKey(serviceId, method));\n if (!fn)\n throw new ServiceMethodNotFoundError(\n `Method \"${method}\" not found on service \"${serviceId}\"`,\n );\n return fn.call(this, ...argHandles);\n },\n );\n\n //\n // Computable\n //\n\n exportCtxFunction(\"getCurrentUnstableMarker\", () => {\n return parent.exportSingleValue(this.getCurrentUnstableMarker(), undefined);\n });\n\n //\n // Logging\n //\n\n exportCtxFunction(\"logInfo\", (message) => {\n this.logInfo(vm.getString(message));\n });\n\n exportCtxFunction(\"logWarn\", (message) => {\n this.logWarn(vm.getString(message));\n });\n\n exportCtxFunction(\"logError\", (message) => {\n this.logError(vm.getString(message));\n });\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAyDA,SAAS,cAAc,MAAkD;AACvE,QAAO,SAAS,SAAY,OAAO,KAAK,KAAK,CAAC,SAAS,SAAS,GAAG;;AAGrE,IAAa,0BAAb,MAGE;CACA,AAAgB,uBAA4D,EAAE;CAE9E,AAAQ;CACR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gBAAgB;IAC/C,MAAM,SAAS,GAAG,UAAU,aAAa;IACzC,MAAM,KAAK,iBAAiB,IAAI,aAAa,WAAW,OAAO,CAAC;AAChE,QAAI,CAAC,GACH,OAAM,IAAI,2BACR,WAAW,OAAO,0BAA0B,UAAU,GACvD;AACH,WAAO,GAAG,KAAK,MAAM,GAAG,WAAW;KAEtC;AAMD,qBAAkB,kCAAkC;AAClD,WAAO,OAAO,kBAAkB,KAAK,0BAA0B,EAAE,OAAU;KAC3E;AAMF,qBAAkB,YAAY,YAAY;AACxC,SAAK,QAAQ,GAAG,UAAU,QAAQ,CAAC;KACnC;AAEF,qBAAkB,YAAY,YAAY;AACxC,SAAK,QAAQ,GAAG,UAAU,QAAQ,CAAC;KACnC;AAEF,qBAAkB,aAAa,YAAY;AACzC,SAAK,SAAS,GAAG,UAAU,QAAQ,CAAC;KACpC;IACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.cjs","names":["ComputableContextHelper","Scope","JsRenderInternal","errors","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\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 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 | undefined,\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 | undefined): 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 | undefined): 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 | undefined): 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 errorId = causeName.slice(causeName.indexOf(\"/uuid:\") + \"/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":";;;;;;;;;;AAwBA,SAAS,oBAAoB,KAAsC;AACjE,QAAO,eAAe,eAAe,YAAY,OAAO,IAAI;;AAoC9D,IAAa,qBAAb,MAAa,mBAAmB;CAC9B,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,AAAgB,YAAY,IAAI,iBAAiB;CAEjD,AAAgB;CAEhB,AAAgB,QAAqB;EACnC,cAAc;EACd,aAAa;EACb,YAAY;EACZ,eAAe;EACf,SAA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,MAAI,CAAC,QACH,OAAM,IAAI,MACR,gEAAgE,UAAU,2DAA4B,aAAa,GACpH;EAGH,MAAM,QAAQ,KAAK,eAAe,IAAI,QAAQ;AAC9C,MAAI,UAAU,OACZ,OAAM,IAAI,MACR,iCAAiC,QAAQ,2DAA4B,aAAa,GACnF;AAGH,SAAO,IAAIC,yCAAe,cAAc,MAAe"}
|
|
1
|
+
{"version":3,"file":"context.cjs","names":["ComputableContextHelper","Scope","JsRenderInternal","errors","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\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 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 errorId = causeName.slice(causeName.indexOf(\"/uuid:\") + \"/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":";;;;;;;;;;AAwBA,SAAS,oBAAoB,KAAsC;AACjE,QAAO,eAAe,eAAe,YAAY,OAAO,IAAI;;AAoC9D,IAAa,qBAAb,MAAa,mBAAmB;CAC9B,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,AAAgB,YAAY,IAAI,iBAAiB;CAEjD,AAAgB;CAEhB,AAAgB,QAAqB;EACnC,cAAc;EACd,aAAa;EACb,YAAY;EACZ,eAAe;EACf,SAAS;EACT,YAAY;EACZ,YAAY;EACZ,UAAU;EACV,aAAa;EACb,aAAa;EACb,gBAAgB;EAChB,aAAa;EACd;;;;;;;;;;CAWD,YACE,AAAgB,OAChB,AAAgB,IAChB,AAAiB,gBACjB,cACA,eACA;EALgB;EACA;EACC;AAIjB,OAAK,mBAAmB,KAAK,MAAM,OAAO,KAAK,GAAG,WAAW,CAAC;AAE9D,OAAK,kBAAkB,MAAM,OAC3B,GAAG,QAAQ,GAAG,QAAQ,OAAO,CAAC,SAAS,SAAS,GAAG,QAAQ,MAAM,Y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