@milaboratories/pl-middle-layer 2.9.1 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/index.cjs +4 -0
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.js +2 -1
  4. package/dist/middle_layer/build_stamp.cjs +1 -1
  5. package/dist/middle_layer/build_stamp.js +1 -1
  6. package/dist/middle_layer/index.cjs +4 -0
  7. package/dist/middle_layer/index.d.ts +2 -1
  8. package/dist/middle_layer/index.js +2 -1
  9. package/dist/middle_layer/middle_layer.cjs +96 -28
  10. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  11. package/dist/middle_layer/middle_layer.d.ts +54 -8
  12. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  13. package/dist/middle_layer/middle_layer.js +96 -28
  14. package/dist/middle_layer/middle_layer.js.map +1 -1
  15. package/dist/middle_layer/project.cjs +39 -17
  16. package/dist/middle_layer/project.cjs.map +1 -1
  17. package/dist/middle_layer/project.d.ts +17 -2
  18. package/dist/middle_layer/project.d.ts.map +1 -1
  19. package/dist/middle_layer/project.js +39 -17
  20. package/dist/middle_layer/project.js.map +1 -1
  21. package/dist/middle_layer/project_holds.cjs +266 -0
  22. package/dist/middle_layer/project_holds.cjs.map +1 -0
  23. package/dist/middle_layer/project_holds.d.ts +50 -0
  24. package/dist/middle_layer/project_holds.d.ts.map +1 -0
  25. package/dist/middle_layer/project_holds.js +262 -0
  26. package/dist/middle_layer/project_holds.js.map +1 -0
  27. package/package.json +6 -6
  28. package/src/middle_layer/index.ts +2 -0
  29. package/src/middle_layer/middle_layer.ts +117 -38
  30. package/src/middle_layer/project.ts +40 -15
  31. package/src/middle_layer/project_close_during_write.test.ts +142 -0
  32. package/src/middle_layer/project_handles.test.ts +168 -0
  33. package/src/middle_layer/project_holds.ts +359 -0
  34. package/src/middle_layer/project_slots.test.ts +331 -0
  35. package/src/test/write_tx_hooks.ts +75 -0
