@milaboratories/pl-middle-layer 1.66.19 → 1.67.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/block_registry/index.cjs +3 -0
- package/dist/block_registry/index.d.ts +2 -1
- package/dist/block_registry/index.js +2 -1
- package/dist/block_registry/location_provider.cjs +117 -0
- package/dist/block_registry/location_provider.cjs.map +1 -0
- package/dist/block_registry/location_provider.js +114 -0
- package/dist/block_registry/location_provider.js.map +1 -0
- package/dist/block_registry/registry.cjs +13 -0
- package/dist/block_registry/registry.cjs.map +1 -1
- package/dist/block_registry/registry.d.ts +14 -1
- package/dist/block_registry/registry.d.ts.map +1 -1
- package/dist/block_registry/registry.js +13 -0
- package/dist/block_registry/registry.js.map +1 -1
- package/dist/block_registry/template_provider.cjs +104 -0
- package/dist/block_registry/template_provider.cjs.map +1 -0
- package/dist/block_registry/template_provider.d.ts +62 -0
- package/dist/block_registry/template_provider.d.ts.map +1 -0
- package/dist/block_registry/template_provider.js +103 -0
- package/dist/block_registry/template_provider.js.map +1 -0
- package/dist/block_registry/watcher.cjs +3 -3
- package/dist/block_registry/watcher.js +2 -2
- package/dist/dev_env/util.js +2 -2
- package/dist/dev_env/util.js.map +1 -1
- package/dist/index.cjs +10 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +5 -1
- package/dist/js_render/computable_context.cjs +1 -1
- package/dist/js_render/computable_context.js +1 -1
- package/dist/middle_layer/driver_kit.d.ts +1 -1
- package/dist/middle_layer/middle_layer.cjs +144 -2
- package/dist/middle_layer/middle_layer.cjs.map +1 -1
- package/dist/middle_layer/middle_layer.d.ts +67 -1
- package/dist/middle_layer/middle_layer.d.ts.map +1 -1
- package/dist/middle_layer/middle_layer.js +146 -4
- package/dist/middle_layer/middle_layer.js.map +1 -1
- package/dist/middle_layer/project.cjs +1 -0
- package/dist/middle_layer/project.cjs.map +1 -1
- package/dist/middle_layer/project.d.ts +2 -2
- package/dist/middle_layer/project.js +4 -4
- package/dist/middle_layer/project.js.map +1 -1
- package/dist/middle_layer/sharing_list.d.ts +1 -1
- package/dist/model/args.cjs +9 -28
- package/dist/model/args.cjs.map +1 -1
- package/dist/model/args.js +9 -28
- package/dist/model/args.js.map +1 -1
- package/dist/model/index.cjs +7 -0
- package/dist/model/index.d.ts +4 -1
- package/dist/model/index.js +4 -1
- package/dist/model/project_helper.cjs +111 -0
- package/dist/model/project_helper.cjs.map +1 -1
- package/dist/model/project_helper.d.ts +76 -1
- package/dist/model/project_helper.d.ts.map +1 -1
- package/dist/model/project_helper.js +111 -0
- package/dist/model/project_helper.js.map +1 -1
- package/dist/model/project_model.d.ts +1 -1
- package/dist/model/sharing_model.d.ts +1 -1
- package/dist/model/template_apply.cjs +67 -0
- package/dist/model/template_apply.cjs.map +1 -0
- package/dist/model/template_apply.d.ts +50 -0
- package/dist/model/template_apply.d.ts.map +1 -0
- package/dist/model/template_apply.js +64 -0
- package/dist/model/template_apply.js.map +1 -0
- package/dist/model/template_export.cjs +82 -0
- package/dist/model/template_export.cjs.map +1 -0
- package/dist/model/template_export.d.ts +9 -0
- package/dist/model/template_export.d.ts.map +1 -0
- package/dist/model/template_export.js +82 -0
- package/dist/model/template_export.js.map +1 -0
- package/dist/model/template_parser.cjs +74 -0
- package/dist/model/template_parser.cjs.map +1 -0
- package/dist/model/template_parser.d.ts +43 -0
- package/dist/model/template_parser.d.ts.map +1 -0
- package/dist/model/template_parser.js +72 -0
- package/dist/model/template_parser.js.map +1 -0
- package/dist/model/template_resolve.cjs +134 -0
- package/dist/model/template_resolve.cjs.map +1 -0
- package/dist/model/template_resolve.d.ts +193 -0
- package/dist/model/template_resolve.d.ts.map +1 -0
- package/dist/model/template_resolve.js +133 -0
- package/dist/model/template_resolve.js.map +1 -0
- package/dist/model/template_serializer.cjs +162 -0
- package/dist/model/template_serializer.cjs.map +1 -0
- package/dist/model/template_serializer.d.ts +17 -0
- package/dist/model/template_serializer.d.ts.map +1 -0
- package/dist/model/template_serializer.js +157 -0
- package/dist/model/template_serializer.js.map +1 -0
- package/dist/mutator/block-pack/block_pack.cjs +1 -1
- package/dist/mutator/block-pack/block_pack.js +1 -1
- package/dist/mutator/migration.cjs +1 -1
- package/dist/mutator/migration.js +1 -1
- package/dist/mutator/project.cjs +35 -5
- package/dist/mutator/project.cjs.map +1 -1
- package/dist/mutator/project.d.ts.map +1 -1
- package/dist/mutator/project.js +35 -5
- package/dist/mutator/project.js.map +1 -1
- package/dist/mutator/template_construct.cjs +77 -0
- package/dist/mutator/template_construct.cjs.map +1 -0
- package/dist/mutator/template_construct.js +77 -0
- package/dist/mutator/template_construct.js.map +1 -0
- package/dist/network_check/template.js +3 -3
- package/dist/network_check/template.js.map +1 -1
- package/package.json +18 -18
- package/src/block_registry/index.ts +1 -0
- package/src/block_registry/location_provider.test.ts +236 -0
- package/src/block_registry/location_provider.ts +124 -0
- package/src/block_registry/registry.ts +22 -0
- package/src/block_registry/template_provider.test.ts +275 -0
- package/src/block_registry/template_provider.ts +168 -0
- package/src/middle_layer/middle_layer.ts +192 -1
- package/src/middle_layer/project.ts +1 -1
- package/src/model/args.test.ts +26 -1
- package/src/model/args.ts +16 -31
- package/src/model/index.ts +21 -0
- package/src/model/project_helper.ts +238 -0
- package/src/model/project_helper_params_init.test.ts +249 -0
- package/src/model/template_apply.test.ts +65 -0
- package/src/model/template_apply.ts +128 -0
- package/src/model/template_export.test.ts +255 -0
- package/src/model/template_export.ts +136 -0
- package/src/model/template_parser.test.ts +264 -0
- package/src/model/template_parser.ts +108 -0
- package/src/model/template_resolve.test.ts +397 -0
- package/src/model/template_resolve.ts +346 -0
- package/src/model/template_serializer.test.ts +398 -0
- package/src/model/template_serializer.ts +232 -0
- package/src/model/template_serializer_fixtures.test.ts +274 -0
- package/src/mutator/project-v3.test.ts +11 -11
- package/src/mutator/project.ts +92 -5
- package/src/mutator/template_construct.test.ts +456 -0
- package/src/mutator/template_construct.ts +150 -0
package/dist/model/args.cjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
let _milaboratories_ts_helpers = require("@milaboratories/ts-helpers");
|
|
2
|
+
let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
|
|
2
3
|
//#region src/model/args.ts
|
|
3
4
|
function outputRef(blockId, name, requireEnrichments) {
|
|
4
5
|
if (requireEnrichments) return {
|
|
@@ -35,43 +36,23 @@ function addAllReferencedBlocks(result, node, allowed) {
|
|
|
35
36
|
case "boolean":
|
|
36
37
|
case "symbol":
|
|
37
38
|
case "undefined": return;
|
|
38
|
-
case "string":
|
|
39
|
-
|
|
39
|
+
case "string": {
|
|
40
|
+
const peeled = (0, _milaboratories_pl_model_common.peelJsonLayers)(node);
|
|
41
|
+
if (peeled !== void 0) addAllReferencedBlocks(result, peeled.value, allowed);
|
|
40
42
|
return;
|
|
43
|
+
}
|
|
41
44
|
case "object":
|
|
42
45
|
if (node === null) return;
|
|
43
46
|
if (isBlockOutputReference(node)) recordRef(result, node.blockId, node.requireEnrichments === true, allowed);
|
|
44
47
|
else if (Array.isArray(node)) for (const child of node) addAllReferencedBlocks(result, child, allowed);
|
|
45
|
-
else for (const [, child] of Object.entries(node))
|
|
48
|
+
else for (const [key, child] of Object.entries(node)) {
|
|
49
|
+
addAllReferencedBlocks(result, key, allowed);
|
|
50
|
+
addAllReferencedBlocks(result, child, allowed);
|
|
51
|
+
}
|
|
46
52
|
return;
|
|
47
53
|
default: (0, _milaboratories_ts_helpers.assertNever)(type);
|
|
48
54
|
}
|
|
49
55
|
}
|
|
50
|
-
/**
|
|
51
|
-
* Detect a PlRef carried inside a string and hand the decoded value to `onParsed`.
|
|
52
|
-
*
|
|
53
|
-
* A PlRef-as-string is canonical `{...}` optionally wrapped by N `JSON.stringify`
|
|
54
|
-
* passes. Each pass adds a symmetric prefix/suffix made only of `"` and `\`
|
|
55
|
-
* chars (the escape padding) of equal length. The regex below is the strict
|
|
56
|
-
* shape gate — non-ref strings fail at the very first character, so we never
|
|
57
|
-
* scan their body. One pass is peeled per call; deeper nesting is unwrapped
|
|
58
|
-
* via recursion in the caller.
|
|
59
|
-
*/
|
|
60
|
-
const EMBEDDED_REF_RE = /^(?<pre>[\\"]*)\{[\s\S]*?__isRef[\s\S]*\}(?<suf>[\\"]*)$/;
|
|
61
|
-
function unwrapEmbeddedRef(s, onParsed) {
|
|
62
|
-
const c0 = s.charCodeAt(0);
|
|
63
|
-
if (c0 !== 123 && c0 !== 34) return;
|
|
64
|
-
const m = EMBEDDED_REF_RE.exec(s);
|
|
65
|
-
if (m === null) return;
|
|
66
|
-
if (m.groups.pre.length !== m.groups.suf.length) return;
|
|
67
|
-
let parsed;
|
|
68
|
-
try {
|
|
69
|
-
parsed = JSON.parse(s);
|
|
70
|
-
} catch {
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
if (parsed !== s) onParsed(parsed);
|
|
74
|
-
}
|
|
75
56
|
function recordRef(result, blockId, requireEnrichments, allowed) {
|
|
76
57
|
if (allowed === void 0 || allowed.has(blockId)) {
|
|
77
58
|
result.upstreams.add(blockId);
|
package/dist/model/args.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"args.cjs","names":[],"sources":["../../src/model/args.ts"],"sourcesContent":["import { assertNever } from \"@milaboratories/ts-helpers\";\nimport type { PlRef } from \"@platforma-sdk/model\";\n\nexport function outputRef(blockId: string, name: string, requireEnrichments?: boolean): PlRef {\n if (requireEnrichments) return { __isRef: true, blockId, name, requireEnrichments };\n else return { __isRef: true, blockId, name };\n}\n\nexport function isBlockOutputReference(obj: unknown): obj is PlRef {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"__isRef\" in obj &&\n obj.__isRef === true &&\n \"blockId\" in obj &&\n \"name\" in obj\n );\n}\n\nexport interface BlockUpstreams {\n /** All direct block dependencies */\n upstreams: Set<string>;\n /** Direct block dependencies which enrichments are also required by current block */\n upstreamsRequiringEnrichments: Set<string>;\n /** True if not-allowed references was encountered */\n missingReferences: boolean;\n}\n\n/** Extracts all resource ids referenced by args object. */\nexport function inferAllReferencedBlocks(args: unknown, allowed?: Set<string>): BlockUpstreams {\n const result = {\n upstreams: new Set<string>(),\n upstreamsRequiringEnrichments: new Set<string>(),\n missingReferences: false,\n };\n addAllReferencedBlocks(result, args, allowed);\n return result;\n}\n\nfunction addAllReferencedBlocks(result: BlockUpstreams, node: unknown, allowed?: Set<string>) {\n const type = typeof node;\n switch (type) {\n case \"function\":\n case \"bigint\":\n case \"number\":\n case \"boolean\":\n case \"symbol\":\n case \"undefined\":\n return;\n case \"string\": {\n
|
|
1
|
+
{"version":3,"file":"args.cjs","names":[],"sources":["../../src/model/args.ts"],"sourcesContent":["import { assertNever } from \"@milaboratories/ts-helpers\";\nimport type { PlRef } from \"@platforma-sdk/model\";\nimport { peelJsonLayers } from \"@milaboratories/pl-model-common\";\n\nexport function outputRef(blockId: string, name: string, requireEnrichments?: boolean): PlRef {\n if (requireEnrichments) return { __isRef: true, blockId, name, requireEnrichments };\n else return { __isRef: true, blockId, name };\n}\n\nexport function isBlockOutputReference(obj: unknown): obj is PlRef {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"__isRef\" in obj &&\n obj.__isRef === true &&\n \"blockId\" in obj &&\n \"name\" in obj\n );\n}\n\nexport interface BlockUpstreams {\n /** All direct block dependencies */\n upstreams: Set<string>;\n /** Direct block dependencies which enrichments are also required by current block */\n upstreamsRequiringEnrichments: Set<string>;\n /** True if not-allowed references was encountered */\n missingReferences: boolean;\n}\n\n/** Extracts all resource ids referenced by args object. */\nexport function inferAllReferencedBlocks(args: unknown, allowed?: Set<string>): BlockUpstreams {\n const result = {\n upstreams: new Set<string>(),\n upstreamsRequiringEnrichments: new Set<string>(),\n missingReferences: false,\n };\n addAllReferencedBlocks(result, args, allowed);\n return result;\n}\n\nfunction addAllReferencedBlocks(result: BlockUpstreams, node: unknown, allowed?: Set<string>) {\n const type = typeof node;\n switch (type) {\n case \"function\":\n case \"bigint\":\n case \"number\":\n case \"boolean\":\n case \"symbol\":\n case \"undefined\":\n return;\n case \"string\": {\n // A reference can be hiding inside a string under any number of `JSON.stringify`\n // passes, and this walk would otherwise never reach it. Peeling is shared with the\n // column-id remapper so that \"how a value hides inside a string\" has one\n // definition; what happens at the bottom is not shared, and here it is deliberately\n // broad — anything the peel produced is walked, including a foreign-schema document\n // that merely contains a reference. That breadth is what makes this detector usable\n // as a guard over carriers the template codec declines to touch.\n const peeled = peelJsonLayers(node as string);\n if (peeled !== undefined) addAllReferencedBlocks(result, peeled.value, allowed);\n return;\n }\n case \"object\": {\n if (node === null) return;\n if (isBlockOutputReference(node)) {\n recordRef(result, node.blockId, node.requireEnrichments === true, allowed);\n } else if (Array.isArray(node)) {\n for (const child of node) addAllReferencedBlocks(result, child, allowed);\n } else {\n // Keys as well as values: a discovered column's `queriesQualifications` is keyed BY\n // column id, so a map key can carry a block id — and dropping the key loses that\n // upstream edge entirely.\n for (const [key, child] of Object.entries(node as object)) {\n addAllReferencedBlocks(result, key, allowed);\n addAllReferencedBlocks(result, child, allowed);\n }\n }\n\n return;\n }\n default:\n assertNever(type);\n }\n}\n\nfunction recordRef(\n result: BlockUpstreams,\n blockId: string,\n requireEnrichments: boolean,\n allowed?: Set<string>,\n) {\n if (allowed === undefined || allowed.has(blockId)) {\n result.upstreams.add(blockId);\n if (requireEnrichments) result.upstreamsRequiringEnrichments.add(blockId);\n } else result.missingReferences = true;\n}\n"],"mappings":";;;AAIA,SAAgB,UAAU,SAAiB,MAAc,oBAAqC;CAC5F,IAAI,oBAAoB,OAAO;EAAE,SAAS;EAAM;EAAS;EAAM;CAAmB;MAC7E,OAAO;EAAE,SAAS;EAAM;EAAS;CAAK;AAC7C;AAEA,SAAgB,uBAAuB,KAA4B;CACjE,OACE,OAAO,QAAQ,YACf,QAAQ,QACR,aAAa,OACb,IAAI,YAAY,QAChB,aAAa,OACb,UAAU;AAEd;;AAYA,SAAgB,yBAAyB,MAAe,SAAuC;CAC7F,MAAM,SAAS;EACb,2BAAW,IAAI,IAAY;EAC3B,+CAA+B,IAAI,IAAY;EAC/C,mBAAmB;CACrB;CACA,uBAAuB,QAAQ,MAAM,OAAO;CAC5C,OAAO;AACT;AAEA,SAAS,uBAAuB,QAAwB,MAAe,SAAuB;CAC5F,MAAM,OAAO,OAAO;CACpB,QAAQ,MAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,aACH;EACF,KAAK,UAAU;GAQb,MAAM,UAAA,GAAA,gCAAA,eAAA,CAAwB,IAAc;GAC5C,IAAI,WAAW,KAAA,GAAW,uBAAuB,QAAQ,OAAO,OAAO,OAAO;GAC9E;EACF;EACA,KAAK;GACH,IAAI,SAAS,MAAM;GACnB,IAAI,uBAAuB,IAAI,GAC7B,UAAU,QAAQ,KAAK,SAAS,KAAK,uBAAuB,MAAM,OAAO;QACpE,IAAI,MAAM,QAAQ,IAAI,GAC3B,KAAK,MAAM,SAAS,MAAM,uBAAuB,QAAQ,OAAO,OAAO;QAKvE,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAc,GAAG;IACzD,uBAAuB,QAAQ,KAAK,OAAO;IAC3C,uBAAuB,QAAQ,OAAO,OAAO;GAC/C;GAGF;EAEF,SACE,CAAA,GAAA,2BAAA,YAAA,CAAY,IAAI;CACpB;AACF;AAEA,SAAS,UACP,QACA,SACA,oBACA,SACA;CACA,IAAI,YAAY,KAAA,KAAa,QAAQ,IAAI,OAAO,GAAG;EACjD,OAAO,UAAU,IAAI,OAAO;EAC5B,IAAI,oBAAoB,OAAO,8BAA8B,IAAI,OAAO;CAC1E,OAAO,OAAO,oBAAoB;AACpC"}
|
package/dist/model/args.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { assertNever } from "@milaboratories/ts-helpers";
|
|
2
|
+
import { peelJsonLayers } from "@milaboratories/pl-model-common";
|
|
2
3
|
//#region src/model/args.ts
|
|
3
4
|
function outputRef(blockId, name, requireEnrichments) {
|
|
4
5
|
if (requireEnrichments) return {
|
|
@@ -35,43 +36,23 @@ function addAllReferencedBlocks(result, node, allowed) {
|
|
|
35
36
|
case "boolean":
|
|
36
37
|
case "symbol":
|
|
37
38
|
case "undefined": return;
|
|
38
|
-
case "string":
|
|
39
|
-
|
|
39
|
+
case "string": {
|
|
40
|
+
const peeled = peelJsonLayers(node);
|
|
41
|
+
if (peeled !== void 0) addAllReferencedBlocks(result, peeled.value, allowed);
|
|
40
42
|
return;
|
|
43
|
+
}
|
|
41
44
|
case "object":
|
|
42
45
|
if (node === null) return;
|
|
43
46
|
if (isBlockOutputReference(node)) recordRef(result, node.blockId, node.requireEnrichments === true, allowed);
|
|
44
47
|
else if (Array.isArray(node)) for (const child of node) addAllReferencedBlocks(result, child, allowed);
|
|
45
|
-
else for (const [, child] of Object.entries(node))
|
|
48
|
+
else for (const [key, child] of Object.entries(node)) {
|
|
49
|
+
addAllReferencedBlocks(result, key, allowed);
|
|
50
|
+
addAllReferencedBlocks(result, child, allowed);
|
|
51
|
+
}
|
|
46
52
|
return;
|
|
47
53
|
default: assertNever(type);
|
|
48
54
|
}
|
|
49
55
|
}
|
|
50
|
-
/**
|
|
51
|
-
* Detect a PlRef carried inside a string and hand the decoded value to `onParsed`.
|
|
52
|
-
*
|
|
53
|
-
* A PlRef-as-string is canonical `{...}` optionally wrapped by N `JSON.stringify`
|
|
54
|
-
* passes. Each pass adds a symmetric prefix/suffix made only of `"` and `\`
|
|
55
|
-
* chars (the escape padding) of equal length. The regex below is the strict
|
|
56
|
-
* shape gate — non-ref strings fail at the very first character, so we never
|
|
57
|
-
* scan their body. One pass is peeled per call; deeper nesting is unwrapped
|
|
58
|
-
* via recursion in the caller.
|
|
59
|
-
*/
|
|
60
|
-
const EMBEDDED_REF_RE = /^(?<pre>[\\"]*)\{[\s\S]*?__isRef[\s\S]*\}(?<suf>[\\"]*)$/;
|
|
61
|
-
function unwrapEmbeddedRef(s, onParsed) {
|
|
62
|
-
const c0 = s.charCodeAt(0);
|
|
63
|
-
if (c0 !== 123 && c0 !== 34) return;
|
|
64
|
-
const m = EMBEDDED_REF_RE.exec(s);
|
|
65
|
-
if (m === null) return;
|
|
66
|
-
if (m.groups.pre.length !== m.groups.suf.length) return;
|
|
67
|
-
let parsed;
|
|
68
|
-
try {
|
|
69
|
-
parsed = JSON.parse(s);
|
|
70
|
-
} catch {
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
if (parsed !== s) onParsed(parsed);
|
|
74
|
-
}
|
|
75
56
|
function recordRef(result, blockId, requireEnrichments, allowed) {
|
|
76
57
|
if (allowed === void 0 || allowed.has(blockId)) {
|
|
77
58
|
result.upstreams.add(blockId);
|
package/dist/model/args.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"args.js","names":[],"sources":["../../src/model/args.ts"],"sourcesContent":["import { assertNever } from \"@milaboratories/ts-helpers\";\nimport type { PlRef } from \"@platforma-sdk/model\";\n\nexport function outputRef(blockId: string, name: string, requireEnrichments?: boolean): PlRef {\n if (requireEnrichments) return { __isRef: true, blockId, name, requireEnrichments };\n else return { __isRef: true, blockId, name };\n}\n\nexport function isBlockOutputReference(obj: unknown): obj is PlRef {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"__isRef\" in obj &&\n obj.__isRef === true &&\n \"blockId\" in obj &&\n \"name\" in obj\n );\n}\n\nexport interface BlockUpstreams {\n /** All direct block dependencies */\n upstreams: Set<string>;\n /** Direct block dependencies which enrichments are also required by current block */\n upstreamsRequiringEnrichments: Set<string>;\n /** True if not-allowed references was encountered */\n missingReferences: boolean;\n}\n\n/** Extracts all resource ids referenced by args object. */\nexport function inferAllReferencedBlocks(args: unknown, allowed?: Set<string>): BlockUpstreams {\n const result = {\n upstreams: new Set<string>(),\n upstreamsRequiringEnrichments: new Set<string>(),\n missingReferences: false,\n };\n addAllReferencedBlocks(result, args, allowed);\n return result;\n}\n\nfunction addAllReferencedBlocks(result: BlockUpstreams, node: unknown, allowed?: Set<string>) {\n const type = typeof node;\n switch (type) {\n case \"function\":\n case \"bigint\":\n case \"number\":\n case \"boolean\":\n case \"symbol\":\n case \"undefined\":\n return;\n case \"string\": {\n
|
|
1
|
+
{"version":3,"file":"args.js","names":[],"sources":["../../src/model/args.ts"],"sourcesContent":["import { assertNever } from \"@milaboratories/ts-helpers\";\nimport type { PlRef } from \"@platforma-sdk/model\";\nimport { peelJsonLayers } from \"@milaboratories/pl-model-common\";\n\nexport function outputRef(blockId: string, name: string, requireEnrichments?: boolean): PlRef {\n if (requireEnrichments) return { __isRef: true, blockId, name, requireEnrichments };\n else return { __isRef: true, blockId, name };\n}\n\nexport function isBlockOutputReference(obj: unknown): obj is PlRef {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"__isRef\" in obj &&\n obj.__isRef === true &&\n \"blockId\" in obj &&\n \"name\" in obj\n );\n}\n\nexport interface BlockUpstreams {\n /** All direct block dependencies */\n upstreams: Set<string>;\n /** Direct block dependencies which enrichments are also required by current block */\n upstreamsRequiringEnrichments: Set<string>;\n /** True if not-allowed references was encountered */\n missingReferences: boolean;\n}\n\n/** Extracts all resource ids referenced by args object. */\nexport function inferAllReferencedBlocks(args: unknown, allowed?: Set<string>): BlockUpstreams {\n const result = {\n upstreams: new Set<string>(),\n upstreamsRequiringEnrichments: new Set<string>(),\n missingReferences: false,\n };\n addAllReferencedBlocks(result, args, allowed);\n return result;\n}\n\nfunction addAllReferencedBlocks(result: BlockUpstreams, node: unknown, allowed?: Set<string>) {\n const type = typeof node;\n switch (type) {\n case \"function\":\n case \"bigint\":\n case \"number\":\n case \"boolean\":\n case \"symbol\":\n case \"undefined\":\n return;\n case \"string\": {\n // A reference can be hiding inside a string under any number of `JSON.stringify`\n // passes, and this walk would otherwise never reach it. Peeling is shared with the\n // column-id remapper so that \"how a value hides inside a string\" has one\n // definition; what happens at the bottom is not shared, and here it is deliberately\n // broad — anything the peel produced is walked, including a foreign-schema document\n // that merely contains a reference. That breadth is what makes this detector usable\n // as a guard over carriers the template codec declines to touch.\n const peeled = peelJsonLayers(node as string);\n if (peeled !== undefined) addAllReferencedBlocks(result, peeled.value, allowed);\n return;\n }\n case \"object\": {\n if (node === null) return;\n if (isBlockOutputReference(node)) {\n recordRef(result, node.blockId, node.requireEnrichments === true, allowed);\n } else if (Array.isArray(node)) {\n for (const child of node) addAllReferencedBlocks(result, child, allowed);\n } else {\n // Keys as well as values: a discovered column's `queriesQualifications` is keyed BY\n // column id, so a map key can carry a block id — and dropping the key loses that\n // upstream edge entirely.\n for (const [key, child] of Object.entries(node as object)) {\n addAllReferencedBlocks(result, key, allowed);\n addAllReferencedBlocks(result, child, allowed);\n }\n }\n\n return;\n }\n default:\n assertNever(type);\n }\n}\n\nfunction recordRef(\n result: BlockUpstreams,\n blockId: string,\n requireEnrichments: boolean,\n allowed?: Set<string>,\n) {\n if (allowed === undefined || allowed.has(blockId)) {\n result.upstreams.add(blockId);\n if (requireEnrichments) result.upstreamsRequiringEnrichments.add(blockId);\n } else result.missingReferences = true;\n}\n"],"mappings":";;;AAIA,SAAgB,UAAU,SAAiB,MAAc,oBAAqC;CAC5F,IAAI,oBAAoB,OAAO;EAAE,SAAS;EAAM;EAAS;EAAM;CAAmB;MAC7E,OAAO;EAAE,SAAS;EAAM;EAAS;CAAK;AAC7C;AAEA,SAAgB,uBAAuB,KAA4B;CACjE,OACE,OAAO,QAAQ,YACf,QAAQ,QACR,aAAa,OACb,IAAI,YAAY,QAChB,aAAa,OACb,UAAU;AAEd;;AAYA,SAAgB,yBAAyB,MAAe,SAAuC;CAC7F,MAAM,SAAS;EACb,2BAAW,IAAI,IAAY;EAC3B,+CAA+B,IAAI,IAAY;EAC/C,mBAAmB;CACrB;CACA,uBAAuB,QAAQ,MAAM,OAAO;CAC5C,OAAO;AACT;AAEA,SAAS,uBAAuB,QAAwB,MAAe,SAAuB;CAC5F,MAAM,OAAO,OAAO;CACpB,QAAQ,MAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,aACH;EACF,KAAK,UAAU;GAQb,MAAM,SAAS,eAAe,IAAc;GAC5C,IAAI,WAAW,KAAA,GAAW,uBAAuB,QAAQ,OAAO,OAAO,OAAO;GAC9E;EACF;EACA,KAAK;GACH,IAAI,SAAS,MAAM;GACnB,IAAI,uBAAuB,IAAI,GAC7B,UAAU,QAAQ,KAAK,SAAS,KAAK,uBAAuB,MAAM,OAAO;QACpE,IAAI,MAAM,QAAQ,IAAI,GAC3B,KAAK,MAAM,SAAS,MAAM,uBAAuB,QAAQ,OAAO,OAAO;QAKvE,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAc,GAAG;IACzD,uBAAuB,QAAQ,KAAK,OAAO;IAC3C,uBAAuB,QAAQ,OAAO,OAAO;GAC/C;GAGF;EAEF,SACE,YAAY,IAAI;CACpB;AACF;AAEA,SAAS,UACP,QACA,SACA,oBACA,SACA;CACA,IAAI,YAAY,KAAA,KAAa,QAAQ,IAAI,OAAO,GAAG;EACjD,OAAO,UAAU,IAAI,OAAO;EAC5B,IAAI,oBAAoB,OAAO,8BAA8B,IAAI,OAAO;CAC1E,OAAO,OAAO,oBAAoB;AACpC"}
|
package/dist/model/index.cjs
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
const require_project_model = require("./project_model.cjs");
|
|
2
2
|
const require_block_pack_spec = require("./block_pack_spec.cjs");
|
|
3
3
|
const require_sharing_model = require("./sharing_model.cjs");
|
|
4
|
+
const require_template_parser = require("./template_parser.cjs");
|
|
5
|
+
const require_template_resolve = require("./template_resolve.cjs");
|
|
6
|
+
const require_template_apply = require("./template_apply.cjs");
|
|
4
7
|
exports.AcceptanceFieldPrefix = require_sharing_model.AcceptanceFieldPrefix;
|
|
5
8
|
exports.BlockArgsAuthorKeyPrefix = require_project_model.BlockArgsAuthorKeyPrefix;
|
|
6
9
|
exports.FrontendFromFolderResourceType = require_block_pack_spec.FrontendFromFolderResourceType;
|
|
@@ -19,6 +22,7 @@ exports.SharingOutboxField = require_sharing_model.SharingOutboxField;
|
|
|
19
22
|
exports.SharingOutboxResourceType = require_sharing_model.SharingOutboxResourceType;
|
|
20
23
|
exports.SharingStateField = require_sharing_model.SharingStateField;
|
|
21
24
|
exports.SharingStateResourceType = require_sharing_model.SharingStateResourceType;
|
|
25
|
+
exports.TemplateEntryRejected = require_template_apply.TemplateEntryRejected;
|
|
22
26
|
exports.acceptanceField = require_sharing_model.acceptanceField;
|
|
23
27
|
exports.acceptanceFieldLogin = require_sharing_model.acceptanceFieldLogin;
|
|
24
28
|
exports.asShareId = require_sharing_model.asShareId;
|
|
@@ -28,3 +32,6 @@ exports.decisionField = require_sharing_model.decisionField;
|
|
|
28
32
|
exports.decodeEnvelopeData = require_sharing_model.decodeEnvelopeData;
|
|
29
33
|
exports.isAcceptanceField = require_sharing_model.isAcceptanceField;
|
|
30
34
|
exports.newShareId = require_sharing_model.newShareId;
|
|
35
|
+
exports.parseBlockPackName = require_template_resolve.parseBlockPackName;
|
|
36
|
+
exports.parseProjectTemplateV1Yaml = require_template_parser.parseProjectTemplateV1Yaml;
|
|
37
|
+
exports.resolveTemplateEntries = require_template_resolve.resolveTemplateEntries;
|
package/dist/model/index.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { AppliedEntry, TemplateApplyProblem, TemplateApplyReport, TemplateEntryRejected } from "./template_apply.js";
|
|
2
|
+
import { BlockPackProvider, ExactResolution, KindResolution, ResolvedEntry, TemplateResolveOutcome, parseBlockPackName, resolveTemplateEntries } from "./template_resolve.js";
|
|
1
3
|
import { BlockArgsAuthorKeyPrefix, ProjectCreatedTimestamp, ProjectField, ProjectId, ProjectLastModifiedTimestamp, ProjectListEntry, ProjectMetaKey, ProjectResourceType, ProjectStructureAuthorKey, ProjectStructureKey, SchemaVersionCurrent, SchemaVersionKey } from "./project_model.js";
|
|
2
4
|
import { AcceptanceFieldPrefix, EnvelopeAcceptance, EnvelopeData, EnvelopeMode, EnvelopeProject, ProjectChangeAction, ProjectFieldUuid, ShareId, ShareProjectsOptions, SharedEnvelopeResourceType, SharingDecision, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, acceptanceField, acceptanceFieldLogin, asShareId, canGrantToEveryone, canImpersonate, decisionField, decodeEnvelopeData, isAcceptanceField, newShareId } from "./sharing_model.js";
|
|
3
5
|
import { BlockPackExplicit, BlockPackSpecAny, BlockPackSpecPrepared, FrontendFromFolder, FrontendFromFolderData, FrontendFromFolderResourceType, FrontendFromLocalTgz, FrontendFromLocalTgzData, FrontendFromLocalTgzResourceType, FrontendFromUrl, FrontendFromUrlData, FrontendFromUrlResourceType, FrontendSpec } from "./block_pack_spec.js";
|
|
4
|
-
|
|
6
|
+
import { TemplateParseOutcome, parseProjectTemplateV1Yaml } from "./template_parser.js";
|
|
7
|
+
export { AcceptanceFieldPrefix, type AppliedEntry, BlockArgsAuthorKeyPrefix, BlockPackExplicit, type BlockPackProvider, BlockPackSpecAny, BlockPackSpecPrepared, EnvelopeAcceptance, EnvelopeData, EnvelopeMode, EnvelopeProject, type ExactResolution, FrontendFromFolder, FrontendFromFolderData, FrontendFromFolderResourceType, FrontendFromLocalTgz, FrontendFromLocalTgzData, FrontendFromLocalTgzResourceType, FrontendFromUrl, FrontendFromUrlData, FrontendFromUrlResourceType, FrontendSpec, type KindResolution, ProjectChangeAction, ProjectCreatedTimestamp, type ProjectField, ProjectFieldUuid, ProjectLastModifiedTimestamp, type ProjectListEntry, ProjectMetaKey, ProjectResourceType, ProjectStructureAuthorKey, ProjectStructureKey, type ResolvedEntry, SchemaVersionCurrent, SchemaVersionKey, ShareId, ShareProjectsOptions, SharedEnvelopeResourceType, SharingDecision, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, type TemplateApplyProblem, type TemplateApplyReport, TemplateEntryRejected, type TemplateParseOutcome, type TemplateResolveOutcome, acceptanceField, acceptanceFieldLogin, asShareId, canGrantToEveryone, canImpersonate, decisionField, decodeEnvelopeData, isAcceptanceField, newShareId, parseBlockPackName, parseProjectTemplateV1Yaml, resolveTemplateEntries };
|
package/dist/model/index.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { BlockArgsAuthorKeyPrefix, ProjectCreatedTimestamp, ProjectLastModifiedTimestamp, ProjectMetaKey, ProjectResourceType, ProjectStructureAuthorKey, ProjectStructureKey, SchemaVersionCurrent, SchemaVersionKey } from "./project_model.js";
|
|
2
2
|
import { FrontendFromFolderResourceType, FrontendFromLocalTgzResourceType, FrontendFromUrlResourceType } from "./block_pack_spec.js";
|
|
3
3
|
import { AcceptanceFieldPrefix, SharedEnvelopeResourceType, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, acceptanceField, acceptanceFieldLogin, asShareId, canGrantToEveryone, canImpersonate, decisionField, decodeEnvelopeData, isAcceptanceField, newShareId } from "./sharing_model.js";
|
|
4
|
-
|
|
4
|
+
import { parseProjectTemplateV1Yaml } from "./template_parser.js";
|
|
5
|
+
import { parseBlockPackName, resolveTemplateEntries } from "./template_resolve.js";
|
|
6
|
+
import { TemplateEntryRejected } from "./template_apply.js";
|
|
7
|
+
export { AcceptanceFieldPrefix, BlockArgsAuthorKeyPrefix, FrontendFromFolderResourceType, FrontendFromLocalTgzResourceType, FrontendFromUrlResourceType, ProjectCreatedTimestamp, ProjectLastModifiedTimestamp, ProjectMetaKey, ProjectResourceType, ProjectStructureAuthorKey, ProjectStructureKey, SchemaVersionCurrent, SchemaVersionKey, SharedEnvelopeResourceType, SharingOutboxField, SharingOutboxResourceType, SharingStateField, SharingStateResourceType, TemplateEntryRejected, acceptanceField, acceptanceFieldLogin, asShareId, canGrantToEveryone, canImpersonate, decisionField, decodeEnvelopeData, isAcceptanceField, newShareId, parseBlockPackName, parseProjectTemplateV1Yaml, resolveTemplateEntries };
|
|
@@ -56,6 +56,44 @@ var ProjectHelper = class {
|
|
|
56
56
|
return;
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Derives this block's template-export params from storage JSON using the VM
|
|
61
|
+
* callback (`__pl_initializationParams_derive`).
|
|
62
|
+
*
|
|
63
|
+
* The template-export counterpart of {@link deriveArgsFromStorage}: instead of
|
|
64
|
+
* the args a workflow runs on, it returns the params that would recreate the
|
|
65
|
+
* block — the inverse of the data model's `init`. Params come back exactly as the block
|
|
66
|
+
* projected them, references included: nothing marks or rewrites them on the way out, so
|
|
67
|
+
* nothing here has to know a kind's params shape or how a reference is spelled.
|
|
68
|
+
*
|
|
69
|
+
* A `{ value: undefined }` result means the block declares no `templateParams`, which only
|
|
70
|
+
* a block built against an older SDK can do. It does not reach a document: the export walk
|
|
71
|
+
* requires a mapping and reports anything else as that block's problem, so an entry always
|
|
72
|
+
* carries params.
|
|
73
|
+
*
|
|
74
|
+
* Unlike {@link derivePrerunArgsFromStorage}, a failure here is surfaced rather
|
|
75
|
+
* than swallowed — a prerun that cannot derive args just skips a block in
|
|
76
|
+
* staging, whereas an export that silently drops a block produces a template
|
|
77
|
+
* that does not describe the project.
|
|
78
|
+
*
|
|
79
|
+
* @param blockConfig The block configuration (provides the model code)
|
|
80
|
+
* @param storageJson Storage as JSON string
|
|
81
|
+
* @returns The derived params with identifiers wrapped, `undefined` if the block declares
|
|
82
|
+
* no lambda, or an error if derivation failed
|
|
83
|
+
*/
|
|
84
|
+
deriveTemplateParamsFromStorage(blockConfig, storageJson) {
|
|
85
|
+
if (blockConfig.modelAPIVersion !== _platforma_sdk_model.BLOCK_STORAGE_FACADE_VERSION) return { error: /* @__PURE__ */ new Error("deriveTemplateParamsFromStorage is only supported for model API version 2") };
|
|
86
|
+
const callback = blockConfig.blockLifecycleCallbacks[_platforma_sdk_model.BlockStorageFacadeCallbacks.InitializationParamsDerive];
|
|
87
|
+
if (callback === void 0) return { error: /* @__PURE__ */ new Error("This version of the block cannot be written to a template. Update the block to a newer version and export again.") };
|
|
88
|
+
try {
|
|
89
|
+
const result = require_index$1.executeSingleLambda(this.quickJs, callback, (0, _platforma_sdk_model.extractCodeWithInfo)(blockConfig), storageJson);
|
|
90
|
+
if (result.error !== void 0) return { error: new Error(result.error) };
|
|
91
|
+
return { value: result.value };
|
|
92
|
+
} catch (e) {
|
|
93
|
+
const cause = (0, _platforma_sdk_model.ensureError)(e);
|
|
94
|
+
return { error: new Error(`Template params derivation from storage failed: ${cause.message}`, { cause }) };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
59
97
|
calculateEnrichmentTargets(req) {
|
|
60
98
|
const blockConfig = req.blockConfig();
|
|
61
99
|
if (blockConfig.enrichmentTargets === void 0) return void 0;
|
|
@@ -91,6 +129,79 @@ var ProjectHelper = class {
|
|
|
91
129
|
}
|
|
92
130
|
}
|
|
93
131
|
/**
|
|
132
|
+
* Checks a template entry's params against the block's kind, creating nothing.
|
|
133
|
+
*
|
|
134
|
+
* The pre-flight half of {@link getInitialStorageFromParamsInVM}: run once per entry
|
|
135
|
+
* before a template is applied, so params a kind rejects are reported against the
|
|
136
|
+
* entry that carries them while there is still no project. Skipping it is safe —
|
|
137
|
+
* initialization runs the same check — but then the report arrives after earlier
|
|
138
|
+
* entries have already been created.
|
|
139
|
+
*
|
|
140
|
+
* Every kind declares a parser, so a pass here means the params were checked against
|
|
141
|
+
* the contract — not merely that they were JSON.
|
|
142
|
+
*
|
|
143
|
+
* A block whose model predates the callback passes unchecked rather than failing.
|
|
144
|
+
* Unlike initialization, this method creates nothing, so there is nothing to get wrong
|
|
145
|
+
* by proceeding, and such a block is refused outright at the point it is applied.
|
|
146
|
+
*
|
|
147
|
+
* @param blockConfig The block configuration (provides the model code)
|
|
148
|
+
* @param params The entry's params. Reference ids may be placeholders: what is being
|
|
149
|
+
* checked is the shape of the params, not what they point at
|
|
150
|
+
* @returns Nothing, or why the params were rejected
|
|
151
|
+
*/
|
|
152
|
+
validateTemplateParamsInVM(blockConfig, params) {
|
|
153
|
+
if (blockConfig.modelAPIVersion !== _platforma_sdk_model.BLOCK_STORAGE_FACADE_VERSION) return { error: /* @__PURE__ */ new Error("validateTemplateParamsInVM is only supported for model API version 2") };
|
|
154
|
+
const callback = blockConfig.blockLifecycleCallbacks[_platforma_sdk_model.BlockStorageFacadeCallbacks.InitializationParamsValidate];
|
|
155
|
+
if (callback === void 0) return { value: void 0 };
|
|
156
|
+
try {
|
|
157
|
+
const result = require_index$1.executeSingleLambda(this.quickJs, callback, (0, _platforma_sdk_model.extractCodeWithInfo)(blockConfig), JSON.stringify(params ?? {}));
|
|
158
|
+
if (result.error !== void 0) return { error: new Error(result.error) };
|
|
159
|
+
return { value: void 0 };
|
|
160
|
+
} catch (e) {
|
|
161
|
+
const cause = (0, _platforma_sdk_model.ensureError)(e);
|
|
162
|
+
return { error: new Error(`Params check failed to run: ${cause.message}`, { cause }) };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Creates initial BlockStorage for a block being created from template params.
|
|
167
|
+
*
|
|
168
|
+
* The inverse of {@link deriveTemplateParamsFromStorage}, and the reason a block
|
|
169
|
+
* can be created by anything other than the UI: it hands the params to the
|
|
170
|
+
* block's own init factory inside the model VM, so the resulting storage is
|
|
171
|
+
* whatever that block considers a correctly-initialized state.
|
|
172
|
+
*
|
|
173
|
+
* **Pointing the entry's references at this project happens in the same call**, before the
|
|
174
|
+
* factory sees them — inside the block's bundle, because recognizing a reference means
|
|
175
|
+
* knowing the reference system and a template engine deliberately does not. Params reach
|
|
176
|
+
* here exactly as the file held them.
|
|
177
|
+
*
|
|
178
|
+
* One call and not two: every VM call builds a fresh runtime and re-evaluates the whole
|
|
179
|
+
* model bundle, so asking the block to relocate and then asking it to initialize would parse
|
|
180
|
+
* it twice per entry, for an intermediate value nothing else reads.
|
|
181
|
+
*
|
|
182
|
+
* `blockIds` holds the entries created so far, so an id it does not name is left as it is —
|
|
183
|
+
* a reference to an entry further down the file keeps pointing at nothing, and the applied
|
|
184
|
+
* block reports itself as missing references rather than being wired to a block below it.
|
|
185
|
+
*
|
|
186
|
+
* @param blockConfig The block configuration (provides the model code)
|
|
187
|
+
* @param params The entry's params, as the document held them
|
|
188
|
+
* @param blockIds template-local entry id → the block id that entry was given
|
|
189
|
+
* @returns The initial storage as JSON string, or why the params yield none
|
|
190
|
+
*/
|
|
191
|
+
getInitialStorageFromParamsInVM(blockConfig, params, blockIds) {
|
|
192
|
+
if (blockConfig.modelAPIVersion !== _platforma_sdk_model.BLOCK_STORAGE_FACADE_VERSION) return { error: /* @__PURE__ */ new Error("getInitialStorageFromParamsInVM is only supported for model API version 2") };
|
|
193
|
+
const callback = blockConfig.blockLifecycleCallbacks[_platforma_sdk_model.BlockStorageFacadeCallbacks.StorageInitialFromParams];
|
|
194
|
+
if (callback === void 0) return { error: /* @__PURE__ */ new Error("This version of the block cannot be created from a template. Use a newer version of the block, or remove the pinned block version from the template entry so a supported one is chosen automatically.") };
|
|
195
|
+
try {
|
|
196
|
+
const result = require_index$1.executeSingleLambda(this.quickJs, callback, (0, _platforma_sdk_model.extractCodeWithInfo)(blockConfig), JSON.stringify(params ?? {}), JSON.stringify(Object.fromEntries(blockIds)));
|
|
197
|
+
if (result.error !== void 0) return { error: new Error(result.error) };
|
|
198
|
+
return { value: result.storageJson };
|
|
199
|
+
} catch (e) {
|
|
200
|
+
const cause = (0, _platforma_sdk_model.ensureError)(e);
|
|
201
|
+
return { error: new Error(`Initial storage creation from params failed: ${cause.message}`, { cause }) };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
94
205
|
* Applies a state update using VM-based transformation.
|
|
95
206
|
* This calls the model's `__pl_storage_applyUpdate` callback which:
|
|
96
207
|
* - Normalizes current storage
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project_helper.cjs","names":["LRUCache","ConsoleLoggerAdapter","BLOCK_STORAGE_FACADE_VERSION","executeSingleLambda","BlockStorageFacadeCallbacks","getDebugFlags"],"sources":["../../src/model/project_helper.ts"],"sourcesContent":["import type { ResultOrError, BlockConfig, BlockStorage, PlRef } from \"@platforma-sdk/model\";\nimport type { StringifiedJson } from \"@milaboratories/pl-model-common\";\nimport {\n extractCodeWithInfo,\n ensureError,\n BlockStorageFacadeCallbacks,\n BLOCK_STORAGE_FACADE_VERSION,\n} from \"@platforma-sdk/model\";\nimport { LRUCache } from \"lru-cache\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { executeSingleLambda } from \"../js_render\";\nimport type { SignedResourceId } from \"@milaboratories/pl-client\";\nimport { ConsoleLoggerAdapter, type MiLogger } from \"@milaboratories/ts-helpers\";\nimport type { StorageDebugView } from \"@milaboratories/pl-model-middle-layer\";\nimport { getDebugFlags } from \"../debug\";\n\ntype EnrichmentTargetsRequest = {\n blockConfig: () => BlockConfig;\n args: () => unknown;\n};\n\ntype EnrichmentTargetsValue = {\n value: PlRef[] | undefined;\n};\n\n/**\n * Result of VM-based storage migration.\n * Returned by migrateStorageInVM().\n *\n * - Error result: { error: string } - serious failure (no context, etc.)\n * - Success result: { newStorageJson: StringifiedJson<BlockStorage>, info: string } - migration succeeded\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: StringifiedJson<BlockStorage>; info: string };\n\n/**\n * Result of args derivation from storage.\n * Returned by __pl_args_derive and __pl_prerunArgs_derive VM callbacks.\n */\ntype ArgsDeriveResult = { error: string } | { error?: undefined; value: unknown };\n\nexport class ProjectHelper {\n private readonly enrichmentTargetsCache = new LRUCache<\n string,\n EnrichmentTargetsValue,\n EnrichmentTargetsRequest\n >({\n max: 256,\n memoMethod: (_key, _value, { context }) => {\n return { value: this.calculateEnrichmentTargets(context) };\n },\n });\n\n constructor(\n private readonly quickJs: QuickJSWASMModule,\n public readonly logger: MiLogger = new ConsoleLoggerAdapter(),\n ) {}\n\n // =============================================================================\n // Args Derivation from Storage (V3+)\n // =============================================================================\n\n /**\n * Derives args directly from storage JSON using VM callback.\n * The VM extracts data from storage and calls the block's args() function.\n *\n * This allows the middle layer to work only with storage JSON,\n * without needing to know the underlying data structure.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived args object, or error if derivation fails\n */\n public deriveArgsFromStorage(\n blockConfig: BlockConfig,\n storageJson: string,\n ): ResultOrError<unknown> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\"deriveArgsFromStorage is only supported for model API version 2\"),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.ArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as ArgsDeriveResult;\n\n if (result.error !== undefined) {\n return { error: new Error(result.error) };\n }\n return { value: result.value };\n } catch (e) {\n return { error: new Error(\"Args derivation from storage failed\", { cause: ensureError(e) }) };\n }\n }\n\n /**\n * Derives prerunArgs directly from storage JSON using VM callback.\n * Falls back to args() if prerunArgs is not defined in the block model.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived prerunArgs, or undefined if derivation fails\n */\n public derivePrerunArgsFromStorage(blockConfig: BlockConfig, storageJson: string): unknown {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"derivePrerunArgsFromStorage is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.PrerunArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as ArgsDeriveResult;\n\n if (result.error !== undefined) {\n // Return undefined if derivation fails (skip block in staging)\n return undefined;\n }\n return result.value;\n } catch {\n // Return undefined if derivation fails (skip block in staging)\n return undefined;\n }\n }\n\n private calculateEnrichmentTargets(req: EnrichmentTargetsRequest): PlRef[] | undefined {\n const blockConfig = req.blockConfig();\n if (blockConfig.enrichmentTargets === undefined) return undefined;\n const args = req.args();\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.enrichmentTargets,\n extractCodeWithInfo(blockConfig),\n args,\n ) as PlRef[];\n return result;\n }\n\n public getEnrichmentTargets(\n blockConfig: () => BlockConfig,\n args: () => unknown,\n key?: { argsRid: SignedResourceId; blockPackRid: SignedResourceId },\n ): PlRef[] | undefined {\n const req = { blockConfig, args };\n if (key === undefined) return this.calculateEnrichmentTargets(req);\n const cacheKey = `${key.argsRid}:${key.blockPackRid}`;\n return this.enrichmentTargetsCache.memo(cacheKey, { context: req }).value;\n }\n\n // =============================================================================\n // VM-based Storage Operations\n // =============================================================================\n\n /**\n * Creates initial BlockStorage for a new block using VM-based transformation.\n * This calls the '__pl_storage_initial' callback registered by DataModel which:\n * - Gets initial data from DataModel.getDefaultData()\n * - Creates BlockStorage with correct version\n *\n * @param blockConfig The block configuration (provides the model code)\n * @returns Initial storage as JSON string\n * @throws Error if storage creation fails\n */\n public getInitialStorageInVM(blockConfig: BlockConfig): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"getInitialStorageInVM is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitial],\n extractCodeWithInfo(blockConfig),\n ) as string;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.getInitialStorageInVM] Initial storage creation failed\", {\n cause: e,\n }),\n );\n throw new Error(`Block initial storage creation failed: ${e}`);\n }\n }\n\n /**\n * Applies a state update using VM-based transformation.\n * This calls the model's `__pl_storage_applyUpdate` callback which:\n * - Normalizes current storage\n * - Updates state while preserving other fields (version, plugins)\n * - Returns the updated storage as JSON string\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param currentStorageJson Current storage as JSON string (must be defined)\n * @param newState New state from developer\n * @returns Updated storage as JSON string\n * @throws Error if storage update fails\n */\n public applyStorageUpdateInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string,\n payload: { operation: string; value: unknown },\n ): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"applyStorageUpdateInVM is only supported for model API version 2\");\n }\n\n if (getDebugFlags().logJsExecStat) {\n this.logger.info(\n `[ProjectHelper.applyStorageUpdateInVM] currentStorageJson=${currentStorageJson.length}B, payload=${JSON.stringify(payload).length}B, operation=${payload.operation}`,\n );\n }\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageApplyUpdate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n payload,\n ) as string;\n return result;\n } catch (e) {\n const payloadJson = JSON.stringify(payload);\n this.logger.error(\n new Error(\n `[ProjectHelper.applyStorageUpdateInVM] Storage update failed (currentStorageJson=${currentStorageJson.length}B, payload=${payloadJson.length}B, operation=${payload.operation})`,\n { cause: e },\n ),\n );\n throw new Error(`Block storage update failed: ${e}`);\n }\n }\n\n /**\n * Gets storage debug view from raw storage data by calling the VM's __pl_storage_debugView callback.\n * Returns structured debug info about the storage (e.g., dataVersion).\n *\n * @param blockConfig Block configuration\n * @param rawStorageJson Raw storage as JSON string (or undefined)\n * @returns Storage debug view as JSON string (e.g., '{\"dataVersion\": \"v1\"}')\n */\n public getStorageDebugViewInVM(\n blockConfig: BlockConfig,\n rawStorageJson: string | undefined,\n ): StringifiedJson<StorageDebugView> | undefined {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"getStorageDebugViewInVM is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageDebugView],\n extractCodeWithInfo(blockConfig),\n rawStorageJson,\n ) as StringifiedJson<StorageDebugView>;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.getStorageDebugViewInVM] Get storage debug view failed\", {\n cause: e,\n }),\n );\n return undefined;\n }\n }\n\n // =============================================================================\n // Block State Migrations\n // =============================================================================\n\n /**\n * Runs block state migrations via VM-based transformation.\n * This calls the model's `__pl_storage_migrate` callback which:\n * - Normalizes current storage to get state and version\n * - Applies DataModel upgrade to reach target version key\n * - Runs all necessary migrations sequentially\n * - Returns new storage with updated state and version\n *\n * The middle layer doesn't need to know about dataVersion or storage internals.\n * All migration logic is encapsulated in the model.\n *\n * @param blockConfig The NEW block configuration (provides the model code with migrations)\n * @param currentStorageJson Current storage as JSON string (or undefined)\n * @returns MigrationResult with new storage or skip/error info\n */\n public migrateStorageInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string | undefined,\n ): MigrationResult {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return { error: \"migrateStorageInVM is only supported for model API version 2\" };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageMigrate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n ) as MigrationResult;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.migrateStorageInVM] Migration failed\", { cause: e }),\n );\n return { error: `VM execution failed: ${e}` };\n }\n }\n}\n"],"mappings":";;;;;;AA0CA,IAAa,gBAAb,MAA2B;CAaN;CACD;CAblB,yBAA0C,IAAIA,UAAAA,SAI5C;EACA,KAAK;EACL,aAAa,MAAM,QAAQ,EAAE,cAAc;GACzC,OAAO,EAAE,OAAO,KAAK,2BAA2B,OAAO,EAAE;EAC3D;CACF,CAAC;CAED,YACE,SACA,SAAmC,IAAIC,2BAAAA,qBAAqB,GAC5D;EAFiB,KAAA,UAAA;EACD,KAAA,SAAA;CACf;;;;;;;;;;;;CAiBH,sBACE,aACA,aACwB;EACxB,IAAI,YAAY,oBAAoBC,qBAAAA,8BAClC,OAAO,EACL,uBAAO,IAAI,MAAM,iEAAiE,EACpF;EAGF,IAAI;GACF,MAAM,SAASC,gBAAAA,oBACb,KAAK,SACL,YAAY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,EACjF,OAAO,EACT,CAAC,CACH;GACA;EACF;CACF;;;;;;;;;;;;;;;;CAqBA,mBACE,aACA,oBACiB;EACjB,IAAI,YAAY,oBAAoBF,qBAAAA,8BAClC,OAAO,EAAE,OAAO,+DAA+D;EAGjF,IAAI;GAOF,OANeC,gBAAAA,oBACb,KAAK,SACL,YAAY,wBAAwBC,qBAAAA,4BAA4B,kBAAA,GAAA,qBAAA,oBAAA,CAC5C,WAAW,GAC/B,kBAEU;EACd,SAAS,GAAG;GACV,KAAK,OAAO,MACV,IAAI,MAAM,uDAAuD,EAAE,OAAO,EAAE,CAAC,CAC/E;GACA,OAAO,EAAE,OAAO,wBAAwB,IAAI;EAC9C;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"project_helper.cjs","names":["LRUCache","ConsoleLoggerAdapter","BLOCK_STORAGE_FACADE_VERSION","executeSingleLambda","BlockStorageFacadeCallbacks","getDebugFlags"],"sources":["../../src/model/project_helper.ts"],"sourcesContent":["import type { ResultOrError, BlockConfig, BlockStorage, PlRef } from \"@platforma-sdk/model\";\nimport type { StringifiedJson } from \"@milaboratories/pl-model-common\";\nimport {\n extractCodeWithInfo,\n ensureError,\n BlockStorageFacadeCallbacks,\n BLOCK_STORAGE_FACADE_VERSION,\n} from \"@platforma-sdk/model\";\nimport { LRUCache } from \"lru-cache\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { executeSingleLambda } from \"../js_render\";\nimport type { SignedResourceId } from \"@milaboratories/pl-client\";\nimport { ConsoleLoggerAdapter, type MiLogger } from \"@milaboratories/ts-helpers\";\nimport type { StorageDebugView } from \"@milaboratories/pl-model-middle-layer\";\nimport { getDebugFlags } from \"../debug\";\n\ntype EnrichmentTargetsRequest = {\n blockConfig: () => BlockConfig;\n args: () => unknown;\n};\n\ntype EnrichmentTargetsValue = {\n value: PlRef[] | undefined;\n};\n\n/**\n * Result of VM-based storage migration.\n * Returned by migrateStorageInVM().\n *\n * - Error result: { error: string } - serious failure (no context, etc.)\n * - Success result: { newStorageJson: StringifiedJson<BlockStorage>, info: string } - migration succeeded\n */\nexport type MigrationResult =\n | { error: string }\n | { error?: undefined; newStorageJson: StringifiedJson<BlockStorage>; info: string };\n\n/**\n * Result of args derivation from storage.\n * Returned by __pl_args_derive and __pl_prerunArgs_derive VM callbacks.\n */\ntype ArgsDeriveResult = { error: string } | { error?: undefined; value: unknown };\n\n/**\n * Result of building initial storage from params.\n * Returned by the __pl_storage_initialFromParams VM callback.\n */\ntype ParamsStorageResult =\n | { error: string }\n | { error?: undefined; storageJson: StringifiedJson<BlockStorage> };\n\n/**\n * Result of checking params against their kind.\n * Returned by the __pl_initializationParams_validate VM callback.\n */\ntype InitializationParamsValidateResult = { error: string } | { error?: undefined };\n\nexport class ProjectHelper {\n private readonly enrichmentTargetsCache = new LRUCache<\n string,\n EnrichmentTargetsValue,\n EnrichmentTargetsRequest\n >({\n max: 256,\n memoMethod: (_key, _value, { context }) => {\n return { value: this.calculateEnrichmentTargets(context) };\n },\n });\n\n constructor(\n private readonly quickJs: QuickJSWASMModule,\n public readonly logger: MiLogger = new ConsoleLoggerAdapter(),\n ) {}\n\n // =============================================================================\n // Args Derivation from Storage (V3+)\n // =============================================================================\n\n /**\n * Derives args directly from storage JSON using VM callback.\n * The VM extracts data from storage and calls the block's args() function.\n *\n * This allows the middle layer to work only with storage JSON,\n * without needing to know the underlying data structure.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived args object, or error if derivation fails\n */\n public deriveArgsFromStorage(\n blockConfig: BlockConfig,\n storageJson: string,\n ): ResultOrError<unknown> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\"deriveArgsFromStorage is only supported for model API version 2\"),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.ArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as ArgsDeriveResult;\n\n if (result.error !== undefined) {\n return { error: new Error(result.error) };\n }\n return { value: result.value };\n } catch (e) {\n return { error: new Error(\"Args derivation from storage failed\", { cause: ensureError(e) }) };\n }\n }\n\n /**\n * Derives prerunArgs directly from storage JSON using VM callback.\n * Falls back to args() if prerunArgs is not defined in the block model.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived prerunArgs, or undefined if derivation fails\n */\n public derivePrerunArgsFromStorage(blockConfig: BlockConfig, storageJson: string): unknown {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"derivePrerunArgsFromStorage is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.PrerunArgsDerive],\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as ArgsDeriveResult;\n\n if (result.error !== undefined) {\n // Return undefined if derivation fails (skip block in staging)\n return undefined;\n }\n return result.value;\n } catch {\n // Return undefined if derivation fails (skip block in staging)\n return undefined;\n }\n }\n\n /**\n * Derives this block's template-export params from storage JSON using the VM\n * callback (`__pl_initializationParams_derive`).\n *\n * The template-export counterpart of {@link deriveArgsFromStorage}: instead of\n * the args a workflow runs on, it returns the params that would recreate the\n * block — the inverse of the data model's `init`. Params come back exactly as the block\n * projected them, references included: nothing marks or rewrites them on the way out, so\n * nothing here has to know a kind's params shape or how a reference is spelled.\n *\n * A `{ value: undefined }` result means the block declares no `templateParams`, which only\n * a block built against an older SDK can do. It does not reach a document: the export walk\n * requires a mapping and reports anything else as that block's problem, so an entry always\n * carries params.\n *\n * Unlike {@link derivePrerunArgsFromStorage}, a failure here is surfaced rather\n * than swallowed — a prerun that cannot derive args just skips a block in\n * staging, whereas an export that silently drops a block produces a template\n * that does not describe the project.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param storageJson Storage as JSON string\n * @returns The derived params with identifiers wrapped, `undefined` if the block declares\n * no lambda, or an error if derivation failed\n */\n public deriveTemplateParamsFromStorage(\n blockConfig: BlockConfig,\n storageJson: string,\n ): ResultOrError<unknown> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\n \"deriveTemplateParamsFromStorage is only supported for model API version 2\",\n ),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsDerive];\n\n // A model built before this callback existed simply has no entry for it. That is\n // NOT the same as a block declaring no `templateParams`: the block may well have\n // params, we just have no way to ask for them. Reporting it as `undefined` params\n // would export the block stripped of its configuration and quietly rebuild a\n // differently-configured project, so it has to be an error.\n // The message names the one action available to whoever pressed Export. It\n // deliberately says nothing about SDKs or callbacks: the person reading it did\n // not build this block and cannot change how it was built.\n if (callback === undefined) {\n return {\n error: new Error(\n \"This version of the block cannot be written to a template. Update the block \" +\n \"to a newer version and export again.\",\n ),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n storageJson,\n ) as ArgsDeriveResult;\n\n if (result.error !== undefined) {\n return { error: new Error(result.error) };\n }\n return { value: result.value };\n } catch (e) {\n const cause = ensureError(e);\n // The reason goes in the message, not only in `cause`: this error is rendered\n // into a per-block export problem and shown to whoever triggered the export,\n // and every layer between here and there carries only `message`.\n return {\n error: new Error(`Template params derivation from storage failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n private calculateEnrichmentTargets(req: EnrichmentTargetsRequest): PlRef[] | undefined {\n const blockConfig = req.blockConfig();\n if (blockConfig.enrichmentTargets === undefined) return undefined;\n const args = req.args();\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.enrichmentTargets,\n extractCodeWithInfo(blockConfig),\n args,\n ) as PlRef[];\n return result;\n }\n\n public getEnrichmentTargets(\n blockConfig: () => BlockConfig,\n args: () => unknown,\n key?: { argsRid: SignedResourceId; blockPackRid: SignedResourceId },\n ): PlRef[] | undefined {\n const req = { blockConfig, args };\n if (key === undefined) return this.calculateEnrichmentTargets(req);\n const cacheKey = `${key.argsRid}:${key.blockPackRid}`;\n return this.enrichmentTargetsCache.memo(cacheKey, { context: req }).value;\n }\n\n // =============================================================================\n // VM-based Storage Operations\n // =============================================================================\n\n /**\n * Creates initial BlockStorage for a new block using VM-based transformation.\n * This calls the '__pl_storage_initial' callback registered by DataModel which:\n * - Gets initial data from DataModel.getDefaultData()\n * - Creates BlockStorage with correct version\n *\n * @param blockConfig The block configuration (provides the model code)\n * @returns Initial storage as JSON string\n * @throws Error if storage creation fails\n */\n public getInitialStorageInVM(blockConfig: BlockConfig): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"getInitialStorageInVM is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitial],\n extractCodeWithInfo(blockConfig),\n ) as string;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.getInitialStorageInVM] Initial storage creation failed\", {\n cause: e,\n }),\n );\n throw new Error(`Block initial storage creation failed: ${e}`);\n }\n }\n\n /**\n * Checks a template entry's params against the block's kind, creating nothing.\n *\n * The pre-flight half of {@link getInitialStorageFromParamsInVM}: run once per entry\n * before a template is applied, so params a kind rejects are reported against the\n * entry that carries them while there is still no project. Skipping it is safe —\n * initialization runs the same check — but then the report arrives after earlier\n * entries have already been created.\n *\n * Every kind declares a parser, so a pass here means the params were checked against\n * the contract — not merely that they were JSON.\n *\n * A block whose model predates the callback passes unchecked rather than failing.\n * Unlike initialization, this method creates nothing, so there is nothing to get wrong\n * by proceeding, and such a block is refused outright at the point it is applied.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param params The entry's params. Reference ids may be placeholders: what is being\n * checked is the shape of the params, not what they point at\n * @returns Nothing, or why the params were rejected\n */\n public validateTemplateParamsInVM(\n blockConfig: BlockConfig,\n params: unknown,\n ): ResultOrError<undefined> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\"validateTemplateParamsInVM is only supported for model API version 2\"),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.InitializationParamsValidate];\n if (callback === undefined) return { value: undefined };\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n JSON.stringify(params ?? {}),\n ) as InitializationParamsValidateResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: undefined };\n } catch (e) {\n const cause = ensureError(e);\n return { error: new Error(`Params check failed to run: ${cause.message}`, { cause }) };\n }\n }\n\n /**\n * Creates initial BlockStorage for a block being created from template params.\n *\n * The inverse of {@link deriveTemplateParamsFromStorage}, and the reason a block\n * can be created by anything other than the UI: it hands the params to the\n * block's own init factory inside the model VM, so the resulting storage is\n * whatever that block considers a correctly-initialized state.\n *\n * **Pointing the entry's references at this project happens in the same call**, before the\n * factory sees them — inside the block's bundle, because recognizing a reference means\n * knowing the reference system and a template engine deliberately does not. Params reach\n * here exactly as the file held them.\n *\n * One call and not two: every VM call builds a fresh runtime and re-evaluates the whole\n * model bundle, so asking the block to relocate and then asking it to initialize would parse\n * it twice per entry, for an intermediate value nothing else reads.\n *\n * `blockIds` holds the entries created so far, so an id it does not name is left as it is —\n * a reference to an entry further down the file keeps pointing at nothing, and the applied\n * block reports itself as missing references rather than being wired to a block below it.\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param params The entry's params, as the document held them\n * @param blockIds template-local entry id → the block id that entry was given\n * @returns The initial storage as JSON string, or why the params yield none\n */\n public getInitialStorageFromParamsInVM(\n blockConfig: BlockConfig,\n params: unknown,\n blockIds: ReadonlyMap<string, string>,\n ): ResultOrError<string> {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return {\n error: new Error(\n \"getInitialStorageFromParamsInVM is only supported for model API version 2\",\n ),\n };\n }\n\n const callback =\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams];\n\n // A model built before this callback existed has no entry for it. Falling back to the\n // params-less initializer is not an option: it would produce a default-configured block\n // that looks like a successful apply, so the block the user gets would silently differ\n // from the one the template describes. Nor could its params be used as written — they name\n // the blocks of the project the template came from, and only this callback knows which of\n // the values in there are references at all.\n //\n // The message offers the two actions available to whoever applied the file. The\n // second one is the reason this branch is reachable at all: kind resolution only\n // ever returns a block that declares a kind, and such a block is new enough to\n // support this — but an entry may pin an exact block version instead, bypassing\n // resolution, and that pin can name anything ever published.\n if (callback === undefined) {\n return {\n error: new Error(\n \"This version of the block cannot be created from a template. Use a newer \" +\n \"version of the block, or remove the pinned block version from the template \" +\n \"entry so a supported one is chosen automatically.\",\n ),\n };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n callback,\n extractCodeWithInfo(blockConfig),\n // Params cross the VM boundary as text, like storage does. `undefined` would\n // stringify to nothing at all, and an entry with no params must go through\n // the params-less initializer rather than reaching this method.\n JSON.stringify(params ?? {}),\n JSON.stringify(Object.fromEntries(blockIds)),\n ) as ParamsStorageResult;\n\n if (result.error !== undefined) return { error: new Error(result.error) };\n return { value: result.storageJson };\n } catch (e) {\n const cause = ensureError(e);\n // The reason goes in the message, not only in `cause`: this error becomes a\n // per-entry apply problem shown to whoever triggered the import, and every\n // layer in between carries only `message`.\n return {\n error: new Error(`Initial storage creation from params failed: ${cause.message}`, {\n cause,\n }),\n };\n }\n }\n\n /**\n * Applies a state update using VM-based transformation.\n * This calls the model's `__pl_storage_applyUpdate` callback which:\n * - Normalizes current storage\n * - Updates state while preserving other fields (version, plugins)\n * - Returns the updated storage as JSON string\n *\n * @param blockConfig The block configuration (provides the model code)\n * @param currentStorageJson Current storage as JSON string (must be defined)\n * @param newState New state from developer\n * @returns Updated storage as JSON string\n * @throws Error if storage update fails\n */\n public applyStorageUpdateInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string,\n payload: { operation: string; value: unknown },\n ): string {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"applyStorageUpdateInVM is only supported for model API version 2\");\n }\n\n if (getDebugFlags().logJsExecStat) {\n this.logger.info(\n `[ProjectHelper.applyStorageUpdateInVM] currentStorageJson=${currentStorageJson.length}B, payload=${JSON.stringify(payload).length}B, operation=${payload.operation}`,\n );\n }\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageApplyUpdate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n payload,\n ) as string;\n return result;\n } catch (e) {\n const payloadJson = JSON.stringify(payload);\n this.logger.error(\n new Error(\n `[ProjectHelper.applyStorageUpdateInVM] Storage update failed (currentStorageJson=${currentStorageJson.length}B, payload=${payloadJson.length}B, operation=${payload.operation})`,\n { cause: e },\n ),\n );\n throw new Error(`Block storage update failed: ${e}`);\n }\n }\n\n /**\n * Gets storage debug view from raw storage data by calling the VM's __pl_storage_debugView callback.\n * Returns structured debug info about the storage (e.g., dataVersion).\n *\n * @param blockConfig Block configuration\n * @param rawStorageJson Raw storage as JSON string (or undefined)\n * @returns Storage debug view as JSON string (e.g., '{\"dataVersion\": \"v1\"}')\n */\n public getStorageDebugViewInVM(\n blockConfig: BlockConfig,\n rawStorageJson: string | undefined,\n ): StringifiedJson<StorageDebugView> | undefined {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n throw new Error(\"getStorageDebugViewInVM is only supported for model API version 2\");\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageDebugView],\n extractCodeWithInfo(blockConfig),\n rawStorageJson,\n ) as StringifiedJson<StorageDebugView>;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.getStorageDebugViewInVM] Get storage debug view failed\", {\n cause: e,\n }),\n );\n return undefined;\n }\n }\n\n // =============================================================================\n // Block State Migrations\n // =============================================================================\n\n /**\n * Runs block state migrations via VM-based transformation.\n * This calls the model's `__pl_storage_migrate` callback which:\n * - Normalizes current storage to get state and version\n * - Applies DataModel upgrade to reach target version key\n * - Runs all necessary migrations sequentially\n * - Returns new storage with updated state and version\n *\n * The middle layer doesn't need to know about dataVersion or storage internals.\n * All migration logic is encapsulated in the model.\n *\n * @param blockConfig The NEW block configuration (provides the model code with migrations)\n * @param currentStorageJson Current storage as JSON string (or undefined)\n * @returns MigrationResult with new storage or skip/error info\n */\n public migrateStorageInVM(\n blockConfig: BlockConfig,\n currentStorageJson: string | undefined,\n ): MigrationResult {\n if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {\n return { error: \"migrateStorageInVM is only supported for model API version 2\" };\n }\n\n try {\n const result = executeSingleLambda(\n this.quickJs,\n blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageMigrate],\n extractCodeWithInfo(blockConfig),\n currentStorageJson,\n ) as MigrationResult;\n return result;\n } catch (e) {\n this.logger.error(\n new Error(\"[ProjectHelper.migrateStorageInVM] Migration failed\", { cause: e }),\n );\n return { error: `VM execution failed: ${e}` };\n }\n }\n}\n"],"mappings":";;;;;;AAwDA,IAAa,gBAAb,MAA2B;CAaN;CACD;CAblB,yBAA0C,IAAIA,UAAAA,SAI5C;EACA,KAAK;EACL,aAAa,MAAM,QAAQ,EAAE,cAAc;GACzC,OAAO,EAAE,OAAO,KAAK,2BAA2B,OAAO,EAAE;EAC3D;CACF,CAAC;CAED,YACE,SACA,SAAmC,IAAIC,2BAAAA,qBAAqB,GAC5D;EAFiB,KAAA,UAAA;EACD,KAAA,SAAA;CACf;;;;;;;;;;;;CAiBH,sBACE,aACA,aACwB;EACxB,IAAI,YAAY,oBAAoBC,qBAAAA,8BAClC,OAAO,EACL,uBAAO,IAAI,MAAM,iEAAiE,EACpF;EAGF,I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C/E;GACA,OAAO,EAAE,OAAO,wBAAwB,IAAI;EAC9C;CACF;AACF"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { BlockConfig, BlockStorage, PlRef, ResultOrError } from "@platforma-sdk/model";
|
|
2
2
|
import { StorageDebugView } from "@milaboratories/pl-model-middle-layer";
|
|
3
3
|
import { MiLogger } from "@milaboratories/ts-helpers";
|
|
4
|
+
import { StringifiedJson } from "@milaboratories/pl-model-common";
|
|
4
5
|
import { SignedResourceId } from "@milaboratories/pl-client";
|
|
5
6
|
import { QuickJSWASMModule } from "quickjs-emscripten";
|
|
6
|
-
import { StringifiedJson } from "@milaboratories/pl-model-common";
|
|
7
7
|
|
|
8
8
|
//#region src/model/project_helper.d.ts
|
|
9
9
|
/**
|
|
@@ -46,6 +46,32 @@ declare class ProjectHelper {
|
|
|
46
46
|
* @returns The derived prerunArgs, or undefined if derivation fails
|
|
47
47
|
*/
|
|
48
48
|
derivePrerunArgsFromStorage(blockConfig: BlockConfig, storageJson: string): unknown;
|
|
49
|
+
/**
|
|
50
|
+
* Derives this block's template-export params from storage JSON using the VM
|
|
51
|
+
* callback (`__pl_initializationParams_derive`).
|
|
52
|
+
*
|
|
53
|
+
* The template-export counterpart of {@link deriveArgsFromStorage}: instead of
|
|
54
|
+
* the args a workflow runs on, it returns the params that would recreate the
|
|
55
|
+
* block — the inverse of the data model's `init`. Params come back exactly as the block
|
|
56
|
+
* projected them, references included: nothing marks or rewrites them on the way out, so
|
|
57
|
+
* nothing here has to know a kind's params shape or how a reference is spelled.
|
|
58
|
+
*
|
|
59
|
+
* A `{ value: undefined }` result means the block declares no `templateParams`, which only
|
|
60
|
+
* a block built against an older SDK can do. It does not reach a document: the export walk
|
|
61
|
+
* requires a mapping and reports anything else as that block's problem, so an entry always
|
|
62
|
+
* carries params.
|
|
63
|
+
*
|
|
64
|
+
* Unlike {@link derivePrerunArgsFromStorage}, a failure here is surfaced rather
|
|
65
|
+
* than swallowed — a prerun that cannot derive args just skips a block in
|
|
66
|
+
* staging, whereas an export that silently drops a block produces a template
|
|
67
|
+
* that does not describe the project.
|
|
68
|
+
*
|
|
69
|
+
* @param blockConfig The block configuration (provides the model code)
|
|
70
|
+
* @param storageJson Storage as JSON string
|
|
71
|
+
* @returns The derived params with identifiers wrapped, `undefined` if the block declares
|
|
72
|
+
* no lambda, or an error if derivation failed
|
|
73
|
+
*/
|
|
74
|
+
deriveTemplateParamsFromStorage(blockConfig: BlockConfig, storageJson: string): ResultOrError<unknown>;
|
|
49
75
|
private calculateEnrichmentTargets;
|
|
50
76
|
getEnrichmentTargets(blockConfig: () => BlockConfig, args: () => unknown, key?: {
|
|
51
77
|
argsRid: SignedResourceId;
|
|
@@ -62,6 +88,55 @@ declare class ProjectHelper {
|
|
|
62
88
|
* @throws Error if storage creation fails
|
|
63
89
|
*/
|
|
64
90
|
getInitialStorageInVM(blockConfig: BlockConfig): string;
|
|
91
|
+
/**
|
|
92
|
+
* Checks a template entry's params against the block's kind, creating nothing.
|
|
93
|
+
*
|
|
94
|
+
* The pre-flight half of {@link getInitialStorageFromParamsInVM}: run once per entry
|
|
95
|
+
* before a template is applied, so params a kind rejects are reported against the
|
|
96
|
+
* entry that carries them while there is still no project. Skipping it is safe —
|
|
97
|
+
* initialization runs the same check — but then the report arrives after earlier
|
|
98
|
+
* entries have already been created.
|
|
99
|
+
*
|
|
100
|
+
* Every kind declares a parser, so a pass here means the params were checked against
|
|
101
|
+
* the contract — not merely that they were JSON.
|
|
102
|
+
*
|
|
103
|
+
* A block whose model predates the callback passes unchecked rather than failing.
|
|
104
|
+
* Unlike initialization, this method creates nothing, so there is nothing to get wrong
|
|
105
|
+
* by proceeding, and such a block is refused outright at the point it is applied.
|
|
106
|
+
*
|
|
107
|
+
* @param blockConfig The block configuration (provides the model code)
|
|
108
|
+
* @param params The entry's params. Reference ids may be placeholders: what is being
|
|
109
|
+
* checked is the shape of the params, not what they point at
|
|
110
|
+
* @returns Nothing, or why the params were rejected
|
|
111
|
+
*/
|
|
112
|
+
validateTemplateParamsInVM(blockConfig: BlockConfig, params: unknown): ResultOrError<undefined>;
|
|
113
|
+
/**
|
|
114
|
+
* Creates initial BlockStorage for a block being created from template params.
|
|
115
|
+
*
|
|
116
|
+
* The inverse of {@link deriveTemplateParamsFromStorage}, and the reason a block
|
|
117
|
+
* can be created by anything other than the UI: it hands the params to the
|
|
118
|
+
* block's own init factory inside the model VM, so the resulting storage is
|
|
119
|
+
* whatever that block considers a correctly-initialized state.
|
|
120
|
+
*
|
|
121
|
+
* **Pointing the entry's references at this project happens in the same call**, before the
|
|
122
|
+
* factory sees them — inside the block's bundle, because recognizing a reference means
|
|
123
|
+
* knowing the reference system and a template engine deliberately does not. Params reach
|
|
124
|
+
* here exactly as the file held them.
|
|
125
|
+
*
|
|
126
|
+
* One call and not two: every VM call builds a fresh runtime and re-evaluates the whole
|
|
127
|
+
* model bundle, so asking the block to relocate and then asking it to initialize would parse
|
|
128
|
+
* it twice per entry, for an intermediate value nothing else reads.
|
|
129
|
+
*
|
|
130
|
+
* `blockIds` holds the entries created so far, so an id it does not name is left as it is —
|
|
131
|
+
* a reference to an entry further down the file keeps pointing at nothing, and the applied
|
|
132
|
+
* block reports itself as missing references rather than being wired to a block below it.
|
|
133
|
+
*
|
|
134
|
+
* @param blockConfig The block configuration (provides the model code)
|
|
135
|
+
* @param params The entry's params, as the document held them
|
|
136
|
+
* @param blockIds template-local entry id → the block id that entry was given
|
|
137
|
+
* @returns The initial storage as JSON string, or why the params yield none
|
|
138
|
+
*/
|
|
139
|
+
getInitialStorageFromParamsInVM(blockConfig: BlockConfig, params: unknown, blockIds: ReadonlyMap<string, string>): ResultOrError<string>;
|
|
65
140
|
/**
|
|
66
141
|
* Applies a state update using VM-based transformation.
|
|
67
142
|
* This calls the model's `__pl_storage_applyUpdate` callback which:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project_helper.d.ts","names":[],"sources":["../../src/model/project_helper.ts"],"mappings":";;;;;;;;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