@milaboratories/pl-middle-layer 1.10.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/dist/block_registry/index.d.ts +4 -0
  2. package/dist/block_registry/index.d.ts.map +1 -0
  3. package/dist/block_registry/registry.d.ts +37 -0
  4. package/dist/block_registry/registry.d.ts.map +1 -0
  5. package/dist/block_registry/registry_spec.d.ts +12 -0
  6. package/dist/block_registry/registry_spec.d.ts.map +1 -0
  7. package/dist/block_registry/watcher.d.ts +15 -0
  8. package/dist/block_registry/watcher.d.ts.map +1 -0
  9. package/dist/block_registry/well_known_registries.d.ts +4 -0
  10. package/dist/block_registry/well_known_registries.d.ts.map +1 -0
  11. package/dist/cfg_render/executor.d.ts +8 -0
  12. package/dist/cfg_render/executor.d.ts.map +1 -0
  13. package/dist/cfg_render/operation.d.ts +29 -0
  14. package/dist/cfg_render/operation.d.ts.map +1 -0
  15. package/dist/cfg_render/renderer.d.ts +6 -0
  16. package/dist/cfg_render/renderer.d.ts.map +1 -0
  17. package/dist/cfg_render/traverse.d.ts +3 -0
  18. package/dist/cfg_render/traverse.d.ts.map +1 -0
  19. package/dist/cfg_render/util.d.ts +5 -0
  20. package/dist/cfg_render/util.d.ts.map +1 -0
  21. package/dist/dev/index.d.ts +21 -0
  22. package/dist/dev/index.d.ts.map +1 -0
  23. package/dist/dev/util.d.ts +3 -0
  24. package/dist/dev/util.d.ts.map +1 -0
  25. package/dist/index.d.ts +13 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +2 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/index.mjs +3587 -0
  30. package/dist/index.mjs.map +1 -0
  31. package/dist/js_render/context.d.ts +68 -0
  32. package/dist/js_render/context.d.ts.map +1 -0
  33. package/dist/js_render/index.d.ts +6 -0
  34. package/dist/js_render/index.d.ts.map +1 -0
  35. package/dist/middle_layer/active_cfg.d.ts +6 -0
  36. package/dist/middle_layer/active_cfg.d.ts.map +1 -0
  37. package/dist/middle_layer/block.d.ts +9 -0
  38. package/dist/middle_layer/block.d.ts.map +1 -0
  39. package/dist/middle_layer/block_ctx.d.ts +20 -0
  40. package/dist/middle_layer/block_ctx.d.ts.map +1 -0
  41. package/dist/middle_layer/block_ctx_unsafe.d.ts +16 -0
  42. package/dist/middle_layer/block_ctx_unsafe.d.ts.map +1 -0
  43. package/dist/middle_layer/driver_kit.d.ts +31 -0
  44. package/dist/middle_layer/driver_kit.d.ts.map +1 -0
  45. package/dist/middle_layer/frontend_path.d.ts +6 -0
  46. package/dist/middle_layer/frontend_path.d.ts.map +1 -0
  47. package/dist/middle_layer/index.d.ts +5 -0
  48. package/dist/middle_layer/index.d.ts.map +1 -0
  49. package/dist/middle_layer/middle_layer.d.ts +78 -0
  50. package/dist/middle_layer/middle_layer.d.ts.map +1 -0
  51. package/dist/middle_layer/navigation_states.d.ts +10 -0
  52. package/dist/middle_layer/navigation_states.d.ts.map +1 -0
  53. package/dist/middle_layer/ops.d.ts +64 -0
  54. package/dist/middle_layer/ops.d.ts.map +1 -0
  55. package/dist/middle_layer/project.d.ts +110 -0
  56. package/dist/middle_layer/project.d.ts.map +1 -0
  57. package/dist/middle_layer/project_list.d.ts +11 -0
  58. package/dist/middle_layer/project_list.d.ts.map +1 -0
  59. package/dist/middle_layer/project_overview.d.ts +8 -0
  60. package/dist/middle_layer/project_overview.d.ts.map +1 -0
  61. package/dist/middle_layer/render.d.ts +6 -0
  62. package/dist/middle_layer/render.d.ts.map +1 -0
  63. package/dist/middle_layer/types.d.ts +11 -0
  64. package/dist/middle_layer/types.d.ts.map +1 -0
  65. package/dist/middle_layer/util.d.ts +3 -0
  66. package/dist/middle_layer/util.d.ts.map +1 -0
  67. package/dist/model/args.d.ts +12 -0
  68. package/dist/model/args.d.ts.map +1 -0
  69. package/dist/model/block_pack.d.ts +8 -0
  70. package/dist/model/block_pack.d.ts.map +1 -0
  71. package/dist/model/block_pack_spec.d.ts +40 -0
  72. package/dist/model/block_pack_spec.d.ts.map +1 -0
  73. package/dist/model/frontend.d.ts +10 -0
  74. package/dist/model/frontend.d.ts.map +1 -0
  75. package/dist/model/index.d.ts +3 -0
  76. package/dist/model/index.d.ts.map +1 -0
  77. package/dist/model/project_model.d.ts +67 -0
  78. package/dist/model/project_model.d.ts.map +1 -0
  79. package/dist/model/project_model_util.d.ts +29 -0
  80. package/dist/model/project_model_util.d.ts.map +1 -0
  81. package/dist/model/template_spec.d.ts +16 -0
  82. package/dist/model/template_spec.d.ts.map +1 -0
  83. package/dist/mutator/block-pack/block_pack.d.ts +17 -0
  84. package/dist/mutator/block-pack/block_pack.d.ts.map +1 -0
  85. package/dist/mutator/block-pack/frontend.d.ts +4 -0
  86. package/dist/mutator/block-pack/frontend.d.ts.map +1 -0
  87. package/dist/mutator/context_export.d.ts +9 -0
  88. package/dist/mutator/context_export.d.ts.map +1 -0
  89. package/dist/mutator/project.d.ts +121 -0
  90. package/dist/mutator/project.d.ts.map +1 -0
  91. package/dist/mutator/template/render_block.d.ts +32 -0
  92. package/dist/mutator/template/render_block.d.ts.map +1 -0
  93. package/dist/mutator/template/render_template.d.ts +12 -0
  94. package/dist/mutator/template/render_template.d.ts.map +1 -0
  95. package/dist/mutator/template/template_loading.d.ts +13 -0
  96. package/dist/mutator/template/template_loading.d.ts.map +1 -0
  97. package/dist/pool/data.d.ts +24 -0
  98. package/dist/pool/data.d.ts.map +1 -0
  99. package/dist/pool/driver.d.ts +22 -0
  100. package/dist/pool/driver.d.ts.map +1 -0
  101. package/dist/pool/index.d.ts +3 -0
  102. package/dist/pool/index.d.ts.map +1 -0
  103. package/dist/pool/p_object_collection.d.ts +29 -0
  104. package/dist/pool/p_object_collection.d.ts.map +1 -0
  105. package/dist/pool/ref_count_pool.d.ts +25 -0
  106. package/dist/pool/ref_count_pool.d.ts.map +1 -0
  107. package/dist/pool/result_pool.d.ts +25 -0
  108. package/dist/pool/result_pool.d.ts.map +1 -0
  109. package/dist/test/block_packs.d.ts +6 -0
  110. package/dist/test/block_packs.d.ts.map +1 -0
  111. package/dist/test/explicit_templates.d.ts +3 -0
  112. package/dist/test/explicit_templates.d.ts.map +1 -0
  113. package/dist/test/known_templates.d.ts +6 -0
  114. package/dist/test/known_templates.d.ts.map +1 -0
  115. package/package.json +55 -0
  116. package/src/block_registry/index.ts +3 -0
  117. package/src/block_registry/registry.test.ts +35 -0
  118. package/src/block_registry/registry.ts +180 -0
  119. package/src/block_registry/registry_spec.ts +13 -0
  120. package/src/block_registry/watcher.ts +72 -0
  121. package/src/block_registry/well_known_registries.ts +13 -0
  122. package/src/cfg_render/executor.test.ts +120 -0
  123. package/src/cfg_render/executor.ts +253 -0
  124. package/src/cfg_render/operation.ts +38 -0
  125. package/src/cfg_render/renderer.ts +540 -0
  126. package/src/cfg_render/traverse.ts +58 -0
  127. package/src/cfg_render/util.ts +29 -0
  128. package/src/dev/index.ts +89 -0
  129. package/src/dev/util.ts +13 -0
  130. package/src/index.ts +21 -0
  131. package/src/js_render/context.ts +768 -0
  132. package/src/js_render/index.ts +41 -0
  133. package/src/middle_layer/active_cfg.ts +56 -0
  134. package/src/middle_layer/block.ts +70 -0
  135. package/src/middle_layer/block_ctx.ts +90 -0
  136. package/src/middle_layer/block_ctx_unsafe.ts +29 -0
  137. package/src/middle_layer/driver_kit.ts +107 -0
  138. package/src/middle_layer/frontend_path.ts +83 -0
  139. package/src/middle_layer/index.ts +4 -0
  140. package/src/middle_layer/middle_layer.test.ts +720 -0
  141. package/src/middle_layer/middle_layer.ts +235 -0
  142. package/src/middle_layer/navigation_states.ts +48 -0
  143. package/src/middle_layer/ops.ts +147 -0
  144. package/src/middle_layer/project.ts +380 -0
  145. package/src/middle_layer/project_list.ts +59 -0
  146. package/src/middle_layer/project_overview.ts +220 -0
  147. package/src/middle_layer/render.test.ts +129 -0
  148. package/src/middle_layer/render.ts +19 -0
  149. package/src/middle_layer/types.ts +16 -0
  150. package/src/middle_layer/util.ts +22 -0
  151. package/src/model/args.ts +62 -0
  152. package/src/model/block_pack.ts +8 -0
  153. package/src/model/block_pack_spec.ts +52 -0
  154. package/src/model/frontend.ts +10 -0
  155. package/src/model/index.ts +2 -0
  156. package/src/model/project_model.test.ts +26 -0
  157. package/src/model/project_model.ts +142 -0
  158. package/src/model/project_model_util.test.ts +88 -0
  159. package/src/model/project_model_util.ts +169 -0
  160. package/src/model/template_spec.ts +18 -0
  161. package/src/mutator/block-pack/block_pack.test.ts +53 -0
  162. package/src/mutator/block-pack/block_pack.ts +187 -0
  163. package/src/mutator/block-pack/frontend.ts +29 -0
  164. package/src/mutator/context_export.ts +25 -0
  165. package/src/mutator/project.test.ts +272 -0
  166. package/src/mutator/project.ts +1112 -0
  167. package/src/mutator/template/render_block.ts +91 -0
  168. package/src/mutator/template/render_template.ts +40 -0
  169. package/src/mutator/template/template_loading.ts +77 -0
  170. package/src/mutator/template/template_render.test.ts +272 -0
  171. package/src/pool/data.ts +239 -0
  172. package/src/pool/driver.ts +325 -0
  173. package/src/pool/index.ts +2 -0
  174. package/src/pool/p_object_collection.ts +122 -0
  175. package/src/pool/ref_count_pool.ts +76 -0
  176. package/src/pool/result_pool.ts +284 -0
  177. package/src/test/block_packs.ts +23 -0
  178. package/src/test/explicit_templates.ts +8 -0
  179. package/src/test/known_templates.ts +24 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,3587 @@