@@ -47,6 +47,7 @@ var Project = class Project {
47
47
  id;
48
48
  rid;
49
49
  projectTree;
50
+ onGone;
50
51
  /** Data for the left panel, contain basic information about block status. */
51
52
  overview;
52
53
  overviewLight;
@@ -75,11 +76,12 @@ var Project = class Project {
75
76
  get destroyed() {
76
77
  return this.abortController.signal.aborted;
77
78
  }
78
- constructor(env, id, rid, projectTree, restoredFromSnapshot = false) {
79
+ constructor(env, id, rid, projectTree, restoredFromSnapshot = false, onGone) {
79
80
  this.env = env;
80
81
  this.id = id;
81
82
  this.rid = rid;
82
83
  this.projectTree = projectTree;
84
+ this.onGone = onGone;
83
85
  this.snapshotGeneration = restoredFromSnapshot ? 0 : -1;
84
86
  this.overview = require_project_overview.projectOverview(projectTree.entry(), this.navigationStates, env).withPreCalculatedValueTree();
85
87
  this.overviewLight = require_project_overview_light.projectOverviewLight(projectTree.entry()).withPreCalculatedValueTree();
@@ -171,8 +173,26 @@ var Project = class Project {
171
173
  this.env.logger.warn(new Error(`failed to capture tree snapshot for project ${this.id}`, { cause: e }));
172
174
  }
173
175
  }
176
+ /**
177
+ * Brings the project tree up to a write that has just committed.
178
+ *
179
+ * The write is already on the backend when this runs, so a project destroyed meanwhile (closed
180
+ * by its last holder, or deleted) must not turn it into a failure: a caller told it failed would
181
+ * retry it and apply it twice. `destroy` marks the project destroyed before it terminates the
182
+ * tree, so a refresh failing on a terminated tree always finds the mark set.
183
+ */
184
+ async refreshAfterWrite() {
185
+ if (this.destroyed) return;
186
+ try {
187
+ await this.projectTree.refreshState();
188
+ } catch (e) {
189
+ if (this.destroyed) return;
190
+ throw e;
191
+ }
192
+ }
174
193
  async refreshLoop() {
175
194
  let retryState;
195
+ let gone = false;
176
196
  while (!this.destroyed) try {
177
197
  await require_project.withProject(this.env.projectHelper, this.env.pl, this.rid, (prj) => {
178
198
  prj.doRefresh();
@@ -196,6 +216,7 @@ var Project = class Project {
196
216
  if (this.destroyed) break;
197
217
  if ((0, _milaboratories_pl_client.isNotFoundError)(error)) {
198
218
  this.env.logger.warn("project refresh routine terminated, because project was externally deleted");
219
+ gone = true;
199
220
  break;
200
221
  } else if ((0, _milaboratories_pl_client.isTimeoutOrCancelError)(error)) {} else {
201
222
  retryState = retryState ? (0, _milaboratories_ts_helpers.nextInfiniteRetryState)(retryState) : (0, _milaboratories_ts_helpers.createInfiniteRetryState)({
@@ -213,6 +234,7 @@ var Project = class Project {
213
234
  }
214
235
  }
215
236
  }
237
+ if (gone) this.onGone?.(this);
216
238
  }
217
239
  /**
218
240
  * Adds new block to the project.
@@ -271,7 +293,7 @@ var Project = class Project {
271
293
  name: "addBlock",
272
294
  lockId: this.projectLockId
273
295
  });
274
- await this.projectTree.refreshState();
296
+ await this.refreshAfterWrite();
275
297
  return blockId;
276
298
  }
277
299
  /**
@@ -291,7 +313,7 @@ var Project = class Project {
291
313
  name: "duplicateBlock",
292
314
  lockId: this.projectLockId
293
315
  });
294
- await this.projectTree.refreshState();
316
+ await this.refreshAfterWrite();
295
317
  return newBlockId;
296
318
  }
297
319
  /**
@@ -312,7 +334,7 @@ var Project = class Project {
312
334
  name: "updateBlockPack",
313
335
  lockId: this.projectLockId
314
336
  });
315
- await this.projectTree.refreshState();
337
+ await this.refreshAfterWrite();
316
338
  }
317
339
  /** Deletes a block with all associated data. */
318
340
  async deleteBlock(blockId, author) {
@@ -321,7 +343,7 @@ var Project = class Project {
321
343
  lockId: this.projectLockId
322
344
  });
323
345
  this.navigationStates.deleteBlock(blockId);
324
- await this.projectTree.refreshState();
346
+ await this.refreshAfterWrite();
325
347
  }
326
348
  /**
327
349
  * Updates block order according to the given array of block ids.
@@ -350,7 +372,7 @@ var Project = class Project {
350
372
  name: "reorderBlocks",
351
373
  lockId: this.projectLockId
352
374
  });
353
- await this.projectTree.refreshState();
375
+ await this.refreshAfterWrite();
354
376
  }
355
377
  /**
356
378
  * Renders production part of the block starting all connected heavy computations.
@@ -362,7 +384,7 @@ var Project = class Project {
362
384
  name: "runBlock",
363
385
  lockId: this.projectLockId
364
386
  });
365
- await this.projectTree.refreshState();
387
+ await this.refreshAfterWrite();
366
388
  }
367
389
  /**
368
390
  * Stops the block if it is running by destroying its production state. All
@@ -374,7 +396,7 @@ var Project = class Project {
374
396
  name: "stopBlock",
375
397
  lockId: this.projectLockId
376
398
  });
377
- await this.projectTree.refreshState();
399
+ await this.refreshAfterWrite();
378
400
  }
379
401
  /**
380
402
  * @deprecated Use mutateBlockStorage() for V3 blocks.
@@ -395,7 +417,7 @@ var Project = class Project {
395
417
  name: "setBlockArgs",
396
418
  lockId: this.projectLockId
397
419
  });
398
- await this.projectTree.refreshState();
420
+ await this.refreshAfterWrite();
399
421
  }
400
422
  /**
401
423
  * @deprecated Use mutateBlockStorage() for V3 blocks.
@@ -416,7 +438,7 @@ var Project = class Project {
416
438
  name: "setUiState",
417
439
  lockId: this.projectLockId
418
440
  });
419
- await this.projectTree.refreshState();
441
+ await this.refreshAfterWrite();
420
442
  }
421
443
  /**
422
444
  * @deprecated Use mutateBlockStorage() for V3 blocks.
@@ -440,7 +462,7 @@ var Project = class Project {
440
462
  name: "setBlockArgsAndUiState",
441
463
  lockId: this.projectLockId
442
464
  });
443
- await this.projectTree.refreshState();
465
+ await this.refreshAfterWrite();
444
466
  }
445
467
  /**
446
468
  * Sets navigation state.
@@ -467,7 +489,7 @@ var Project = class Project {
467
489
  name: "mutateBlockStorage",
468
490
  lockId: this.projectLockId
469
491
  });
470
- await this.projectTree.refreshState();
492
+ await this.refreshAfterWrite();
471
493
  }
472
494
  /**
473
495
  * Reads the block's initialization params as its own model projects them from the current
@@ -490,7 +512,7 @@ var Project = class Project {
490
512
  await require_project.withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, void 0, (mut) => {
491
513
  mut.setBlockSettings(blockId, newValue);
492
514
  }, { name: "setBlockSettings" });
493
- await this.projectTree.refreshState();
515
+ await this.refreshAfterWrite();
494
516
  }
495
517
  /**
496
518
  * Sets raw block storage content directly.
@@ -503,7 +525,7 @@ var Project = class Project {
503
525
  await require_project.withProjectAuthored(this.env.projectHelper, this.env.pl, this.rid, void 0, (mut) => {
504
526
  mut.setBlockStorageRaw(blockId, rawStorageJson);
505
527
  }, { name: "setBlockStorageRaw" });
506
- await this.projectTree.refreshState();
528
+ await this.refreshAfterWrite();
507
529
  }
508
530
  /** Resets arguments and ui state of the block to initial state */
509
531
  async resetBlockArgsAndUiState(blockId, author) {
@@ -531,7 +553,7 @@ var Project = class Project {
531
553
  });
532
554
  await tx.commit();
533
555
  });
534
- await this.projectTree.refreshState();
556
+ await this.refreshAfterWrite();
535
557
  }
536
558
  getBlockComputables(blockId) {
537
559
  const cached = this.blockComputables.get(blockId);
@@ -709,7 +731,7 @@ var Project = class Project {
709
731
  dumpState() {
710
732
  return this.projectTree.dumpState();
711
733
  }
712
- static async init(env, id, rid) {
734
+ static async init(env, id, rid, onGone) {
713
735
  await require_migration.applyProjectMigrations(env.pl, rid);
714
736
  await require_project.withProject(env.projectHelper, env.pl, rid, (_) => {}, { name: "init" });
715
737
  const { tree: projectTree, restored } = await loadProjectTree(env, rid);
@@ -720,7 +742,7 @@ var Project = class Project {
720
742
  await node_fs_promises.default.writeFile(`${(0, _milaboratories_pl_client.resourceIdToString)(rid)}.json`, stringifyForDump(state));
721
743
  await node_fs_promises.default.writeFile(`${(0, _milaboratories_pl_client.resourceIdToString)(rid)}.stats.json`, stringifyForDump(stats));
722
744
  }
723
- return new Project(env, id, rid, projectTree, restored);
745
+ return new Project(env, id, rid, projectTree, restored, onGone);
724
746
  }
725
747
  };
726
748
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"project.cjs","names":["resourceIdToString","NavigationStates","projectOverview","projectOverviewLight","activeConfigs","parseSignedResourceId","withProject","setTimeout","isNotFoundError","isTimeoutOrCancelError","nextInfiniteRetryState","createInfiniteRetryState","randomUUID","extractConfig","ModelAPIVersionMismatchError","BLOCK_STORAGE_FACADE_VERSION","BlockStorageFacadeCallbacks","BlockInitParamsRejectedError","cacheBlockPackTemplate","withProjectAuthored","DefaultRetryOptions","ensureSignedResourceIdNotNull","field","projectFieldName","Pl","cachedDeserialize","notEmpty","blockOutputs","blockDependencies","blockDependents","Computable","getBlockParameters","labelBlockColumnLinks","readBlockActionContextTree","BlockStatusWatch","frontendData","applyProjectMigrations","treeDumpStats","fs","SynchronizedTreeState","isUnauthenticated","isPermissionDenied","TreeStateUpdateError","projectStatusFieldRegex","treeFilter","ProjectStatusFieldPattern","finalityStopRules","TreeFinality","getBlockPackInfo","checkBlockFlag"],"sources":["../../src/middle_layer/project.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"./middle_layer\";\nimport type {\n FieldData,\n Filter,\n OptionalAnyResourceId,\n PlClient,\n SignedResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n DefaultRetryOptions,\n ensureSignedResourceIdNotNull,\n field,\n isNotFoundError,\n isPermissionDenied,\n isTimeoutOrCancelError,\n isUnauthenticated,\n parseSignedResourceId,\n Pl,\n resourceIdToString,\n treeFilter,\n TreeFinality,\n} from \"@milaboratories/pl-client\";\nimport { finalityStopRules } from \"./finality_stop_rules\";\nimport type { ComputableStableDefined, ComputableValueOrErrors } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport { projectOverview } from \"./project_overview\";\nimport { blockDependencies, blockDependents, labelBlockColumnLinks } from \"./column_links\";\nimport type { BlockPackSpecAny } from \"../model\";\nimport { randomUUID } from \"node:crypto\";\nimport { withProject, withProjectAuthored } from \"../mutator/project\";\nimport type {\n ExtendedResourceData,\n PlTreeNodeAccessor,\n PruningFunction,\n} from \"@milaboratories/pl-tree\";\nimport {\n SynchronizedTreeState,\n treeDumpStats,\n TreeStateUpdateError,\n} from \"@milaboratories/pl-tree\";\nimport type { TreeSnapshotStore } from \"./tree_snapshot_store\";\nimport { setTimeout } from \"node:timers/promises\";\nimport { frontendData } from \"./frontend_path\";\nimport type { NavigationState } from \"@milaboratories/pl-model-common\";\nimport { getBlockParameters, blockOutputs } from \"./block\";\nimport type { BlockActionContextMode, BlockActionContextNode } from \"./block_action_context\";\nimport { readBlockActionContextTree } from \"./block_action_context\";\nimport { getBlockPackInfo } from \"./util\";\nimport { BlockStatusWatch } from \"./block_status_tree\";\nimport type { BlockStatusSummary, BlockStatusTree } from \"@milaboratories/pl-model-middle-layer\";\nimport type { FrontendData } from \"../model/frontend\";\nimport type { ProjectId, ProjectStructure } from \"../model/project_model\";\nimport {\n projectFieldName,\n ProjectStatusFieldPattern,\n projectStatusFieldRegex,\n} from \"../model/project_model\";\nimport {\n cachedDeserialize,\n notEmpty,\n type MiLogger,\n createInfiniteRetryState,\n nextInfiniteRetryState,\n type InfiniteRetryState,\n} from \"@milaboratories/ts-helpers\";\nimport type { BlockPackInfo } from \"../model/block_pack\";\nimport type {\n ProjectOverview,\n AuthorMarker,\n BlockSettings,\n BlockStateInternalV3,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport type { BlockId, ColumnLink } from \"@milaboratories/pl-model-common\";\nimport { activeConfigs } from \"./active_cfg\";\nimport { NavigationStates } from \"./navigation_states\";\nimport {\n checkBlockFlag,\n extractConfig,\n BLOCK_STORAGE_FACADE_VERSION,\n BlockStorageFacadeCallbacks,\n type BlockKindReference,\n} from \"@platforma-sdk/model\";\nimport {\n BlockInitParamsRejectedError,\n ModelAPIVersionMismatchError,\n} from \"@milaboratories/pl-errors\";\nimport fs from \"node:fs/promises\";\nimport canonicalize from \"canonicalize\";\nimport type { ProjectOverviewLight } from \"./project_overview_light\";\nimport { projectOverviewLight } from \"./project_overview_light\";\nimport { applyProjectMigrations } from \"../mutator/migration\";\nimport { cacheBlockPackTemplate } from \"../mutator/template/template_cache\";\n\ntype BlockStateComputables = {\n readonly fullState: Computable<BlockStateInternalV3>;\n /** Column links of the block, nested into its full state. */\n readonly dependencies: Computable<ColumnLink[] | undefined>;\n readonly dependents: Computable<ColumnLink[] | undefined>;\n};\n\nfunction stringifyForDump(object: unknown): string {\n return JSON.stringify(object, (key, value) => {\n if (typeof value === \"bigint\") return resourceIdToString(value as OptionalAnyResourceId);\n else if (\n ArrayBuffer.isView(value) ||\n value instanceof Int8Array ||\n value instanceof Uint8Array ||\n value instanceof Uint8ClampedArray ||\n value instanceof Int16Array ||\n value instanceof Uint16Array ||\n value instanceof Int32Array ||\n value instanceof Uint32Array ||\n value instanceof Float32Array ||\n value instanceof Float64Array ||\n value instanceof BigInt64Array ||\n value instanceof BigUint64Array\n )\n return Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString(\"base64\");\n else if (Buffer.isBuffer(value)) return value.toString(\"base64\");\n\n return value;\n });\n}\n\n/** Releases what the computables of a block hold. */\nfunction resetBlockState(computables: BlockStateComputables): void {\n computables.fullState.resetState();\n computables.dependencies.resetState();\n computables.dependents.resetState();\n}\n\n/** Options of {@link Project.addBlock}. */\nexport type AddBlockOps = {\n /**\n * Start the block from initialization params instead of the model's default state. The block's\n * model checks the params against its kind and builds its initial storage from them. Only a\n * block with model API version 2 whose SDK has the params initializer can be created this way.\n */\n init?: {\n /** The kind's initialization params, as a template entry holds them. */\n params: unknown;\n /**\n * Ids used inside `params` in place of block ids, each mapped to the id of a block of this\n * project. The block's model replaces them in every reference it recognizes. An id that is\n * not listed is left as it is, so params that already hold real block ids need no map.\n */\n blockIds?: Readonly<Record<string, BlockId>>;\n };\n /** Refuse to add a block whose model API version differs from this one. */\n requireModelAPIVersion?: number;\n};\n\n/** Data access object, to manipulate and read single opened (!) project data. */\nexport class Project {\n /** Data for the left panel, contain basic information about block status. */\n public readonly overview: ComputableStableDefined<ProjectOverview>;\n private readonly overviewLight: Computable<ProjectOverviewLight>;\n\n private readonly navigationStates = new NavigationStates();\n // null is set for deleted blocks\n private readonly blockComputables = new Map<string, BlockStateComputables | null>();\n\n private readonly blockFrontends = new Map<string, ComputableStableDefined<FrontendData>>();\n\n /** Live status watches, keyed by {@link blockStatusKey}. One per block whose status is shown;\n * each owns a synchronized tree, so they are started and terminated explicitly. */\n private readonly blockStatusWatches = new Map<string, Promise<BlockStatusWatch>>();\n private readonly activeConfigs: Computable<unknown[]>;\n private readonly refreshLoopResult: Promise<void>;\n\n private readonly abortController = new AbortController();\n\n /** Tree change generation as of the snapshot currently on disk, or -1 when this session has\n * not written one. Compared against the tree's current generation to skip writing a mirror\n * that has not moved, which is what makes a project left open and idle go quiet. */\n private snapshotGeneration: number;\n\n /** When a snapshot was last attempted, for the periodic write's wall-clock gate.\n *\n * Zero, not the construction time, so the first write lands on the first maintenance pass\n * after the tree has settled rather than a full interval later. Sessions shorter than one\n * interval are the common case for a desktop app that is quit with a project still open, and\n * seeding this to now would leave every one of them with nothing on disk. Set on every\n * attempt, successful or not, so a persistently failing write retries at the interval rather\n * than on every pass of the loop. */\n private lastSnapshotAt = 0;\n\n private get destroyed() {\n return this.abortController.signal.aborted;\n }\n\n constructor(\n private readonly env: MiddleLayerEnvironment,\n public readonly id: ProjectId /* Project ID, exposed to outer consumers, who work with ML */,\n readonly rid: SignedResourceId /* Contains signature, not exposed outside middle layer. */,\n private readonly projectTree: SynchronizedTreeState,\n /** Whether this tree was seeded from a snapshot. When it was, the file on disk already\n * holds generation 0, so an idle warm reopen writes nothing at all. */\n restoredFromSnapshot: boolean = false,\n ) {\n this.snapshotGeneration = restoredFromSnapshot ? 0 : -1;\n this.overview = projectOverview(\n projectTree.entry(),\n this.navigationStates,\n env,\n ).withPreCalculatedValueTree();\n this.overviewLight = projectOverviewLight(projectTree.entry()).withPreCalculatedValueTree();\n this.refreshLoopResult = this.refreshLoop();\n this.refreshLoopResult.catch((err) => {\n env.logger.warn(new Error(\"Error during refresh loop\", { cause: err })); // TODO (safe voiding for now)\n });\n this.activeConfigs = activeConfigs(projectTree.entry(), env);\n }\n\n get projectLockId(): string {\n return \"project:\" + this.id.toString();\n }\n\n /**\n * Periodic snapshot write, carried on the maintenance loop rather than a timer of its own.\n *\n * Gated on the tree having changed since the last snapshot, so a project left open and idle\n * writes once and then goes quiet, and on wall clock, so a project changing continuously\n * writes at most once per interval.\n */\n private async maybeWriteSnapshot(): Promise<void> {\n const store = this.env.treeSnapshots;\n if (store === undefined) return;\n\n const generation = this.projectTree.changeGeneration;\n if (generation === this.snapshotGeneration) return;\n if (Date.now() - this.lastSnapshotAt < this.env.ops.treeSnapshotOps.writeInterval) return;\n\n await this.writeSnapshot(store, generation);\n }\n\n /**\n * Starts the close-boundary snapshot and returns without waiting for the write.\n *\n * On top of the periodic write, since closing is a natural point to persist. Change-gated but\n * not interval-gated: rewriting a mirror that has not moved is pure waste, but a mirror that\n * has moved is worth keeping however recently the last write happened.\n *\n * The **capture is synchronous and happens here**, before the caller destroys the tree,\n * because destroying it invalidates it and a later capture would be refused. Only the encode\n * and the write are deferred: they are up to ten megabytes of work, and project switching\n * should not wait for them. Deferring is safe only because a capture is a copy rather than a\n * view of the tree.\n *\n * The returned promise never rejects. The caller is expected to keep it so it can be drained\n * at shutdown, not to await it here.\n */\n public snapshotOnClose(): Promise<void> {\n const store = this.env.treeSnapshots;\n if (store === undefined) return Promise.resolve();\n\n const generation = this.projectTree.changeGeneration;\n if (generation === this.snapshotGeneration) return Promise.resolve();\n\n let snapshot;\n try {\n snapshot = this.projectTree.capture(parseSignedResourceId(this.rid).signature);\n } catch (e: unknown) {\n this.env.logger.warn(\n new Error(`failed to capture tree snapshot for project ${this.id} on close`, { cause: e }),\n );\n return Promise.resolve();\n }\n\n this.lastSnapshotAt = Date.now();\n\n // Queued behind any in-flight periodic write rather than racing it. Both would land\n // atomically, but the loser would be a wasted encode of the same mirror.\n const previous = this.snapshotInFlight ?? Promise.resolve();\n const write = previous.then(async () => {\n if (this.snapshotGeneration >= generation) return; // the in-flight write covered it\n if (await store.write(this.rid, snapshot)) this.snapshotGeneration = generation;\n });\n\n this.snapshotInFlight = write.finally(() => {\n this.snapshotInFlight = undefined;\n });\n return this.snapshotInFlight;\n }\n\n /** In-flight snapshot write, if any. Both triggers can fire close together (the close write\n * lands while the loop is mid-write), and encoding ten megabytes twice for the same mirror\n * is worth avoiding. */\n private snapshotInFlight: Promise<void> | undefined;\n\n /** Serializes writes, and skips one that the in-flight write has already made redundant. */\n private async writeSnapshot(store: TreeSnapshotStore, generation: number): Promise<void> {\n // A loop, not a single check: with three or more callers, re-checking only once would let\n // a waiter install its own promise over another's and clear the field while that write is\n // still running. Two callers is the most that can happen today, so this is a guard against\n // the next caller rather than a live fix.\n while (this.snapshotInFlight !== undefined) {\n await this.snapshotInFlight;\n if (this.snapshotGeneration >= generation) return;\n }\n\n this.snapshotInFlight = this.captureAndWrite(store, generation).finally(() => {\n this.snapshotInFlight = undefined;\n });\n await this.snapshotInFlight;\n }\n\n /** Captures and writes, never throwing: a snapshot is an optimisation and must not fail\n * whatever triggered it. */\n private async captureAndWrite(store: TreeSnapshotStore, generation: number): Promise<void> {\n // Recorded before the attempt and regardless of its outcome, so a failing disk is retried\n // once per interval instead of on every pass of the maintenance loop.\n this.lastSnapshotAt = Date.now();\n try {\n // The root's signature is the session witness a later open compares against.\n const snapshot = this.projectTree.capture(parseSignedResourceId(this.rid).signature);\n\n // Only a real write advances the change gate. Marking the generation persisted after a\n // failed write would tell both triggers the tree is already on disk, so one transient\n // I/O error would cost the rest of the session, close write included.\n if (await store.write(this.rid, snapshot)) this.snapshotGeneration = generation;\n } catch (e: unknown) {\n this.env.logger.warn(\n new Error(`failed to capture tree snapshot for project ${this.id}`, { cause: e }),\n );\n }\n }\n\n private async refreshLoop(): Promise<void> {\n let retryState: InfiniteRetryState | undefined;\n while (!this.destroyed) {\n try {\n await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (prj) => {\n prj.doRefresh();\n },\n {\n name: \"doRefresh\",\n lockId: this.projectLockId,\n abortSignal: this.abortController.signal,\n },\n );\n await this.activeConfigs.getValue();\n await setTimeout(this.env.ops.projectRefreshInterval, undefined, {\n signal: this.abortController.signal,\n });\n\n await this.maybeWriteSnapshot();\n\n // Block computables housekeeping\n const overviewLight = await this.overviewLight.getValue();\n const existingBlocks = new Set(overviewLight.listOfBlocks);\n // Doing cleanup for deleted blocks\n for (const blockId of this.blockComputables.keys()) {\n if (!existingBlocks.has(blockId)) {\n const computables = this.blockComputables.get(blockId);\n if (computables !== undefined && computables !== null) resetBlockState(computables);\n this.blockComputables.set(blockId, null);\n }\n }\n retryState = undefined;\n } catch (error: unknown) {\n // If we're destroyed, exit gracefully regardless of error type\n if (this.destroyed) break;\n\n if (isNotFoundError(error)) {\n this.env.logger.warn(\n \"project refresh routine terminated, because project was externally deleted\",\n );\n break;\n } else if (isTimeoutOrCancelError(error)) {\n // Timeout during normal operation, continue the loop\n } else {\n retryState = retryState\n ? nextInfiniteRetryState(retryState)\n : createInfiniteRetryState({\n type: \"exponentialWithMaxDelayBackoff\",\n initialDelay: 1000,\n maxDelay: 60_000,\n backoffMultiplier: 2,\n jitter: 0,\n });\n this.env.logger.error(\n new Error(`[refreshLoop] unexpected exception, retrying in ${retryState.nextDelay}ms`, {\n cause: error,\n }),\n );\n try {\n await setTimeout(retryState.nextDelay, undefined, {\n signal: this.abortController.signal,\n });\n } catch {\n // Aborted during retry delay, will exit via while condition or destroyed check\n break;\n }\n }\n }\n }\n }\n\n /**\n * Adds new block to the project.\n *\n * @param blockLabel block label / title visible to the user\n * @param blockPackSpec object describing the \"block type\", read more in the type docs\n * @param before id of the block to insert new block before\n * @param blockId internal id to be assigned for the block, this arg can be omitted\n * then, randomly generated UUID will be assigned automatically\n * @param ops see {@link AddBlockOps}\n *\n * @return returns newly created block id\n * @throws ModelAPIVersionMismatchError when `ops.requireModelAPIVersion` differs from the\n * block's model API version; nothing is created\n * @throws BlockInitParamsRejectedError when the block does not accept `ops.init.params`;\n * nothing is created\n * */\n public async addBlock(\n blockLabel: string,\n blockPackSpec: BlockPackSpecAny,\n before?: string,\n author: AuthorMarker | undefined = undefined,\n blockId: string = randomUUID(),\n ops: AddBlockOps = {},\n ): Promise<string> {\n const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);\n const blockCfg = extractConfig(preparedBp.config);\n\n if (\n ops.requireModelAPIVersion !== undefined &&\n blockCfg.modelAPIVersion !== ops.requireModelAPIVersion\n )\n throw new ModelAPIVersionMismatchError(\n blockId,\n ops.requireModelAPIVersion,\n blockCfg.modelAPIVersion,\n );\n\n this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);\n throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);\n\n // The block's own model turns the params into its initial storage, and may decline them.\n // Asked before the template is cached and before the transaction, so a refusal changes\n // nothing on the backend.\n let initialStorage: string | undefined;\n if (ops.init !== undefined) {\n if (blockCfg.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION)\n throw new ModelAPIVersionMismatchError(\n blockId,\n BLOCK_STORAGE_FACADE_VERSION,\n blockCfg.modelAPIVersion,\n );\n if (\n blockCfg.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams] ===\n undefined\n )\n throw new BlockInitParamsRejectedError(\n \"this version of the block was built before blocks could be created from \" +\n \"initialization params; use a newer version of the block\",\n );\n const storage = this.env.projectHelper.getInitialStorageFromParamsInVM(\n blockCfg,\n ops.init.params,\n new Map(Object.entries(ops.init.blockIds ?? {})),\n );\n if (storage.error !== undefined)\n throw new BlockInitParamsRejectedError(storage.error.message);\n initialStorage = storage.value;\n }\n\n // Pre-materialize template via cache (separate transaction(s))\n const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);\n\n // Build NewBlockSpec based on model API version\n const newBlockSpec =\n blockCfg.modelAPIVersion === BLOCK_STORAGE_FACADE_VERSION\n ? { storageMode: \"fromModel\" as const, blockPack: cachedBp, initialStorage }\n : {\n storageMode: \"legacy\" as const,\n blockPack: cachedBp,\n legacyState: canonicalize({\n args: blockCfg.initialArgs,\n uiState: blockCfg.initialUiState,\n })!,\n };\n\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n return mut.addBlock(\n {\n id: blockId,\n label: blockLabel,\n renderingMode: blockCfg.renderingMode,\n },\n newBlockSpec,\n before,\n );\n },\n {\n retryOptions: {\n ...DefaultRetryOptions,\n backoffMultiplier: DefaultRetryOptions.backoffMultiplier * 1.1,\n },\n name: \"addBlock\",\n lockId: this.projectLockId,\n },\n );\n\n await this.projectTree.refreshState();\n\n return blockId;\n }\n\n /**\n * Duplicates an existing block by copying all its fields and state.\n * This method works at the mutator level for efficient block copying.\n *\n * @param originalBlockId id of the block to duplicate\n * @param before id of the block to insert new block before\n * @param author author marker for the duplication operation\n * @param newBlockId internal id to be assigned for the duplicated block,\n * if omitted, a randomly generated UUID will be assigned\n *\n * @return returns newly created block id\n * */\n public async duplicateBlock(\n originalBlockId: string,\n before?: string,\n author: AuthorMarker | undefined = undefined,\n newBlockId: string = randomUUID(),\n ): Promise<string> {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.duplicateBlock(originalBlockId, newBlockId, before),\n { name: \"duplicateBlock\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n\n return newBlockId;\n }\n\n /**\n * Update block to new block pack, optionally resetting args and ui state to\n * initial values\n * */\n public async updateBlockPack(\n blockId: string,\n blockPackSpec: BlockPackSpecAny,\n resetArgs: boolean = false,\n author?: AuthorMarker,\n ): Promise<void> {\n const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);\n const blockCfg = extractConfig(preparedBp.config);\n\n this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);\n throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);\n\n // Pre-materialize template via cache (separate transaction(s))\n const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);\n\n // resetState signals to mutator to reset storage\n // For v2+ blocks: mutator gets initial storage directly via getInitialStorageInVM\n // For v1 blocks: we pass the legacy state format\n const resetState = resetArgs\n ? {\n state:\n blockCfg.modelAPIVersion === 1\n ? { args: blockCfg.initialArgs, uiState: blockCfg.initialUiState }\n : {},\n }\n : undefined;\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.migrateBlockPack(blockId, cachedBp, resetState),\n { name: \"updateBlockPack\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /** Deletes a block with all associated data. */\n public async deleteBlock(blockId: string, author?: AuthorMarker): Promise<void> {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.deleteBlock(blockId),\n { name: \"deleteBlock\", lockId: this.projectLockId },\n );\n this.navigationStates.deleteBlock(blockId);\n await this.projectTree.refreshState();\n }\n\n /**\n * Updates block order according to the given array of block ids.\n *\n * Provided array must contain exactly the same set of ids current project cosists of,\n * an error will be thrown instead.\n */\n public async reorderBlocks(blocks: string[], author?: AuthorMarker): Promise<void> {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n const currentStructure = mut.structure;\n if (currentStructure.groups.length !== 1)\n throw new Error(\"Unexpected project structure, non-singular block group\");\n const currentGroup = currentStructure.groups[0];\n if (currentGroup.blocks.length !== blocks.length)\n throw new Error(`Length mismatch: ${currentGroup.blocks.length} !== ${blocks.length}`);\n if (new Set<string>(blocks).size !== blocks.length) throw new Error(`Repeated block ids`);\n const newStructure: ProjectStructure = {\n groups: [\n {\n id: currentGroup.id,\n label: currentGroup.label,\n blocks: blocks.map((blockId) => {\n const block = currentGroup.blocks.find((b) => b.id === blockId);\n if (block === undefined) throw new Error(`Can't find block: ${blockId}`);\n return block;\n }),\n },\n ],\n };\n mut.updateStructure(newStructure);\n },\n { name: \"reorderBlocks\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * Renders production part of the block starting all connected heavy computations.\n * Upstream blocks of the specified block will be started automatically if in\n * stale state.\n * */\n public async runBlock(blockId: string): Promise<void> {\n await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (mut) => mut.renderProduction([blockId], true),\n { name: \"runBlock\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * Stops the block if it is running by destroying its production state. All\n * its downstreams will also be destroyed or moved to limbo if already\n * calculated.\n * */\n public async stopBlock(blockId: string): Promise<void> {\n await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (mut) => mut.stopProduction(blockId),\n { name: \"stopBlock\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\n * Sets block args, and changes whole project state accordingly.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setBlockArgs(blockId: string, args: unknown, author?: AuthorMarker) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n const state = mut.mergeBlockState(blockId, { args });\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setBlockArgs\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\n * Sets ui block state associated with the block.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setUiState(blockId: string, uiState: unknown, author?: AuthorMarker) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n const state = mut.mergeBlockState(blockId, { uiState });\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setUiState\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\n * Sets block args and ui state, and changes the whole project state accordingly.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setBlockArgsAndUiState(\n blockId: string,\n args: unknown, // keep for v1/v2 compatibility\n uiState: unknown, // keep for v1/v2 compatibility\n author?: AuthorMarker,\n ) {\n // Normalize to unified state format { args, uiState } for v1/v2 blocks\n const state = { args, uiState };\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setBlockArgsAndUiState\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * Sets navigation state.\n * */\n //\n public async setNavigationState(blockId: string, state: NavigationState): Promise<void> {\n this.navigationStates.setState(blockId, state);\n }\n\n /**\n * Mutates block storage for Model API v3 blocks.\n * Applies a storage operation (e.g., 'update-data') which triggers\n * args derivation (args(data) and prerunArgs(data)).\n * The derived args are stored atomically with the data.\n *\n * @param blockId - The block ID\n * @param payload - Storage mutation payload with operation and value\n * @param author - Optional author marker for collaborative editing\n */\n public async mutateBlockStorage(\n blockId: string,\n payload: { operation: string; value: unknown },\n author?: AuthorMarker,\n ) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.setStates([{ modelAPIVersion: 2, blockId, payload }]),\n { name: \"mutateBlockStorage\", lockId: this.projectLockId },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * Reads the block's initialization params as its own model projects them from the current\n * storage, with the kind the block declares: the entry a template export writes for this block.\n * Passing the result as {@link AddBlockOps.init} to {@link addBlock} with the same block pack\n * recreates the block's configuration.\n *\n * @returns `kind` is undefined for a block that declares none; `params` is undefined when the\n * block has no storage yet\n * @throws when the project has no such block, or the block's model fails to project its params\n */\n public async getBlockInitializationParams(\n blockId: BlockId,\n ): Promise<{ kind: BlockKindReference | undefined; params: unknown }> {\n return await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (prj) => prj.getBlockInitializationParams(blockId),\n { name: \"getBlockInitializationParams\", lockId: this.projectLockId },\n );\n }\n\n /** Update block settings */\n public async setBlockSettings(blockId: string, newValue: BlockSettings) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n undefined,\n (mut) => {\n mut.setBlockSettings(blockId, newValue);\n },\n { name: \"setBlockSettings\" },\n );\n await this.projectTree.refreshState();\n }\n\n /**\n * Sets raw block storage content directly.\n * This bypasses all normalization and VM transformations.\n *\n * @param blockId The block to set storage for\n * @param rawStorageJson Raw storage as JSON string\n */\n public async setBlockStorageRaw(blockId: string, rawStorageJson: string): Promise<void> {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n undefined,\n (mut) => {\n mut.setBlockStorageRaw(blockId, rawStorageJson);\n },\n { name: \"setBlockStorageRaw\" },\n );\n await this.projectTree.refreshState();\n }\n\n /** Resets arguments and ui state of the block to initial state */\n public async resetBlockArgsAndUiState(blockId: string, author?: AuthorMarker): Promise<void> {\n await this.env.pl.withWriteTx(\"BlockInputsReset\", async (tx) => {\n // reading default arg values from block pack\n const bpHolderRid = ensureSignedResourceIdNotNull(\n (await tx.getField(field(this.rid, projectFieldName(blockId, \"blockPack\")))).value,\n );\n const bpRid = ensureSignedResourceIdNotNull(\n (await tx.getField(field(bpHolderRid, Pl.HolderRefField))).value,\n );\n const bpData = await tx.getResourceData(bpRid, false);\n const config = extractConfig(cachedDeserialize<BlockPackInfo>(notEmpty(bpData.data)).config);\n\n await withProjectAuthored(\n this.env.projectHelper,\n tx,\n this.rid,\n author,\n (prj) => {\n if (config.modelAPIVersion === BLOCK_STORAGE_FACADE_VERSION) {\n // V2+: Reset to initial storage via VM\n prj.resetToInitialStorage(blockId);\n } else {\n // V1: Use legacy state format\n const initialState = { args: config.initialArgs, uiState: config.initialUiState };\n prj.setStates([{ modelAPIVersion: 1, blockId, state: initialState }]);\n }\n },\n { name: \"resetBlockArgsAndUiState\", lockId: this.projectLockId },\n );\n await tx.commit();\n });\n await this.projectTree.refreshState();\n }\n\n private getBlockComputables(blockId: string): BlockStateComputables {\n const cached = this.blockComputables.get(blockId);\n if (cached === null) throw new Error(`Block ${blockId} is deleted`);\n if (cached === undefined) {\n // state consists of inputs (args + ui state) and outputs\n const outputs = blockOutputs(this.projectTree.entry(), blockId, this.env);\n const dependencies = blockDependencies(this.projectTree.entry(), blockId, this.env);\n const dependents = blockDependents(this.projectTree.entry(), blockId, this.env);\n const fullState = Computable.make(\n (ctx) => {\n // Links are computed only for a block whose UI reads them.\n const linked = readsColumnLinks(ctx.accessor(this.projectTree.entry()).node(), blockId);\n return {\n parameters: getBlockParameters(this.projectTree.entry(), blockId, ctx),\n outputs,\n navigationState: this.navigationStates.getState(blockId),\n overview: this.overview,\n dependencies: linked ? dependencies : undefined,\n dependents: linked ? dependents : undefined,\n };\n },\n {\n postprocessValue: (v) => {\n const blockOverview = v.overview?.blocks?.find((b) => b.id == blockId);\n const sdkVersion = blockOverview?.sdkVersion;\n const toString = sdkVersion && shouldStillUseStringErrors(sdkVersion);\n const newOutputs =\n toString && v.outputs !== undefined ? convertErrorsToStrings(v.outputs) : v.outputs;\n\n return {\n ...v.parameters,\n outputs: newOutputs,\n navigationState: v.navigationState,\n // The block state already nests the overview, so labelling by its titles adds\n // nothing to watch.\n columnLinks: labelBlockColumnLinks({ ...v, blockId }, v.overview?.blocks ?? []),\n } as BlockStateInternalV3;\n },\n },\n );\n\n const computables: BlockStateComputables = {\n fullState: fullState.withPreCalculatedValueTree(),\n dependencies,\n dependents,\n };\n\n this.blockComputables.set(blockId, computables);\n\n return computables;\n }\n return cached;\n }\n\n /**\n * Returns a computable, that can be used to retrieve and watch full block state,\n * including outputs, arguments, ui state.\n * */\n /**\n * Reads the block action context tree of a block render (see readBlockActionContextTree): current state, not\n * watched. Undefined when the block has no action context.\n */\n public async getBlockActionContext(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<BlockActionContextNode | undefined> {\n return await readBlockActionContextTree(this.env.pl, this.rid, blockId, mode);\n }\n\n /**\n * Starts watching the live status of a block render, and returns the folded summary.\n *\n * One watch per block and mode: calling it again while a watch is open returns the same\n * computable. The watch owns a synchronized tree, so the caller must call\n * {@link unwatchBlockStatus} once it stops showing the status; {@link destroy} terminates\n * whatever is left.\n *\n * The summary survives a re-run of the block: a new render gets a new status context, and the\n * watch re-seeds itself onto it.\n */\n public async watchBlockStatus(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<Computable<BlockStatusSummary>> {\n return (await this.retainBlockStatusWatch(blockId, mode)).summary;\n }\n\n /**\n * Starts watching the action-context tree of a block render, context by context. Takes the same\n * hold as {@link watchBlockStatus}, released by {@link unwatchBlockStatus}, and shares its\n * synchronized tree.\n */\n public async watchBlockStatusTree(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<Computable<BlockStatusTree>> {\n return (await this.retainBlockStatusWatch(blockId, mode)).tree;\n }\n\n /**\n * Sets which contexts of {@link watchBlockStatusTree} show their children. A no-op while nobody\n * watches the block: the expansion lives with the watch.\n */\n public async setBlockStatusTreeExpanded(\n blockId: string,\n contextIds: readonly string[],\n mode: BlockActionContextMode = \"prod\",\n ): Promise<void> {\n const pending = this.blockStatusWatches.get(blockStatusKey(blockId, mode));\n if (pending === undefined) return;\n (await pending).setExpanded(contextIds);\n }\n\n private async retainBlockStatusWatch(\n blockId: string,\n mode: BlockActionContextMode,\n ): Promise<BlockStatusWatch> {\n if (this.destroyed)\n throw new Error(`cannot watch the status of ${blockId}: the project is closed`);\n\n const key = blockStatusKey(blockId, mode);\n const existing = this.blockStatusWatches.get(key);\n if (existing !== undefined) {\n const watch = await existing;\n watch.retain();\n return watch;\n }\n\n const started = BlockStatusWatch.start({\n env: this.env,\n projectRid: this.rid,\n blockId,\n mode,\n projectGeneration: () => (this.destroyed ? -1 : this.projectTree.changeGeneration),\n });\n this.blockStatusWatches.set(key, started);\n // A failed start must not leave a rejected promise in the map for every later caller. Only\n // this start's own entry is dropped: by the time a late rejection lands, the key may already\n // hold a newer, live watch.\n started.catch(() => {\n if (this.blockStatusWatches.get(key) === started) this.blockStatusWatches.delete(key);\n });\n return await started;\n }\n\n /**\n * Releases one hold taken by {@link watchBlockStatus}. The tree is terminated when the last\n * holder lets go, so two callers watching one block do not cut each other off.\n */\n public async unwatchBlockStatus(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<void> {\n const key = blockStatusKey(blockId, mode);\n const pending = this.blockStatusWatches.get(key);\n if (pending === undefined) return;\n\n let watch: BlockStatusWatch;\n try {\n watch = await pending;\n } catch {\n // The start failed; its own catch handler drops the entry. Nothing to release, and a\n // caller letting go must not see that failure again.\n return;\n }\n\n if (await watch.release()) {\n if (this.blockStatusWatches.get(key) === pending) this.blockStatusWatches.delete(key);\n }\n }\n\n private async terminateBlockStatusWatches(): Promise<void> {\n const watches = [...this.blockStatusWatches.values()];\n this.blockStatusWatches.clear();\n await Promise.all(\n watches.map(async (watch) => {\n try {\n await (await watch).terminate();\n } catch (e: unknown) {\n // A watch whose start rejected has nothing to terminate; anything else is logged.\n this.env.logger.warn(new Error(\"block status watch termination failed\", { cause: e }));\n }\n }),\n );\n }\n\n public getBlockState(blockId: string): Computable<BlockStateInternalV3> {\n return this.getBlockComputables(blockId).fullState;\n }\n\n /**\n * Returns a computable, that can be used to retrieve and watch path of the\n * folder containing frontend code.\n * */\n public getBlockFrontend(blockId: string): ComputableStableDefined<FrontendData> {\n const cached = this.blockFrontends.get(blockId);\n if (cached === undefined) {\n const fd = frontendData(\n this.projectTree.entry(),\n blockId,\n this.env,\n ).withPreCalculatedValueTree();\n this.blockFrontends.set(blockId, fd);\n return fd;\n }\n return cached;\n }\n\n /** Called by middle layer on close */\n public async destroy(): Promise<void> {\n // terminating the project service loop\n this.abortController.abort();\n try {\n await this.refreshLoopResult;\n } catch (e: unknown) {\n // Error was already logged in the constructor's catch handler, but log again for context\n this.env.logger.warn(\n new Error(\"Refresh loop had terminated with error before destroy\", { cause: e }),\n );\n }\n\n // terminating the status trees before the project tree: they are seeded from it\n await this.terminateBlockStatusWatches();\n\n // terminating the synchronized project tree\n try {\n await this.projectTree.terminate();\n } catch (e: unknown) {\n // TODO: SynchronizedTreeState.terminate() can throw if mainLoop had an error before termination\n // Log error but continue cleanup - we must clean up remaining resources\n this.env.logger.warn(new Error(\"Project tree termination failed\", { cause: e }));\n }\n\n // the following will deregister all external resource holders, like\n // downloaded files, running uploads and alike\n this.overview.resetState();\n this.blockFrontends.forEach((c) => c.resetState());\n this.blockComputables.forEach((c) => {\n if (c !== null) resetBlockState(c);\n });\n this.activeConfigs.resetState();\n }\n\n /** @deprecated */\n public async destroyAndAwaitTermination(): Promise<void> {\n await this.destroy();\n }\n\n public dumpState(): ExtendedResourceData[] {\n return this.projectTree.dumpState();\n }\n\n public static async init(\n env: MiddleLayerEnvironment,\n id: ProjectId,\n rid: SignedResourceId,\n ): Promise<Project> {\n // Applying migrations to the project resource, if needed\n await applyProjectMigrations(env.pl, rid);\n\n // Doing a no-op mutation to apply all migration and schema fixes\n await withProject(env.projectHelper, env.pl, rid, (_) => {}, { name: \"init\" });\n\n // Loading project tree, warm from a persisted mirror when one is usable\n const { tree: projectTree, restored } = await loadProjectTree(env, rid);\n\n if (env.ops.debugOps.dumpInitialTreeState) {\n const state = projectTree.dumpState();\n state.sort((a, b) => (b.data?.byteLength ?? 0) - (a.data?.byteLength ?? 0));\n const stats = treeDumpStats(state);\n await fs.writeFile(`${resourceIdToString(rid)}.json`, stringifyForDump(state));\n await fs.writeFile(`${resourceIdToString(rid)}.stats.json`, stringifyForDump(stats));\n }\n\n return new Project(env, id, rid, projectTree, restored);\n }\n}\n\n/**\n * Opens the project tree, seeded from a persisted mirror when there is a usable one.\n *\n * Carries the fail-safe: if the restored tree fails its first refresh on authentication,\n * permission or an inconsistency, the snapshot is deleted and the open is retried cold. Once,\n * and only for that first refresh, so a genuinely dead session still surfaces as itself rather\n * than being masked as a slow open.\n *\n * The fail-safe is what bounds every case the cache key does not cover: a rotated master\n * secret, a revoked grant, a snapshot valid in itself but no longer matching what the backend\n * will serve. Without it, an explicit-root tree propagates the refresh failure rather than\n * healing, so the project would fail to open on every attempt until someone deleted the cache\n * directory by hand.\n */\nasync function loadProjectTree(\n env: MiddleLayerEnvironment,\n rid: SignedResourceId,\n): Promise<{ tree: SynchronizedTreeState; restored: boolean }> {\n const treeOps = {\n ...env.ops.defaultTreeOptions,\n pruning: projectTreePruning(env.logger),\n fieldFilter: projectTreeFieldFilter(),\n traverseStopRules: projectTreeTraverseStopRules(),\n };\n const cold = async () => ({\n tree: await SynchronizedTreeState.init(env.pl, rid, treeOps, env.logger),\n restored: false,\n });\n\n const store = env.treeSnapshots;\n if (store === undefined) return await cold();\n\n const snapshot = await store.read(rid);\n if (!snapshot.ok) {\n env.logger.info(`project tree opening cold, snapshot miss: ${snapshot.miss}`);\n return await cold();\n }\n\n try {\n const tree = await SynchronizedTreeState.init(\n env.pl,\n rid,\n { ...treeOps, restoreFrom: snapshot.tree },\n env.logger,\n );\n\n // Read from the tree rather than assumed: a snapshot can be handed over and still be\n // refused, in which case this open was cold and the file on disk does not describe the\n // tree we now hold.\n const restored = tree.wasRestoredFromSnapshot;\n if (restored) store.noteRestored();\n else env.logger.info(\"project tree opening cold: the snapshot was not applied\");\n\n return { tree, restored };\n } catch (e: unknown) {\n // Retry cold on ANY failure of the warm open, not only on the classified ones. A cold open\n // is exactly what this code did before snapshots existed, so the retry cannot regress\n // anything, whereas rethrowing here leaves a project that fails to open on every attempt\n // until someone deletes the cache directory by hand: the snapshot stays on disk and the\n // next open restores it and fails the same way. That is the outcome this fail-safe exists\n // to prevent, and the error classes that can reach here are not a closed set.\n env.logger.warn(\n new Error(\"restored project tree failed its first refresh, opening cold\", { cause: e }),\n );\n\n // Deleting is reserved for failures that implicate the snapshot itself. Anything else (a\n // timeout, a dropped connection) says nothing about the file, and throwing it away would\n // destroy a mirror that is still good, along with the evidence a later signature refresh\n // would repair.\n if (isSnapshotFailsafeError(e)) await store.discard(rid);\n\n return await cold();\n }\n}\n\n/** The failures that implicate the snapshot rather than the link or the session: a rotated\n * master secret, a revoked grant, or state the tree cannot reconcile. Only these delete the\n * file; every other failure still falls back to a cold open, it just keeps the file.\n *\n * The cause chain is walked because a wrapper anywhere between the tree update and here would\n * otherwise silently disarm the inconsistency arm. `isUnauthenticated` and `isPermissionDenied`\n * do their own one-level unwrapping. */\nexport function isSnapshotFailsafeError(e: unknown): boolean {\n if (isUnauthenticated(e) || isPermissionDenied(e)) return true;\n for (let cause: unknown = e, depth = 0; cause !== undefined && depth < 8; depth++) {\n if (cause instanceof TreeStateUpdateError) return true;\n cause = (cause as { cause?: unknown } | null)?.cause;\n }\n return false;\n}\n\n/** Key of a status watch in {@link Project.blockStatusWatches}. */\nfunction blockStatusKey(blockId: string, mode: BlockActionContextMode): string {\n return `${mode}:${blockId}`;\n}\n\nexport function projectTreePruning(logger: MiLogger): PruningFunction {\n return (r: ExtendedResourceData): FieldData[] => {\n if (r.fields.length > 1000)\n logger.warn(\n `resource with excessive field count: type=${r.type.name} id=${r.id} fields=${r.fields.length}` +\n ` names=[${r.fields\n .slice(0, 10)\n .map((f) => f.name)\n .join(\", \")}, ...]`,\n );\n if (r.type.name.startsWith(\"StreamWorkdir/\")) return [];\n switch (r.type.name) {\n case \"BlockPackCustom\":\n return r.fields.filter((f) => f.name !== \"template\");\n case \"UserProject\":\n return r.fields.filter(\n (f) => !f.name.startsWith(\"__serviceTemplate\") && !projectStatusFieldRegex.test(f.name),\n );\n case \"Blob\":\n return [];\n default:\n return r.fields;\n }\n };\n}\n\n/** ResourceTree analogue of projectTreePruning() used by modern backend path. */\nexport function projectTreeFieldFilter(): Filter {\n return treeFilter.not(\n treeFilter.or(\n // StreamWorkdir/* — pruned entirely\n treeFilter.resourceTypeMatch(\"^StreamWorkdir/\"),\n // BlockPackCustom: drop `template`\n treeFilter.and(\n treeFilter.resourceTypeEq(\"BlockPackCustom\"),\n treeFilter.fieldNameEq(\"template\"),\n ),\n // UserProject: drop `__serviceTemplate*`\n treeFilter.and(\n treeFilter.resourceTypeEq(\"UserProject\"),\n treeFilter.fieldNameMatch(\"^__serviceTemplate\"),\n ),\n // UserProject: drop the status-context fields, see ProjectStatusFieldPattern\n treeFilter.and(\n treeFilter.resourceTypeEq(\"UserProject\"),\n treeFilter.fieldNameMatch(ProjectStatusFieldPattern),\n ),\n // Blob — pruned entirely\n treeFilter.resourceTypeEq(\"Blob\"),\n ),\n );\n}\n\n/** Stop rules for the project tree's ResourceTree walks: {@link TreeFinality}'s declared clauses,\n * which may stop before the predicate calls a resource final where an entry declares so. */\nexport function projectTreeTraverseStopRules(): Filter {\n return finalityStopRules(TreeFinality);\n}\n\n/** Whether the block's model declares that its UI reads the column links of the block state. */\nfunction readsColumnLinks(prj: PlTreeNodeAccessor, blockId: string): boolean {\n const info = getBlockPackInfo(prj, blockId);\n return info !== undefined && checkBlockFlag(info.cfg.featureFlags, \"supportsColumnLinks\");\n}\n\n/** Returns true if sdk version of the block is old and we need to convert\n * ErrorLike errors to strings like it was.\n * We need it for keeping old blocks and new UI compatibility. */\nfunction shouldStillUseStringErrors(sdkVersion: string): boolean {\n return !isVersionGreater(sdkVersion, \"1.26.0\");\n}\n\n/** Checks if sdk version is greater that a target version. */\nfunction isVersionGreater(sdkVersion: string, targetVersion: string): boolean {\n const version = sdkVersion.split(\".\").map(Number);\n const target = targetVersion.split(\".\").map(Number);\n\n return (\n version[0] > target[0] ||\n (version[0] === target[0] && version[1] > target[1]) ||\n (version[0] === target[0] && version[1] === target[1] && version[2] > target[2])\n );\n}\n\n/** Converts ErrorLike errors to strings in the outputs like it was in old ML versions. */\nfunction convertErrorsToStrings(\n outputs: Record<string, ComputableValueOrErrors<unknown>>,\n): Record<string, ComputableValueOrErrors<unknown>> {\n const result: Record<string, ComputableValueOrErrors<unknown>> = {};\n for (const [key, val] of Object.entries(outputs)) {\n if (val.ok) {\n result[key] = val;\n continue;\n }\n\n result[key] = {\n ok: false,\n errors: val.errors.map((e) => {\n if (typeof e === \"string\") {\n return e;\n } else if (e.type == \"PlError\" && e.fullMessage !== undefined) {\n return e.fullMessage;\n }\n return e.message;\n }),\n moreErrors: val.moreErrors,\n };\n }\n\n return result;\n}\n\n/** Throws when the connected backend doesn't advertise every capability the\n * block-pack requires (as declared in `meta.requiredCapabilities`).\n *\n * The matching set is the desktop's install gate moved server-side so both\n * the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's\n * `add_block` tool, programmatic block installs, tests) reject incompatible\n * blocks consistently. */\nexport function throwIfMissingServerCapabilities(\n pl: PlClient,\n requiredCapabilities: readonly string[] | undefined,\n): void {\n if (!requiredCapabilities || requiredCapabilities.length === 0) return;\n const advertised = (pl.serverInfo.capabilities ?? []) as readonly string[];\n const filterFn = (c: string) => !advertised.includes(c);\n if (!requiredCapabilities.some(filterFn)) return;\n const missing = requiredCapabilities.filter(filterFn);\n throw new Error(\n `Block cannot be added: connected backend does not advertise capabilities ` +\n `${JSON.stringify(missing)}. ` +\n `Backend advertises ${JSON.stringify(advertised)}. ` +\n `Upgrade the backend or remove the requirement from the block manifest.`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoGA,SAAS,iBAAiB,QAAyB;CACjD,OAAO,KAAK,UAAU,SAAS,KAAK,UAAU;EAC5C,IAAI,OAAO,UAAU,UAAU,QAAA,GAAOA,0BAAAA,mBAAAA,CAAmB,KAA8B;OAClF,IACH,YAAY,OAAO,KAAK,KACxB,iBAAiB,aACjB,iBAAiB,cACjB,iBAAiB,qBACjB,iBAAiB,cACjB,iBAAiB,eACjB,iBAAiB,cACjB,iBAAiB,eACjB,iBAAiB,gBACjB,iBAAiB,gBACjB,iBAAiB,iBACjB,iBAAiB,gBAEjB,OAAO,OAAO,KAAK,MAAM,QAAQ,MAAM,YAAY,MAAM,UAAU,CAAC,CAAC,SAAS,QAAQ;OACnF,IAAI,OAAO,SAAS,KAAK,GAAG,OAAO,MAAM,SAAS,QAAQ;EAE/D,OAAO;CACT,CAAC;AACH;;AAGA,SAAS,gBAAgB,aAA0C;CACjE,YAAY,UAAU,WAAW;CACjC,YAAY,aAAa,WAAW;CACpC,YAAY,WAAW,WAAW;AACpC;;AAwBA,IAAa,U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ACL,KAAK,UAAU,UAAU,EAAE,yEAErD;AACF"}
1
+ {"version":3,"file":"project.cjs","names":["resourceIdToString","NavigationStates","projectOverview","projectOverviewLight","activeConfigs","parseSignedResourceId","withProject","setTimeout","isNotFoundError","isTimeoutOrCancelError","nextInfiniteRetryState","createInfiniteRetryState","randomUUID","extractConfig","ModelAPIVersionMismatchError","BLOCK_STORAGE_FACADE_VERSION","BlockStorageFacadeCallbacks","BlockInitParamsRejectedError","cacheBlockPackTemplate","withProjectAuthored","DefaultRetryOptions","ensureSignedResourceIdNotNull","field","projectFieldName","Pl","cachedDeserialize","notEmpty","blockOutputs","blockDependencies","blockDependents","Computable","getBlockParameters","labelBlockColumnLinks","readBlockActionContextTree","BlockStatusWatch","frontendData","applyProjectMigrations","treeDumpStats","fs","SynchronizedTreeState","isUnauthenticated","isPermissionDenied","TreeStateUpdateError","projectStatusFieldRegex","treeFilter","ProjectStatusFieldPattern","finalityStopRules","TreeFinality","getBlockPackInfo","checkBlockFlag"],"sources":["../../src/middle_layer/project.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"./middle_layer\";\nimport type {\n FieldData,\n Filter,\n OptionalAnyResourceId,\n PlClient,\n SignedResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n DefaultRetryOptions,\n ensureSignedResourceIdNotNull,\n field,\n isNotFoundError,\n isPermissionDenied,\n isTimeoutOrCancelError,\n isUnauthenticated,\n parseSignedResourceId,\n Pl,\n resourceIdToString,\n treeFilter,\n TreeFinality,\n} from \"@milaboratories/pl-client\";\nimport { finalityStopRules } from \"./finality_stop_rules\";\nimport type { ComputableStableDefined, ComputableValueOrErrors } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport { projectOverview } from \"./project_overview\";\nimport { blockDependencies, blockDependents, labelBlockColumnLinks } from \"./column_links\";\nimport type { BlockPackSpecAny } from \"../model\";\nimport { randomUUID } from \"node:crypto\";\nimport { withProject, withProjectAuthored } from \"../mutator/project\";\nimport type {\n ExtendedResourceData,\n PlTreeNodeAccessor,\n PruningFunction,\n} from \"@milaboratories/pl-tree\";\nimport {\n SynchronizedTreeState,\n treeDumpStats,\n TreeStateUpdateError,\n} from \"@milaboratories/pl-tree\";\nimport type { TreeSnapshotStore } from \"./tree_snapshot_store\";\nimport { setTimeout } from \"node:timers/promises\";\nimport { frontendData } from \"./frontend_path\";\nimport type { NavigationState } from \"@milaboratories/pl-model-common\";\nimport { getBlockParameters, blockOutputs } from \"./block\";\nimport type { BlockActionContextMode, BlockActionContextNode } from \"./block_action_context\";\nimport { readBlockActionContextTree } from \"./block_action_context\";\nimport { getBlockPackInfo } from \"./util\";\nimport { BlockStatusWatch } from \"./block_status_tree\";\nimport type { BlockStatusSummary, BlockStatusTree } from \"@milaboratories/pl-model-middle-layer\";\nimport type { FrontendData } from \"../model/frontend\";\nimport type { ProjectId, ProjectStructure } from \"../model/project_model\";\nimport {\n projectFieldName,\n ProjectStatusFieldPattern,\n projectStatusFieldRegex,\n} from \"../model/project_model\";\nimport {\n cachedDeserialize,\n notEmpty,\n type MiLogger,\n createInfiniteRetryState,\n nextInfiniteRetryState,\n type InfiniteRetryState,\n} from \"@milaboratories/ts-helpers\";\nimport type { BlockPackInfo } from \"../model/block_pack\";\nimport type {\n ProjectOverview,\n AuthorMarker,\n BlockSettings,\n BlockStateInternalV3,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport type { BlockId, ColumnLink } from \"@milaboratories/pl-model-common\";\nimport { activeConfigs } from \"./active_cfg\";\nimport { NavigationStates } from \"./navigation_states\";\nimport {\n checkBlockFlag,\n extractConfig,\n BLOCK_STORAGE_FACADE_VERSION,\n BlockStorageFacadeCallbacks,\n type BlockKindReference,\n} from \"@platforma-sdk/model\";\nimport {\n BlockInitParamsRejectedError,\n ModelAPIVersionMismatchError,\n} from \"@milaboratories/pl-errors\";\nimport fs from \"node:fs/promises\";\nimport canonicalize from \"canonicalize\";\nimport type { ProjectOverviewLight } from \"./project_overview_light\";\nimport { projectOverviewLight } from \"./project_overview_light\";\nimport { applyProjectMigrations } from \"../mutator/migration\";\nimport { cacheBlockPackTemplate } from \"../mutator/template/template_cache\";\n\ntype BlockStateComputables = {\n readonly fullState: Computable<BlockStateInternalV3>;\n /** Column links of the block, nested into its full state. */\n readonly dependencies: Computable<ColumnLink[] | undefined>;\n readonly dependents: Computable<ColumnLink[] | undefined>;\n};\n\nfunction stringifyForDump(object: unknown): string {\n return JSON.stringify(object, (key, value) => {\n if (typeof value === \"bigint\") return resourceIdToString(value as OptionalAnyResourceId);\n else if (\n ArrayBuffer.isView(value) ||\n value instanceof Int8Array ||\n value instanceof Uint8Array ||\n value instanceof Uint8ClampedArray ||\n value instanceof Int16Array ||\n value instanceof Uint16Array ||\n value instanceof Int32Array ||\n value instanceof Uint32Array ||\n value instanceof Float32Array ||\n value instanceof Float64Array ||\n value instanceof BigInt64Array ||\n value instanceof BigUint64Array\n )\n return Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString(\"base64\");\n else if (Buffer.isBuffer(value)) return value.toString(\"base64\");\n\n return value;\n });\n}\n\n/** Releases what the computables of a block hold. */\nfunction resetBlockState(computables: BlockStateComputables): void {\n computables.fullState.resetState();\n computables.dependencies.resetState();\n computables.dependents.resetState();\n}\n\n/** Options of {@link Project.addBlock}. */\nexport type AddBlockOps = {\n /**\n * Start the block from initialization params instead of the model's default state. The block's\n * model checks the params against its kind and builds its initial storage from them. Only a\n * block with model API version 2 whose SDK has the params initializer can be created this way.\n */\n init?: {\n /** The kind's initialization params, as a template entry holds them. */\n params: unknown;\n /**\n * Ids used inside `params` in place of block ids, each mapped to the id of a block of this\n * project. The block's model replaces them in every reference it recognizes. An id that is\n * not listed is left as it is, so params that already hold real block ids need no map.\n */\n blockIds?: Readonly<Record<string, BlockId>>;\n };\n /** Refuse to add a block whose model API version differs from this one. */\n requireModelAPIVersion?: number;\n};\n\n/** Data access object, to manipulate and read single opened (!) project data. */\nexport class Project {\n /** Data for the left panel, contain basic information about block status. */\n public readonly overview: ComputableStableDefined<ProjectOverview>;\n private readonly overviewLight: Computable<ProjectOverviewLight>;\n\n private readonly navigationStates = new NavigationStates();\n // null is set for deleted blocks\n private readonly blockComputables = new Map<string, BlockStateComputables | null>();\n\n private readonly blockFrontends = new Map<string, ComputableStableDefined<FrontendData>>();\n\n /** Live status watches, keyed by {@link blockStatusKey}. One per block whose status is shown;\n * each owns a synchronized tree, so they are started and terminated explicitly. */\n private readonly blockStatusWatches = new Map<string, Promise<BlockStatusWatch>>();\n private readonly activeConfigs: Computable<unknown[]>;\n private readonly refreshLoopResult: Promise<void>;\n\n private readonly abortController = new AbortController();\n\n /** Tree change generation as of the snapshot currently on disk, or -1 when this session has\n * not written one. Compared against the tree's current generation to skip writing a mirror\n * that has not moved, which is what makes a project left open and idle go quiet. */\n private snapshotGeneration: number;\n\n /** When a snapshot was last attempted, for the periodic write's wall-clock gate.\n *\n * Zero, not the construction time, so the first write lands on the first maintenance pass\n * after the tree has settled rather than a full interval later. Sessions shorter than one\n * interval are the common case for a desktop app that is quit with a project still open, and\n * seeding this to now would leave every one of them with nothing on disk. Set on every\n * attempt, successful or not, so a persistently failing write retries at the interval rather\n * than on every pass of the loop. */\n private lastSnapshotAt = 0;\n\n private get destroyed() {\n return this.abortController.signal.aborted;\n }\n\n constructor(\n private readonly env: MiddleLayerEnvironment,\n public readonly id: ProjectId /* Project ID, exposed to outer consumers, who work with ML */,\n readonly rid: SignedResourceId /* Contains signature, not exposed outside middle layer. */,\n private readonly projectTree: SynchronizedTreeState,\n /** Whether this tree was seeded from a snapshot. When it was, the file on disk already\n * holds generation 0, so an idle warm reopen writes nothing at all. */\n restoredFromSnapshot: boolean = false,\n /** Called once, from the maintenance loop, when the loop finds the project was deleted\n * elsewhere. The loop has stopped by then; the owner is expected to destroy the project. */\n private readonly onGone?: (project: Project) => void,\n ) {\n this.snapshotGeneration = restoredFromSnapshot ? 0 : -1;\n this.overview = projectOverview(\n projectTree.entry(),\n this.navigationStates,\n env,\n ).withPreCalculatedValueTree();\n this.overviewLight = projectOverviewLight(projectTree.entry()).withPreCalculatedValueTree();\n this.refreshLoopResult = this.refreshLoop();\n this.refreshLoopResult.catch((err) => {\n env.logger.warn(new Error(\"Error during refresh loop\", { cause: err })); // TODO (safe voiding for now)\n });\n this.activeConfigs = activeConfigs(projectTree.entry(), env);\n }\n\n get projectLockId(): string {\n return \"project:\" + this.id.toString();\n }\n\n /**\n * Periodic snapshot write, carried on the maintenance loop rather than a timer of its own.\n *\n * Gated on the tree having changed since the last snapshot, so a project left open and idle\n * writes once and then goes quiet, and on wall clock, so a project changing continuously\n * writes at most once per interval.\n */\n private async maybeWriteSnapshot(): Promise<void> {\n const store = this.env.treeSnapshots;\n if (store === undefined) return;\n\n const generation = this.projectTree.changeGeneration;\n if (generation === this.snapshotGeneration) return;\n if (Date.now() - this.lastSnapshotAt < this.env.ops.treeSnapshotOps.writeInterval) return;\n\n await this.writeSnapshot(store, generation);\n }\n\n /**\n * Starts the close-boundary snapshot and returns without waiting for the write.\n *\n * On top of the periodic write, since closing is a natural point to persist. Change-gated but\n * not interval-gated: rewriting a mirror that has not moved is pure waste, but a mirror that\n * has moved is worth keeping however recently the last write happened.\n *\n * The **capture is synchronous and happens here**, before the caller destroys the tree,\n * because destroying it invalidates it and a later capture would be refused. Only the encode\n * and the write are deferred: they are up to ten megabytes of work, and project switching\n * should not wait for them. Deferring is safe only because a capture is a copy rather than a\n * view of the tree.\n *\n * The returned promise never rejects. The caller is expected to keep it so it can be drained\n * at shutdown, not to await it here.\n */\n public snapshotOnClose(): Promise<void> {\n const store = this.env.treeSnapshots;\n if (store === undefined) return Promise.resolve();\n\n const generation = this.projectTree.changeGeneration;\n if (generation === this.snapshotGeneration) return Promise.resolve();\n\n let snapshot;\n try {\n snapshot = this.projectTree.capture(parseSignedResourceId(this.rid).signature);\n } catch (e: unknown) {\n this.env.logger.warn(\n new Error(`failed to capture tree snapshot for project ${this.id} on close`, { cause: e }),\n );\n return Promise.resolve();\n }\n\n this.lastSnapshotAt = Date.now();\n\n // Queued behind any in-flight periodic write rather than racing it. Both would land\n // atomically, but the loser would be a wasted encode of the same mirror.\n const previous = this.snapshotInFlight ?? Promise.resolve();\n const write = previous.then(async () => {\n if (this.snapshotGeneration >= generation) return; // the in-flight write covered it\n if (await store.write(this.rid, snapshot)) this.snapshotGeneration = generation;\n });\n\n this.snapshotInFlight = write.finally(() => {\n this.snapshotInFlight = undefined;\n });\n return this.snapshotInFlight;\n }\n\n /** In-flight snapshot write, if any. Both triggers can fire close together (the close write\n * lands while the loop is mid-write), and encoding ten megabytes twice for the same mirror\n * is worth avoiding. */\n private snapshotInFlight: Promise<void> | undefined;\n\n /** Serializes writes, and skips one that the in-flight write has already made redundant. */\n private async writeSnapshot(store: TreeSnapshotStore, generation: number): Promise<void> {\n // A loop, not a single check: with three or more callers, re-checking only once would let\n // a waiter install its own promise over another's and clear the field while that write is\n // still running. Two callers is the most that can happen today, so this is a guard against\n // the next caller rather than a live fix.\n while (this.snapshotInFlight !== undefined) {\n await this.snapshotInFlight;\n if (this.snapshotGeneration >= generation) return;\n }\n\n this.snapshotInFlight = this.captureAndWrite(store, generation).finally(() => {\n this.snapshotInFlight = undefined;\n });\n await this.snapshotInFlight;\n }\n\n /** Captures and writes, never throwing: a snapshot is an optimisation and must not fail\n * whatever triggered it. */\n private async captureAndWrite(store: TreeSnapshotStore, generation: number): Promise<void> {\n // Recorded before the attempt and regardless of its outcome, so a failing disk is retried\n // once per interval instead of on every pass of the maintenance loop.\n this.lastSnapshotAt = Date.now();\n try {\n // The root's signature is the session witness a later open compares against.\n const snapshot = this.projectTree.capture(parseSignedResourceId(this.rid).signature);\n\n // Only a real write advances the change gate. Marking the generation persisted after a\n // failed write would tell both triggers the tree is already on disk, so one transient\n // I/O error would cost the rest of the session, close write included.\n if (await store.write(this.rid, snapshot)) this.snapshotGeneration = generation;\n } catch (e: unknown) {\n this.env.logger.warn(\n new Error(`failed to capture tree snapshot for project ${this.id}`, { cause: e }),\n );\n }\n }\n\n /**\n * Brings the project tree up to a write that has just committed.\n *\n * The write is already on the backend when this runs, so a project destroyed meanwhile (closed\n * by its last holder, or deleted) must not turn it into a failure: a caller told it failed would\n * retry it and apply it twice. `destroy` marks the project destroyed before it terminates the\n * tree, so a refresh failing on a terminated tree always finds the mark set.\n */\n private async refreshAfterWrite(): Promise<void> {\n if (this.destroyed) return;\n try {\n await this.projectTree.refreshState();\n } catch (e: unknown) {\n if (this.destroyed) return;\n throw e;\n }\n }\n\n private async refreshLoop(): Promise<void> {\n let retryState: InfiniteRetryState | undefined;\n let gone = false;\n while (!this.destroyed) {\n try {\n await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (prj) => {\n prj.doRefresh();\n },\n {\n name: \"doRefresh\",\n lockId: this.projectLockId,\n abortSignal: this.abortController.signal,\n },\n );\n await this.activeConfigs.getValue();\n await setTimeout(this.env.ops.projectRefreshInterval, undefined, {\n signal: this.abortController.signal,\n });\n\n await this.maybeWriteSnapshot();\n\n // Block computables housekeeping\n const overviewLight = await this.overviewLight.getValue();\n const existingBlocks = new Set(overviewLight.listOfBlocks);\n // Doing cleanup for deleted blocks\n for (const blockId of this.blockComputables.keys()) {\n if (!existingBlocks.has(blockId)) {\n const computables = this.blockComputables.get(blockId);\n if (computables !== undefined && computables !== null) resetBlockState(computables);\n this.blockComputables.set(blockId, null);\n }\n }\n retryState = undefined;\n } catch (error: unknown) {\n // If we're destroyed, exit gracefully regardless of error type\n if (this.destroyed) break;\n\n if (isNotFoundError(error)) {\n this.env.logger.warn(\n \"project refresh routine terminated, because project was externally deleted\",\n );\n gone = true;\n break;\n } else if (isTimeoutOrCancelError(error)) {\n // Timeout during normal operation, continue the loop\n } else {\n retryState = retryState\n ? nextInfiniteRetryState(retryState)\n : createInfiniteRetryState({\n type: \"exponentialWithMaxDelayBackoff\",\n initialDelay: 1000,\n maxDelay: 60_000,\n backoffMultiplier: 2,\n jitter: 0,\n });\n this.env.logger.error(\n new Error(`[refreshLoop] unexpected exception, retrying in ${retryState.nextDelay}ms`, {\n cause: error,\n }),\n );\n try {\n await setTimeout(retryState.nextDelay, undefined, {\n signal: this.abortController.signal,\n });\n } catch {\n // Aborted during retry delay, will exit via while condition or destroyed check\n break;\n }\n }\n }\n }\n if (gone) this.onGone?.(this);\n }\n\n /**\n * Adds new block to the project.\n *\n * @param blockLabel block label / title visible to the user\n * @param blockPackSpec object describing the \"block type\", read more in the type docs\n * @param before id of the block to insert new block before\n * @param blockId internal id to be assigned for the block, this arg can be omitted\n * then, randomly generated UUID will be assigned automatically\n * @param ops see {@link AddBlockOps}\n *\n * @return returns newly created block id\n * @throws ModelAPIVersionMismatchError when `ops.requireModelAPIVersion` differs from the\n * block's model API version; nothing is created\n * @throws BlockInitParamsRejectedError when the block does not accept `ops.init.params`;\n * nothing is created\n * */\n public async addBlock(\n blockLabel: string,\n blockPackSpec: BlockPackSpecAny,\n before?: string,\n author: AuthorMarker | undefined = undefined,\n blockId: string = randomUUID(),\n ops: AddBlockOps = {},\n ): Promise<string> {\n const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);\n const blockCfg = extractConfig(preparedBp.config);\n\n if (\n ops.requireModelAPIVersion !== undefined &&\n blockCfg.modelAPIVersion !== ops.requireModelAPIVersion\n )\n throw new ModelAPIVersionMismatchError(\n blockId,\n ops.requireModelAPIVersion,\n blockCfg.modelAPIVersion,\n );\n\n this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);\n throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);\n\n // The block's own model turns the params into its initial storage, and may decline them.\n // Asked before the template is cached and before the transaction, so a refusal changes\n // nothing on the backend.\n let initialStorage: string | undefined;\n if (ops.init !== undefined) {\n if (blockCfg.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION)\n throw new ModelAPIVersionMismatchError(\n blockId,\n BLOCK_STORAGE_FACADE_VERSION,\n blockCfg.modelAPIVersion,\n );\n if (\n blockCfg.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams] ===\n undefined\n )\n throw new BlockInitParamsRejectedError(\n \"this version of the block was built before blocks could be created from \" +\n \"initialization params; use a newer version of the block\",\n );\n const storage = this.env.projectHelper.getInitialStorageFromParamsInVM(\n blockCfg,\n ops.init.params,\n new Map(Object.entries(ops.init.blockIds ?? {})),\n );\n if (storage.error !== undefined)\n throw new BlockInitParamsRejectedError(storage.error.message);\n initialStorage = storage.value;\n }\n\n // Pre-materialize template via cache (separate transaction(s))\n const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);\n\n // Build NewBlockSpec based on model API version\n const newBlockSpec =\n blockCfg.modelAPIVersion === BLOCK_STORAGE_FACADE_VERSION\n ? { storageMode: \"fromModel\" as const, blockPack: cachedBp, initialStorage }\n : {\n storageMode: \"legacy\" as const,\n blockPack: cachedBp,\n legacyState: canonicalize({\n args: blockCfg.initialArgs,\n uiState: blockCfg.initialUiState,\n })!,\n };\n\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n return mut.addBlock(\n {\n id: blockId,\n label: blockLabel,\n renderingMode: blockCfg.renderingMode,\n },\n newBlockSpec,\n before,\n );\n },\n {\n retryOptions: {\n ...DefaultRetryOptions,\n backoffMultiplier: DefaultRetryOptions.backoffMultiplier * 1.1,\n },\n name: \"addBlock\",\n lockId: this.projectLockId,\n },\n );\n\n await this.refreshAfterWrite();\n\n return blockId;\n }\n\n /**\n * Duplicates an existing block by copying all its fields and state.\n * This method works at the mutator level for efficient block copying.\n *\n * @param originalBlockId id of the block to duplicate\n * @param before id of the block to insert new block before\n * @param author author marker for the duplication operation\n * @param newBlockId internal id to be assigned for the duplicated block,\n * if omitted, a randomly generated UUID will be assigned\n *\n * @return returns newly created block id\n * */\n public async duplicateBlock(\n originalBlockId: string,\n before?: string,\n author: AuthorMarker | undefined = undefined,\n newBlockId: string = randomUUID(),\n ): Promise<string> {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.duplicateBlock(originalBlockId, newBlockId, before),\n { name: \"duplicateBlock\", lockId: this.projectLockId },\n );\n await this.refreshAfterWrite();\n\n return newBlockId;\n }\n\n /**\n * Update block to new block pack, optionally resetting args and ui state to\n * initial values\n * */\n public async updateBlockPack(\n blockId: string,\n blockPackSpec: BlockPackSpecAny,\n resetArgs: boolean = false,\n author?: AuthorMarker,\n ): Promise<void> {\n const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);\n const blockCfg = extractConfig(preparedBp.config);\n\n this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);\n throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);\n\n // Pre-materialize template via cache (separate transaction(s))\n const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);\n\n // resetState signals to mutator to reset storage\n // For v2+ blocks: mutator gets initial storage directly via getInitialStorageInVM\n // For v1 blocks: we pass the legacy state format\n const resetState = resetArgs\n ? {\n state:\n blockCfg.modelAPIVersion === 1\n ? { args: blockCfg.initialArgs, uiState: blockCfg.initialUiState }\n : {},\n }\n : undefined;\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.migrateBlockPack(blockId, cachedBp, resetState),\n { name: \"updateBlockPack\", lockId: this.projectLockId },\n );\n await this.refreshAfterWrite();\n }\n\n /** Deletes a block with all associated data. */\n public async deleteBlock(blockId: string, author?: AuthorMarker): Promise<void> {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.deleteBlock(blockId),\n { name: \"deleteBlock\", lockId: this.projectLockId },\n );\n this.navigationStates.deleteBlock(blockId);\n await this.refreshAfterWrite();\n }\n\n /**\n * Updates block order according to the given array of block ids.\n *\n * Provided array must contain exactly the same set of ids current project cosists of,\n * an error will be thrown instead.\n */\n public async reorderBlocks(blocks: string[], author?: AuthorMarker): Promise<void> {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n const currentStructure = mut.structure;\n if (currentStructure.groups.length !== 1)\n throw new Error(\"Unexpected project structure, non-singular block group\");\n const currentGroup = currentStructure.groups[0];\n if (currentGroup.blocks.length !== blocks.length)\n throw new Error(`Length mismatch: ${currentGroup.blocks.length} !== ${blocks.length}`);\n if (new Set<string>(blocks).size !== blocks.length) throw new Error(`Repeated block ids`);\n const newStructure: ProjectStructure = {\n groups: [\n {\n id: currentGroup.id,\n label: currentGroup.label,\n blocks: blocks.map((blockId) => {\n const block = currentGroup.blocks.find((b) => b.id === blockId);\n if (block === undefined) throw new Error(`Can't find block: ${blockId}`);\n return block;\n }),\n },\n ],\n };\n mut.updateStructure(newStructure);\n },\n { name: \"reorderBlocks\", lockId: this.projectLockId },\n );\n await this.refreshAfterWrite();\n }\n\n /**\n * Renders production part of the block starting all connected heavy computations.\n * Upstream blocks of the specified block will be started automatically if in\n * stale state.\n * */\n public async runBlock(blockId: string): Promise<void> {\n await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (mut) => mut.renderProduction([blockId], true),\n { name: \"runBlock\", lockId: this.projectLockId },\n );\n await this.refreshAfterWrite();\n }\n\n /**\n * Stops the block if it is running by destroying its production state. All\n * its downstreams will also be destroyed or moved to limbo if already\n * calculated.\n * */\n public async stopBlock(blockId: string): Promise<void> {\n await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (mut) => mut.stopProduction(blockId),\n { name: \"stopBlock\", lockId: this.projectLockId },\n );\n await this.refreshAfterWrite();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\n * Sets block args, and changes whole project state accordingly.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setBlockArgs(blockId: string, args: unknown, author?: AuthorMarker) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n const state = mut.mergeBlockState(blockId, { args });\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setBlockArgs\", lockId: this.projectLockId },\n );\n await this.refreshAfterWrite();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\n * Sets ui block state associated with the block.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setUiState(blockId: string, uiState: unknown, author?: AuthorMarker) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n const state = mut.mergeBlockState(blockId, { uiState });\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setUiState\", lockId: this.projectLockId },\n );\n await this.refreshAfterWrite();\n }\n\n /**\n * @deprecated Use mutateBlockStorage() for V3 blocks.\n * Sets block args and ui state, and changes the whole project state accordingly.\n * Along with setting arguments one can specify author marker, that will be\n * transactionally associated with the block, to facilitate conflict resolution\n * in collaborative editing scenario.\n * */\n public async setBlockArgsAndUiState(\n blockId: string,\n args: unknown, // keep for v1/v2 compatibility\n uiState: unknown, // keep for v1/v2 compatibility\n author?: AuthorMarker,\n ) {\n // Normalize to unified state format { args, uiState } for v1/v2 blocks\n const state = { args, uiState };\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => {\n mut.setStates([{ modelAPIVersion: 1, blockId, state }]);\n },\n { name: \"setBlockArgsAndUiState\", lockId: this.projectLockId },\n );\n await this.refreshAfterWrite();\n }\n\n /**\n * Sets navigation state.\n * */\n //\n public async setNavigationState(blockId: string, state: NavigationState): Promise<void> {\n this.navigationStates.setState(blockId, state);\n }\n\n /**\n * Mutates block storage for Model API v3 blocks.\n * Applies a storage operation (e.g., 'update-data') which triggers\n * args derivation (args(data) and prerunArgs(data)).\n * The derived args are stored atomically with the data.\n *\n * @param blockId - The block ID\n * @param payload - Storage mutation payload with operation and value\n * @param author - Optional author marker for collaborative editing\n */\n public async mutateBlockStorage(\n blockId: string,\n payload: { operation: string; value: unknown },\n author?: AuthorMarker,\n ) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n author,\n (mut) => mut.setStates([{ modelAPIVersion: 2, blockId, payload }]),\n { name: \"mutateBlockStorage\", lockId: this.projectLockId },\n );\n await this.refreshAfterWrite();\n }\n\n /**\n * Reads the block's initialization params as its own model projects them from the current\n * storage, with the kind the block declares: the entry a template export writes for this block.\n * Passing the result as {@link AddBlockOps.init} to {@link addBlock} with the same block pack\n * recreates the block's configuration.\n *\n * @returns `kind` is undefined for a block that declares none; `params` is undefined when the\n * block has no storage yet\n * @throws when the project has no such block, or the block's model fails to project its params\n */\n public async getBlockInitializationParams(\n blockId: BlockId,\n ): Promise<{ kind: BlockKindReference | undefined; params: unknown }> {\n return await withProject(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n (prj) => prj.getBlockInitializationParams(blockId),\n { name: \"getBlockInitializationParams\", lockId: this.projectLockId },\n );\n }\n\n /** Update block settings */\n public async setBlockSettings(blockId: string, newValue: BlockSettings) {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n undefined,\n (mut) => {\n mut.setBlockSettings(blockId, newValue);\n },\n { name: \"setBlockSettings\" },\n );\n await this.refreshAfterWrite();\n }\n\n /**\n * Sets raw block storage content directly.\n * This bypasses all normalization and VM transformations.\n *\n * @param blockId The block to set storage for\n * @param rawStorageJson Raw storage as JSON string\n */\n public async setBlockStorageRaw(blockId: string, rawStorageJson: string): Promise<void> {\n await withProjectAuthored(\n this.env.projectHelper,\n this.env.pl,\n this.rid,\n undefined,\n (mut) => {\n mut.setBlockStorageRaw(blockId, rawStorageJson);\n },\n { name: \"setBlockStorageRaw\" },\n );\n await this.refreshAfterWrite();\n }\n\n /** Resets arguments and ui state of the block to initial state */\n public async resetBlockArgsAndUiState(blockId: string, author?: AuthorMarker): Promise<void> {\n await this.env.pl.withWriteTx(\"BlockInputsReset\", async (tx) => {\n // reading default arg values from block pack\n const bpHolderRid = ensureSignedResourceIdNotNull(\n (await tx.getField(field(this.rid, projectFieldName(blockId, \"blockPack\")))).value,\n );\n const bpRid = ensureSignedResourceIdNotNull(\n (await tx.getField(field(bpHolderRid, Pl.HolderRefField))).value,\n );\n const bpData = await tx.getResourceData(bpRid, false);\n const config = extractConfig(cachedDeserialize<BlockPackInfo>(notEmpty(bpData.data)).config);\n\n await withProjectAuthored(\n this.env.projectHelper,\n tx,\n this.rid,\n author,\n (prj) => {\n if (config.modelAPIVersion === BLOCK_STORAGE_FACADE_VERSION) {\n // V2+: Reset to initial storage via VM\n prj.resetToInitialStorage(blockId);\n } else {\n // V1: Use legacy state format\n const initialState = { args: config.initialArgs, uiState: config.initialUiState };\n prj.setStates([{ modelAPIVersion: 1, blockId, state: initialState }]);\n }\n },\n { name: \"resetBlockArgsAndUiState\", lockId: this.projectLockId },\n );\n await tx.commit();\n });\n await this.refreshAfterWrite();\n }\n\n private getBlockComputables(blockId: string): BlockStateComputables {\n const cached = this.blockComputables.get(blockId);\n if (cached === null) throw new Error(`Block ${blockId} is deleted`);\n if (cached === undefined) {\n // state consists of inputs (args + ui state) and outputs\n const outputs = blockOutputs(this.projectTree.entry(), blockId, this.env);\n const dependencies = blockDependencies(this.projectTree.entry(), blockId, this.env);\n const dependents = blockDependents(this.projectTree.entry(), blockId, this.env);\n const fullState = Computable.make(\n (ctx) => {\n // Links are computed only for a block whose UI reads them.\n const linked = readsColumnLinks(ctx.accessor(this.projectTree.entry()).node(), blockId);\n return {\n parameters: getBlockParameters(this.projectTree.entry(), blockId, ctx),\n outputs,\n navigationState: this.navigationStates.getState(blockId),\n overview: this.overview,\n dependencies: linked ? dependencies : undefined,\n dependents: linked ? dependents : undefined,\n };\n },\n {\n postprocessValue: (v) => {\n const blockOverview = v.overview?.blocks?.find((b) => b.id == blockId);\n const sdkVersion = blockOverview?.sdkVersion;\n const toString = sdkVersion && shouldStillUseStringErrors(sdkVersion);\n const newOutputs =\n toString && v.outputs !== undefined ? convertErrorsToStrings(v.outputs) : v.outputs;\n\n return {\n ...v.parameters,\n outputs: newOutputs,\n navigationState: v.navigationState,\n // The block state already nests the overview, so labelling by its titles adds\n // nothing to watch.\n columnLinks: labelBlockColumnLinks({ ...v, blockId }, v.overview?.blocks ?? []),\n } as BlockStateInternalV3;\n },\n },\n );\n\n const computables: BlockStateComputables = {\n fullState: fullState.withPreCalculatedValueTree(),\n dependencies,\n dependents,\n };\n\n this.blockComputables.set(blockId, computables);\n\n return computables;\n }\n return cached;\n }\n\n /**\n * Returns a computable, that can be used to retrieve and watch full block state,\n * including outputs, arguments, ui state.\n * */\n /**\n * Reads the block action context tree of a block render (see readBlockActionContextTree): current state, not\n * watched. Undefined when the block has no action context.\n */\n public async getBlockActionContext(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<BlockActionContextNode | undefined> {\n return await readBlockActionContextTree(this.env.pl, this.rid, blockId, mode);\n }\n\n /**\n * Starts watching the live status of a block render, and returns the folded summary.\n *\n * One watch per block and mode: calling it again while a watch is open returns the same\n * computable. The watch owns a synchronized tree, so the caller must call\n * {@link unwatchBlockStatus} once it stops showing the status; {@link destroy} terminates\n * whatever is left.\n *\n * The summary survives a re-run of the block: a new render gets a new status context, and the\n * watch re-seeds itself onto it.\n */\n public async watchBlockStatus(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<Computable<BlockStatusSummary>> {\n return (await this.retainBlockStatusWatch(blockId, mode)).summary;\n }\n\n /**\n * Starts watching the action-context tree of a block render, context by context. Takes the same\n * hold as {@link watchBlockStatus}, released by {@link unwatchBlockStatus}, and shares its\n * synchronized tree.\n */\n public async watchBlockStatusTree(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<Computable<BlockStatusTree>> {\n return (await this.retainBlockStatusWatch(blockId, mode)).tree;\n }\n\n /**\n * Sets which contexts of {@link watchBlockStatusTree} show their children. A no-op while nobody\n * watches the block: the expansion lives with the watch.\n */\n public async setBlockStatusTreeExpanded(\n blockId: string,\n contextIds: readonly string[],\n mode: BlockActionContextMode = \"prod\",\n ): Promise<void> {\n const pending = this.blockStatusWatches.get(blockStatusKey(blockId, mode));\n if (pending === undefined) return;\n (await pending).setExpanded(contextIds);\n }\n\n private async retainBlockStatusWatch(\n blockId: string,\n mode: BlockActionContextMode,\n ): Promise<BlockStatusWatch> {\n if (this.destroyed)\n throw new Error(`cannot watch the status of ${blockId}: the project is closed`);\n\n const key = blockStatusKey(blockId, mode);\n const existing = this.blockStatusWatches.get(key);\n if (existing !== undefined) {\n const watch = await existing;\n watch.retain();\n return watch;\n }\n\n const started = BlockStatusWatch.start({\n env: this.env,\n projectRid: this.rid,\n blockId,\n mode,\n projectGeneration: () => (this.destroyed ? -1 : this.projectTree.changeGeneration),\n });\n this.blockStatusWatches.set(key, started);\n // A failed start must not leave a rejected promise in the map for every later caller. Only\n // this start's own entry is dropped: by the time a late rejection lands, the key may already\n // hold a newer, live watch.\n started.catch(() => {\n if (this.blockStatusWatches.get(key) === started) this.blockStatusWatches.delete(key);\n });\n return await started;\n }\n\n /**\n * Releases one hold taken by {@link watchBlockStatus}. The tree is terminated when the last\n * holder lets go, so two callers watching one block do not cut each other off.\n */\n public async unwatchBlockStatus(\n blockId: string,\n mode: BlockActionContextMode = \"prod\",\n ): Promise<void> {\n const key = blockStatusKey(blockId, mode);\n const pending = this.blockStatusWatches.get(key);\n if (pending === undefined) return;\n\n let watch: BlockStatusWatch;\n try {\n watch = await pending;\n } catch {\n // The start failed; its own catch handler drops the entry. Nothing to release, and a\n // caller letting go must not see that failure again.\n return;\n }\n\n if (await watch.release()) {\n if (this.blockStatusWatches.get(key) === pending) this.blockStatusWatches.delete(key);\n }\n }\n\n private async terminateBlockStatusWatches(): Promise<void> {\n const watches = [...this.blockStatusWatches.values()];\n this.blockStatusWatches.clear();\n await Promise.all(\n watches.map(async (watch) => {\n try {\n await (await watch).terminate();\n } catch (e: unknown) {\n // A watch whose start rejected has nothing to terminate; anything else is logged.\n this.env.logger.warn(new Error(\"block status watch termination failed\", { cause: e }));\n }\n }),\n );\n }\n\n public getBlockState(blockId: string): Computable<BlockStateInternalV3> {\n return this.getBlockComputables(blockId).fullState;\n }\n\n /**\n * Returns a computable, that can be used to retrieve and watch path of the\n * folder containing frontend code.\n * */\n public getBlockFrontend(blockId: string): ComputableStableDefined<FrontendData> {\n const cached = this.blockFrontends.get(blockId);\n if (cached === undefined) {\n const fd = frontendData(\n this.projectTree.entry(),\n blockId,\n this.env,\n ).withPreCalculatedValueTree();\n this.blockFrontends.set(blockId, fd);\n return fd;\n }\n return cached;\n }\n\n /** Called by middle layer on close */\n public async destroy(): Promise<void> {\n // terminating the project service loop\n this.abortController.abort();\n try {\n await this.refreshLoopResult;\n } catch (e: unknown) {\n // Error was already logged in the constructor's catch handler, but log again for context\n this.env.logger.warn(\n new Error(\"Refresh loop had terminated with error before destroy\", { cause: e }),\n );\n }\n\n // terminating the status trees before the project tree: they are seeded from it\n await this.terminateBlockStatusWatches();\n\n // terminating the synchronized project tree\n try {\n await this.projectTree.terminate();\n } catch (e: unknown) {\n // TODO: SynchronizedTreeState.terminate() can throw if mainLoop had an error before termination\n // Log error but continue cleanup - we must clean up remaining resources\n this.env.logger.warn(new Error(\"Project tree termination failed\", { cause: e }));\n }\n\n // the following will deregister all external resource holders, like\n // downloaded files, running uploads and alike\n this.overview.resetState();\n this.blockFrontends.forEach((c) => c.resetState());\n this.blockComputables.forEach((c) => {\n if (c !== null) resetBlockState(c);\n });\n this.activeConfigs.resetState();\n }\n\n /** @deprecated */\n public async destroyAndAwaitTermination(): Promise<void> {\n await this.destroy();\n }\n\n public dumpState(): ExtendedResourceData[] {\n return this.projectTree.dumpState();\n }\n\n public static async init(\n env: MiddleLayerEnvironment,\n id: ProjectId,\n rid: SignedResourceId,\n onGone?: (project: Project) => void,\n ): Promise<Project> {\n // Applying migrations to the project resource, if needed\n await applyProjectMigrations(env.pl, rid);\n\n // Doing a no-op mutation to apply all migration and schema fixes\n await withProject(env.projectHelper, env.pl, rid, (_) => {}, { name: \"init\" });\n\n // Loading project tree, warm from a persisted mirror when one is usable\n const { tree: projectTree, restored } = await loadProjectTree(env, rid);\n\n if (env.ops.debugOps.dumpInitialTreeState) {\n const state = projectTree.dumpState();\n state.sort((a, b) => (b.data?.byteLength ?? 0) - (a.data?.byteLength ?? 0));\n const stats = treeDumpStats(state);\n await fs.writeFile(`${resourceIdToString(rid)}.json`, stringifyForDump(state));\n await fs.writeFile(`${resourceIdToString(rid)}.stats.json`, stringifyForDump(stats));\n }\n\n return new Project(env, id, rid, projectTree, restored, onGone);\n }\n}\n\n/**\n * Opens the project tree, seeded from a persisted mirror when there is a usable one.\n *\n * Carries the fail-safe: if the restored tree fails its first refresh on authentication,\n * permission or an inconsistency, the snapshot is deleted and the open is retried cold. Once,\n * and only for that first refresh, so a genuinely dead session still surfaces as itself rather\n * than being masked as a slow open.\n *\n * The fail-safe is what bounds every case the cache key does not cover: a rotated master\n * secret, a revoked grant, a snapshot valid in itself but no longer matching what the backend\n * will serve. Without it, an explicit-root tree propagates the refresh failure rather than\n * healing, so the project would fail to open on every attempt until someone deleted the cache\n * directory by hand.\n */\nasync function loadProjectTree(\n env: MiddleLayerEnvironment,\n rid: SignedResourceId,\n): Promise<{ tree: SynchronizedTreeState; restored: boolean }> {\n const treeOps = {\n ...env.ops.defaultTreeOptions,\n pruning: projectTreePruning(env.logger),\n fieldFilter: projectTreeFieldFilter(),\n traverseStopRules: projectTreeTraverseStopRules(),\n };\n const cold = async () => ({\n tree: await SynchronizedTreeState.init(env.pl, rid, treeOps, env.logger),\n restored: false,\n });\n\n const store = env.treeSnapshots;\n if (store === undefined) return await cold();\n\n const snapshot = await store.read(rid);\n if (!snapshot.ok) {\n env.logger.info(`project tree opening cold, snapshot miss: ${snapshot.miss}`);\n return await cold();\n }\n\n try {\n const tree = await SynchronizedTreeState.init(\n env.pl,\n rid,\n { ...treeOps, restoreFrom: snapshot.tree },\n env.logger,\n );\n\n // Read from the tree rather than assumed: a snapshot can be handed over and still be\n // refused, in which case this open was cold and the file on disk does not describe the\n // tree we now hold.\n const restored = tree.wasRestoredFromSnapshot;\n if (restored) store.noteRestored();\n else env.logger.info(\"project tree opening cold: the snapshot was not applied\");\n\n return { tree, restored };\n } catch (e: unknown) {\n // Retry cold on ANY failure of the warm open, not only on the classified ones. A cold open\n // is exactly what this code did before snapshots existed, so the retry cannot regress\n // anything, whereas rethrowing here leaves a project that fails to open on every attempt\n // until someone deletes the cache directory by hand: the snapshot stays on disk and the\n // next open restores it and fails the same way. That is the outcome this fail-safe exists\n // to prevent, and the error classes that can reach here are not a closed set.\n env.logger.warn(\n new Error(\"restored project tree failed its first refresh, opening cold\", { cause: e }),\n );\n\n // Deleting is reserved for failures that implicate the snapshot itself. Anything else (a\n // timeout, a dropped connection) says nothing about the file, and throwing it away would\n // destroy a mirror that is still good, along with the evidence a later signature refresh\n // would repair.\n if (isSnapshotFailsafeError(e)) await store.discard(rid);\n\n return await cold();\n }\n}\n\n/** The failures that implicate the snapshot rather than the link or the session: a rotated\n * master secret, a revoked grant, or state the tree cannot reconcile. Only these delete the\n * file; every other failure still falls back to a cold open, it just keeps the file.\n *\n * The cause chain is walked because a wrapper anywhere between the tree update and here would\n * otherwise silently disarm the inconsistency arm. `isUnauthenticated` and `isPermissionDenied`\n * do their own one-level unwrapping. */\nexport function isSnapshotFailsafeError(e: unknown): boolean {\n if (isUnauthenticated(e) || isPermissionDenied(e)) return true;\n for (let cause: unknown = e, depth = 0; cause !== undefined && depth < 8; depth++) {\n if (cause instanceof TreeStateUpdateError) return true;\n cause = (cause as { cause?: unknown } | null)?.cause;\n }\n return false;\n}\n\n/** Key of a status watch in {@link Project.blockStatusWatches}. */\nfunction blockStatusKey(blockId: string, mode: BlockActionContextMode): string {\n return `${mode}:${blockId}`;\n}\n\nexport function projectTreePruning(logger: MiLogger): PruningFunction {\n return (r: ExtendedResourceData): FieldData[] => {\n if (r.fields.length > 1000)\n logger.warn(\n `resource with excessive field count: type=${r.type.name} id=${r.id} fields=${r.fields.length}` +\n ` names=[${r.fields\n .slice(0, 10)\n .map((f) => f.name)\n .join(\", \")}, ...]`,\n );\n if (r.type.name.startsWith(\"StreamWorkdir/\")) return [];\n switch (r.type.name) {\n case \"BlockPackCustom\":\n return r.fields.filter((f) => f.name !== \"template\");\n case \"UserProject\":\n return r.fields.filter(\n (f) => !f.name.startsWith(\"__serviceTemplate\") && !projectStatusFieldRegex.test(f.name),\n );\n case \"Blob\":\n return [];\n default:\n return r.fields;\n }\n };\n}\n\n/** ResourceTree analogue of projectTreePruning() used by modern backend path. */\nexport function projectTreeFieldFilter(): Filter {\n return treeFilter.not(\n treeFilter.or(\n // StreamWorkdir/* — pruned entirely\n treeFilter.resourceTypeMatch(\"^StreamWorkdir/\"),\n // BlockPackCustom: drop `template`\n treeFilter.and(\n treeFilter.resourceTypeEq(\"BlockPackCustom\"),\n treeFilter.fieldNameEq(\"template\"),\n ),\n // UserProject: drop `__serviceTemplate*`\n treeFilter.and(\n treeFilter.resourceTypeEq(\"UserProject\"),\n treeFilter.fieldNameMatch(\"^__serviceTemplate\"),\n ),\n // UserProject: drop the status-context fields, see ProjectStatusFieldPattern\n treeFilter.and(\n treeFilter.resourceTypeEq(\"UserProject\"),\n treeFilter.fieldNameMatch(ProjectStatusFieldPattern),\n ),\n // Blob — pruned entirely\n treeFilter.resourceTypeEq(\"Blob\"),\n ),\n );\n}\n\n/** Stop rules for the project tree's ResourceTree walks: {@link TreeFinality}'s declared clauses,\n * which may stop before the predicate calls a resource final where an entry declares so. */\nexport function projectTreeTraverseStopRules(): Filter {\n return finalityStopRules(TreeFinality);\n}\n\n/** Whether the block's model declares that its UI reads the column links of the block state. */\nfunction readsColumnLinks(prj: PlTreeNodeAccessor, blockId: string): boolean {\n const info = getBlockPackInfo(prj, blockId);\n return info !== undefined && checkBlockFlag(info.cfg.featureFlags, \"supportsColumnLinks\");\n}\n\n/** Returns true if sdk version of the block is old and we need to convert\n * ErrorLike errors to strings like it was.\n * We need it for keeping old blocks and new UI compatibility. */\nfunction shouldStillUseStringErrors(sdkVersion: string): boolean {\n return !isVersionGreater(sdkVersion, \"1.26.0\");\n}\n\n/** Checks if sdk version is greater that a target version. */\nfunction isVersionGreater(sdkVersion: string, targetVersion: string): boolean {\n const version = sdkVersion.split(\".\").map(Number);\n const target = targetVersion.split(\".\").map(Number);\n\n return (\n version[0] > target[0] ||\n (version[0] === target[0] && version[1] > target[1]) ||\n (version[0] === target[0] && version[1] === target[1] && version[2] > target[2])\n );\n}\n\n/** Converts ErrorLike errors to strings in the outputs like it was in old ML versions. */\nfunction convertErrorsToStrings(\n outputs: Record<string, ComputableValueOrErrors<unknown>>,\n): Record<string, ComputableValueOrErrors<unknown>> {\n const result: Record<string, ComputableValueOrErrors<unknown>> = {};\n for (const [key, val] of Object.entries(outputs)) {\n if (val.ok) {\n result[key] = val;\n continue;\n }\n\n result[key] = {\n ok: false,\n errors: val.errors.map((e) => {\n if (typeof e === \"string\") {\n return e;\n } else if (e.type == \"PlError\" && e.fullMessage !== undefined) {\n return e.fullMessage;\n }\n return e.message;\n }),\n moreErrors: val.moreErrors,\n };\n }\n\n return result;\n}\n\n/** Throws when the connected backend doesn't advertise every capability the\n * block-pack requires (as declared in `meta.requiredCapabilities`).\n *\n * The matching set is the desktop's install gate moved server-side so both\n * the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's\n * `add_block` tool, programmatic block installs, tests) reject incompatible\n * blocks consistently. */\nexport function throwIfMissingServerCapabilities(\n pl: PlClient,\n requiredCapabilities: readonly string[] | undefined,\n): void {\n if (!requiredCapabilities || requiredCapabilities.length === 0) return;\n const advertised = (pl.serverInfo.capabilities ?? []) as readonly string[];\n const filterFn = (c: string) => !advertised.includes(c);\n if (!requiredCapabilities.some(filterFn)) return;\n const missing = requiredCapabilities.filter(filterFn);\n throw new Error(\n `Block cannot be added: connected backend does not advertise capabilities ` +\n `${JSON.stringify(missing)}. ` +\n `Backend advertises ${JSON.stringify(advertised)}. ` +\n `Upgrade the backend or remove the requirement from the block manifest.`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoGA,SAAS,iBAAiB,QAAyB;CACjD,OAAO,KAAK,UAAU,SAAS,KAAK,UAAU;EAC5C,IAAI,OAAO,UAAU,UAAU,QAAA,GAAOA,0BAAAA,mBAAAA,CAAmB,KAA8B;OAClF,IACH,YAAY,OAAO,KAAK,KACxB,iBAAiB,aACjB,iBAAiB,cACjB,iBAAiB,qBACjB,iBAAiB,cACjB,iBAAiB,eACjB,iBAAiB,cACjB,iBAAiB,eACjB,iBAAiB,gBACjB,iBAAiB,gBACjB,iBAAiB,iBACjB,iBAAiB,gBAEjB,OAAO,OAAO,KAAK,MAAM,QAAQ,MAAM,YAAY,MAAM,UAAU,CAAC,CAAC,SAAS,QAAQ;OACnF,IAAI,OAAO,SAAS,KAAK,GAAG,OAAO,MAAM,SAAS,QAAQ;EAE/D,OAAO;CACT,CAAC;AACH;;AAGA,SAAS,gBAAgB,aAA0C;CACjE,YAAY,UAAU,WAAW;CACjC,YAAY,aAAa,WAAW;CACpC,YAAY,WAAW,WAAW;AACpC;;AAwBA,IAAa,UAAb,MAAa,QAAQ;CAuCA;CACD;CACP;CACQ;CAMA;;CA9CnB;CACA;CAEA,mBAAoC,IAAIC,0BAAAA,iBAAiB;CAEzD,mCAAoC,IAAI,IAA0C;CAElF,iCAAkC,IAAI,IAAmD;;;CAIzF,qCAAsC,IAAI,IAAuC;CACjF;CACA;CAEA,kBAAmC,IAAI,gBAAgB;;;;CAKvD;;;;;;;;;CAUA,iBAAyB;CAEzB,IAAY,YAAY;EACtB,OAAO,KAAK,gBAAgB,OAAO;CACrC;CAEA,YACE,KACA,IACA,KACA,aAGA,uBAAgC,OAGhC,QACA;EAViB,KAAA,MAAA;EACD,KAAA,KAAA;EACP,KAAA,MAAA;EACQ,KAAA,cAAA;EAMA,KAAA,SAAA;EAEj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,WAAW,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAChD,MAAM,SAAS,cAAc,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;CAElD,OACE,QAAQ,KAAK,OAAO,MACnB,QAAQ,OAAO,OAAO,MAAM,QAAQ,KAAK,OAAO,MAChD,QAAQ,OAAO,OAAO,MAAM,QAAQ,OAAO,OAAO,MAAM,QAAQ,KAAK,OAAO;AAEjF;;AAGA,SAAS,uBACP,SACkD;CAClD,MAAM,SAA2D,CAAC;CAClE,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,OAAO,GAAG;EAChD,IAAI,IAAI,IAAI;GACV,OAAO,OAAO;GACd;EACF;EAEA,OAAO,OAAO;GACZ,IAAI;GACJ,QAAQ,IAAI,OAAO,KAAK,MAAM;IAC5B,IAAI,OAAO,MAAM,UACf,OAAO;SACF,IAAI,EAAE,QAAQ,aAAa,EAAE,gBAAgB,KAAA,GAClD,OAAO,EAAE;IAEX,OAAO,EAAE;GACX,CAAC;GACD,YAAY,IAAI;EAClB;CACF;CAEA,OAAO;AACT;;;;;;;;AASA,SAAgB,iCACd,IACA,sBACM;CACN,IAAI,CAAC,wBAAwB,qBAAqB,WAAW,GAAG;CAChE,MAAM,aAAc,GAAG,WAAW,gBAAgB,CAAC;CACnD,MAAM,YAAY,MAAc,CAAC,WAAW,SAAS,CAAC;CACtD,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GAAG;CAC1C,MAAM,UAAU,qBAAqB,OAAO,QAAQ;CACpD,MAAM,IAAI,MACR,4EACK,KAAK,UAAU,OAAO,EAAE,uBACL,KAAK,UAAU,UAAU,EAAE,yEAErD;AACF"}
@@ -37,6 +37,9 @@ export declare class Project {
37
37
  readonly id: ProjectId$1;
38
38
  readonly rid: SignedResourceId;
39
39
  private readonly projectTree;
40
+ /** Called once, from the maintenance loop, when the loop finds the project was deleted
41
+ * elsewhere. The loop has stopped by then; the owner is expected to destroy the project. */
42
+ private readonly onGone?;
40
43
  /** Data for the left panel, contain basic information about block status. */
41
44
  readonly overview: ComputableStableDefined<ProjectOverview>;
42
45
  private readonly overviewLight;
@@ -66,7 +69,10 @@ export declare class Project {
66
69
  constructor(env: MiddleLayerEnvironment, id: ProjectId$1, rid: SignedResourceId, projectTree: SynchronizedTreeState,
67
70
  /** Whether this tree was seeded from a snapshot. When it was, the file on disk already
68
71
  * holds generation 0, so an idle warm reopen writes nothing at all. */
69
- restoredFromSnapshot?: boolean);
72
+ restoredFromSnapshot?: boolean,
73
+ /** Called once, from the maintenance loop, when the loop finds the project was deleted
74
+ * elsewhere. The loop has stopped by then; the owner is expected to destroy the project. */
75
+ onGone?: ((project: Project) => void) | undefined);
70
76
  get projectLockId(): string;
71
77
  /**
72
78
  * Periodic snapshot write, carried on the maintenance loop rather than a timer of its own.
@@ -102,6 +108,15 @@ export declare class Project {
102
108
  /** Captures and writes, never throwing: a snapshot is an optimisation and must not fail
103
109
  * whatever triggered it. */
104
110
  private captureAndWrite;
111
+ /**
112
+ * Brings the project tree up to a write that has just committed.
113
+ *
114
+ * The write is already on the backend when this runs, so a project destroyed meanwhile (closed
115
+ * by its last holder, or deleted) must not turn it into a failure: a caller told it failed would
116
+ * retry it and apply it twice. `destroy` marks the project destroyed before it terminates the
117
+ * tree, so a refresh failing on a terminated tree always finds the mark set.
118
+ */
119
+ private refreshAfterWrite;
105
120
  private refreshLoop;
106
121
  /**
107
122
  * Adds new block to the project.
@@ -280,6 +295,6 @@ export declare class Project {
280
295
  /** @deprecated */
281
296
  destroyAndAwaitTermination(): Promise<void>;
282
297
  dumpState(): ExtendedResourceData[];
283
- static init(env: MiddleLayerEnvironment, id: ProjectId$1, rid: SignedResourceId): Promise<Project>;
298
+ static init(env: MiddleLayerEnvironment, id: ProjectId$1, rid: SignedResourceId, onGone?: (project: Project) => void): Promise<Project>;
284
299
  }
285
300
  //# sourceMappingURL=project.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"project.d.ts","names":["ProjectId"],"sources":["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