1
+ var Kt = Object.defineProperty;
2
+ var Mt = (o, e, t) => e in o ? Kt(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
+ var d = (o, e, t) => Mt(o, typeof e != "symbol" ? e + "" : e, t);
4
+ import { executePSpecPredicate as $t, mapPObjectData as z, mapValueInVOE as Ut, mapPTableDef as ct, isFunctionHandle as ut, normalizeBlockConfig as xe, DefaultNavigationState as Gt } from "@platforma-sdk/model";
5
+ export * from "@platforma-sdk/model";
6
+ export * from "@milaboratories/pl-model-middle-layer";
7
+ import { request as ne } from "undici";
8
+ import { RegistryV1 as U, tryLoadPackDescription as lt, loadPackDescription as He } from "@platforma-sdk/block-tools";
9
+ import T from "node:fs";
10
+ import I from "node:path";
11
+ import Ht from "yaml";
12
+ import { assertNever as D, notEmpty as w, HmacSha256Signer as dt, ConsoleLoggerAdapter as _t } from "@milaboratories/ts-helpers";
13
+ import * as Wt from "node:fs/promises";
14
+ import { resourceTypesEqual as K, field as S, Pl as y, PlClient as zt, isNullResourceId as ce, ensureResourceIdNotNull as we, isResource as qt, isResourceRef as Yt, isNotNullResourceId as _e, resourceType as X, resourceTypeToString as Qt, resourceIdToString as pt, isNotFoundError as Zt, isTimeoutOrCancelError as Xt, toGlobalResourceId as er } from "@milaboratories/pl-client";
15
+ export * from "@milaboratories/pl-client";
16
+ import { FieldType as Xs, ResourceType as en } from "@milaboratories/pl-client";
17
+ import { SynchronizedTreeState as ht, PlError as tr } from "@milaboratories/pl-tree";
18
+ import { Computable as P, ChangeSource as We, PollComputablePool as rr, WatchableValue as or } from "@milaboratories/computable";
19
+ import { randomUUID as Y, createHash as he } from "node:crypto";
20
+ import ft from "denque";
21
+ import { Templates as sr } from "@platforma-sdk/workflow-tengo";
22
+ import Ee from "canonicalize";
23
+ import nr from "node:assert";
24
+ import { Scope as Se, getQuickJS as ir } from "quickjs-emscripten";
25
+ import { setTimeout as ar } from "node:timers/promises";
26
+ import * as gt from "node:os";
27
+ import { createDownloadClient as cr, createLogsClient as ur, createUploadBlobClient as lr, createUploadProgressClient as dr, createLsFilesClient as pr, DownloadDriver as hr, UploadDriver as fr, LogsStreamDriver as gr, LogsDriver as mr, LsDriver as vr, DownloadUrlDriver as yr } from "@milaboratories/pl-drivers";
28
+ async function ze(o) {
29
+ try {
30
+ return await Wt.stat(o, { bigint: !0 });
31
+ } catch (e) {
32
+ if (e.code === "ENOENT")
33
+ return;
34
+ throw e;
35
+ }
36
+ }
37
+ const br = [U.PlPackageYamlConfigFile], wr = [U.PlPackageJsonConfigFile], je = ["backend", "dist", "tengo", "tpl", "main.plj.gz"], Te = ["config", "dist", "config.json"], mt = ["frontend", "dist"], qe = "block-model/dist/config.json", Sr = "block-ui/package.json", kr = [
38
+ je,
39
+ Te,
40
+ br,
41
+ wr,
42
+ mt
43
+ ];
44
+ async function Cr(o) {
45
+ return await ze(I.join(o, ...Te)) !== void 0 || await ze(I.join(o, ...je)) !== void 0;
46
+ }
47
+ function Pr(o, e) {
48
+ try {
49
+ return require.resolve(e, {
50
+ paths: [o]
51
+ });
52
+ } catch (t) {
53
+ if (t.code !== "MODULE_NOT_FOUND") throw t;
54
+ }
55
+ }
56
+ function me(o, e) {
57
+ const t = Pr(o, e);
58
+ if (t === void 0) throw new Error(`Can't resolve ${e} against ${o}`);
59
+ return t;
60
+ }
61
+ async function Ye(o, e) {
62
+ if (I.isAbsolute(o) || (o = I.resolve(o)), await Cr(o))
63
+ return {
64
+ workflow: I.join(o, ...je),
65
+ config: I.join(o, ...Te),
66
+ ui: I.join(o, ...mt)
67
+ };
68
+ {
69
+ const t = me(o, qe), r = me(o, qe), s = me(o, Sr);
70
+ return { workflow: t, config: r, ui: I.resolve(s, "..", "dist") };
71
+ }
72
+ }
73
+ async function Fr(o) {
74
+ try {
75
+ return await T.promises.readFile(o, "utf8");
76
+ } catch (e) {
77
+ if (e.code === "ENOENT")
78
+ return;
79
+ throw e;
80
+ }
81
+ }
82
+ async function Br(o) {
83
+ try {
84
+ return await T.promises.stat(o, { bigint: !0 });
85
+ } catch (e) {
86
+ if (e.code === "ENOENT")
87
+ return;
88
+ throw e;
89
+ }
90
+ }
91
+ async function vt(o) {
92
+ let e = 0n;
93
+ for (const t of kr) {
94
+ const r = I.join(o, ...t), s = await Br(r);
95
+ s !== void 0 && e < s.mtimeNs && (e = s.mtimeNs);
96
+ }
97
+ return e.toString();
98
+ }
99
+ async function Ae(o) {
100
+ const e = await T.promises.stat(o.components.workflow.file, { bigint: !0 }), t = await T.promises.stat(o.components.model.file, { bigint: !0 });
101
+ return (e.mtimeNs > t.mtimeNs ? e.mtimeNs : t.mtimeNs).toString();
102
+ }
103
+ class Hs {
104
+ constructor(e, t) {
105
+ this.registrySpecs = e, this.http = t;
106
+ }
107
+ async getPackagesForRoot(e) {
108
+ const t = [];
109
+ switch (e.type) {
110
+ case "remote_v1":
111
+ const r = this.http !== void 0 ? { dispatcher: this.http } : {}, n = await (await ne(
112
+ `${e.url}/${U.GlobalOverviewPath}`,
113
+ r
114
+ )).body.json();
115
+ for (const i of n) {
116
+ const { organization: a, package: u, latestMeta: c, latestVersion: l } = i;
117
+ t.push({
118
+ organization: a,
119
+ package: u,
120
+ name: u,
121
+ latestVersion: l,
122
+ latestMeta: c,
123
+ registryLabel: e.label,
124
+ latestSpec: {
125
+ type: "from-registry-v1",
126
+ registryUrl: e.url,
127
+ organization: a,
128
+ package: u,
129
+ version: l
130
+ // `${regSpec.url}/${packageContentPrefix({ organization, package: pkg, version: latestVersion })}`
131
+ },
132
+ otherVersions: i.allVersions
133
+ });
134
+ }
135
+ return t;
136
+ case "folder_with_dev_packages":
137
+ for (const i of await T.promises.readdir(e.path, { withFileTypes: !0 })) {
138
+ if (!i.isDirectory()) continue;
139
+ const a = I.join(e.path, i.name), u = await Fr(
140
+ I.join(a, U.PlPackageYamlConfigFile)
141
+ );
142
+ if (u !== void 0) {
143
+ const l = U.PlPackageConfigData.parse(Ht.parse(u)), p = await vt(a);
144
+ t.push({
145
+ organization: l.organization,
146
+ package: l.package,
147
+ // TODO delete
148
+ name: l.package,
149
+ latestVersion: "DEV",
150
+ latestMeta: l.meta,
151
+ registryLabel: e.label,
152
+ latestSpec: {
153
+ type: "dev-v1",
154
+ folder: a,
155
+ mtime: p
156
+ },
157
+ otherVersions: []
158
+ });
159
+ }
160
+ const c = await lt(a);
161
+ if (c !== void 0) {
162
+ const l = await Ae(c);
163
+ t.push({
164
+ organization: c.id.organization,
165
+ package: c.id.name,
166
+ // TODO delete
167
+ name: c.id.name,
168
+ latestVersion: `${c.id.version}-DEV`,
169
+ latestMeta: c.meta,
170
+ registryLabel: e.label,
171
+ latestSpec: {
172
+ type: "dev-v2",
173
+ folder: a,
174
+ mtime: l
175
+ },
176
+ otherVersions: []
177
+ });
178
+ }
179
+ }
180
+ return t;
181
+ default:
182
+ return D(e);
183
+ }
184
+ }
185
+ async getPackagesOverview() {
186
+ const e = [];
187
+ for (const t of this.registrySpecs)
188
+ e.push(...await this.getPackagesForRoot(t));
189
+ return e;
190
+ }
191
+ }
192
+ const _s = {
193
+ type: "remote_v1",
194
+ label: "Central Release Registry",
195
+ url: "https://block.registry.platforma.bio/releases"
196
+ }, Ws = {
197
+ type: "remote_v1",
198
+ label: "Central Dev Snapshot registry",
199
+ url: "https://block.registry.platforma.bio/dev"
200
+ }, Rr = {
201
+ groups: [{ id: "default", label: "Default", blocks: [] }]
202
+ }, Or = {
203
+ stagingRefreshTimestamp: 0,
204
+ blocksInLimbo: []
205
+ }, Dr = {
206
+ label: "New Project"
207
+ }, xr = { name: "UserProject", version: "2" }, yt = "SchemaVersion", bt = "1", Ie = "ProjectCreated", Q = "ProjectLastModified", Z = "ProjectMeta", G = "ProjectStructure", ue = "BlockRenderingState", Er = "BlockFrontendState/", jr = /^BlockFrontendState\/(?<blockid>.*)$/;
208
+ function ke(o) {
209
+ return `${Er}${o}`;
210
+ }
211
+ const Tr = "BlockArgsAuthor/";
212
+ function Ce(o) {
213
+ return `${Tr}${o}`;
214
+ }
215
+ const Pe = "ProjectStructureAuthor";
216
+ function Ar(o) {
217
+ const e = o.match(jr);
218
+ if (e !== null)
219
+ return e.groups.blockid;
220
+ }
221
+ const Ir = "__serviceTemplate_";
222
+ function Fe(o) {
223
+ return `${Ir}${o}`;
224
+ }
225
+ function C(o, e) {
226
+ return `${o}-${e}`;
227
+ }
228
+ const Vr = /^(?<blockId>.*)-(?<fieldName>blockPack|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;
229
+ function Nr(o) {
230
+ const e = o.match(Vr);
231
+ if (e === null) return;
232
+ const { blockId: t, fieldName: r } = e.groups;
233
+ return { blockId: t, fieldName: r };
234
+ }
235
+ const Lr = "projects", wt = { name: "Projects", version: "1" }, Jr = (o) => K(o.type, wt) ? o.fields : [];
236
+ async function Kr(o, e, t, r) {
237
+ const s = await ht.init(o, e, {
238
+ ...r.ops.defaultTreeOptions,
239
+ pruning: Jr
240
+ });
241
+ return { computable: P.make((i) => {
242
+ const a = i.accessor(s.entry()).node(), u = t.getValue(i);
243
+ if (a === void 0) return;
244
+ const c = [];
245
+ for (const l of a.listDynamicFields()) {
246
+ const p = a.traverse(l);
247
+ if (p === void 0) continue;
248
+ const h = w(p.getKeyValueAsJson(Z)), g = w(p.getKeyValueAsJson(Ie)), b = w(p.getKeyValueAsJson(Q));
249
+ c.push({
250
+ id: l,
251
+ rid: p.id,
252
+ created: new Date(g),
253
+ lastModified: new Date(b),
254
+ opened: u.indexOf(p.id) >= 0,
255
+ meta: h
256
+ });
257
+ }
258
+ return c.sort((l) => -l.lastModified.valueOf()), c;
259
+ }).withStableType(), tree: s };
260
+ }
261
+ const Mr = {
262
+ name: "EphRenderTemplate",
263
+ version: "1"
264
+ }, $r = {
265
+ name: "RenderTemplate",
266
+ version: "1"
267
+ };
268
+ function St(o, e, t, r, s) {
269
+ if (s.length === 0) throw new Error("Zero output names provided");
270
+ const n = t ? o.createEphemeral(Mr) : o.createStruct($r), i = S(n, "template"), a = S(n, "inputs");
271
+ return o.createField(i, "Input", e), o.createField(a, "Input", y.createPlMap(o, r, t)), o.lockInputs(n), y.futureRecord(o, n, s, "Output", "outputs/");
272
+ }
273
+ const Ur = { name: "BContextEnd", version: "1" }, Gr = { name: "BContext", version: "1" }, Hr = "id", _r = "parent/", Wr = ["context", "result"];
274
+ function Qe(o, e, t) {
275
+ return St(o, e, !0, t, Wr);
276
+ }
277
+ function zr(o) {
278
+ const e = o.createEphemeral(Ur);
279
+ return o.lock(e), e;
280
+ }
281
+ function qr(o, e) {
282
+ if (e.length === 0) return zr(o);
283
+ if (e.length === 1) return e[0];
284
+ const t = o.createEphemeral(Gr);
285
+ o.createField(S(t, Hr), "Input", y.createPlString(o, Y()));
286
+ for (let r = 0; r < e.length; r++)
287
+ o.createField(S(t, `${_r}${r}`), "Input", e[r]);
288
+ return o.lock(t), t;
289
+ }
290
+ const Yr = { name: "TengoTemplateGet", version: "1" }, Qr = "registry", Zr = "templateURI", Xr = "template", eo = { name: "TengoTemplatePack", version: "1" }, to = {
291
+ name: "TengoTemplatePackConvert",
292
+ version: "1"
293
+ }, ro = "templatePack", oo = "template";
294
+ async function so(o) {
295
+ switch (o.type) {
296
+ case "from-file":
297
+ return {
298
+ type: "explicit",
299
+ content: await T.promises.readFile(o.path)
300
+ };
301
+ case "from-registry":
302
+ case "explicit":
303
+ return o;
304
+ default:
305
+ return D(o);
306
+ }
307
+ }
308
+ function no(o, e) {
309
+ const t = o.createStruct(Yr), r = S(t, Qr), s = S(t, Zr), n = S(t, Xr);
310
+ return o.setField(r, o.createValue(y.JsonString, Buffer.from(JSON.stringify(e.registry)))), o.setField(s, o.createValue(y.JsonString, Buffer.from(JSON.stringify(e.path)))), n;
311
+ }
312
+ function io(o, e) {
313
+ const t = o.createValue(eo, e.content), r = o.createStruct(to), s = S(r, ro), n = S(r, oo);
314
+ return o.setField(s, t), n;
315
+ }
316
+ function Ve(o, e) {
317
+ switch (e.type) {
318
+ case "from-registry":
319
+ return no(o, e);
320
+ case "explicit":
321
+ return io(o, e);
322
+ default:
323
+ return D(e);
324
+ }
325
+ }
326
+ const kt = { name: "Frontend/FromUrl", version: "1" }, Ct = {
327
+ name: "Frontend/FromFolder",
328
+ version: "1"
329
+ };
330
+ function ao(o, e) {
331
+ switch (e.type) {
332
+ case "url":
333
+ return o.createValue(
334
+ kt,
335
+ JSON.stringify({ url: e.url })
336
+ );
337
+ case "local":
338
+ return o.createValue(
339
+ Ct,
340
+ JSON.stringify({
341
+ path: e.path,
342
+ signature: e.signature
343
+ })
344
+ );
345
+ default:
346
+ return D(e);
347
+ }
348
+ }
349
+ const co = { name: "BlockPackCustom", version: "1" }, Pt = "template", Ft = "frontend";
350
+ function Ze(o) {
351
+ return o.endsWith("/") ? o : `${o}/`;
352
+ }
353
+ class uo {
354
+ constructor(e, t) {
355
+ this.signer = e, this.http = t;
356
+ }
357
+ async getBlockConfig(e) {
358
+ switch (e.type) {
359
+ case "explicit":
360
+ return e.config;
361
+ case "dev":
362
+ case "dev-v1": {
363
+ const t = await Ye(e.folder), r = await T.promises.readFile(t.config, { encoding: "utf-8" });
364
+ return JSON.parse(r);
365
+ }
366
+ case "dev-v2": {
367
+ const t = await He(e.folder), r = await T.promises.readFile(t.components.model.file, {
368
+ encoding: "utf-8"
369
+ });
370
+ return JSON.parse(r);
371
+ }
372
+ case "from-registry-v1": {
373
+ const t = this.http !== void 0 ? { dispatcher: this.http } : {}, r = `${Ze(e.registryUrl)}${U.packageContentPrefix(e)}`;
374
+ return await (await ne(`${r}/config.json`, t)).body.json();
375
+ }
376
+ default:
377
+ return D(e);
378
+ }
379
+ }
380
+ async prepare(e) {
381
+ switch (e.type) {
382
+ case "explicit":
383
+ return e;
384
+ case "dev":
385
+ case "dev-v1": {
386
+ const t = await Ye(e.folder), r = await T.promises.readFile(t.workflow), s = JSON.parse(
387
+ await T.promises.readFile(t.config, "utf-8")
388
+ ), n = t.ui;
389
+ return {
390
+ type: "explicit",
391
+ template: {
392
+ type: "explicit",
393
+ content: r
394
+ },
395
+ config: s,
396
+ frontend: {
397
+ type: "local",
398
+ path: n,
399
+ signature: this.signer.sign(n)
400
+ },
401
+ source: e
402
+ };
403
+ }
404
+ case "dev-v2": {
405
+ const t = await He(e.folder), r = JSON.parse(
406
+ await T.promises.readFile(t.components.model.file, {
407
+ encoding: "utf-8"
408
+ })
409
+ ), s = await T.promises.readFile(t.components.workflow.file), n = t.components.ui.folder, i = { ...e };
410
+ return e.mtime === void 0 && (i.mtime = await Ae(t)), {
411
+ type: "explicit",
412
+ template: {
413
+ type: "explicit",
414
+ content: s
415
+ },
416
+ config: r,
417
+ frontend: {
418
+ type: "local",
419
+ path: n,
420
+ signature: this.signer.sign(n)
421
+ },
422
+ source: i
423
+ };
424
+ }
425
+ case "from-registry-v1": {
426
+ const t = this.http !== void 0 ? { dispatcher: this.http } : {}, r = `${Ze(e.registryUrl)}${U.packageContentPrefix(e)}`, s = `${r}/template.plj.gz`, n = await ne(s, t);
427
+ if (n.statusCode !== 200)
428
+ throw new Error(
429
+ `Block not found in registry (url = ${s} ; code = ${n.statusCode}): ` + JSON.stringify(e)
430
+ );
431
+ const i = new Uint8Array(await n.body.arrayBuffer()), u = await (await ne(`${r}/config.json`, t)).body.json();
432
+ return {
433
+ type: "explicit",
434
+ template: {
435
+ type: "explicit",
436
+ content: i
437
+ },
438
+ config: u,
439
+ frontend: {
440
+ type: "url",
441
+ url: `${r}/frontend.tgz`
442
+ },
443
+ source: e
444
+ };
445
+ }
446
+ default:
447
+ return D(e);
448
+ }
449
+ }
450
+ }
451
+ function lo(o, e) {
452
+ const t = { config: e.config, source: e.source }, r = o.createStruct(co, JSON.stringify(t));
453
+ return o.createField(S(r, Pt), "Input", Ve(o, e.template)), o.createField(S(r, Ft), "Input", ao(o, e.frontend)), o.lock(r), r;
454
+ }
455
+ function Xe(o, e) {
456
+ switch (e.type) {
457
+ case "explicit":
458
+ return lo(o, e);
459
+ default:
460
+ return D(e.type);
461
+ }
462
+ }
463
+ function se(o, e) {
464
+ return { __isRef: !0, blockId: o, name: e };
465
+ }
466
+ function po(o) {
467
+ return typeof o == "object" && o !== null && o.__isRef === !0 && "blockId" in o && "name" in o;
468
+ }
469
+ function Be(o, e, t) {
470
+ const r = typeof e;
471
+ switch (r) {
472
+ case "function":
473
+ case "bigint":
474
+ case "number":
475
+ case "string":
476
+ case "boolean":
477
+ case "symbol":
478
+ case "undefined":
479
+ return;
480
+ case "object":
481
+ if (e === null) return;
482
+ if (po(e))
483
+ t === void 0 || t.has(e.blockId) ? o.upstreams.add(e.blockId) : o.missingReferences = !0;
484
+ else if (Array.isArray(e))
485
+ for (const s of e) Be(o, s, t);
486
+ else
487
+ for (const [, s] of Object.entries(e))
488
+ Be(o, s, t);
489
+ return;
490
+ default:
491
+ D(r);
492
+ }
493
+ }
494
+ function ho(o, e) {
495
+ const t = { upstreams: /* @__PURE__ */ new Set(), missingReferences: !1 };
496
+ return Be(t, o, e), t;
497
+ }
498
+ function V(o) {
499
+ return {
500
+ *[Symbol.iterator]() {
501
+ for (const e of o.groups) for (const t of e.blocks) yield t;
502
+ }
503
+ };
504
+ }
505
+ class Bt {
506
+ constructor(e) {
507
+ /** Nodes are stored in the map in topological order */
508
+ d(this, "nodes");
509
+ this.nodes = e;
510
+ }
511
+ traverseIds(e, ...t) {
512
+ const r = /* @__PURE__ */ new Set();
513
+ return this.traverse(e, t, (s) => r.add(s.id)), r;
514
+ }
515
+ traverseIdsExcludingRoots(e, ...t) {
516
+ const r = this.traverseIds(e, ...t);
517
+ for (const s of t) r.delete(s);
518
+ return r;
519
+ }
520
+ traverse(e, t, r) {
521
+ let s = [...t];
522
+ const n = new Set(s);
523
+ for (; s.length > 0; ) {
524
+ let i = [];
525
+ for (const a of s) {
526
+ const u = this.nodes.get(a);
527
+ r(u), u[e].forEach((c) => {
528
+ n.has(c) || (n.add(c), i.push(c));
529
+ });
530
+ }
531
+ s = i;
532
+ }
533
+ }
534
+ }
535
+ function Re(o) {
536
+ const e = /* @__PURE__ */ new Map();
537
+ let t;
538
+ for (const { id: r } of V(o)) {
539
+ const s = {
540
+ id: r,
541
+ missingReferences: !1
542
+ };
543
+ e.set(r, s), t === void 0 ? s.upstream = /* @__PURE__ */ new Set() : (s.upstream = /* @__PURE__ */ new Set([t.id]), t.downstream = /* @__PURE__ */ new Set([s.id])), t = s;
544
+ }
545
+ return t !== void 0 && (t.downstream = /* @__PURE__ */ new Set()), new Bt(e);
546
+ }
547
+ function ie(o, e) {
548
+ const t = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Set();
549
+ for (const { id: s } of V(o)) {
550
+ const n = e(s);
551
+ if (n === void 0) continue;
552
+ const i = ho(n, r), a = {
553
+ id: s,
554
+ missingReferences: i.missingReferences,
555
+ upstream: i.upstreams,
556
+ downstream: /* @__PURE__ */ new Set()
557
+ // will be populated from downstream blocks
558
+ };
559
+ t.set(s, a), i.upstreams.forEach((u) => t.get(u).downstream.add(s)), r.add(s);
560
+ }
561
+ return new Bt(t);
562
+ }
563
+ function fo(o, e) {
564
+ if (o.size !== e.size) return !1;
565
+ for (const t of o) if (!e.has(t)) return !1;
566
+ return !0;
567
+ }
568
+ function Oe(o, e) {
569
+ if (o.size > e.size) return Oe(e, o);
570
+ for (const t of o) if (e.has(t)) return !0;
571
+ return !1;
572
+ }
573
+ function et(o, e) {
574
+ const t = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Set(), s = /* @__PURE__ */ new Set();
575
+ return o.nodes.forEach((n) => {
576
+ const i = e.nodes.get(n.id);
577
+ i === void 0 ? t.add(n.id) : (!fo(n.upstream, i.upstream) || Oe(n.upstream, s)) && s.add(n.id);
578
+ }), e.nodes.forEach((n) => {
579
+ o.nodes.has(n.id) ? Oe(n.upstream, s) && s.add(n.id) : r.add(n.id);
580
+ }), { onlyInA: t, onlyInB: r, different: s };
581
+ }
582
+ let ve;
583
+ async function Rt() {
584
+ if (ve === void 0) {
585
+ const o = await so(sr["pframes.export-pframe"]);
586
+ if (o.type !== "explicit") throw new Error("Unexpected prepared template type.");
587
+ const e = he("sha256").update(o.content).digest("hex");
588
+ ve = { spec: o, hash: e };
589
+ }
590
+ return ve;
591
+ }
592
+ function go(o, e, t) {
593
+ return St(o, e, !0, { pf: t }, ["result"]).result;
594
+ }
595
+ function ye(o, e) {
596
+ let t = !1, r, s;
597
+ return () => {
598
+ if (!t)
599
+ return t = !0, r = o(), s = e(), s;
600
+ const n = o();
601
+ return r !== n && (r = n, s = e()), e();
602
+ };
603
+ }
604
+ class tt {
605
+ constructor(e, t) {
606
+ d(this, "currentInputsC", ye(
607
+ () => this.fields.currentArgs.modCount,
608
+ () => JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())
609
+ ));
610
+ d(this, "actualProductionInputsC", ye(
611
+ () => {
612
+ var e;
613
+ return (e = this.fields.prodArgs) == null ? void 0 : e.modCount;
614
+ },
615
+ () => {
616
+ var t;
617
+ const e = (t = this.fields.prodArgs) == null ? void 0 : t.value;
618
+ if (e !== void 0)
619
+ return JSON.parse(Buffer.from(e).toString());
620
+ }
621
+ ));
622
+ d(this, "productionStaleC", ye(
623
+ () => {
624
+ var e;
625
+ return `${this.fields.currentArgs.modCount}_${(e = this.fields.prodArgs) == null ? void 0 : e.modCount}`;
626
+ },
627
+ () => this.fields.prodArgs === void 0 || Buffer.compare(this.fields.currentArgs.value, this.fields.prodArgs.value) !== 0
628
+ ));
629
+ this.id = e, this.fields = t;
630
+ }
631
+ check() {
632
+ if (this.fields.prodOutput === void 0 != (this.fields.prodCtx === void 0))
633
+ throw new Error("inconsistent prod fields");
634
+ if (this.fields.stagingOutput === void 0 != (this.fields.stagingCtx === void 0))
635
+ throw new Error("inconsistent stage fields");
636
+ if (this.fields.prodOutputPrevious === void 0 != (this.fields.prodCtxPrevious === void 0))
637
+ throw new Error("inconsistent prod cache fields");
638
+ if (this.fields.stagingOutputPrevious === void 0 != (this.fields.stagingCtxPrevious === void 0))
639
+ throw new Error("inconsistent stage cache fields");
640
+ if (this.fields.blockPack === void 0) throw new Error("no block pack field");
641
+ if (this.fields.currentArgs === void 0) throw new Error("no current args field");
642
+ }
643
+ get currentInputs() {
644
+ return this.currentInputsC();
645
+ }
646
+ get stagingRendered() {
647
+ return this.fields.stagingCtx !== void 0;
648
+ }
649
+ get productionRendered() {
650
+ return this.fields.prodCtx !== void 0;
651
+ }
652
+ get productionStale() {
653
+ return this.productionRendered && this.productionStaleC();
654
+ }
655
+ get requireProductionRendering() {
656
+ return !this.productionRendered || this.productionStaleC();
657
+ }
658
+ get actualProductionInputs() {
659
+ return this.actualProductionInputsC();
660
+ }
661
+ getTemplate(e) {
662
+ return e.getFutureFieldValue(
663
+ y.unwrapHolder(e, this.fields.blockPack.ref),
664
+ Pt,
665
+ "Input"
666
+ );
667
+ }
668
+ }
669
+ const mo = (o) => {
670
+ throw new Error(`No new block info for ${o}`);
671
+ };
672
+ class le {
673
+ constructor(e, t, r, s, n, i, a, u, c, l, p, h) {
674
+ d(this, "globalModCount", 0);
675
+ d(this, "fieldsChanged", !1);
676
+ //
677
+ // Change trackers
678
+ //
679
+ d(this, "lastModifiedChanged", !1);
680
+ d(this, "structureChanged", !1);
681
+ d(this, "metaChanged", !1);
682
+ d(this, "renderingStateChanged", !1);
683
+ d(this, "changedBlockFrontendStates", /* @__PURE__ */ new Set());
684
+ /** Set blocks will be assigned current mutator author marker on save */
685
+ d(this, "blocksWithChangedInputs", /* @__PURE__ */ new Set());
686
+ //
687
+ // Graph calculation
688
+ //
689
+ d(this, "stagingGraph");
690
+ d(this, "pendingProductionGraph");
691
+ d(this, "actualProductionGraph");
692
+ this.rid = e, this.tx = t, this.author = r, this.schema = s, this.lastModified = n, this.meta = i, this.struct = a, this.renderingState = u, this.blocksInLimbo = c, this.blockInfos = l, this.blockFrontendStates = p, this.ctxExportTplHolder = h;
693
+ }
694
+ fixProblems() {
695
+ this.blockInfos.forEach((e) => {
696
+ (e.fields.prodArgs === void 0 || e.fields.prodOutput === void 0 || e.fields.prodCtx === void 0) && this.deleteBlockFields(e.id, "prodArgs", "prodOutput", "prodCtx");
697
+ });
698
+ }
699
+ get wasModified() {
700
+ return this.lastModifiedChanged || this.structureChanged || this.fieldsChanged || this.metaChanged || this.renderingStateChanged || this.changedBlockFrontendStates.size > 0;
701
+ }
702
+ get structure() {
703
+ return JSON.parse(JSON.stringify(this.struct));
704
+ }
705
+ getStagingGraph() {
706
+ return this.stagingGraph === void 0 && (this.stagingGraph = Re(this.struct)), this.stagingGraph;
707
+ }
708
+ getPendingProductionGraph() {
709
+ return this.pendingProductionGraph === void 0 && (this.pendingProductionGraph = ie(
710
+ this.struct,
711
+ (e) => this.getBlockInfo(e).currentInputs
712
+ )), this.pendingProductionGraph;
713
+ }
714
+ getActualProductionGraph() {
715
+ return this.actualProductionGraph === void 0 && (this.actualProductionGraph = ie(
716
+ this.struct,
717
+ (e) => this.getBlockInfo(e).actualProductionInputs
718
+ )), this.actualProductionGraph;
719
+ }
720
+ //
721
+ // Generic helpers to interact with project state
722
+ //
723
+ getBlockInfo(e) {
724
+ return w(this.blockInfos.get(e));
725
+ }
726
+ getBlock(e) {
727
+ for (const t of V(this.struct)) if (t.id === e) return t;
728
+ throw new Error("block not found");
729
+ }
730
+ setBlockFieldObj(e, t, r) {
731
+ const s = S(this.rid, C(e, t));
732
+ if (r.ref === void 0) throw new Error("Can't set value with empty ref");
733
+ this.getBlockInfo(e).fields[t] === void 0 ? this.tx.createField(s, "Dynamic", r.ref) : this.tx.setField(s, r.ref), this.getBlockInfo(e).fields[t] = {
734
+ modCount: this.globalModCount++,
735
+ ...r
736
+ }, this.fieldsChanged = !0;
737
+ }
738
+ setBlockField(e, t, r, s, n) {
739
+ this.setBlockFieldObj(e, t, { ref: r, status: s, value: n });
740
+ }
741
+ deleteBlockFields(e, ...t) {
742
+ let r = !1;
743
+ const s = this.getBlockInfo(e);
744
+ for (const n of t) {
745
+ const i = s.fields;
746
+ n in i && (this.tx.removeField(S(this.rid, C(e, n))), delete i[n], this.fieldsChanged = !0, r = !0);
747
+ }
748
+ return r;
749
+ }
750
+ updateLastModified() {
751
+ this.lastModified = Date.now(), this.lastModifiedChanged = !0;
752
+ }
753
+ //
754
+ // Main project actions
755
+ //
756
+ resetStagingRefreshTimestamp() {
757
+ this.renderingState.stagingRefreshTimestamp = Date.now(), this.renderingStateChanged = !0;
758
+ }
759
+ resetStaging(e) {
760
+ var r, s, n;
761
+ const t = this.getBlockInfo(e).fields;
762
+ ((r = t.stagingOutput) == null ? void 0 : r.status) === "Ready" && ((s = t.stagingCtx) == null ? void 0 : s.status) === "Ready" && ((n = t.stagingUiCtx) == null ? void 0 : n.status) === "Ready" && (this.setBlockFieldObj(e, "stagingOutputPrevious", t.stagingOutput), this.setBlockFieldObj(e, "stagingCtxPrevious", t.stagingCtx), this.setBlockFieldObj(e, "stagingUiCtxPrevious", t.stagingUiCtx)), this.deleteBlockFields(e, "stagingOutput", "stagingCtx", "stagingUiCtx") && this.resetStagingRefreshTimestamp();
763
+ }
764
+ resetProduction(e) {
765
+ var r, s, n;
766
+ const t = this.getBlockInfo(e).fields;
767
+ ((r = t.prodOutput) == null ? void 0 : r.status) === "Ready" && ((s = t.prodCtx) == null ? void 0 : s.status) === "Ready" && ((n = t.prodUiCtx) == null ? void 0 : n.status) === "Ready" && (this.setBlockFieldObj(e, "prodOutputPrevious", t.prodOutput), this.setBlockFieldObj(e, "prodCtxPrevious", t.prodCtx), this.setBlockFieldObj(e, "prodUiCtxPrevious", t.prodUiCtx)), this.deleteBlockFields(e, "prodOutput", "prodCtx", "prodUiCtx", "prodArgs");
768
+ }
769
+ /** Running blocks are reset, already computed moved to limbo. Returns if
770
+ * either of the actions were actually performed. */
771
+ resetOrLimboProduction(e) {
772
+ var r, s;
773
+ const t = this.getBlockInfo(e).fields;
774
+ return ((r = t.prodOutput) == null ? void 0 : r.status) === "Ready" && ((s = t.prodCtx) == null ? void 0 : s.status) === "Ready" ? this.blocksInLimbo.has(e) ? !1 : (this.blocksInLimbo.add(e), this.renderingStateChanged = !0, this.deleteBlockFields(e, "prodOutputPrevious", "prodCtxPrevious", "prodUiCtxPrevious"), !0) : this.deleteBlockFields(e, "prodOutput", "prodCtx", "prodUiCtx", "prodArgs");
775
+ }
776
+ /** Optimally sets inputs for multiple blocks in one go */
777
+ setArgs(e) {
778
+ const t = [];
779
+ for (const { blockId: r, args: s } of e) {
780
+ const n = this.getBlockInfo(r);
781
+ JSON.parse(s);
782
+ const i = Buffer.from(s);
783
+ if (Buffer.compare(n.fields.currentArgs.value, i) === 0) continue;
784
+ const a = this.tx.createValue(y.JsonObject, i);
785
+ this.setBlockField(r, "currentArgs", a, "Ready", i), this.blocksWithChangedInputs.add(r), t.push(r);
786
+ }
787
+ this.getStagingGraph().traverse("downstream", t, ({ id: r }) => this.resetStaging(r)), t.length > 0 && this.updateLastModified();
788
+ }
789
+ setUiState(e, t) {
790
+ if (this.blockInfos.get(e) === void 0) throw new Error("no such block");
791
+ this.blockFrontendStates.get(e) !== t && (t === void 0 ? this.blockFrontendStates.delete(e) : this.blockFrontendStates.set(e, t), this.changedBlockFrontendStates.add(e), this.blocksWithChangedInputs.add(e), this.updateLastModified());
792
+ }
793
+ /** Update block label */
794
+ setBlockLabel(e, t) {
795
+ const r = this.structure;
796
+ let s = !1;
797
+ for (const n of V(r))
798
+ if (n.id === e) {
799
+ n.label = t, s = !0;
800
+ break;
801
+ }
802
+ if (!s) throw new Error(`block ${e} not found`);
803
+ this.updateStructure(r), this.updateLastModified();
804
+ }
805
+ createCtx(e, t) {
806
+ const r = [];
807
+ return e.forEach((s) => {
808
+ const n = this.getBlockInfo(s);
809
+ if (n.fields[t] === void 0 || n.fields[t].ref === void 0)
810
+ throw new Error("One of the upstreams staging is not rendered.");
811
+ r.push(y.unwrapHolder(this.tx, n.fields[t].ref));
812
+ }), qr(this.tx, r);
813
+ }
814
+ exportCtx(e) {
815
+ return go(this.tx, y.unwrapHolder(this.tx, this.ctxExportTplHolder), e);
816
+ }
817
+ renderStagingFor(e) {
818
+ this.resetStaging(e);
819
+ const t = this.getBlockInfo(e), r = this.createCtx(this.getStagingGraph().nodes.get(e).upstream, "stagingCtx");
820
+ if (this.getBlock(e).renderingMode !== "Heavy") throw new Error("not supported yet");
821
+ const s = t.getTemplate(this.tx), n = Qe(this.tx, s, {
822
+ args: t.fields.currentArgs.ref,
823
+ blockId: this.tx.createValue(y.JsonString, JSON.stringify(e)),
824
+ isProduction: this.tx.createValue(y.JsonBool, JSON.stringify(!1)),
825
+ context: r
826
+ });
827
+ this.setBlockField(
828
+ e,
829
+ "stagingCtx",
830
+ y.wrapInEphHolder(this.tx, n.context),
831
+ "NotReady"
832
+ ), this.setBlockField(e, "stagingUiCtx", this.exportCtx(n.context), "NotReady"), this.setBlockField(e, "stagingOutput", n.result, "NotReady");
833
+ }
834
+ renderProductionFor(e) {
835
+ this.resetProduction(e);
836
+ const t = this.getBlockInfo(e), r = this.createCtx(
837
+ this.getPendingProductionGraph().nodes.get(e).upstream,
838
+ "prodCtx"
839
+ );
840
+ if (this.getBlock(e).renderingMode === "Light")
841
+ throw new Error("Can't render production for light block.");
842
+ const s = t.getTemplate(this.tx), n = Qe(this.tx, s, {
843
+ args: t.fields.currentArgs.ref,
844
+ blockId: this.tx.createValue(y.JsonString, JSON.stringify(e)),
845
+ isProduction: this.tx.createValue(y.JsonBool, JSON.stringify(!0)),
846
+ context: r
847
+ });
848
+ this.setBlockField(
849
+ e,
850
+ "prodCtx",
851
+ y.wrapInEphHolder(this.tx, n.context),
852
+ "NotReady"
853
+ ), this.setBlockField(e, "prodUiCtx", this.exportCtx(n.context), "NotReady"), this.setBlockField(e, "prodOutput", n.result, "NotReady"), this.setBlockFieldObj(e, "prodArgs", t.fields.currentArgs), this.blocksInLimbo.delete(e) && (this.renderingStateChanged = !0);
854
+ }
855
+ //
856
+ // Structure changes
857
+ //
858
+ /** Very generic method, better check for more specialized case-specific methods first. */
859
+ updateStructure(e, t = mo) {
860
+ const r = this.getStagingGraph(), s = this.getActualProductionGraph(), n = Re(e), i = ie(
861
+ e,
862
+ (c) => {
863
+ var l;
864
+ return (l = this.blockInfos.get(c)) == null ? void 0 : l.actualProductionInputs;
865
+ }
866
+ ), a = et(r, n), u = et(s, i);
867
+ for (const c of a.onlyInA) {
868
+ const { fields: l } = this.getBlockInfo(c);
869
+ this.deleteBlockFields(c, ...Object.keys(l)), this.blockInfos.delete(c), this.blocksInLimbo.delete(c) && (this.renderingStateChanged = !0), this.blockFrontendStates.delete(c) && this.changedBlockFrontendStates.add(c);
870
+ }
871
+ for (const c of a.onlyInB) {
872
+ const l = new tt(c, {});
873
+ this.blockInfos.set(c, l);
874
+ const p = t(c), h = Xe(this.tx, p.blockPack);
875
+ this.setBlockField(c, "blockPack", y.wrapInHolder(this.tx, h), "NotReady");
876
+ const g = Buffer.from(p.args), b = this.tx.createValue(y.JsonObject, g);
877
+ this.setBlockField(c, "currentArgs", b, "Ready", g), l.check();
878
+ }
879
+ for (const c of a.different) this.resetStaging(c);
880
+ s.traverse("downstream", [...u.different], (c) => {
881
+ this.resetOrLimboProduction(c.id);
882
+ }), (a.onlyInB.size > 0 || a.onlyInA.size > 0 || a.different.size > 0) && this.resetStagingRefreshTimestamp(), this.struct = e, this.structureChanged = !0, this.stagingGraph = void 0, this.pendingProductionGraph = void 0, this.actualProductionGraph = void 0, this.updateLastModified();
883
+ }
884
+ //
885
+ // Structure change helpers
886
+ //
887
+ addBlock(e, t, r) {
888
+ const s = this.structure;
889
+ if (r === void 0)
890
+ s.groups[s.groups.length - 1].blocks.push(e);
891
+ else {
892
+ let n = !1;
893
+ for (const i of s.groups) {
894
+ const a = i.blocks.findIndex((u) => u.id === r);
895
+ if (!(a < 0)) {
896
+ i.blocks.splice(a, 0, e), n = !0;
897
+ break;
898
+ }
899
+ }
900
+ if (!n) throw new Error(`Can't find element with id: ${r}`);
901
+ }
902
+ this.updateStructure(s, (n) => {
903
+ if (n !== e.id) throw new Error("Unexpected");
904
+ return t;
905
+ });
906
+ }
907
+ deleteBlock(e) {
908
+ const t = this.structure;
909
+ let r = !1;
910
+ for (const s of t.groups) {
911
+ const n = s.blocks.findIndex((i) => i.id === e);
912
+ if (!(n < 0)) {
913
+ s.blocks.splice(n, 1), r = !0;
914
+ break;
915
+ }
916
+ }
917
+ if (!r) throw new Error(`Can't find element with id: ${e}`);
918
+ this.updateStructure(t);
919
+ }
920
+ //
921
+ // Block-pack migration
922
+ //
923
+ migrateBlockPack(e, t, r) {
924
+ const s = this.getBlockInfo(e);
925
+ this.setBlockField(
926
+ e,
927
+ "blockPack",
928
+ y.wrapInHolder(this.tx, Xe(this.tx, t)),
929
+ "NotReady"
930
+ ), r !== void 0 ? (this.setArgs([{ blockId: e, args: r }]), this.setUiState(e, void 0)) : this.getStagingGraph().traverse("downstream", [e], ({ id: n }) => this.resetStaging(n)), s.productionRendered && this.getActualProductionGraph().traverse(
931
+ "downstream",
932
+ [e],
933
+ ({ id: n }) => this.resetOrLimboProduction(n)
934
+ ), this.updateLastModified();
935
+ }
936
+ //
937
+ // Render
938
+ //
939
+ renderProduction(e, t = !1) {
940
+ const r = new Set(e), s = this.getPendingProductionGraph();
941
+ if (t)
942
+ s.traverse("upstream", e, (i) => {
943
+ r.add(i.id);
944
+ });
945
+ else
946
+ for (const i of r) {
947
+ const a = s.nodes.get(i);
948
+ if (a === void 0) throw new Error(`Can't find block with id: ${i}`);
949
+ for (const u of a.upstream)
950
+ if (!r.has(u))
951
+ throw new Error("Can't render blocks not including all upstreams.");
952
+ }
953
+ const n = /* @__PURE__ */ new Set();
954
+ for (const i of V(this.structure)) {
955
+ if (!r.has(i.id)) continue;
956
+ let a = this.getBlockInfo(i.id).requireProductionRendering || this.blocksInLimbo.has(i.id);
957
+ if (!a) {
958
+ for (const u of s.nodes.get(i.id).upstream)
959
+ if (n.has(u)) {
960
+ a = !0;
961
+ break;
962
+ }
963
+ }
964
+ a && (this.renderProductionFor(i.id), n.add(i.id));
965
+ }
966
+ return s.traverse("downstream", [...n], (i) => {
967
+ n.has(i.id) || this.resetOrLimboProduction(i.id);
968
+ }), n.size > 0 && this.updateLastModified(), n;
969
+ }
970
+ /** Stops running blocks from the list and modify states of other blocks
971
+ * accordingly */
972
+ stopProduction(...e) {
973
+ var i, a;
974
+ const t = this.getActualProductionGraph(), r = new ft(e), s = new Set(e), n = [];
975
+ for (; !r.isEmpty(); ) {
976
+ const u = r.shift(), c = this.getBlockInfo(u).fields;
977
+ if (!(((i = c.prodOutput) == null ? void 0 : i.status) === "Ready" && ((a = c.prodCtx) == null ? void 0 : a.status) === "Ready") && this.deleteBlockFields(u, "prodOutput", "prodCtx", "prodUiCtx", "prodArgs")) {
978
+ n.push(u);
979
+ for (const l of t.traverseIdsExcludingRoots("downstream", u))
980
+ s.has(l) || (r.push(l), s.add(l));
981
+ }
982
+ }
983
+ for (const u of t.traverseIdsExcludingRoots("downstream", ...n))
984
+ this.resetOrLimboProduction(u);
985
+ }
986
+ traverseWithStagingLag(e) {
987
+ const t = /* @__PURE__ */ new Map();
988
+ this.getStagingGraph().nodes.forEach((s) => {
989
+ let i = this.getBlockInfo(s.id).stagingRendered ? 0 : 1;
990
+ s.upstream.forEach((a) => {
991
+ const u = t.get(a);
992
+ u !== 0 && (i = Math.max(u + 1, i));
993
+ }), e(s.id, i), t.set(s.id, i);
994
+ });
995
+ }
996
+ /** @param stagingRenderingRate rate in blocks per second */
997
+ refreshStagings(e) {
998
+ const t = Date.now() - this.renderingState.stagingRefreshTimestamp, r = e === void 0 ? void 0 : 1 + Math.max(0, t * e / 1e3);
999
+ let s = 0;
1000
+ this.traverseWithStagingLag((n, i) => {
1001
+ i !== 0 && (r === void 0 || i <= r) && (this.renderStagingFor(n), s++);
1002
+ }), s > 0 && this.resetStagingRefreshTimestamp();
1003
+ }
1004
+ //
1005
+ // Meta
1006
+ //
1007
+ /** Updates project metadata */
1008
+ setMeta(e) {
1009
+ this.meta = e, this.metaChanged = !0, this.updateLastModified();
1010
+ }
1011
+ //
1012
+ // Maintenance
1013
+ //
1014
+ /** @param stagingRenderingRate rate in blocks per second */
1015
+ doRefresh(e) {
1016
+ this.refreshStagings(e), this.blockInfos.forEach((t) => {
1017
+ var r, s, n, i;
1018
+ ((r = t.fields.prodCtx) == null ? void 0 : r.status) === "Ready" && ((s = t.fields.prodOutput) == null ? void 0 : s.status) === "Ready" && this.deleteBlockFields(
1019
+ t.id,
1020
+ "prodOutputPrevious",
1021
+ "prodCtxPrevious",
1022
+ "prodUiCtxPrevious"
1023
+ ), ((n = t.fields.stagingCtx) == null ? void 0 : n.status) === "Ready" && ((i = t.fields.stagingOutput) == null ? void 0 : i.status) === "Ready" && this.deleteBlockFields(
1024
+ t.id,
1025
+ "stagingOutputPrevious",
1026
+ "stagingCtxPrevious",
1027
+ "stagingUiCtxPrevious"
1028
+ );
1029
+ });
1030
+ }
1031
+ assignAuthorMarkers() {
1032
+ const e = this.author ? JSON.stringify(this.author) : void 0;
1033
+ for (const t of this.blocksWithChangedInputs)
1034
+ e === void 0 ? this.tx.deleteKValue(this.rid, Ce(t)) : this.tx.setKValue(this.rid, Ce(t), e);
1035
+ (this.metaChanged || this.structureChanged) && (e === void 0 ? this.tx.deleteKValue(this.rid, Pe) : this.tx.setKValue(this.rid, Pe, e));
1036
+ }
1037
+ save() {
1038
+ if (this.wasModified) {
1039
+ this.lastModifiedChanged && this.tx.setKValue(this.rid, Q, JSON.stringify(this.lastModified)), this.structureChanged && this.tx.setKValue(this.rid, G, JSON.stringify(this.struct)), this.renderingStateChanged && this.tx.setKValue(
1040
+ this.rid,
1041
+ ue,
1042
+ JSON.stringify({
1043
+ ...this.renderingState,
1044
+ blocksInLimbo: [...this.blocksInLimbo]
1045
+ })
1046
+ ), this.metaChanged && this.tx.setKValue(this.rid, Z, JSON.stringify(this.meta));
1047
+ for (const e of this.changedBlockFrontendStates) {
1048
+ const t = this.blockFrontendStates.get(e);
1049
+ t === void 0 ? this.tx.deleteKValue(this.rid, ke(e)) : this.tx.setKValue(this.rid, ke(e), t);
1050
+ }
1051
+ this.assignAuthorMarkers();
1052
+ }
1053
+ }
1054
+ static async load(e, t, r) {
1055
+ const s = e.getResourceData(t, !0), n = e.getKValueJson(t, yt), i = e.getKValueJson(t, Q), a = e.getKValueJson(t, Z), u = e.getKValueJson(t, G), c = e.getKValueJson(t, ue), l = e.listKeyValuesString(t), [
1056
+ p,
1057
+ h,
1058
+ g,
1059
+ b,
1060
+ B,
1061
+ { stagingRefreshTimestamp: M, blocksInLimbo: ee },
1062
+ te
1063
+ ] = await Promise.all([
1064
+ s,
1065
+ n,
1066
+ i,
1067
+ a,
1068
+ u,
1069
+ c,
1070
+ l
1071
+ ]);
1072
+ if (h !== bt)
1073
+ throw new Error(
1074
+ `Can't act on this project resource because it has a wrong schema version: ${h}`
1075
+ );
1076
+ const $ = /* @__PURE__ */ new Map();
1077
+ for (const v of p.fields) {
1078
+ const O = Nr(v.name);
1079
+ if (O === void 0) continue;
1080
+ let F = $.get(O.blockId);
1081
+ F === void 0 && (F = {
1082
+ id: O.blockId,
1083
+ fields: {}
1084
+ }, $.set(O.blockId, F)), F.fields[O.fieldName] = ce(v.value) ? { modCount: 0 } : { modCount: 0, ref: v.value };
1085
+ }
1086
+ const H = await Rt(), re = Fe(H.hash), k = p.fields.find(
1087
+ (v) => v.name === re
1088
+ );
1089
+ let L;
1090
+ k !== void 0 ? L = we(k.value) : (L = y.wrapInHolder(e, Ve(e, H.spec)), e.createField(
1091
+ S(t, Fe(H.hash)),
1092
+ "Dynamic",
1093
+ L
1094
+ ));
1095
+ const _ = { stagingRefreshTimestamp: M }, j = new Set(ee), x = /* @__PURE__ */ new Map();
1096
+ for (const v of te) {
1097
+ const O = Ar(v.key);
1098
+ O !== void 0 && x.set(O, v.value);
1099
+ }
1100
+ const R = [];
1101
+ $.forEach(({ id: v, fields: O }) => {
1102
+ for (const [, F] of Object.entries(O))
1103
+ if (F.ref !== void 0) {
1104
+ if (!qt(F.ref) || Yt(F.ref))
1105
+ throw new Error("unexpected behaviour");
1106
+ R.push([F, e.getResourceData(F.ref, !1)]);
1107
+ }
1108
+ });
1109
+ for (const [v, O] of R) {
1110
+ const F = await O;
1111
+ v.value = F.data, _e(F.error) ? v.status = "Error" : F.resourceReady || _e(F.originalResourceId) ? v.status = "Ready" : v.status = "NotReady";
1112
+ }
1113
+ const J = /* @__PURE__ */ new Map();
1114
+ $.forEach(({ id: v, fields: O }) => J.set(v, new tt(v, O)));
1115
+ const N = /* @__PURE__ */ new Set();
1116
+ for (const v of V(B)) {
1117
+ if (!J.has(v.id))
1118
+ throw new Error(`Inconsistent project structure: no inputs for ${v.id}`);
1119
+ N.add(v.id);
1120
+ }
1121
+ J.forEach((v) => {
1122
+ if (!N.has(v.id))
1123
+ throw new Error(`Inconsistent project structure: no structure entry for ${v.id}`);
1124
+ v.check();
1125
+ });
1126
+ const oe = new le(
1127
+ t,
1128
+ e,
1129
+ r,
1130
+ h,
1131
+ g,
1132
+ b,
1133
+ B,
1134
+ _,
1135
+ j,
1136
+ J,
1137
+ x,
1138
+ L
1139
+ );
1140
+ return oe.fixProblems(), oe;
1141
+ }
1142
+ }
1143
+ async function vo(o, e = Dr) {
1144
+ const t = o.createEphemeral(xr);
1145
+ o.lock(t);
1146
+ const r = String(Date.now());
1147
+ o.setKValue(t, yt, JSON.stringify(bt)), o.setKValue(t, Ie, r), o.setKValue(t, Q, r), o.setKValue(t, Z, JSON.stringify(e)), o.setKValue(t, G, JSON.stringify(Rr)), o.setKValue(t, ue, JSON.stringify(Or));
1148
+ const s = await Rt();
1149
+ return o.createField(
1150
+ S(t, Fe(s.hash)),
1151
+ "Dynamic",
1152
+ y.wrapInHolder(o, Ve(o, s.spec))
1153
+ ), t;
1154
+ }
1155
+ async function be(o, e, t) {
1156
+ return A(o, e, void 0, t);
1157
+ }
1158
+ async function A(o, e, t, r) {
1159
+ if (o instanceof zt)
1160
+ return await o.withWriteTx("ProjectAction", async (s) => {
1161
+ const n = await le.load(s, e, t), i = await r(n);
1162
+ return n.wasModified && (n.save(), await s.commit()), i;
1163
+ });
1164
+ {
1165
+ const s = await le.load(o, e, t), n = await r(s);
1166
+ return s.save(), n;
1167
+ }
1168
+ }
1169
+ function* yo(o) {
1170
+ switch (o.type) {
1171
+ case "Json":
1172
+ return;
1173
+ case "JsonPartitioned":
1174
+ for (const [, e] of Object.entries(o.parts)) yield e;
1175
+ return;
1176
+ case "BinaryPartitioned":
1177
+ for (const [, { index: e, values: t }] of Object.entries(o.parts))
1178
+ yield e, yield t;
1179
+ return;
1180
+ default:
1181
+ D(o);
1182
+ }
1183
+ }
1184
+ function rt(o, e) {
1185
+ return Object.fromEntries(
1186
+ Object.entries(o).map(([t, r]) => [t, e(r, t)])
1187
+ );
1188
+ }
1189
+ function bo(o, e) {
1190
+ switch (o.type) {
1191
+ case "Json":
1192
+ return { ...o };
1193
+ case "JsonPartitioned":
1194
+ return { ...o, parts: rt(o.parts, e) };
1195
+ case "BinaryPartitioned":
1196
+ return {
1197
+ ...o,
1198
+ parts: rt(o.parts, (t) => ({
1199
+ index: e(t.index),
1200
+ values: e(t.values)
1201
+ }))
1202
+ };
1203
+ default:
1204
+ D(o);
1205
+ }
1206
+ }
1207
+ const wo = X("PColumnData/JsonPartitioned", "1"), So = X(
1208
+ "PColumnData/Partitioned/JsonPartitioned",
1209
+ "1"
1210
+ ), ko = X("PColumnData/BinaryPartitioned", "1"), Co = X(
1211
+ "PColumnData/Partitioned/BinaryPartitioned",
1212
+ "1"
1213
+ ), Po = X("PColumnData/Json", "1");
1214
+ function Fo(o) {
1215
+ if (!o.getIsReadyOrError()) throw new Error("Data not ready.");
1216
+ const e = o.getDataAsJson();
1217
+ if (e === void 0)
1218
+ throw new Error("unexpected data info structure, no resource data");
1219
+ if (K(o.resourceType, Po)) {
1220
+ const t = e;
1221
+ return {
1222
+ type: "Json",
1223
+ keyLength: t.keyLength,
1224
+ data: t.data
1225
+ };
1226
+ } else if (K(o.resourceType, wo)) {
1227
+ const t = e, r = Object.fromEntries(
1228
+ o.listInputFields().map((s) => [s, o.traverse({ field: s, errorIfFieldNotSet: !0 }).resourceInfo])
1229
+ );
1230
+ return {
1231
+ type: "JsonPartitioned",
1232
+ partitionKeyLength: t.partitionKeyLength,
1233
+ parts: r
1234
+ };
1235
+ } else if (K(o.resourceType, So)) {
1236
+ const t = e, r = {};
1237
+ for (const s of o.listInputFields()) {
1238
+ const n = o.traverse({ field: s, errorIfFieldNotSet: !0 }), i = n.listInputFields();
1239
+ if (i === void 0) throw new Error(`no partition keys for super key ${s}`);
1240
+ for (const a of i) {
1241
+ const u = s.slice(0, s.length - 1) + "," + a.slice(1, a.length);
1242
+ r[u] = n.traverse({ field: a, errorIfFieldNotSet: !0 }).resourceInfo;
1243
+ }
1244
+ }
1245
+ return {
1246
+ type: "JsonPartitioned",
1247
+ partitionKeyLength: t.superPartitionKeyLength + t.partitionKeyLength,
1248
+ parts: r
1249
+ };
1250
+ } else if (K(o.resourceType, ko)) {
1251
+ const t = e, r = {};
1252
+ for (const s of o.listInputFields())
1253
+ if (s.endsWith(".index")) {
1254
+ const n = s.slice(0, s.length - 6);
1255
+ let i = r[n];
1256
+ i === void 0 && (i = {}, r[n] = i), i.index = o.traverse({ field: s, errorIfFieldNotSet: !0 }).resourceInfo;
1257
+ } else if (s.endsWith(".values")) {
1258
+ const n = s.slice(0, s.length - 7);
1259
+ let i = r[n];
1260
+ i === void 0 && (i = {}, r[n] = i), i.values = o.traverse({ field: s, errorIfFieldNotSet: !0 }).resourceInfo;
1261
+ } else throw new Error(`unrecognized part field name: ${s}`);
1262
+ for (const [s, n] of Object.entries(r)) {
1263
+ if (n.index === void 0) throw new Error(`no index for part ${s}`);
1264
+ if (n.values === void 0) throw new Error(`no values for part ${s}`);
1265
+ }
1266
+ return {
1267
+ type: "BinaryPartitioned",
1268
+ partitionKeyLength: t.partitionKeyLength,
1269
+ parts: r
1270
+ };
1271
+ } else if (K(o.resourceType, Co)) {
1272
+ const t = e, r = {};
1273
+ for (const s of o.listInputFields()) {
1274
+ const n = o.traverse({ field: s, errorIfFieldNotSet: !0 }), i = n.listInputFields();
1275
+ if (i === void 0) throw new Error(`no partition keys for super key ${s}`);
1276
+ for (const a of i)
1277
+ if (a.endsWith(".index")) {
1278
+ const u = a.slice(0, a.length - 6), c = s.slice(0, s.length - 1) + "," + u.slice(1, u.length);
1279
+ let l = r[c];
1280
+ l === void 0 && (l = {}, r[c] = l), r[c].index = n.traverse({
1281
+ field: a,
1282
+ errorIfFieldNotSet: !0
1283
+ }).resourceInfo;
1284
+ } else if (a.endsWith(".values")) {
1285
+ const u = a.slice(0, a.length - 7), c = s.slice(0, s.length - 1) + "," + u.slice(1, u.length);
1286
+ let l = r[c];
1287
+ l === void 0 && (l = {}, r[c] = l), r[c].values = n.traverse({
1288
+ field: a,
1289
+ errorIfFieldNotSet: !0
1290
+ }).resourceInfo;
1291
+ } else throw new Error(`unrecognized part field name: ${a}`);
1292
+ }
1293
+ return {
1294
+ type: "BinaryPartitioned",
1295
+ partitionKeyLength: t.superPartitionKeyLength + t.partitionKeyLength,
1296
+ parts: r
1297
+ };
1298
+ }
1299
+ throw new Error(`unsupported resource type: ${Qt(o.resourceType)}`);
1300
+ }
1301
+ function Ot(o, e) {
1302
+ const t = he("sha256");
1303
+ return t.update(Ee(o)), t.update(String(ce(e.originalId) ? e.id : e.originalId)), t.digest().toString("hex");
1304
+ }
1305
+ function Dt(o, e = !0, t = !1, r = "") {
1306
+ var a, u, c;
1307
+ const s = /^(?<name>.*)\.(?<type>spec|data)$/, n = /* @__PURE__ */ new Map();
1308
+ for (const l of o.listInputFields()) {
1309
+ const p = l.match(s);
1310
+ if (!p) {
1311
+ if (e) throw new Error(`unexpected field name ${l}`);
1312
+ continue;
1313
+ }
1314
+ let h = w((a = p.groups) == null ? void 0 : a.name);
1315
+ if (!h.startsWith(r)) {
1316
+ if (e) throw new Error(`unexpected field name ${l}`);
1317
+ continue;
1318
+ }
1319
+ h = h.slice(r.length);
1320
+ const g = w((u = p.groups) == null ? void 0 : u.type);
1321
+ let b = n.get(h);
1322
+ switch (b === void 0 && (b = {}, n.set(h, b)), g) {
1323
+ case "spec":
1324
+ b.spec = (c = o.traverse({
1325
+ field: l,
1326
+ ignoreError: t,
1327
+ pureFieldErrorToUndefined: t
1328
+ })) == null ? void 0 : c.getDataAsJson();
1329
+ break;
1330
+ case "data":
1331
+ b.hasData = !0, b.data = () => o.traverseOrError({
1332
+ field: l,
1333
+ ignoreError: t
1334
+ });
1335
+ default:
1336
+ continue;
1337
+ }
1338
+ }
1339
+ const i = o.getInputsLocked();
1340
+ if (i)
1341
+ for (const [, l] of n) l.data === void 0 && (l.hasData = !1);
1342
+ return { locked: i, results: n };
1343
+ }
1344
+ function Bo(o, e = !0, t = "") {
1345
+ if (!o.getIsReadyOrError()) throw new Error("resource is not ready");
1346
+ const r = Dt(o, e, !1, t);
1347
+ nr(r.locked);
1348
+ const s = {};
1349
+ for (const [n, i] of r.results) {
1350
+ if (i.spec === void 0) throw new Error(`no spec for key ${n}`);
1351
+ if (i.hasData !== !0 || i.data === void 0)
1352
+ throw new Error(`no data for key ${n}`);
1353
+ const a = i.data();
1354
+ if (a === void 0) throw new Error(`no data for key ${n}`);
1355
+ if (!a.ok) throw new tr(a.error);
1356
+ s[n] = {
1357
+ id: Ot(i.spec, a.value),
1358
+ spec: i.spec,
1359
+ data: a.value
1360
+ };
1361
+ }
1362
+ return s;
1363
+ }
1364
+ class Ne {
1365
+ constructor(e, t) {
1366
+ d(this, "allSpecsAvailable");
1367
+ this.ctx = e, this.blocks = t;
1368
+ let r = !0;
1369
+ e: for (const s of t.values())
1370
+ for (const n of [s.prod, s.staging])
1371
+ if (n !== void 0) {
1372
+ if (!n.locked) {
1373
+ r = !1;
1374
+ break e;
1375
+ }
1376
+ for (const i of n.results.values())
1377
+ if (i.spec === void 0) {
1378
+ r = !1;
1379
+ break e;
1380
+ }
1381
+ }
1382
+ this.allSpecsAvailable = r;
1383
+ }
1384
+ getBlockLabel(e) {
1385
+ var t, r;
1386
+ return w((r = (t = this.blocks.get(e)) == null ? void 0 : t.info) == null ? void 0 : r.label, `block "${e}" not found`);
1387
+ }
1388
+ getData() {
1389
+ const e = this.getDataWithErrors(), t = [];
1390
+ for (const r of e.entries)
1391
+ r.obj.id !== void 0 && r.obj.data.ok && t.push({
1392
+ ref: r.ref,
1393
+ obj: {
1394
+ id: r.obj.id,
1395
+ spec: r.obj.spec,
1396
+ data: r.obj.data.value
1397
+ }
1398
+ });
1399
+ return {
1400
+ entries: t,
1401
+ isComplete: e.isComplete,
1402
+ instabilityMarker: e.instabilityMarker
1403
+ };
1404
+ }
1405
+ getDataWithErrors() {
1406
+ const e = [];
1407
+ let t = !0, r;
1408
+ const s = (i) => {
1409
+ r === void 0 && (r = i), t = !1;
1410
+ }, n = (i, a, u) => {
1411
+ if (u.spec !== void 0 && u.hasData === !0 && u.data !== void 0) {
1412
+ const c = u.data();
1413
+ c !== void 0 ? e.push({
1414
+ ref: se(i, a),
1415
+ obj: {
1416
+ id: c.ok ? Ot(u.spec, c.value) : void 0,
1417
+ spec: u.spec,
1418
+ data: c
1419
+ }
1420
+ }) : s(`no_data:${i}:${a}`);
1421
+ }
1422
+ };
1423
+ for (const [i, a] of this.blocks) {
1424
+ const u = /* @__PURE__ */ new Set();
1425
+ if (a.prod !== void 0) {
1426
+ a.prod.locked || s(`prod_not_locked:${i}`);
1427
+ for (const [c, l] of a.prod.results)
1428
+ u.add(c), n(i, c, l);
1429
+ }
1430
+ if (a.staging !== void 0) {
1431
+ a.staging.locked || s(`staging_not_locked:${i}`);
1432
+ for (const [c, l] of a.staging.results)
1433
+ u.has(c) || n(i, c, l);
1434
+ }
1435
+ }
1436
+ return { entries: e, isComplete: t, instabilityMarker: r };
1437
+ }
1438
+ getSpecs() {
1439
+ const e = [];
1440
+ let t = !0, r;
1441
+ const s = (n) => {
1442
+ r === void 0 && (r = n), t = !1;
1443
+ };
1444
+ for (const [n, i] of this.blocks) {
1445
+ const a = /* @__PURE__ */ new Set();
1446
+ if (i.staging !== void 0) {
1447
+ i.staging.locked || s(`staging_not_locked:${n}`);
1448
+ for (const [u, c] of i.staging.results)
1449
+ c.spec !== void 0 && (e.push({
1450
+ ref: se(n, u),
1451
+ obj: c.spec
1452
+ }), a.add(u));
1453
+ } else s(`staging_not_rendered:${n}`);
1454
+ if (i.prod !== void 0) {
1455
+ i.prod.locked || s(`prod_not_locked:${n}`);
1456
+ for (const [u, c] of i.prod.results)
1457
+ a.has(u) || c.spec !== void 0 && e.push({
1458
+ ref: se(n, u),
1459
+ obj: c.spec
1460
+ });
1461
+ }
1462
+ }
1463
+ return { entries: e, isComplete: t, instabilityMarker: r };
1464
+ }
1465
+ calculateOptions(e) {
1466
+ const t = [];
1467
+ for (const r of this.blocks.values()) {
1468
+ const s = /* @__PURE__ */ new Set(), n = (i) => {
1469
+ for (const [a, u] of i.results)
1470
+ s.has(a) || u.spec === void 0 || (s.add(a), $t(e, u.spec) && t.push({
1471
+ label: r.info.label + " / " + a,
1472
+ ref: se(r.info.id, a),
1473
+ spec: u.spec
1474
+ }));
1475
+ };
1476
+ r.staging !== void 0 && n(r.staging), r.prod !== void 0 && n(r.prod);
1477
+ }
1478
+ return t;
1479
+ }
1480
+ static create(e, t, r) {
1481
+ const s = e.accessor(t).node(), n = w(s.getKeyValueAsJson(G)), a = Re(n).traverseIds("upstream", r), u = /* @__PURE__ */ new Map();
1482
+ for (const c of V(n)) {
1483
+ if (!a.has(c.id)) continue;
1484
+ const l = ot(
1485
+ s.traverse({
1486
+ field: C(c.id, "prodCtx"),
1487
+ ignoreError: !0,
1488
+ pureFieldErrorToUndefined: !0,
1489
+ stableIfNotFound: !0
1490
+ }) !== void 0,
1491
+ s.traverseOrError({
1492
+ field: C(c.id, "prodUiCtx"),
1493
+ stableIfNotFound: !0
1494
+ })
1495
+ ), p = ot(
1496
+ s.traverse({
1497
+ field: C(c.id, "stagingCtx"),
1498
+ ignoreError: !0,
1499
+ pureFieldErrorToUndefined: !0
1500
+ }) !== void 0,
1501
+ s.traverseOrError({
1502
+ field: C(c.id, "stagingUiCtx")
1503
+ })
1504
+ );
1505
+ u.set(c.id, { info: c, prod: l, staging: p });
1506
+ }
1507
+ return new Ne(e, u);
1508
+ }
1509
+ }
1510
+ function ot(o, e) {
1511
+ if (e === void 0)
1512
+ return o ? { locked: !1, results: /* @__PURE__ */ new Map() } : void 0;
1513
+ if (e.ok) return Dt(e.value, !1, !0);
1514
+ }
1515
+ function Le(o, e) {
1516
+ const t = o.persist(), r = w(
1517
+ o.traverse({
1518
+ field: C(e, "currentArgs"),
1519
+ errorIfFieldNotSet: !0
1520
+ }).getDataAsString()
1521
+ ), s = o.getKeyValueAsString(ke(e));
1522
+ return {
1523
+ blockId: e,
1524
+ args: r,
1525
+ uiState: s,
1526
+ blockMeta: (n) => {
1527
+ const i = n.accessor(t).node(), a = w(i.getKeyValueAsJson(G)), u = /* @__PURE__ */ new Map();
1528
+ for (const c of V(a)) u.set(c.id, c);
1529
+ return u;
1530
+ }
1531
+ };
1532
+ }
1533
+ function xt(o, e) {
1534
+ const t = o.persist();
1535
+ return {
1536
+ ...Le(o, e),
1537
+ prod: (r) => {
1538
+ var s;
1539
+ return (s = r.accessor(t).node({ ignoreError: !0 }).traverse({
1540
+ field: C(e, "prodOutput"),
1541
+ stableIfNotFound: !0,
1542
+ ignoreError: !0
1543
+ })) == null ? void 0 : s.persist();
1544
+ },
1545
+ staging: (r) => {
1546
+ var n;
1547
+ const s = (n = r.accessor(t).node({ ignoreError: !0 }).traverse({
1548
+ field: C(e, "stagingOutput"),
1549
+ ignoreError: !0
1550
+ })) == null ? void 0 : n.persist();
1551
+ return s === void 0 && r.markUnstable("staging_not_rendered"), s;
1552
+ },
1553
+ getResultsPool: (r) => Ne.create(r, t, e)
1554
+ };
1555
+ }
1556
+ function* E(o, e) {
1557
+ switch (yield o, o.type) {
1558
+ case "GetFromCtx":
1559
+ case "Immediate":
1560
+ return;
1561
+ case "Isolate":
1562
+ yield* E(o.cfg);
1563
+ return;
1564
+ case "MakeObject":
1565
+ for (const [, t] of Object.entries(o.template)) yield* E(t);
1566
+ return;
1567
+ case "MakeArray":
1568
+ for (const t of o.template) yield* E(t);
1569
+ return;
1570
+ case "GetJsonField":
1571
+ case "GetResourceField":
1572
+ yield* E(o.source), yield* E(o.field);
1573
+ return;
1574
+ case "MapRecordValues":
1575
+ case "MapArrayValues":
1576
+ case "MapResourceFields":
1577
+ yield* E(o.source), yield* E(o.mapping);
1578
+ return;
1579
+ case "Flatten":
1580
+ case "GetResourceValueAsJson":
1581
+ case "GetBlobContent":
1582
+ case "GetBlobContentAsString":
1583
+ case "GetBlobContentAsJson":
1584
+ case "GetDownloadedBlobContent":
1585
+ case "GetOnDemandBlobContent":
1586
+ case "GetImportProgress":
1587
+ case "GetLastLogs":
1588
+ case "GetProgressLog":
1589
+ case "GetLogHandle":
1590
+ yield* E(o.source);
1591
+ return;
1592
+ case "IsEmpty":
1593
+ yield* E(o.arg);
1594
+ return;
1595
+ case "Not":
1596
+ yield* E(o.operand);
1597
+ return;
1598
+ case "And":
1599
+ case "Or":
1600
+ yield* E(o.operand1), yield* E(o.operand2);
1601
+ return;
1602
+ default:
1603
+ D(o);
1604
+ }
1605
+ }
1606
+ function Ro(o, e) {
1607
+ const t = {};
1608
+ for (const [r, s] of Object.entries(o)) t[r] = e(s);
1609
+ return t;
1610
+ }
1611
+ function de(o, e) {
1612
+ return o === void 0 ? void 0 : e(o);
1613
+ }
1614
+ function Oo(o) {
1615
+ switch (o.type) {
1616
+ case "GetImportProgress":
1617
+ return !0;
1618
+ default:
1619
+ return !1;
1620
+ }
1621
+ }
1622
+ function Do(o) {
1623
+ for (const e of E(o)) if (Oo(e)) return !0;
1624
+ return !1;
1625
+ }
1626
+ function fe(o) {
1627
+ return {
1628
+ type: "ReturnResult",
1629
+ result: o
1630
+ };
1631
+ }
1632
+ function f(o) {
1633
+ return () => fe(o);
1634
+ }
1635
+ const xo = (o) => {
1636
+ const e = {};
1637
+ for (const [t, r] of Object.entries(o)) e[t] = r;
1638
+ return f(e);
1639
+ }, Eo = (o) => {
1640
+ const e = o.source;
1641
+ if (e === void 0) return f(void 0);
1642
+ const t = [];
1643
+ for (const r of e)
1644
+ r instanceof Array ? t.push(...r) : t.push(r);
1645
+ return f(t);
1646
+ }, jo = (o) => {
1647
+ const e = o.source, t = o.field;
1648
+ return e === void 0 || t === void 0 ? f(void 0) : ({ cCtx: r }) => {
1649
+ var s;
1650
+ return fe((s = r.accessor(e).node().traverse(t)) == null ? void 0 : s.persist());
1651
+ };
1652
+ };
1653
+ function Et(o, e) {
1654
+ const t = {}, r = o.length;
1655
+ for (let s = 0; s < r; s++) t[String(s)] = e(o[s]);
1656
+ return t;
1657
+ }
1658
+ function To(o, e) {
1659
+ return (t) => {
1660
+ const r = t.source;
1661
+ return r === void 0 ? f(void 0) : () => ({
1662
+ type: "ScheduleSubroutine",
1663
+ subroutine: jt(r.length),
1664
+ args: Et(r, (s) => m({ ...o, [e.itVar]: s }, e.mapping))
1665
+ });
1666
+ };
1667
+ }
1668
+ function jt(o) {
1669
+ return (e) => {
1670
+ const t = [];
1671
+ for (let r = 0; r < o; r++) t.push(e[String(r)]);
1672
+ return f(t);
1673
+ };
1674
+ }
1675
+ function Ao(o, e) {
1676
+ return (t) => {
1677
+ const r = t.source;
1678
+ if (r === void 0) return f(void 0);
1679
+ const s = {};
1680
+ for (const [n, i] of Object.entries(r)) {
1681
+ const a = { ...o, [e.itVar]: i };
1682
+ s[n] = m(a, e.mapping);
1683
+ }
1684
+ return () => ({
1685
+ type: "ScheduleSubroutine",
1686
+ subroutine: Io,
1687
+ args: s
1688
+ });
1689
+ };
1690
+ }
1691
+ const Io = (o) => f(o), Vo = (o) => {
1692
+ const e = o.arg;
1693
+ return f(e === void 0 ? void 0 : e.length === 0);
1694
+ }, No = (o) => {
1695
+ const e = o.operand;
1696
+ return f(e === void 0 ? void 0 : !e);
1697
+ }, Lo = (o) => {
1698
+ const e = o.operand1, t = o.operand2;
1699
+ return f(e === void 0 || t === void 0 ? void 0 : e && t);
1700
+ }, Jo = (o) => {
1701
+ const e = o.operand1, t = o.operand2;
1702
+ return f(e === void 0 || t === void 0 ? void 0 : e || t);
1703
+ }, Ko = (o) => {
1704
+ const e = o.source;
1705
+ return e === void 0 ? f(void 0) : ({ cCtx: t }) => {
1706
+ var r;
1707
+ return fe((r = t.accessor(e).node()) == null ? void 0 : r.getDataAsJson());
1708
+ };
1709
+ }, Mo = (o) => {
1710
+ const e = o.source, t = o.field;
1711
+ return f(e === void 0 || t === void 0 ? void 0 : e[t]);
1712
+ };
1713
+ function $o(o, e) {
1714
+ return (t) => {
1715
+ const r = t.source;
1716
+ return r === void 0 ? f(void 0) : ({ cCtx: s }) => {
1717
+ const n = s.accessor(r).node(), i = {};
1718
+ for (const a of n.listInputFields()) {
1719
+ const u = n.traverse(a);
1720
+ if (u === void 0) i[a] = f(void 0);
1721
+ else {
1722
+ const c = { ...o, [e.itVar]: u.persist() };
1723
+ i[a] = m(c, e.mapping);
1724
+ }
1725
+ }
1726
+ return {
1727
+ type: "ScheduleSubroutine",
1728
+ subroutine: Uo,
1729
+ args: i
1730
+ };
1731
+ };
1732
+ };
1733
+ }
1734
+ const Uo = (o) => f(o), Go = (o) => {
1735
+ const e = o.source;
1736
+ return e === void 0 ? f(void 0) : ({ drivers: t }) => ({
1737
+ type: "ScheduleComputable",
1738
+ computable: P.make(
1739
+ (r) => t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),
1740
+ {
1741
+ postprocessValue: async (r) => {
1742
+ if (r !== void 0)
1743
+ return await t.blobDriver.getContent(r.handle);
1744
+ }
1745
+ }
1746
+ )
1747
+ });
1748
+ }, Ho = (o) => {
1749
+ const e = o.source;
1750
+ return e === void 0 ? f(void 0) : ({ cCtx: t, drivers: r }) => {
1751
+ const s = t.accessor(e).node().resourceInfo;
1752
+ return {
1753
+ type: "ScheduleComputable",
1754
+ computable: P.make(() => r.blobDriver.getDownloadedBlob(s), {
1755
+ postprocessValue: async (n) => n === void 0 ? void 0 : (await r.blobDriver.getContent(n.handle)).toString()
1756
+ })
1757
+ };
1758
+ };
1759
+ }, _o = (o) => {
1760
+ const e = o.source;
1761
+ return e === void 0 ? f(void 0) : ({ drivers: t }) => ({
1762
+ type: "ScheduleComputable",
1763
+ computable: P.make(
1764
+ (r) => t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),
1765
+ {
1766
+ postprocessValue: async (r) => {
1767
+ if (r == null) return;
1768
+ const s = await t.blobDriver.getContent(r.handle);
1769
+ if (s != null)
1770
+ return JSON.parse(Buffer.from(s).toString());
1771
+ }
1772
+ }
1773
+ )
1774
+ });
1775
+ }, Wo = (o) => {
1776
+ const e = o.source;
1777
+ return e === void 0 ? f(void 0) : ({ drivers: t }) => ({
1778
+ type: "ScheduleComputable",
1779
+ computable: t.blobDriver.getDownloadedBlob(e)
1780
+ });
1781
+ }, zo = (o) => {
1782
+ const e = o.source;
1783
+ return e === void 0 ? f(void 0) : ({ drivers: t }) => ({
1784
+ type: "ScheduleComputable",
1785
+ computable: t.blobDriver.getOnDemandBlob(e)
1786
+ });
1787
+ }, qo = (o) => {
1788
+ const e = o.source;
1789
+ return e === void 0 ? f(void 0) : ({ drivers: t }) => ({
1790
+ type: "ScheduleComputable",
1791
+ computable: t.uploadDriver.getProgressId(e)
1792
+ });
1793
+ }, Yo = (o) => (e) => {
1794
+ const t = e.source;
1795
+ return t === void 0 ? f(void 0) : ({ drivers: r }) => ({
1796
+ type: "ScheduleComputable",
1797
+ computable: r.logDriver.getLastLogs(t, o)
1798
+ });
1799
+ }, Qo = (o) => (e) => {
1800
+ const t = e.source;
1801
+ return t === void 0 ? f(void 0) : ({ drivers: r }) => ({
1802
+ type: "ScheduleComputable",
1803
+ computable: r.logDriver.getProgressLog(t, o)
1804
+ });
1805
+ }, Zo = (o) => {
1806
+ const e = o.source;
1807
+ return e === void 0 ? f(void 0) : ({ drivers: t }) => ({
1808
+ type: "ScheduleComputable",
1809
+ computable: t.logDriver.getLogHandle(e)
1810
+ });
1811
+ };
1812
+ function m(o, e) {
1813
+ switch (e.type) {
1814
+ case "GetFromCtx":
1815
+ const t = o[e.variable];
1816
+ return typeof t == "function" ? (r) => fe(t(r.cCtx)) : (t === void 0 && console.log("asdasd"), f(t));
1817
+ case "Isolate":
1818
+ return ({ drivers: r }) => ({
1819
+ type: "ScheduleComputable",
1820
+ computable: Vt(r, o, e.cfg)
1821
+ });
1822
+ case "Immediate":
1823
+ return f(e.value);
1824
+ case "GetJsonField":
1825
+ return () => ({
1826
+ type: "ScheduleSubroutine",
1827
+ subroutine: Mo,
1828
+ args: {
1829
+ source: m(o, e.source),
1830
+ field: m(o, e.field)
1831
+ }
1832
+ });
1833
+ case "MapArrayValues":
1834
+ return () => ({
1835
+ type: "ScheduleSubroutine",
1836
+ subroutine: To(o, e),
1837
+ args: {
1838
+ source: m(o, e.source)
1839
+ }
1840
+ });
1841
+ case "MapRecordValues":
1842
+ return () => ({
1843
+ type: "ScheduleSubroutine",
1844
+ subroutine: Ao(o, e),
1845
+ args: {
1846
+ source: m(o, e.source)
1847
+ }
1848
+ });
1849
+ case "MakeObject":
1850
+ return () => ({
1851
+ type: "ScheduleSubroutine",
1852
+ subroutine: xo,
1853
+ args: Ro(e.template, (r) => m(o, r))
1854
+ });
1855
+ case "MakeArray":
1856
+ return () => ({
1857
+ type: "ScheduleSubroutine",
1858
+ subroutine: jt(e.template.length),
1859
+ args: Et(e.template, (r) => m(o, r))
1860
+ });
1861
+ case "Flatten":
1862
+ return () => ({
1863
+ type: "ScheduleSubroutine",
1864
+ subroutine: Eo,
1865
+ args: {
1866
+ source: m(o, e.source)
1867
+ }
1868
+ });
1869
+ case "IsEmpty":
1870
+ return () => ({
1871
+ type: "ScheduleSubroutine",
1872
+ subroutine: Vo,
1873
+ args: {
1874
+ arg: m(o, e.arg)
1875
+ }
1876
+ });
1877
+ case "Not":
1878
+ return () => ({
1879
+ type: "ScheduleSubroutine",
1880
+ subroutine: No,
1881
+ args: {
1882
+ operand: m(o, e.operand)
1883
+ }
1884
+ });
1885
+ case "And":
1886
+ return () => ({
1887
+ type: "ScheduleSubroutine",
1888
+ subroutine: Lo,
1889
+ args: {
1890
+ operand1: m(o, e.operand1),
1891
+ operand2: m(o, e.operand2)
1892
+ }
1893
+ });
1894
+ case "Or":
1895
+ return () => ({
1896
+ type: "ScheduleSubroutine",
1897
+ subroutine: Jo,
1898
+ args: {
1899
+ operand1: m(o, e.operand1),
1900
+ operand2: m(o, e.operand2)
1901
+ }
1902
+ });
1903
+ case "MapResourceFields":
1904
+ return () => ({
1905
+ type: "ScheduleSubroutine",
1906
+ subroutine: $o(o, e),
1907
+ args: {
1908
+ source: m(o, e.source)
1909
+ }
1910
+ });
1911
+ case "GetResourceField":
1912
+ return () => ({
1913
+ type: "ScheduleSubroutine",
1914
+ subroutine: jo,
1915
+ args: {
1916
+ source: m(o, e.source),
1917
+ field: m(o, e.field)
1918
+ }
1919
+ });
1920
+ case "GetResourceValueAsJson":
1921
+ return () => ({
1922
+ type: "ScheduleSubroutine",
1923
+ subroutine: Ko,
1924
+ args: {
1925
+ source: m(o, e.source)
1926
+ }
1927
+ });
1928
+ case "GetBlobContent":
1929
+ return () => ({
1930
+ type: "ScheduleSubroutine",
1931
+ subroutine: Go,
1932
+ args: {
1933
+ source: m(o, e.source)
1934
+ }
1935
+ });
1936
+ case "GetBlobContentAsString":
1937
+ return () => ({
1938
+ type: "ScheduleSubroutine",
1939
+ subroutine: Ho,
1940
+ args: {
1941
+ source: m(o, e.source)
1942
+ }
1943
+ });
1944
+ case "GetBlobContentAsJson":
1945
+ return () => ({
1946
+ type: "ScheduleSubroutine",
1947
+ subroutine: _o,
1948
+ args: {
1949
+ source: m(o, e.source)
1950
+ }
1951
+ });
1952
+ case "GetDownloadedBlobContent":
1953
+ return () => ({
1954
+ type: "ScheduleSubroutine",
1955
+ subroutine: Wo,
1956
+ args: {
1957
+ source: m(o, e.source)
1958
+ }
1959
+ });
1960
+ case "GetOnDemandBlobContent":
1961
+ return () => ({
1962
+ type: "ScheduleSubroutine",
1963
+ subroutine: zo,
1964
+ args: {
1965
+ source: m(o, e.source)
1966
+ }
1967
+ });
1968
+ case "GetImportProgress":
1969
+ return () => ({
1970
+ type: "ScheduleSubroutine",
1971
+ subroutine: qo,
1972
+ args: {
1973
+ source: m(o, e.source)
1974
+ }
1975
+ });
1976
+ case "GetLastLogs":
1977
+ return () => ({
1978
+ type: "ScheduleSubroutine",
1979
+ subroutine: Yo(e.lines),
1980
+ args: {
1981
+ source: m(o, e.source)
1982
+ }
1983
+ });
1984
+ case "GetProgressLog":
1985
+ return () => ({
1986
+ type: "ScheduleSubroutine",
1987
+ subroutine: Qo(e.patternToSearch),
1988
+ args: {
1989
+ source: m(o, e.source)
1990
+ }
1991
+ });
1992
+ case "GetLogHandle":
1993
+ return () => ({
1994
+ type: "ScheduleSubroutine",
1995
+ subroutine: Zo,
1996
+ args: {
1997
+ source: m(o, e.source)
1998
+ }
1999
+ });
2000
+ default:
2001
+ return D(e);
2002
+ }
2003
+ }
2004
+ const Xo = ["$prod", "$staging"];
2005
+ function es(o) {
2006
+ return {
2007
+ $blockId: o.blockId,
2008
+ $args: JSON.parse(o.args),
2009
+ $ui: o.uiState !== void 0 ? JSON.parse(o.uiState) : void 0,
2010
+ $prod: o.prod,
2011
+ $staging: o.staging
2012
+ };
2013
+ }
2014
+ const Tt = Symbol(), At = "return", ts = { op: Tt, arg: At };
2015
+ function rs(o) {
2016
+ return o.op == Tt && o.arg == At;
2017
+ }
2018
+ function os() {
2019
+ return { pendingSubroutines: /* @__PURE__ */ new Map() };
2020
+ }
2021
+ function st(o, e, t, r) {
2022
+ const s = new ft(t), n = (a, u) => {
2023
+ if (rs(a))
2024
+ return e.result = u, !1;
2025
+ const c = w(e.pendingSubroutines.get(a.op));
2026
+ if (a.arg in c.args) throw new Error("argument already set");
2027
+ return c.args[a.arg] = u, c.argCounter--, c.argCounter === 0 && (e.pendingSubroutines.delete(a.op), s.push({
2028
+ destination: c.destination,
2029
+ operation: c.subroutine(c.args)
2030
+ })), !0;
2031
+ }, i = [];
2032
+ e: for (; s.length > 0; ) {
2033
+ const a = s.shift(), u = a.operation(o);
2034
+ switch (u.type) {
2035
+ case "ReturnResult":
2036
+ if (!n(a.destination, u.result)) break e;
2037
+ break;
2038
+ case "ScheduleSubroutine":
2039
+ const c = Symbol(), l = Object.entries(u.args), p = l.length;
2040
+ if (p === 0)
2041
+ s.push({
2042
+ destination: a.destination,
2043
+ operation: u.subroutine({})
2044
+ });
2045
+ else {
2046
+ for (const [h, g] of l)
2047
+ s.push({
2048
+ destination: { op: c, arg: h },
2049
+ operation: g
2050
+ });
2051
+ e.pendingSubroutines.set(c, {
2052
+ argCounter: p,
2053
+ args: {},
2054
+ subroutine: u.subroutine,
2055
+ destination: a.destination
2056
+ });
2057
+ }
2058
+ break;
2059
+ case "ScheduleComputable":
2060
+ if (!r)
2061
+ throw new Error("asynchronous operations are forbidden in this context");
2062
+ i.push({
2063
+ destination: a.destination,
2064
+ computable: u.computable
2065
+ });
2066
+ break;
2067
+ default:
2068
+ D(u);
2069
+ }
2070
+ }
2071
+ return i;
2072
+ }
2073
+ function It(o, e, t, r = {}) {
2074
+ return Vt(o, es(e), t, r);
2075
+ }
2076
+ function Vt(o, e, t, r = {}) {
2077
+ const s = Ee({
2078
+ ctx: Object.fromEntries(Object.entries(e).filter(([n]) => Xo.indexOf(n) === -1)),
2079
+ cfg: t
2080
+ });
2081
+ return P.makeRaw(
2082
+ (n) => {
2083
+ const i = { drivers: o, cCtx: n }, a = os();
2084
+ return {
2085
+ ir: st(
2086
+ i,
2087
+ a,
2088
+ [
2089
+ {
2090
+ destination: ts,
2091
+ operation: m(e, t)
2092
+ }
2093
+ ],
2094
+ !0
2095
+ ),
2096
+ async postprocessValue(c, l) {
2097
+ const p = [];
2098
+ for (const B of c)
2099
+ p.push({ destination: B.destination, operation: f(B.computable) });
2100
+ const h = {
2101
+ drivers: o,
2102
+ get cCtx() {
2103
+ throw new Error("asynchronous operations are forbidden in this context");
2104
+ }
2105
+ }, g = /* @__PURE__ */ new Map();
2106
+ for (const [B, M] of a.pendingSubroutines)
2107
+ g.set(B, { ...M, args: { ...M.args } });
2108
+ const b = {
2109
+ result: a.result,
2110
+ pendingSubroutines: g
2111
+ };
2112
+ if (st(h, b, p, !1), !("result" in b))
2113
+ throw new Error("illegal cfg rendering stack state, no result");
2114
+ return b.result;
2115
+ }
2116
+ };
2117
+ },
2118
+ { ...r, key: s }
2119
+ );
2120
+ }
2121
+ function ss(o) {
2122
+ return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
2123
+ }
2124
+ function nt(o) {
2125
+ return o !== void 0 ? Buffer.from(o).toString("base64") : void 0;
2126
+ }
2127
+ class pe {
2128
+ constructor(e, t, r, s, n) {
2129
+ d(this, "callbackRegistry");
2130
+ d(this, "fnJSONStringify");
2131
+ d(this, "fnJSONParse");
2132
+ d(this, "computablesToResolve", {});
2133
+ d(this, "computableCtx");
2134
+ d(this, "accessors", /* @__PURE__ */ new Map());
2135
+ d(this, "meta");
2136
+ //
2137
+ // Result Pool
2138
+ //
2139
+ d(this, "_resultPool");
2140
+ if (this.scope = e, this.vm = t, this.blockCtx = r, this.env = s, this.computableCtx = n, this.callbackRegistry = this.scope.manage(this.vm.newObject()), this.fnJSONStringify = e.manage(
2141
+ t.getProp(t.global, "JSON").consume((i) => t.getProp(i, "stringify"))
2142
+ ), t.typeof(this.fnJSONStringify) !== "function")
2143
+ throw new Error("JSON.stringify() not found.");
2144
+ if (this.fnJSONParse = e.manage(
2145
+ t.getProp(t.global, "JSON").consume((i) => t.getProp(i, "parse"))
2146
+ ), t.typeof(this.fnJSONParse) !== "function") throw new Error("JSON.parse() not found.");
2147
+ this.meta = r.blockMeta(n), this.injectCtx();
2148
+ }
2149
+ resetComputableCtx() {
2150
+ this.computableCtx = void 0, this.accessors.clear();
2151
+ }
2152
+ static cleanErrorContext(e) {
2153
+ typeof e == "object" && e !== null && "context" in e && delete e.context;
2154
+ }
2155
+ evaluateBundle(e) {
2156
+ try {
2157
+ this.vm.unwrapResult(this.vm.evalCode(e, "bundle.js", { type: "global" })).dispose();
2158
+ } catch (t) {
2159
+ throw pe.cleanErrorContext(t), t;
2160
+ }
2161
+ }
2162
+ runCallback(e, ...t) {
2163
+ try {
2164
+ return Se.withScope((r) => {
2165
+ const s = r.manage(this.vm.getProp(this.callbackRegistry, e));
2166
+ if (this.vm.typeof(s) !== "function")
2167
+ throw new Error(`No such callback: ${e}`);
2168
+ return this.scope.manage(
2169
+ this.vm.unwrapResult(
2170
+ this.vm.callFunction(
2171
+ s,
2172
+ this.vm.undefined,
2173
+ ...t.map((n) => this.exportObjectUniversal(n, r))
2174
+ )
2175
+ )
2176
+ );
2177
+ });
2178
+ } catch (r) {
2179
+ throw pe.cleanErrorContext(r), r;
2180
+ }
2181
+ }
2182
+ //
2183
+ // Methods for injected ctx object
2184
+ //
2185
+ getAccessorHandleByName(e) {
2186
+ if (this.computableCtx === void 0)
2187
+ throw new Error("Accessors can't be used in this context");
2188
+ const t = (r, s) => {
2189
+ if (!this.accessors.has(r)) {
2190
+ const n = this.blockCtx[s];
2191
+ if (n === void 0) throw new Error("Staging context not available");
2192
+ const i = n(this.computableCtx);
2193
+ i ? this.accessors.set(r, this.computableCtx.accessor(i).node({ ignoreError: !0 })) : this.accessors.set(r, void 0);
2194
+ }
2195
+ return this.accessors.get(r) ? r : void 0;
2196
+ };
2197
+ if (e === "staging") return t("staging", "staging");
2198
+ if (e === "main") return t("main", "prod");
2199
+ }
2200
+ //
2201
+ // Accessors
2202
+ //
2203
+ resolveWithCommon(e, t, ...r) {
2204
+ return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t, ...r));
2205
+ }
2206
+ getResourceType(e) {
2207
+ return this.getAccessor(e).resourceType;
2208
+ }
2209
+ getInputsLocked(e) {
2210
+ return this.getAccessor(e).getInputsLocked();
2211
+ }
2212
+ getOutputsLocked(e) {
2213
+ return this.getAccessor(e).getOutputsLocked();
2214
+ }
2215
+ getIsReadyOrError(e) {
2216
+ return this.getAccessor(e).getIsReadyOrError();
2217
+ }
2218
+ getIsFinal(e) {
2219
+ return this.getAccessor(e).getIsFinal();
2220
+ }
2221
+ getError(e) {
2222
+ return this.wrapAccessor(this.getAccessor(e).getError());
2223
+ }
2224
+ listInputFields(e) {
2225
+ return this.getAccessor(e).listInputFields();
2226
+ }
2227
+ listOutputFields(e) {
2228
+ return this.getAccessor(e).listOutputFields();
2229
+ }
2230
+ listDynamicFields(e) {
2231
+ return this.getAccessor(e).listDynamicFields();
2232
+ }
2233
+ getKeyValueBase64(e, t) {
2234
+ return nt(this.getAccessor(e).getKeyValue(t));
2235
+ }
2236
+ getKeyValueAsString(e, t) {
2237
+ return this.getAccessor(e).getKeyValueAsString(t);
2238
+ }
2239
+ getDataBase64(e) {
2240
+ return nt(this.getAccessor(e).getData());
2241
+ }
2242
+ getDataAsString(e) {
2243
+ return this.getAccessor(e).getDataAsString();
2244
+ }
2245
+ //
2246
+ // Accessor helpers
2247
+ //
2248
+ parsePObjectCollection(e, t, r) {
2249
+ const s = this.getAccessor(e);
2250
+ if (!s.getIsReadyOrError()) return;
2251
+ const n = Bo(s, t, r), i = {};
2252
+ for (const [a, u] of Object.entries(n))
2253
+ i[a] = z(u, (c) => this.wrapAccessor(c));
2254
+ return i;
2255
+ }
2256
+ //
2257
+ // Blobs
2258
+ //
2259
+ registerComputable(e, t) {
2260
+ const r = `${e}_${Y()}`;
2261
+ return this.computablesToResolve[r] = t, r;
2262
+ }
2263
+ getBlobContentAsString(e) {
2264
+ const t = this.getAccessor(e).resourceInfo;
2265
+ return this.registerComputable(
2266
+ "getBlobContentAsString",
2267
+ P.make((r) => this.env.driverKit.blobDriver.getDownloadedBlob(t, r), {
2268
+ postprocessValue: async (r) => {
2269
+ if (r !== void 0)
2270
+ return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString(
2271
+ "utf-8"
2272
+ );
2273
+ }
2274
+ })
2275
+ );
2276
+ }
2277
+ getBlobContentAsBase64(e) {
2278
+ const t = this.getAccessor(e).resourceInfo;
2279
+ return this.registerComputable(
2280
+ "getBlobContentAsBase64",
2281
+ P.make((r) => this.env.driverKit.blobDriver.getDownloadedBlob(t, r), {
2282
+ postprocessValue: async (r) => {
2283
+ if (r !== void 0)
2284
+ return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString(
2285
+ "base64"
2286
+ );
2287
+ }
2288
+ })
2289
+ );
2290
+ }
2291
+ getDownloadedBlobContentHandle(e) {
2292
+ const t = this.getAccessor(e).resourceInfo;
2293
+ return this.registerComputable(
2294
+ "getDownloadedBlobContentHandle",
2295
+ this.env.driverKit.blobDriver.getDownloadedBlob(t)
2296
+ );
2297
+ }
2298
+ getOnDemandBlobContentHandle(e) {
2299
+ const t = this.getAccessor(e).persist();
2300
+ return this.registerComputable(
2301
+ "getOnDemandBlobContentHandle",
2302
+ this.env.driverKit.blobDriver.getOnDemandBlob(t)
2303
+ );
2304
+ }
2305
+ //
2306
+ // Import progress
2307
+ //
2308
+ getImportProgress(e) {
2309
+ const t = this.getAccessor(e).persist();
2310
+ return this.registerComputable(
2311
+ "getImportProgress",
2312
+ this.env.driverKit.uploadDriver.getProgressId(t)
2313
+ );
2314
+ }
2315
+ //
2316
+ // Logs
2317
+ //
2318
+ getLastLogs(e, t) {
2319
+ const r = this.getAccessor(e).persist();
2320
+ return this.registerComputable(
2321
+ "getLastLogs",
2322
+ this.env.driverKit.logDriver.getLastLogs(r, t)
2323
+ );
2324
+ }
2325
+ getProgressLog(e, t) {
2326
+ const r = this.getAccessor(e).persist();
2327
+ return this.registerComputable(
2328
+ "getProgressLog",
2329
+ this.env.driverKit.logDriver.getProgressLog(r, t)
2330
+ );
2331
+ }
2332
+ getLogHandle(e) {
2333
+ const t = this.getAccessor(e).persist();
2334
+ return this.registerComputable(
2335
+ "getLogHandle",
2336
+ this.env.driverKit.logDriver.getLogHandle(t)
2337
+ );
2338
+ }
2339
+ //
2340
+ // Blocks
2341
+ //
2342
+ getBlockLabel(e) {
2343
+ const t = this.meta.get(e);
2344
+ if (t === void 0) throw new Error(`Block ${e} not found.`);
2345
+ return t.label;
2346
+ }
2347
+ get resultPool() {
2348
+ if (this._resultPool === void 0) {
2349
+ if (this.computableCtx === void 0)
2350
+ throw new Error(
2351
+ "can't use result pool in this context (most porbably called from the future mapper)"
2352
+ );
2353
+ this._resultPool = w(
2354
+ this.blockCtx.getResultsPool,
2355
+ "getResultsPool"
2356
+ )(this.computableCtx);
2357
+ }
2358
+ return this._resultPool;
2359
+ }
2360
+ calculateOptions(e) {
2361
+ return this.resultPool.calculateOptions(e);
2362
+ }
2363
+ getDataFromResultPool() {
2364
+ const e = this.resultPool.getData();
2365
+ return e.instabilityMarker !== void 0 && this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`), {
2366
+ isComplete: e.isComplete,
2367
+ entries: e.entries.map((t) => ({
2368
+ ref: t.ref,
2369
+ obj: z(t.obj, (r) => this.wrapAccessor(r))
2370
+ }))
2371
+ };
2372
+ }
2373
+ getDataWithErrorsFromResultPool() {
2374
+ const e = this.resultPool.getDataWithErrors();
2375
+ return e.instabilityMarker !== void 0 && this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`), {
2376
+ isComplete: e.isComplete,
2377
+ entries: e.entries.map((t) => ({
2378
+ ref: t.ref,
2379
+ obj: {
2380
+ id: t.obj.id,
2381
+ spec: t.obj.spec,
2382
+ data: Ut(t.obj.data, (r) => this.wrapAccessor(r))
2383
+ }
2384
+ }))
2385
+ };
2386
+ }
2387
+ getSpecsFromResultPool() {
2388
+ const e = this.resultPool.getSpecs();
2389
+ return e.instabilityMarker !== void 0 && this.computableCtx.markUnstable(`specs_from_pool_incomplete:${e.instabilityMarker}`), e;
2390
+ }
2391
+ //
2392
+ // PFrames / PTables
2393
+ //
2394
+ createPFrame(e) {
2395
+ if (this.computableCtx === void 0)
2396
+ throw new Error(
2397
+ "can't instantiate PFrames from this context (most porbably called from the future mapper)"
2398
+ );
2399
+ return this.env.driverKit.pFrameDriver.createPFrame(
2400
+ e.map((t) => z(t, (r) => this.getAccessor(r))),
2401
+ this.computableCtx
2402
+ );
2403
+ }
2404
+ createPTable(e) {
2405
+ if (this.computableCtx === void 0)
2406
+ throw new Error(
2407
+ "can't instantiate PTable from this context (most porbably called from the future mapper)"
2408
+ );
2409
+ return this.env.driverKit.pFrameDriver.createPTable(
2410
+ ct(e, (t) => z(t, (r) => this.getAccessor(r))),
2411
+ this.computableCtx
2412
+ );
2413
+ }
2414
+ //
2415
+ // Helpers
2416
+ //
2417
+ getAccessor(e) {
2418
+ const t = this.accessors.get(e);
2419
+ if (t === void 0) throw new Error("No such accessor");
2420
+ return t;
2421
+ }
2422
+ wrapAccessor(e) {
2423
+ if (e !== void 0) {
2424
+ const t = Y();
2425
+ return this.accessors.set(t, e), t;
2426
+ }
2427
+ }
2428
+ //
2429
+ // QuickJS Helpers
2430
+ //
2431
+ exportSingleValue(e, t) {
2432
+ const r = this.tryExportSingleValue(e, t);
2433
+ if (r === void 0) throw new Error(`Can't export value: ${e}`);
2434
+ return r;
2435
+ }
2436
+ tryExportSingleValue(e, t) {
2437
+ let r, s = !1;
2438
+ switch (typeof e) {
2439
+ case "string":
2440
+ r = this.vm.newString(e), s = !0;
2441
+ break;
2442
+ case "number":
2443
+ r = this.vm.newNumber(e), s = !0;
2444
+ break;
2445
+ case "undefined":
2446
+ r = this.vm.undefined;
2447
+ break;
2448
+ case "boolean":
2449
+ r = e ? this.vm.true : this.vm.false;
2450
+ break;
2451
+ default:
2452
+ if (e === null) {
2453
+ r = this.vm.null;
2454
+ break;
2455
+ }
2456
+ if (ss(e)) {
2457
+ r = this.vm.newArrayBuffer(e), s = !0;
2458
+ break;
2459
+ }
2460
+ return;
2461
+ }
2462
+ return s && t != null ? t.manage(r) : r;
2463
+ }
2464
+ exportObjectUniversal(e, t) {
2465
+ const r = this.tryExportSingleValue(e, t);
2466
+ return r !== void 0 ? r : this.exportObjectViaJson(e, t);
2467
+ }
2468
+ exportObjectViaJson(e, t) {
2469
+ const r = this.vm.newString(JSON.stringify(e)).consume(
2470
+ (s) => this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse, this.vm.undefined, s))
2471
+ );
2472
+ return t !== void 0 ? t.manage(r) : r;
2473
+ }
2474
+ importObjectUniversal(e) {
2475
+ switch (this.vm.typeof(e)) {
2476
+ case "undefined":
2477
+ return;
2478
+ case "boolean":
2479
+ case "number":
2480
+ case "string":
2481
+ return this.vm.dump(e);
2482
+ default:
2483
+ return this.importObjectViaJson(e);
2484
+ }
2485
+ }
2486
+ importObjectViaJson(e) {
2487
+ const t = this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify, this.vm.undefined, e)).consume((r) => this.vm.getString(r));
2488
+ if (t !== "undefined")
2489
+ return JSON.parse(t);
2490
+ }
2491
+ injectCtx() {
2492
+ Se.withScope((e) => {
2493
+ const t = e.manage(this.vm.newObject());
2494
+ this.vm.setProp(t, "args", e.manage(this.vm.newString(this.blockCtx.args))), this.blockCtx.uiState !== void 0 && this.vm.setProp(
2495
+ t,
2496
+ "uiState",
2497
+ e.manage(this.vm.newString(this.blockCtx.uiState))
2498
+ ), this.vm.setProp(t, "callbackRegistry", this.callbackRegistry);
2499
+ const r = (s, n) => {
2500
+ this.vm.newFunction(s, n).consume((i) => this.vm.setProp(t, s, i));
2501
+ };
2502
+ r("getAccessorHandleByName", (s) => this.exportSingleValue(
2503
+ this.getAccessorHandleByName(this.vm.getString(s)),
2504
+ void 0
2505
+ )), r("resolveWithCommon", (s, n, ...i) => this.exportSingleValue(
2506
+ this.resolveWithCommon(
2507
+ this.vm.getString(s),
2508
+ this.importObjectViaJson(n),
2509
+ ...i.map(
2510
+ (a) => this.importObjectViaJson(a)
2511
+ )
2512
+ ),
2513
+ void 0
2514
+ )), r("getResourceType", (s) => this.exportObjectViaJson(this.getResourceType(this.vm.getString(s)), void 0)), r("getInputsLocked", (s) => this.exportSingleValue(this.getInputsLocked(this.vm.getString(s)), void 0)), r("getOutputsLocked", (s) => this.exportSingleValue(this.getOutputsLocked(this.vm.getString(s)), void 0)), r("getIsReadyOrError", (s) => this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(s)), void 0)), r("getIsFinal", (s) => this.exportSingleValue(this.getIsFinal(this.vm.getString(s)), void 0)), r("getError", (s) => this.exportSingleValue(this.getError(this.vm.getString(s)), void 0)), r("listInputFields", (s) => this.exportObjectViaJson(this.listInputFields(this.vm.getString(s)), void 0)), r("listOutputFields", (s) => this.exportObjectViaJson(this.listInputFields(this.vm.getString(s)), void 0)), r("listDynamicFields", (s) => this.exportObjectViaJson(this.listInputFields(this.vm.getString(s)), void 0)), r("getKeyValueBase64", (s, n) => this.exportSingleValue(
2515
+ this.getKeyValueBase64(this.vm.getString(s), this.vm.getString(n)),
2516
+ void 0
2517
+ )), r("getKeyValueAsString", (s, n) => this.exportSingleValue(
2518
+ this.getKeyValueAsString(this.vm.getString(s), this.vm.getString(n)),
2519
+ void 0
2520
+ )), r("getDataBase64", (s) => this.exportSingleValue(this.getDataBase64(this.vm.getString(s)), void 0)), r("getDataAsString", (s) => this.exportSingleValue(this.getDataAsString(this.vm.getString(s)), void 0)), r("parsePObjectCollection", (s, n, i) => this.exportObjectUniversal(
2521
+ this.parsePObjectCollection(
2522
+ this.vm.getString(s),
2523
+ this.vm.dump(n),
2524
+ this.vm.getString(i)
2525
+ ),
2526
+ void 0
2527
+ )), r("getBlobContentAsBase64", (s) => this.exportSingleValue(
2528
+ this.getBlobContentAsBase64(this.vm.getString(s)),
2529
+ void 0
2530
+ )), r("getBlobContentAsString", (s) => this.exportSingleValue(
2531
+ this.getBlobContentAsString(this.vm.getString(s)),
2532
+ void 0
2533
+ )), r("getDownloadedBlobContentHandle", (s) => this.exportSingleValue(
2534
+ this.getDownloadedBlobContentHandle(this.vm.getString(s)),
2535
+ void 0
2536
+ )), r("getOnDemandBlobContentHandle", (s) => this.exportSingleValue(
2537
+ this.getOnDemandBlobContentHandle(this.vm.getString(s)),
2538
+ void 0
2539
+ )), r("getImportProgress", (s) => this.exportSingleValue(this.getImportProgress(this.vm.getString(s)), void 0)), r("getLastLogs", (s, n) => this.exportSingleValue(
2540
+ this.getLastLogs(this.vm.getString(s), this.vm.getNumber(n)),
2541
+ void 0
2542
+ )), r("getProgressLog", (s, n) => this.exportSingleValue(
2543
+ this.getProgressLog(this.vm.getString(s), this.vm.getString(n)),
2544
+ void 0
2545
+ )), r("getLogHandle", (s) => this.exportSingleValue(this.getLogHandle(this.vm.getString(s)), void 0)), r("getBlockLabel", (s) => this.exportSingleValue(this.getBlockLabel(this.vm.getString(s)), void 0)), r("getDataFromResultPool", (s) => this.exportObjectUniversal(this.getDataFromResultPool(), void 0)), r("getDataWithErrorsFromResultPool", (s) => this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(), void 0)), r("getSpecsFromResultPool", (s) => this.exportObjectUniversal(this.getSpecsFromResultPool(), void 0)), r("calculateOptions", (s) => this.exportObjectUniversal(
2546
+ this.calculateOptions(this.importObjectViaJson(s)),
2547
+ void 0
2548
+ )), r("createPFrame", (s) => this.exportSingleValue(
2549
+ this.createPFrame(this.importObjectViaJson(s)),
2550
+ void 0
2551
+ )), r("createPTable", (s) => this.exportSingleValue(
2552
+ this.createPTable(this.importObjectViaJson(s)),
2553
+ void 0
2554
+ )), this.vm.setProp(this.vm.global, "cfgRenderCtx", t);
2555
+ });
2556
+ }
2557
+ }
2558
+ function ns(o, e, t, r, s = {}) {
2559
+ return P.makeRaw((n) => {
2560
+ const i = new Se();
2561
+ n.addOnDestroy(() => i.dispose());
2562
+ const a = i.manage(o.quickJs.newRuntime());
2563
+ a.setMemoryLimit(1024 * 640), a.setMaxStackSize(1024 * 320);
2564
+ const u = i.manage(a.newContext()), c = new pe(i, u, e, o, n);
2565
+ c.evaluateBundle(r.content);
2566
+ const l = c.runCallback(t);
2567
+ return c.resetComputableCtx(), {
2568
+ ir: c.computablesToResolve,
2569
+ postprocessValue: async (p) => {
2570
+ for (const [h, g] of Object.entries(p)) c.runCallback(h, g);
2571
+ return c.importObjectUniversal(l);
2572
+ }
2573
+ };
2574
+ }, s);
2575
+ }
2576
+ function De(o, e, t, r, s = {}) {
2577
+ if (ut(t)) {
2578
+ if (r === void 0) throw new Error("No code bundle.");
2579
+ return ns(o, e, t, r, s);
2580
+ } else return It(o.driverKit, e, t, s);
2581
+ }
2582
+ function is(o, e, t) {
2583
+ return P.make(
2584
+ (r) => {
2585
+ var b, B, M, ee, te, $, H, re;
2586
+ const s = r.accessor(o).node(), n = w(s.getKeyValueAsJson(Ie)), i = w(s.getKeyValueAsJson(Q)), a = w(s.getKeyValueAsJson(Z)), u = w(s.getKeyValueAsJson(G)), c = w(
2587
+ s.getKeyValueAsJson(ue)
2588
+ ), l = /* @__PURE__ */ new Map();
2589
+ for (const { id: k } of V(u)) {
2590
+ const L = s.traverse({
2591
+ field: C(k, "currentArgs"),
2592
+ assertFieldType: "Dynamic",
2593
+ errorIfFieldNotSet: !0
2594
+ });
2595
+ let _;
2596
+ const j = s.traverse({
2597
+ field: C(k, "prodArgs"),
2598
+ assertFieldType: "Dynamic",
2599
+ stableIfNotFound: !0
2600
+ });
2601
+ if (j !== void 0) {
2602
+ const x = s.getField({
2603
+ field: C(k, "prodOutput"),
2604
+ assertFieldType: "Dynamic",
2605
+ errorIfFieldNotFound: !0
2606
+ }), R = s.getField({
2607
+ field: C(k, "prodUiCtx"),
2608
+ assertFieldType: "Dynamic",
2609
+ errorIfFieldNotFound: !0
2610
+ });
2611
+ _ = {
2612
+ arguments: j.getDataAsJson(),
2613
+ stale: L.id !== j.id,
2614
+ outputError: x.error !== void 0 || R.error !== void 0 || ((b = x.value) == null ? void 0 : b.getError()) !== void 0 || ((B = R.value) == null ? void 0 : B.getError()) !== void 0,
2615
+ outputsError: ((M = x.error) == null ? void 0 : M.getDataAsString()) ?? ((te = (ee = x.value) == null ? void 0 : ee.getError()) == null ? void 0 : te.getDataAsString()),
2616
+ exportsError: (($ = R.error) == null ? void 0 : $.getDataAsString()) ?? ((re = (H = R.value) == null ? void 0 : H.getError()) == null ? void 0 : re.getDataAsString()),
2617
+ finished: (x.value !== void 0 && x.value.getIsReadyOrError() || x.error !== void 0 && x.error.getIsReadyOrError()) && (R.value !== void 0 && R.value.getIsReadyOrError() || R.error !== void 0 && R.error.getIsReadyOrError())
2618
+ };
2619
+ }
2620
+ l.set(k, { currentArguments: L.getDataAsJson(), prod: _ });
2621
+ }
2622
+ const p = ie(u, (k) => l.get(k).currentArguments), h = new Set(c.blocksInLimbo), g = [...V(u)].map(({ id: k, label: L, renderingMode: _ }) => {
2623
+ var Ke, Me, $e, Ue;
2624
+ const j = w(l.get(k)), x = w(p.nodes.get(k));
2625
+ let R = "NotCalculated";
2626
+ j.prod !== void 0 && (h.has(k) ? R = "Limbo" : R = j.prod.finished ? "Done" : "Running");
2627
+ const J = s.traverse(
2628
+ {
2629
+ field: C(k, "blockPack"),
2630
+ assertFieldType: "Dynamic",
2631
+ errorIfFieldNotSet: !0
2632
+ },
2633
+ { field: y.HolderRefField, assertFieldType: "Input", errorIfFieldNotFound: !0 }
2634
+ ), N = J == null ? void 0 : J.getDataAsJson(), { sections: oe, inputsValid: v, sdkVersion: O } = de(N == null ? void 0 : N.config, (ge) => {
2635
+ const W = xe(ge), Ge = Le(s, k);
2636
+ return {
2637
+ sections: De(
2638
+ t,
2639
+ Ge,
2640
+ W.sections,
2641
+ W.code
2642
+ ),
2643
+ inputsValid: De(
2644
+ t,
2645
+ Ge,
2646
+ W.inputsValid,
2647
+ W.code
2648
+ ),
2649
+ sdkVersion: W.sdkVersion
2650
+ };
2651
+ }) || {}, F = de(
2652
+ N,
2653
+ (ge) => t.blockUpdateWatcher.get(ge.source, r)
2654
+ );
2655
+ return {
2656
+ id: k,
2657
+ label: L,
2658
+ renderingMode: _,
2659
+ stale: ((Ke = j.prod) == null ? void 0 : Ke.stale) !== !1 || R === "Limbo",
2660
+ missingReference: x.missingReferences,
2661
+ upstreams: [...p.traverseIdsExcludingRoots("upstream", k)],
2662
+ downstreams: [...p.traverseIdsExcludingRoots("downstream", k)],
2663
+ calculationStatus: R,
2664
+ outputErrors: ((Me = j.prod) == null ? void 0 : Me.outputError) === !0,
2665
+ outputsError: ($e = j.prod) == null ? void 0 : $e.outputsError,
2666
+ exportsError: (Ue = j.prod) == null ? void 0 : Ue.exportsError,
2667
+ sections: oe,
2668
+ inputsValid: v,
2669
+ currentBlockPack: N == null ? void 0 : N.source,
2670
+ updatedBlockPack: F,
2671
+ sdkVersion: O,
2672
+ navigationState: e.getState(k)
2673
+ };
2674
+ });
2675
+ return {
2676
+ meta: a,
2677
+ created: new Date(n),
2678
+ lastModified: new Date(i),
2679
+ authorMarker: s.getKeyValueAsJson(Pe),
2680
+ blocks: g
2681
+ };
2682
+ },
2683
+ {
2684
+ postprocessValue: (r) => {
2685
+ const s = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set();
2686
+ return {
2687
+ ...r,
2688
+ blocks: r.blocks.map((i) => {
2689
+ i.inputsValid || s.add(i.id), i.stale && n.add(i.id);
2690
+ const a = i.stale || i.upstreams.findIndex((c) => n.has(c)) !== -1, u = a && !!i.inputsValid && !i.missingReference && i.upstreams.findIndex((c) => s.has(c)) === -1;
2691
+ return { ...i, canRun: u, stale: a };
2692
+ })
2693
+ };
2694
+ }
2695
+ }
2696
+ ).withStableType();
2697
+ }
2698
+ function Nt(o, e) {
2699
+ var t, r;
2700
+ return de(
2701
+ (r = (t = o.traverse(
2702
+ {
2703
+ field: C(e, "blockPack"),
2704
+ assertFieldType: "Dynamic",
2705
+ errorIfFieldNotSet: !0
2706
+ },
2707
+ { field: y.HolderRefField, assertFieldType: "Input", errorIfFieldNotFound: !0 }
2708
+ )) == null ? void 0 : t.getDataAsJson()) == null ? void 0 : r.config,
2709
+ (s) => xe(s)
2710
+ );
2711
+ }
2712
+ function as(o, e) {
2713
+ const t = o.node();
2714
+ if (K(t.resourceType, kt)) {
2715
+ const r = t.getDataAsJson();
2716
+ if (r === void 0) throw new Error("No resource data.");
2717
+ return e.frontendDownloadDriver.getPath(new URL(r.url)).withStableType();
2718
+ } else if (K(t.resourceType, Ct)) {
2719
+ const r = t.getDataAsJson();
2720
+ if (r === void 0) throw new Error("No resource data.");
2721
+ return e.signer.verify(
2722
+ r.path,
2723
+ r.signature,
2724
+ `Frontend path signature mismatch for: ${r.path}`
2725
+ ), r.path;
2726
+ } else
2727
+ throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`);
2728
+ }
2729
+ function cs(o, e) {
2730
+ if (o !== void 0)
2731
+ return P.make(
2732
+ (t) => as(t.accessor(o), e),
2733
+ {
2734
+ postprocessValue: (t) => {
2735
+ if (t !== void 0) {
2736
+ if (typeof t == "string") return t;
2737
+ if (t.error !== void 0) throw new Error(t.error);
2738
+ return t.path;
2739
+ }
2740
+ }
2741
+ }
2742
+ ).withStableType();
2743
+ }
2744
+ function us(o, e, t) {
2745
+ return P.make(
2746
+ (r) => {
2747
+ var a;
2748
+ const s = r.accessor(o).node(), n = Nt(s, e), i = (a = s.traverse(
2749
+ {
2750
+ field: C(e, "blockPack"),
2751
+ assertFieldType: "Dynamic"
2752
+ },
2753
+ { field: y.HolderRefField, assertFieldType: "Input", errorIfFieldNotFound: !0 },
2754
+ { field: Ft, assertFieldType: "Input" }
2755
+ )) == null ? void 0 : a.persist();
2756
+ return { path: cs(i, t), sdkVersion: n == null ? void 0 : n.sdkVersion };
2757
+ },
2758
+ { mode: "StableOnlyLive" }
2759
+ );
2760
+ }
2761
+ function ls(o, e, t) {
2762
+ return P.make(
2763
+ (r) => {
2764
+ const s = r.accessor(o).node(), n = Le(s, e);
2765
+ return {
2766
+ author: s.getKeyValueAsJson(Ce(e)),
2767
+ args: JSON.parse(n.args),
2768
+ ui: n.uiState !== void 0 ? JSON.parse(n.uiState) : void 0
2769
+ };
2770
+ },
2771
+ { key: "inputs#" + pt(o.rid) + e }
2772
+ );
2773
+ }
2774
+ function ds(o, e, t) {
2775
+ return P.make(
2776
+ (r) => {
2777
+ const s = r.accessor(o).node(), n = xt(s, e), i = Nt(s, e);
2778
+ return de(i, (a) => {
2779
+ const u = {};
2780
+ for (const [c, l] of Object.entries(a.outputs))
2781
+ u[c] = P.wrapError(
2782
+ De(t, n, l, a.code)
2783
+ );
2784
+ return u;
2785
+ });
2786
+ },
2787
+ { key: "outputs#" + pt(o.rid) + e }
2788
+ ).withStableType();
2789
+ }
2790
+ function ps(o, e) {
2791
+ return P.make((t) => {
2792
+ const r = t.accessor(o).node(), s = w(r.getKeyValueAsJson(G)), n = [];
2793
+ for (const { id: i, renderingMode: a } of V(s)) {
2794
+ const u = r.traverse(
2795
+ {
2796
+ field: C(i, "blockPack"),
2797
+ assertFieldType: "Dynamic",
2798
+ errorIfFieldNotSet: !0
2799
+ },
2800
+ { field: y.HolderRefField, assertFieldType: "Input", errorIfFieldNotFound: !0 }
2801
+ ), c = u == null ? void 0 : u.getDataAsJson();
2802
+ if ((c == null ? void 0 : c.config) === void 0) continue;
2803
+ const l = xe(c.config), p = Object.entries(l.outputs).map(([, g]) => g).filter((g) => !ut(g) && Do(g)).map((g) => g);
2804
+ if (p.length === 0) continue;
2805
+ const h = xt(r, i);
2806
+ for (const g of p)
2807
+ n.push(P.wrapError(It(e.driverKit, h, g)));
2808
+ }
2809
+ return n;
2810
+ });
2811
+ }
2812
+ class hs {
2813
+ constructor() {
2814
+ d(this, "states", /* @__PURE__ */ new Map());
2815
+ }
2816
+ setState(e, t) {
2817
+ const r = this.states.get(e);
2818
+ if (r === void 0) {
2819
+ this.states.set(e, { state: t, change: new We() });
2820
+ return;
2821
+ }
2822
+ r.state = { ...t }, r.change.markChanged();
2823
+ }
2824
+ readState(e, t) {
2825
+ let r = this.states.get(t);
2826
+ return r === void 0 && (r = { state: { ...Gt }, change: new We() }, this.states.set(t, r)), r.change.attachWatcher(e.watcher), r.state;
2827
+ }
2828
+ getState(e) {
2829
+ return P.make(
2830
+ (t) => this.readState(t, e),
2831
+ { key: `navigationState#${e}` }
2832
+ );
2833
+ }
2834
+ deleteBlock(e) {
2835
+ const t = this.states.get(e);
2836
+ t !== void 0 && (this.states.delete(e), t.change.markChanged());
2837
+ }
2838
+ }
2839
+ class Je {
2840
+ constructor(e, t, r) {
2841
+ /** Underlying pl resource id */
2842
+ d(this, "rid");
2843
+ /** Data for the left panel, contain basic information about block status. */
2844
+ d(this, "overview");
2845
+ d(this, "navigationStates", new hs());
2846
+ d(this, "blockComputables", /* @__PURE__ */ new Map());
2847
+ d(this, "blockFrontends", /* @__PURE__ */ new Map());
2848
+ d(this, "activeConfigs");
2849
+ d(this, "refreshLoopResult");
2850
+ d(this, "abortController", new AbortController());
2851
+ d(this, "destroyed", !1);
2852
+ this.env = e, this.projectTree = r, this.overview = is(
2853
+ r.entry(),
2854
+ this.navigationStates,
2855
+ e
2856
+ ).withPreCalculatedValueTree(), this.rid = t, this.refreshLoopResult = this.refreshLoop(), this.activeConfigs = ps(r.entry(), e);
2857
+ }
2858
+ async refreshLoop() {
2859
+ for (; !this.destroyed; )
2860
+ try {
2861
+ await be(this.env.pl, this.rid, (e) => {
2862
+ e.doRefresh(this.env.ops.stagingRenderingRate);
2863
+ }), await this.activeConfigs.getValue(), await ar(this.env.ops.projectRefreshInterval, this.abortController.signal);
2864
+ } catch (e) {
2865
+ if (Zt(e)) {
2866
+ console.warn(
2867
+ "project refresh routine terminated, because project was externally deleted"
2868
+ );
2869
+ break;
2870
+ } else if (!Xt(e))
2871
+ throw new Error("Unexpected exception", { cause: e });
2872
+ }
2873
+ }
2874
+ /**
2875
+ * Adds new block to the project.
2876
+ *
2877
+ * @param blockLabel block label / title visible to the user
2878
+ * @param blockPackSpec object describing the "block type", read more in the type docs
2879
+ * @param before id of the block to insert new block before
2880
+ * @param blockId internal id to be assigned for the block, this arg can be omitted
2881
+ * then, randomly generated UUID will be assigned automatically
2882
+ *
2883
+ * @return returns newly created block id
2884
+ * */
2885
+ async addBlock(e, t, r, s = void 0, n = Y()) {
2886
+ const i = await this.env.bpPreparer.prepare(t), a = await this.env.bpPreparer.getBlockConfig(t);
2887
+ return await A(
2888
+ this.env.pl,
2889
+ this.rid,
2890
+ s,
2891
+ (u) => u.addBlock(
2892
+ {
2893
+ id: n,
2894
+ label: e,
2895
+ renderingMode: a.renderingMode
2896
+ },
2897
+ {
2898
+ args: JSON.stringify(a.initialArgs),
2899
+ blockPack: i
2900
+ },
2901
+ r
2902
+ )
2903
+ ), await this.projectTree.refreshState(), n;
2904
+ }
2905
+ /**
2906
+ * Update block to new block pack, optionally resetting args and ui state to
2907
+ * initial values
2908
+ * */
2909
+ async updateBlockPack(e, t, r = !1, s) {
2910
+ const n = await this.env.bpPreparer.prepare(t), i = await this.env.bpPreparer.getBlockConfig(t);
2911
+ await A(
2912
+ this.env.pl,
2913
+ this.rid,
2914
+ s,
2915
+ (a) => a.migrateBlockPack(
2916
+ e,
2917
+ n,
2918
+ r ? JSON.stringify(i.initialArgs) : void 0
2919
+ )
2920
+ ), await this.projectTree.refreshState();
2921
+ }
2922
+ /** Deletes a block with all associated data. */
2923
+ async deleteBlock(e, t) {
2924
+ await A(this.env.pl, this.rid, t, (r) => r.deleteBlock(e)), this.navigationStates.deleteBlock(e), await this.projectTree.refreshState();
2925
+ }
2926
+ /**
2927
+ * Updates block order according to the given array of block ids.
2928
+ *
2929
+ * Provided array must contain exactly the same set of ids current project cosists of,
2930
+ * an error will be thrown instead.
2931
+ */
2932
+ async reorderBlocks(e, t) {
2933
+ await A(this.env.pl, this.rid, t, (r) => {
2934
+ const s = r.structure;
2935
+ if (s.groups.length !== 1)
2936
+ throw new Error("Unexpected project structure, non-sinular block group");
2937
+ const n = s.groups[0];
2938
+ if (n.blocks.length !== e.length)
2939
+ throw new Error(`Lengh mismatch: ${n.blocks.length} !== ${e.length}`);
2940
+ if (new Set(e).size !== e.length) throw new Error("Repeated block ids");
2941
+ const i = {
2942
+ groups: [
2943
+ {
2944
+ id: n.id,
2945
+ label: n.label,
2946
+ blocks: e.map((a) => {
2947
+ const u = n.blocks.find((c) => c.id === a);
2948
+ if (u === void 0) throw new Error(`Can't find block: ${a}`);
2949
+ return u;
2950
+ })
2951
+ }
2952
+ ]
2953
+ };
2954
+ r.updateStructure(i);
2955
+ }), await this.projectTree.refreshState();
2956
+ }
2957
+ /**
2958
+ * Renders production part of the block starting all connected heavy computations.
2959
+ * Upstream blocks of the specified block will be started automatically if in
2960
+ * stale state.
2961
+ * */
2962
+ async runBlock(e) {
2963
+ await be(this.env.pl, this.rid, (t) => t.renderProduction([e], !0)), await this.projectTree.refreshState();
2964
+ }
2965
+ /**
2966
+ * Stops the block if it is running by destroying its production state. All
2967
+ * its downstreams will also be destroyed or moved to limbo if already
2968
+ * calculated.
2969
+ * */
2970
+ async stopBlock(e) {
2971
+ await be(this.env.pl, this.rid, (t) => t.stopProduction(e)), await this.projectTree.refreshState();
2972
+ }
2973
+ /** Update block label. */
2974
+ async setBlockLabel(e, t, r) {
2975
+ await A(this.env.pl, this.rid, r, (s) => {
2976
+ s.setBlockLabel(e, t);
2977
+ }), await this.projectTree.refreshState();
2978
+ }
2979
+ /**
2980
+ * Sets block args, and changes whole project state accordingly.
2981
+ * Along with setting arguments one can specify author marker, that will be
2982
+ * transactionally associated with the block, to facilitate conflict resolution
2983
+ * in collaborative editing scenario.
2984
+ * */
2985
+ async setBlockArgs(e, t, r) {
2986
+ await A(
2987
+ this.env.pl,
2988
+ this.rid,
2989
+ r,
2990
+ (s) => s.setArgs([{ blockId: e, args: JSON.stringify(t) }])
2991
+ ), await this.projectTree.refreshState();
2992
+ }
2993
+ /**
2994
+ * Sets ui block state associated with the block.
2995
+ * Along with setting arguments one can specify author marker, that will be
2996
+ * transactionally associated with the block, to facilitate conflict resolution
2997
+ * in collaborative editing scenario.
2998
+ * */
2999
+ async setUiState(e, t, r) {
3000
+ await A(
3001
+ this.env.pl,
3002
+ this.rid,
3003
+ r,
3004
+ (s) => s.setUiState(e, t === void 0 ? void 0 : JSON.stringify(t))
3005
+ ), await this.projectTree.refreshState();
3006
+ }
3007
+ /**
3008
+ * Sets navigation state.
3009
+ * */
3010
+ async setNavigationState(e, t) {
3011
+ this.navigationStates.setState(e, t);
3012
+ }
3013
+ /**
3014
+ * Sets block args and ui state, and changes the whole project state accordingly.
3015
+ * Along with setting arguments one can specify author marker, that will be
3016
+ * transactionally associated with the block, to facilitate conflict resolution
3017
+ * in collaborative editing scenario.
3018
+ * */
3019
+ async setBlockArgsAndUiState(e, t, r, s) {
3020
+ await A(this.env.pl, this.rid, s, (n) => {
3021
+ n.setArgs([{ blockId: e, args: JSON.stringify(t) }]), n.setUiState(e, JSON.stringify(r));
3022
+ }), await this.projectTree.refreshState();
3023
+ }
3024
+ /** Resets arguments and ui state of the block to initial state */
3025
+ async resetBlockArgsAndUiState(e, t) {
3026
+ await this.env.pl.withWriteTx("BlockInputsReset", async (r) => {
3027
+ const s = we(
3028
+ (await r.getField(S(this.rid, C(e, "blockPack")))).value
3029
+ ), n = we(
3030
+ (await r.getField(S(s, y.HolderRefField))).value
3031
+ ), i = await r.getResourceData(n, !1), a = JSON.parse(
3032
+ Buffer.from(w(i.data)).toString("utf-8")
3033
+ );
3034
+ await A(r, this.rid, t, (u) => {
3035
+ u.setArgs([{ blockId: e, args: JSON.stringify(a.config.initialArgs) }]), u.setUiState(e, void 0);
3036
+ }), await r.commit();
3037
+ }), await this.projectTree.refreshState();
3038
+ }
3039
+ getBlockComputables(e) {
3040
+ const t = this.blockComputables.get(e);
3041
+ if (t === void 0) {
3042
+ const r = ds(this.projectTree.entry(), e, this.env), n = {
3043
+ fullState: P.make(
3044
+ (i) => ({
3045
+ argsAndUiState: ls(this.projectTree.entry(), e),
3046
+ outputs: r,
3047
+ navigationState: this.navigationStates.getState(e)
3048
+ }),
3049
+ {
3050
+ postprocessValue: (i) => ({
3051
+ ...i.argsAndUiState,
3052
+ outputs: i.outputs,
3053
+ navigationState: i.navigationState
3054
+ })
3055
+ }
3056
+ ).withPreCalculatedValueTree()
3057
+ };
3058
+ return this.blockComputables.set(e, n), n;
3059
+ }
3060
+ return t;
3061
+ }
3062
+ /**
3063
+ * Returns a computable, that can be used to retrieve and watch full block state,
3064
+ * including outputs, arguments, ui state.
3065
+ * */
3066
+ getBlockState(e) {
3067
+ return this.getBlockComputables(e).fullState;
3068
+ }
3069
+ /**
3070
+ * Returns a computable, that can be used to retrieve and watch path of the
3071
+ * folder containing frontend code.
3072
+ * */
3073
+ getBlockFrontend(e) {
3074
+ const t = this.blockFrontends.get(e);
3075
+ if (t === void 0) {
3076
+ const r = us(
3077
+ this.projectTree.entry(),
3078
+ e,
3079
+ this.env
3080
+ ).withPreCalculatedValueTree();
3081
+ return this.blockFrontends.set(e, r), r;
3082
+ }
3083
+ return t;
3084
+ }
3085
+ /** Called by middle layer on close */
3086
+ async destroy() {
3087
+ this.destroyed = !0, this.abortController.abort(), await this.refreshLoopResult, await this.projectTree.terminate(), this.overview.resetState(), this.blockFrontends.forEach((e) => e.resetState()), this.blockComputables.forEach((e) => {
3088
+ e.fullState.resetState();
3089
+ }), this.activeConfigs.resetState();
3090
+ }
3091
+ /** @deprecated */
3092
+ async destroyAndAwaitTermination() {
3093
+ await this.destroy();
3094
+ }
3095
+ static async init(e, t) {
3096
+ const r = await ht.init(e.pl, t, e.ops.defaultTreeOptions);
3097
+ return new Je(e, t, r);
3098
+ }
3099
+ }
3100
+ const Lt = {
3101
+ platformLocalStorageNameToPath: {},
3102
+ localStorageNameToPath: { local: gt.homedir() },
3103
+ blobDriverOps: {
3104
+ cacheSoftSizeBytes: 100 * 1024 * 1024,
3105
+ // 100MB
3106
+ nConcurrentDownloads: 10
3107
+ },
3108
+ uploadDriverOps: {
3109
+ nConcurrentPartUploads: 10,
3110
+ nConcurrentGetProgresses: 10,
3111
+ pollingInterval: 1e3,
3112
+ stopPollingDelay: 1e3
3113
+ },
3114
+ logStreamDriverOps: {
3115
+ nConcurrentGetLogs: 10,
3116
+ pollingInterval: 1e3,
3117
+ stopPollingDelay: 1e3
3118
+ }
3119
+ }, fs = {
3120
+ ...Lt,
3121
+ defaultTreeOptions: {
3122
+ pollingInterval: 350,
3123
+ stopPollingDelay: 2500
3124
+ },
3125
+ devBlockUpdateRecheckInterval: 1e3,
3126
+ projectRefreshInterval: 700,
3127
+ stagingRenderingRate: 5
3128
+ }, gs = {
3129
+ minDelay: 1500
3130
+ }, ms = "__no_updates__";
3131
+ class vs extends rr {
3132
+ constructor(t = {}) {
3133
+ super({ ...t, ...gs });
3134
+ d(this, "http");
3135
+ this.http = t.http;
3136
+ }
3137
+ getKey(t) {
3138
+ switch (t.type) {
3139
+ case "dev":
3140
+ case "dev-v1":
3141
+ return `dev_1_${t.folder}_${t.mtime}`;
3142
+ case "dev-v2":
3143
+ return `dev_2_${t.folder}_${t.mtime}`;
3144
+ default:
3145
+ return ms;
3146
+ }
3147
+ }
3148
+ async readValue(t) {
3149
+ try {
3150
+ switch (t.type) {
3151
+ case "dev":
3152
+ case "dev-v1": {
3153
+ const r = await vt(t.folder);
3154
+ return r === t.mtime ? void 0 : { ...t, mtime: r };
3155
+ }
3156
+ case "dev-v2": {
3157
+ const r = await lt(t.folder);
3158
+ if (r === void 0) return;
3159
+ const s = await Ae(r);
3160
+ return s === t.mtime ? void 0 : { ...t, mtime: s };
3161
+ }
3162
+ default:
3163
+ return;
3164
+ }
3165
+ } catch {
3166
+ return;
3167
+ }
3168
+ }
3169
+ resultsEqual(t, r) {
3170
+ if (t === void 0 && r === void 0) return !0;
3171
+ if (t === void 0 || r === void 0) return !1;
3172
+ if (t.type === "from-registry-v1" || r.type === "from-registry-v1")
3173
+ throw new Error("Unexpected, not yet supported.");
3174
+ return t.folder === r.folder && t.mtime === r.mtime;
3175
+ }
3176
+ }
3177
+ class it {
3178
+ constructor() {
3179
+ d(this, "resources", /* @__PURE__ */ new Map());
3180
+ }
3181
+ check(e) {
3182
+ const t = this.resources.get(e);
3183
+ if (t === void 0) throw new Error("Unexpected state.");
3184
+ if (t.refCount === 0) {
3185
+ this.resources.delete(e);
3186
+ const r = t.resource;
3187
+ r != null && typeof r[Symbol.dispose] == "function" && r[Symbol.dispose]();
3188
+ }
3189
+ }
3190
+ acquire(e) {
3191
+ const t = this.calculateParamsKey(e);
3192
+ let r = this.resources.get(t);
3193
+ r === void 0 && (r = { refCount: 0, resource: this.createNewResource(e) }, this.resources.set(t, r)), r.refCount++;
3194
+ let s = !1;
3195
+ return {
3196
+ resource: r.resource,
3197
+ key: t,
3198
+ unref: () => {
3199
+ s || (r.refCount--, s = !0, this.check(t));
3200
+ }
3201
+ };
3202
+ }
3203
+ getByKey(e) {
3204
+ if (!this.resources.has(e)) throw new Error(`resource not found, key = ${e}`);
3205
+ return this.resources.get(e).resource;
3206
+ }
3207
+ tryGetByKey(e) {
3208
+ var t;
3209
+ return (t = this.resources.get(e)) == null ? void 0 : t.resource;
3210
+ }
3211
+ }
3212
+ const ys = require("@milaboratories/pframes-node");
3213
+ function at(o) {
3214
+ return String(o.id);
3215
+ }
3216
+ class bs {
3217
+ constructor(e, t) {
3218
+ d(this, "pFrame", new ys.PFrame());
3219
+ d(this, "blobIdToResource", /* @__PURE__ */ new Map());
3220
+ d(this, "blobHandleComputables", /* @__PURE__ */ new Map());
3221
+ d(this, "preloadBlob", async (e) => {
3222
+ const t = e.map((r) => this.getOrCreateComputableForBlob(r));
3223
+ for (const r of t) await r.awaitStableFullValue();
3224
+ });
3225
+ d(this, "resolveBlob", async (e) => {
3226
+ const t = this.getOrCreateComputableForBlob(e);
3227
+ return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);
3228
+ });
3229
+ this.blobDriver = e, this.columns = t, this.pFrame.setDataSource(this);
3230
+ for (const r of t) {
3231
+ for (const n of yo(r.data)) this.blobIdToResource.set(at(n), n);
3232
+ const s = bo(r.data, at);
3233
+ try {
3234
+ this.pFrame.addColumnSpec(r.id, r.spec), this.pFrame.setColumnData(r.id, s);
3235
+ } catch (n) {
3236
+ throw new Error(
3237
+ `Adding column ${r.id} to PFrame failed: ${n}; Spec: ${r.spec}, DataInfo: ${s}.`
3238
+ );
3239
+ }
3240
+ }
3241
+ }
3242
+ getOrCreateComputableForBlob(e) {
3243
+ let t = this.blobHandleComputables.get(e);
3244
+ if (t !== void 0) return t;
3245
+ const r = this.blobIdToResource.get(e);
3246
+ if (r === void 0) throw new Error(`Blob with id ${e} not found.`);
3247
+ return t = this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(), this.blobHandleComputables.set(e, t), t;
3248
+ }
3249
+ [Symbol.dispose]() {
3250
+ for (const e of this.blobHandleComputables.values()) e.resetState();
3251
+ this.pFrame.dispose();
3252
+ }
3253
+ }
3254
+ class ws {
3255
+ constructor(e) {
3256
+ d(this, "pFrames");
3257
+ d(this, "pTables");
3258
+ this.blobDriver = e, this.pFrames = new class extends it {
3259
+ constructor(t) {
3260
+ super(), this.blobDriver = t;
3261
+ }
3262
+ createNewResource(t) {
3263
+ return new bs(this.blobDriver, t);
3264
+ }
3265
+ calculateParamsKey(t) {
3266
+ return ks(t);
3267
+ }
3268
+ }(this.blobDriver), this.pTables = new class extends it {
3269
+ constructor(t) {
3270
+ super(), this.pFrames = t;
3271
+ }
3272
+ async createNewResource(t) {
3273
+ const s = await this.pFrames.getByKey(t.pFrameHandle).pFrame.createTable({
3274
+ src: q(t.def.src),
3275
+ filters: t.def.filters
3276
+ });
3277
+ return t.def.sorting.length !== 0 ? s.sort(t.def.sorting) : s;
3278
+ }
3279
+ calculateParamsKey(t) {
3280
+ return Ss(t);
3281
+ }
3282
+ }(this.pFrames);
3283
+ }
3284
+ //
3285
+ // Internal / Config API Methods
3286
+ //
3287
+ createPFrame(e, t) {
3288
+ const r = e.map((n) => z(n, (i) => Fo(i))), s = this.pFrames.acquire(r);
3289
+ return t.addOnDestroy(s.unref), s.key;
3290
+ }
3291
+ createPTable(e, t) {
3292
+ const r = this.createPFrame(Cs(e.src), t), s = ct(e, (i) => i.id), n = this.pTables.acquire({ def: s, pFrameHandle: r });
3293
+ return t.addOnDestroy(n.unref), n.key;
3294
+ }
3295
+ //
3296
+ // PFrame istance methods
3297
+ //
3298
+ async findColumns(e, t) {
3299
+ const r = {
3300
+ ...t,
3301
+ compatibleWith: t.compatibleWith.length !== 0 ? [{ axesSpec: t.compatibleWith, qualifications: [] }] : []
3302
+ };
3303
+ return {
3304
+ hits: (await this.pFrames.getByKey(e).pFrame.findColumns(r)).hits.map(
3305
+ (s) => s.hit
3306
+ )
3307
+ };
3308
+ }
3309
+ async getColumnSpec(e, t) {
3310
+ return this.pFrames.getByKey(e).pFrame.getColumnSpec(t);
3311
+ }
3312
+ async listColumns(e) {
3313
+ return this.pFrames.getByKey(e).pFrame.listColumns();
3314
+ }
3315
+ async calculateTableData(e, t) {
3316
+ let r = await this.pFrames.getByKey(e).pFrame.createTable({
3317
+ src: q(t.src),
3318
+ filters: t.filters
3319
+ });
3320
+ if (t.sorting.length > 0) {
3321
+ const i = await r.sort(t.sorting);
3322
+ r.dispose(), r = i;
3323
+ }
3324
+ const s = r.getSpec(), n = await r.getData([...s.keys()]);
3325
+ return r.dispose(), s.map((i, a) => ({
3326
+ spec: i,
3327
+ data: n[a]
3328
+ }));
3329
+ }
3330
+ async getUniqueValues(e, t) {
3331
+ return await this.pFrames.getByKey(e).pFrame.getUniqueValues(t);
3332
+ }
3333
+ //
3334
+ // PTable istance methods
3335
+ //
3336
+ async getShape(e) {
3337
+ return (await this.pTables.getByKey(e)).getShape();
3338
+ }
3339
+ async getSpec(e) {
3340
+ return (await this.pTables.getByKey(e)).getSpec();
3341
+ }
3342
+ async getData(e, t, r) {
3343
+ return (await this.pTables.getByKey(e)).getData(t, r);
3344
+ }
3345
+ }
3346
+ function q(o) {
3347
+ switch (o.type) {
3348
+ case "column":
3349
+ return {
3350
+ type: "column",
3351
+ columnId: o.column,
3352
+ qualifications: []
3353
+ };
3354
+ case "inner":
3355
+ case "full":
3356
+ return {
3357
+ type: o.type,
3358
+ entries: o.entries.map((e) => q(e))
3359
+ };
3360
+ case "outer":
3361
+ return {
3362
+ type: "outer",
3363
+ primary: q(o.primary),
3364
+ secondary: o.secondary.map((e) => q(e))
3365
+ };
3366
+ default:
3367
+ D(o);
3368
+ }
3369
+ }
3370
+ function Ss(o) {
3371
+ const e = he("sha256");
3372
+ return e.update(o.pFrameHandle), e.update(Ee(o.def)), e.digest().toString("hex");
3373
+ }
3374
+ function ks(o) {
3375
+ const e = o.map((s) => s.id).sort(), t = he("sha256");
3376
+ let r = "";
3377
+ for (const s of e)
3378
+ r !== s && (t.update(s), r = s);
3379
+ return t.digest().toString("hex");
3380
+ }
3381
+ function Cs(o) {
3382
+ const e = /* @__PURE__ */ new Map();
3383
+ return ae(o, e), [...e.values()];
3384
+ }
3385
+ function ae(o, e) {
3386
+ switch (o.type) {
3387
+ case "column":
3388
+ e.set(o.column.id, o.column);
3389
+ return;
3390
+ case "full":
3391
+ case "inner":
3392
+ for (const t of o.entries) ae(t, e);
3393
+ return;
3394
+ case "outer":
3395
+ ae(o.primary, e);
3396
+ for (const t of o.secondary) ae(t, e);
3397
+ return;
3398
+ default:
3399
+ D(o);
3400
+ }
3401
+ }
3402
+ async function Ps(o, e, t) {
3403
+ const r = { ...Lt, ...t };
3404
+ Fs(e, r);
3405
+ const s = new dt(r.localSecret), n = cr(e, o, r.platformLocalStorageNameToPath), i = ur(o, e), a = lr(o, e), u = dr(o, e), c = pr(o, e), l = new hr(
3406
+ e,
3407
+ n,
3408
+ i,
3409
+ r.blobDownloadPath,
3410
+ s,
3411
+ r.blobDriverOps
3412
+ ), p = new fr(
3413
+ e,
3414
+ s,
3415
+ a,
3416
+ u,
3417
+ r.uploadDriverOps
3418
+ ), h = new gr(i, r.logStreamDriverOps), g = new mr(h, l), b = new vr(e, c, o, s, r.localStorageNameToPath), B = new ws(l);
3419
+ return {
3420
+ blobDriver: l,
3421
+ logDriver: g,
3422
+ lsDriver: b,
3423
+ signer: s,
3424
+ uploadDriver: p,
3425
+ pFrameDriver: B
3426
+ };
3427
+ }
3428
+ function Fs(o, e) {
3429
+ e.localStorageNameToPath.local != gt.homedir() && o.warn(`'local' storage with homedir was overwrote: ${e.localStorageNameToPath.local}`);
3430
+ const t = Object.keys(e.platformLocalStorageNameToPath), r = Object.keys(e.localStorageNameToPath).find(
3431
+ (s) => t.includes(s)
3432
+ );
3433
+ if (r)
3434
+ throw new Error(
3435
+ `Platform local storages include one or more local storages: ${r}. Note that we automatically included 'local' storage with user's home directory.`
3436
+ );
3437
+ }
3438
+ class Jt {
3439
+ constructor(e, t, r, s, n, i, a) {
3440
+ d(this, "pl");
3441
+ /** Contains a reactive list of projects along with their meta information. */
3442
+ d(this, "projectList");
3443
+ //
3444
+ // Projects
3445
+ //
3446
+ d(this, "openedProjectsByRid", /* @__PURE__ */ new Map());
3447
+ this.env = e, this.driverKit = t, this.signer = r, this.projectListResourceId = s, this.openedProjectsList = n, this.projectListTree = i, this.projectList = a, this.pl = this.env.pl;
3448
+ }
3449
+ /** Returns extended API driver kit used internally by middle layer. */
3450
+ get internalDriverKit() {
3451
+ return this.env.driverKit;
3452
+ }
3453
+ //
3454
+ // Project List Manipulation
3455
+ //
3456
+ /** Creates a project with initial state and adds it to project list. */
3457
+ async createProject(e, t = Y()) {
3458
+ const r = await this.pl.withWriteTx("MLCreateProject", async (s) => {
3459
+ const n = await vo(s, e);
3460
+ return s.createField(S(this.projectListResourceId, t), "Dynamic", n), await s.commit(), await er(n);
3461
+ });
3462
+ return await this.projectListTree.refreshState(), r;
3463
+ }
3464
+ /** Updates project metadata */
3465
+ async setProjectMeta(e, t, r) {
3466
+ await A(this.pl, e, r, async (s) => {
3467
+ s.setMeta(t);
3468
+ }), await this.projectListTree.refreshState();
3469
+ }
3470
+ /** Permanently deletes project from the project list, this will result in
3471
+ * destruction of all attached objects, like files, analysis results etc. */
3472
+ async deleteProject(e) {
3473
+ await this.pl.withWriteTx("MLRemoveProject", async (t) => {
3474
+ t.removeField(S(this.projectListResourceId, e)), await t.commit();
3475
+ }), await this.projectListTree.refreshState();
3476
+ }
3477
+ async projectIdToResourceId(e) {
3478
+ return await this.pl.withReadTx("Project id to resource id", async (t) => {
3479
+ const r = (await t.getField(S(this.projectListResourceId, e))).value;
3480
+ if (ce(r)) throw new Error("Unexpected project list structure.");
3481
+ return r;
3482
+ });
3483
+ }
3484
+ async ensureProjectRid(e) {
3485
+ return typeof e == "string" ? await this.projectIdToResourceId(e) : e;
3486
+ }
3487
+ /** Opens a project, and starts corresponding project maintenance loop. */
3488
+ async openProject(e) {
3489
+ const t = await this.ensureProjectRid(e);
3490
+ if (this.openedProjectsByRid.has(t)) throw new Error(`Project ${t} already opened`);
3491
+ this.openedProjectsByRid.set(t, await Je.init(this.env, t)), this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()]);
3492
+ }
3493
+ /** Closes the project, and deallocate all corresponding resources. */
3494
+ async closeProject(e) {
3495
+ const t = this.openedProjectsByRid.get(e);
3496
+ if (t === void 0) throw new Error(`Project ${e} not found among opened projects`);
3497
+ this.openedProjectsByRid.delete(e), await t.destroy(), this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()]);
3498
+ }
3499
+ /** Returns a project access object for opened project, for the given project
3500
+ * resource id. */
3501
+ getOpenedProject(e) {
3502
+ const t = this.openedProjectsByRid.get(e);
3503
+ if (t === void 0) throw new Error(`Project ${e} not found among opened projects`);
3504
+ return t;
3505
+ }
3506
+ /** Deallocates all runtime resources consumed by this object and awaits
3507
+ * actual termination of event loops and other processes associated with
3508
+ * them. */
3509
+ async close() {
3510
+ await Promise.all([...this.openedProjectsByRid.values()].map((e) => e.destroy())), this.env.quickJs, await this.projectListTree.terminate();
3511
+ }
3512
+ /** @deprecated */
3513
+ async closeAndAwaitTermination() {
3514
+ await this.close();
3515
+ }
3516
+ /** Generates sufficiently random string to be used as local secret for the
3517
+ * middle layer */
3518
+ static generateLocalSecret() {
3519
+ return dt.generateSecret();
3520
+ }
3521
+ /** Initialize middle layer */
3522
+ static async init(e, t) {
3523
+ const r = { ...fs, ...t }, s = await e.withWriteTx("MLInitialization", async (h) => {
3524
+ const g = S(h.clientRoot, Lr);
3525
+ h.createField(g, "Dynamic");
3526
+ const b = await h.getField(g);
3527
+ if (ce(b.value)) {
3528
+ const B = h.createEphemeral(wt);
3529
+ return h.lock(B), h.setField(g, B), await h.commit(), await B.globalId;
3530
+ } else
3531
+ return b.value;
3532
+ }), n = new _t(console), i = await Ps(e, n, r), a = new uo(i.signer), u = new yr(
3533
+ n,
3534
+ e.httpDispatcher,
3535
+ r.frontendDownloadPath
3536
+ ), c = {
3537
+ pl: e,
3538
+ signer: i.signer,
3539
+ ops: r,
3540
+ bpPreparer: a,
3541
+ frontendDownloadDriver: u,
3542
+ driverKit: i,
3543
+ blockUpdateWatcher: new vs({
3544
+ minDelay: r.devBlockUpdateRecheckInterval,
3545
+ http: e.httpDispatcher
3546
+ }),
3547
+ quickJs: await ir()
3548
+ }, l = new or([]), p = await Kr(e, s, l, c);
3549
+ return new Jt(
3550
+ c,
3551
+ i,
3552
+ i.signer,
3553
+ s,
3554
+ l,
3555
+ p.tree,
3556
+ p.computable
3557
+ );
3558
+ }
3559
+ }
3560
+ export {
3561
+ Hs as BlockPackRegistry,
3562
+ Ws as CentralDevSnapshotRegistry,
3563
+ _s as CentralRegistry,
3564
+ Lt as DefaultDriverKitOps,
3565
+ fs as DefaultMiddleLayerOps,
3566
+ Xs as FieldType,
3567
+ Ct as FrontendFromFolderResourceType,
3568
+ kt as FrontendFromUrlResourceType,
3569
+ Jt as MiddleLayer,
3570
+ Je as Project,
3571
+ en as ResourceType,
3572
+ Yr as TengoTemplateGet,
3573
+ Qr as TengoTemplateGetRegistry,
3574
+ Xr as TengoTemplateGetTemplate,
3575
+ Zr as TengoTemplateGetTemplateURI,
3576
+ eo as TengoTemplatePack,
3577
+ to as TengoTemplatePackConvert,
3578
+ oo as TengoTemplatePackConvertTemplate,
3579
+ ro as TengoTemplatePackConvertTemplatePack,
3580
+ St as createRenderTemplate,
3581
+ vt as getDevV1PacketMtime,
3582
+ Ae as getDevV2PacketMtime,
3583
+ Ps as initDriverKit,
3584
+ Ve as loadTemplate,
3585
+ so as prepareTemplateSpec
3586
+ };
3587
+ //# sourceMappingURL=index.mjs.map