@milaboratories/pl-middle-layer 1.66.19 → 1.67.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/block_registry/index.cjs +3 -0
  2. package/dist/block_registry/index.d.ts +2 -1
  3. package/dist/block_registry/index.js +2 -1
  4. package/dist/block_registry/location_provider.cjs +117 -0
  5. package/dist/block_registry/location_provider.cjs.map +1 -0
  6. package/dist/block_registry/location_provider.js +114 -0
  7. package/dist/block_registry/location_provider.js.map +1 -0
  8. package/dist/block_registry/registry.cjs +13 -0
  9. package/dist/block_registry/registry.cjs.map +1 -1
  10. package/dist/block_registry/registry.d.ts +14 -1
  11. package/dist/block_registry/registry.d.ts.map +1 -1
  12. package/dist/block_registry/registry.js +13 -0
  13. package/dist/block_registry/registry.js.map +1 -1
  14. package/dist/block_registry/template_provider.cjs +104 -0
  15. package/dist/block_registry/template_provider.cjs.map +1 -0
  16. package/dist/block_registry/template_provider.d.ts +62 -0
  17. package/dist/block_registry/template_provider.d.ts.map +1 -0
  18. package/dist/block_registry/template_provider.js +103 -0
  19. package/dist/block_registry/template_provider.js.map +1 -0
  20. package/dist/block_registry/watcher.cjs +3 -3
  21. package/dist/block_registry/watcher.js +2 -2
  22. package/dist/dev_env/util.js +2 -2
  23. package/dist/dev_env/util.js.map +1 -1
  24. package/dist/index.cjs +10 -0
  25. package/dist/index.d.ts +5 -1
  26. package/dist/index.js +5 -1
  27. package/dist/js_render/computable_context.cjs +1 -1
  28. package/dist/js_render/computable_context.js +1 -1
  29. package/dist/middle_layer/driver_kit.d.ts +1 -1
  30. package/dist/middle_layer/middle_layer.cjs +144 -2
  31. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  32. package/dist/middle_layer/middle_layer.d.ts +67 -1
  33. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  34. package/dist/middle_layer/middle_layer.js +146 -4
  35. package/dist/middle_layer/middle_layer.js.map +1 -1
  36. package/dist/middle_layer/project.cjs +1 -0
  37. package/dist/middle_layer/project.cjs.map +1 -1
  38. package/dist/middle_layer/project.d.ts +2 -2
  39. package/dist/middle_layer/project.js +4 -4
  40. package/dist/middle_layer/project.js.map +1 -1
  41. package/dist/middle_layer/sharing_list.d.ts +1 -1
  42. package/dist/model/args.cjs +9 -28
  43. package/dist/model/args.cjs.map +1 -1
  44. package/dist/model/args.js +9 -28
  45. package/dist/model/args.js.map +1 -1
  46. package/dist/model/index.cjs +7 -0
  47. package/dist/model/index.d.ts +4 -1
  48. package/dist/model/index.js +4 -1
  49. package/dist/model/project_helper.cjs +111 -0
  50. package/dist/model/project_helper.cjs.map +1 -1
  51. package/dist/model/project_helper.d.ts +76 -1
  52. package/dist/model/project_helper.d.ts.map +1 -1
  53. package/dist/model/project_helper.js +111 -0
  54. package/dist/model/project_helper.js.map +1 -1
  55. package/dist/model/project_model.d.ts +1 -1
  56. package/dist/model/sharing_model.d.ts +1 -1
  57. package/dist/model/template_apply.cjs +67 -0
  58. package/dist/model/template_apply.cjs.map +1 -0
  59. package/dist/model/template_apply.d.ts +50 -0
  60. package/dist/model/template_apply.d.ts.map +1 -0
  61. package/dist/model/template_apply.js +64 -0
  62. package/dist/model/template_apply.js.map +1 -0
  63. package/dist/model/template_export.cjs +82 -0
  64. package/dist/model/template_export.cjs.map +1 -0
  65. package/dist/model/template_export.d.ts +9 -0
  66. package/dist/model/template_export.d.ts.map +1 -0
  67. package/dist/model/template_export.js +82 -0
  68. package/dist/model/template_export.js.map +1 -0
  69. package/dist/model/template_parser.cjs +74 -0
  70. package/dist/model/template_parser.cjs.map +1 -0
  71. package/dist/model/template_parser.d.ts +43 -0
  72. package/dist/model/template_parser.d.ts.map +1 -0
  73. package/dist/model/template_parser.js +72 -0
  74. package/dist/model/template_parser.js.map +1 -0
  75. package/dist/model/template_resolve.cjs +134 -0
  76. package/dist/model/template_resolve.cjs.map +1 -0
  77. package/dist/model/template_resolve.d.ts +193 -0
  78. package/dist/model/template_resolve.d.ts.map +1 -0
  79. package/dist/model/template_resolve.js +133 -0
  80. package/dist/model/template_resolve.js.map +1 -0
  81. package/dist/model/template_serializer.cjs +162 -0
  82. package/dist/model/template_serializer.cjs.map +1 -0
  83. package/dist/model/template_serializer.d.ts +17 -0
  84. package/dist/model/template_serializer.d.ts.map +1 -0
  85. package/dist/model/template_serializer.js +157 -0
  86. package/dist/model/template_serializer.js.map +1 -0
  87. package/dist/mutator/block-pack/block_pack.cjs +1 -1
  88. package/dist/mutator/block-pack/block_pack.js +1 -1
  89. package/dist/mutator/migration.cjs +1 -1
  90. package/dist/mutator/migration.js +1 -1
  91. package/dist/mutator/project.cjs +35 -5
  92. package/dist/mutator/project.cjs.map +1 -1
  93. package/dist/mutator/project.d.ts.map +1 -1
  94. package/dist/mutator/project.js +35 -5
  95. package/dist/mutator/project.js.map +1 -1
  96. package/dist/mutator/template_construct.cjs +77 -0
  97. package/dist/mutator/template_construct.cjs.map +1 -0
  98. package/dist/mutator/template_construct.js +77 -0
  99. package/dist/mutator/template_construct.js.map +1 -0
  100. package/dist/network_check/template.js +3 -3
  101. package/dist/network_check/template.js.map +1 -1
  102. package/package.json +17 -17
  103. package/src/block_registry/index.ts +1 -0
  104. package/src/block_registry/location_provider.test.ts +236 -0
  105. package/src/block_registry/location_provider.ts +124 -0
  106. package/src/block_registry/registry.ts +22 -0
  107. package/src/block_registry/template_provider.test.ts +275 -0
  108. package/src/block_registry/template_provider.ts +168 -0
  109. package/src/middle_layer/middle_layer.ts +192 -1
  110. package/src/middle_layer/project.ts +1 -1
  111. package/src/model/args.test.ts +26 -1
  112. package/src/model/args.ts +16 -31
  113. package/src/model/index.ts +21 -0
  114. package/src/model/project_helper.ts +238 -0
  115. package/src/model/project_helper_params_init.test.ts +249 -0
  116. package/src/model/template_apply.test.ts +65 -0
  117. package/src/model/template_apply.ts +128 -0
  118. package/src/model/template_export.test.ts +255 -0
  119. package/src/model/template_export.ts +136 -0
  120. package/src/model/template_parser.test.ts +264 -0
  121. package/src/model/template_parser.ts +108 -0
  122. package/src/model/template_resolve.test.ts +397 -0
  123. package/src/model/template_resolve.ts +346 -0
  124. package/src/model/template_serializer.test.ts +398 -0
  125. package/src/model/template_serializer.ts +232 -0
  126. package/src/model/template_serializer_fixtures.test.ts +274 -0
  127. package/src/mutator/project-v3.test.ts +11 -11
  128. package/src/mutator/project.ts +92 -5
  129. package/src/mutator/template_construct.test.ts +456 -0
  130. package/src/mutator/template_construct.ts +150 -0
@@ -3,12 +3,16 @@ require("../block_registry/index.cjs");
3
3
  const require_project_model = require("../model/project_model.cjs");
4
4
  const require_project_list = require("./project_list.cjs");
5
5
  const require_sharing_model = require("../model/sharing_model.cjs");
6
+ const require_template_resolve = require("../model/template_resolve.cjs");
7
+ const require_template_apply = require("../model/template_apply.cjs");
6
8
  const require_block_pack = require("../mutator/block-pack/block_pack.cjs");
7
9
  const require_index$1 = require("../debug/index.cjs");
8
10
  const require_project = require("../mutator/project.cjs");
11
+ const require_template_construct = require("../mutator/template_construct.cjs");
12
+ const require_template_cache = require("../mutator/template/template_cache.cjs");
13
+ const require_project$1 = require("./project.cjs");
9
14
  const require_sharing = require("../mutator/sharing.cjs");
10
15
  const require_sharing_list = require("./sharing_list.cjs");
11
- const require_project$1 = require("./project.cjs");
12
16
  const require_ops = require("./ops.cjs");
13
17
  const require_watcher = require("../block_registry/watcher.cjs");
14
18
  const require_driver_kit = require("./driver_kit.cjs");
@@ -17,12 +21,12 @@ const require_project_helper = require("../model/project_helper.cjs");
17
21
  let _platforma_sdk_model = require("@platforma-sdk/model");
18
22
  let undici = require("undici");
19
23
  let _milaboratories_ts_helpers = require("@milaboratories/ts-helpers");
24
+ let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
20
25
  let _milaboratories_pl_client = require("@milaboratories/pl-client");
21
26
  let lru_cache = require("lru-cache");
22
27
  let _milaboratories_computable = require("@milaboratories/computable");
23
28
  let node_crypto = require("node:crypto");
24
29
  let quickjs_emscripten = require("quickjs-emscripten");
25
- let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
26
30
  //#region src/middle_layer/middle_layer.ts
27
31
  /**
28
32
  * Main access object to work with pl from UI.
@@ -191,6 +195,144 @@ var MiddleLayer = class MiddleLayer {
191
195
  }, { name: "setProjectMeta" });
192
196
  await this.projectListTree.refreshState();
193
197
  }
198
+ /**
199
+ * Renders a project as a `template-v1` YAML document, or reports every reason it
200
+ * cannot be — the backing call for an "Export Project as Template…" command.
201
+ *
202
+ * Takes a project id rather than an open {@link Project} because exporting is a
203
+ * property of the stored project, not of a session with it: the command belongs on
204
+ * a project card, where the project is usually closed. Opening one to read it would
205
+ * spin up trees and watchers for a one-shot read, and then have to decide whether to
206
+ * close them again.
207
+ *
208
+ * Read-only — the underlying mutator touches no field, so the transaction is never
209
+ * committed and the project list needs no refresh.
210
+ *
211
+ * @param id - project id of the project to export
212
+ */
213
+ async exportProjectAsTemplate(id) {
214
+ const rid = await this.resolveProjectId(id);
215
+ return await require_project.withProject(this.env.projectHelper, this.pl, rid, (prj) => prj.exportAsTemplateV1(), { name: "exportProjectAsTemplate" });
216
+ }
217
+ /**
218
+ * Creates the blocks a `template-v1` document describes in an existing project, in the
219
+ * order the document lists them — the backing call for a "Create Project from Template
220
+ * file…" command, which is `createProject` followed by this.
221
+ *
222
+ * Takes a project id rather than an open {@link Project}, like
223
+ * {@link exportProjectAsTemplate} and for the same reason: applying a template is a
224
+ * property of the stored project, not of a session with it, and the flow that needs it
225
+ * has just created the project and has no session yet. An already-open session picks the
226
+ * new blocks up through its own refresh loop.
227
+ *
228
+ * Three stages, and their order is the design:
229
+ *
230
+ * 1. **Resolve every entry** to a concrete block pack, through `provider`.
231
+ * 2. **Prepare every block**: fetch it, check it can run against this backend, cache its
232
+ * workflow template, and offer the entry's params to the block's kind for a shape
233
+ * check.
234
+ * 3. **Create the blocks**, in one transaction — each one's params first pointed at this
235
+ * project by the block's own model, since which values in there are references is
236
+ * knowledge only the block has.
237
+ *
238
+ * The first two create nothing, so either of them failing leaves the project exactly as it
239
+ * was. They are also what leaves stage 3 with only in-memory work, and hence able to be a
240
+ * single transaction.
241
+ *
242
+ * **Stage 3 is all or nothing too**, because it is that one transaction: an entry it cannot
243
+ * create throws, the transaction is never committed, and the project keeps none of the
244
+ * blocks the apply had placed. So `problems` non-empty always means `added` is empty, at
245
+ * every stage — a caller never has to reconcile a half-built project, and never has to ask
246
+ * which of the blocks present came from the file.
247
+ *
248
+ * What is NOT checked before the work starts: which entries an entry references. Reading
249
+ * that means reading the params, which only the block can do, and no block exists until
250
+ * stage 2 has fetched one. A file whose entry references one listed below it therefore
251
+ * applies, and the block it creates reports itself as missing references — the same way a
252
+ * reference to a deleted block already behaves.
253
+ *
254
+ * @param id Project to apply into
255
+ * @param document A parsed template document
256
+ * @param provider Where each entry's block comes from
257
+ * @param options `allowUnstable` widens resolution to pre-release implementations, for
258
+ * the whole document
259
+ */
260
+ async applyTemplateToProject(id, document, provider, options = {}) {
261
+ const resolution = await require_template_resolve.resolveTemplateEntries(document, provider, { allowUnstable: options.allowUnstable ?? false });
262
+ if (resolution.problems.length > 0) return {
263
+ added: [],
264
+ problems: resolution.problems
265
+ };
266
+ const byEntryId = new Map(document.blocks.map((entry) => [entry.id, entry]));
267
+ const prepared = /* @__PURE__ */ new Map();
268
+ const problems = [];
269
+ for (const entry of resolution.resolved) try {
270
+ const documentEntry = byEntryId.get(entry.entryId);
271
+ const preparedBp = await this.env.bpPreparer.prepare(entry.spec);
272
+ const blockCfg = (0, _platforma_sdk_model.extractConfig)(preparedBp.config);
273
+ const mismatch = require_template_apply.kindMismatch(documentEntry.kind, preparedBp.config.kind);
274
+ if (mismatch !== void 0) {
275
+ const locator = documentEntry.location ?? documentEntry.block;
276
+ problems.push({
277
+ entryId: entry.entryId,
278
+ error: locator === void 0 ? `${mismatch}.` : `${mismatch} (${locator}).`
279
+ });
280
+ continue;
281
+ }
282
+ this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);
283
+ require_project$1.throwIfMissingServerCapabilities(this.pl, preparedBp.requiredCapabilities);
284
+ const cachedBp = await require_template_cache.cacheBlockPackTemplate(this.pl, preparedBp);
285
+ const checked = this.env.projectHelper.validateTemplateParamsInVM(blockCfg, documentEntry.params);
286
+ if (checked.error !== void 0) {
287
+ problems.push({
288
+ entryId: entry.entryId,
289
+ error: checked.error.message
290
+ });
291
+ continue;
292
+ }
293
+ prepared.set(entry.entryId, {
294
+ blockPack: cachedBp,
295
+ label: entry.title
296
+ });
297
+ } catch (e) {
298
+ problems.push({
299
+ entryId: entry.entryId,
300
+ error: `This entry's block could not be installed: ${(0, _platforma_sdk_model.ensureError)(e).message}`
301
+ });
302
+ }
303
+ if (problems.length > 0) return {
304
+ added: [],
305
+ problems
306
+ };
307
+ const rid = await this.resolveProjectId(id);
308
+ let added = [];
309
+ try {
310
+ await require_project.withProjectAuthored(this.env.projectHelper, this.pl, rid, options.author, (mut) => {
311
+ added = require_template_construct.applyTemplateEntries({
312
+ document,
313
+ placer: mut,
314
+ entries: prepared,
315
+ projectHelper: this.env.projectHelper
316
+ });
317
+ }, {
318
+ name: "applyTemplateToProject",
319
+ lockId: `project:${id}`
320
+ });
321
+ } catch (e) {
322
+ if (!(e instanceof require_template_apply.TemplateEntryRejected)) throw e;
323
+ return {
324
+ added: [],
325
+ problems: [{
326
+ entryId: e.entryId,
327
+ error: e.message
328
+ }]
329
+ };
330
+ }
331
+ return {
332
+ added,
333
+ problems: []
334
+ };
335
+ }
194
336
  /** Permanently deletes project from the project list, this will result in
195
337
  * destruction of all attached objects, like files, analysis results etc. */
196
338
  async deleteProject(id) {
@@ -1 +1 @@
1
- {"version":3,"file":"middle_layer.cjs","names":["canGrantToEveryone","canImpersonate","LRUCache","createProject","withProjectAuthored","ProjectMetaKey","isNotNullSignedResourceId","duplicateProject","ensureProjectListRid","buildShareEnvelope","GrantType","isEnvelopeProjectField","envelopeProjectFieldUuid","isAcceptanceField","acceptanceFieldLogin","decodeEnvelopeData","copyEnvelopeProjectsIntoList","resourceIdsToStrings","Project","HmacSha256Signer","DefaultMiddleLayerOpsSettings","DefaultMiddleLayerOpsPaths","getDebugFlags","ProjectsField","ProjectsResourceType","SharingOutboxField","SharingOutboxResourceType","SharingStateField","SharingStateResourceType","initDriverKit","RetryAgent","V2RegistryProvider","BlockPackPreparer","RuntimeCapabilities","REQUIRES_PFRAMES_VERSION","createModelServiceRegistry","BlockEventDispatcher","BlockUpdateWatcher","ProjectHelper","WatchableValue","createProjectList","createOutgoingShares","createSharingStateTree","createPendingSharesTree","createPendingSharesComputable","createLiveEnvelopesComputable"],"sources":["../../src/middle_layer/middle_layer.ts"],"sourcesContent":["import type {\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n Role,\n} from \"@milaboratories/pl-client\";\nimport {\n isEveryoneUserLogin,\n field,\n GrantType,\n isNotNullSignedResourceId,\n isNullSignedResourceId,\n resourceIdToString,\n} from \"@milaboratories/pl-client\";\nimport { LRUCache } from \"lru-cache\";\nimport {\n createProjectList,\n ensureProjectListRid,\n ProjectsField,\n ProjectsResourceType,\n} from \"./project_list\";\nimport { createProject, duplicateProject, withProjectAuthored } from \"../mutator/project\";\nimport { ProjectMetaKey } from \"../model/project_model\";\nimport type { ProjectId } from \"../model/project_model\";\nimport type { SynchronizedTreeState } from \"@milaboratories/pl-tree\";\nimport {\n acceptanceFieldLogin,\n canGrantToEveryone,\n canImpersonate,\n decodeEnvelopeData,\n isAcceptanceField,\n SharingOutboxField,\n SharingOutboxResourceType,\n SharingStateField,\n SharingStateResourceType,\n type EnvelopeAcceptance,\n type EnvelopeData,\n type ProjectChangeAction,\n type ProjectFieldUuid,\n type ShareId,\n type ShareProjectsOptions,\n} from \"../model/sharing_model\";\nimport {\n buildShareEnvelope,\n copyEnvelopeProjectsIntoList,\n envelopeProjectFieldUuid,\n isEnvelopeProjectField,\n resourceIdsToStrings,\n writeEnvelopeAcceptance,\n writeSharingDecision,\n type EnvelopeProjectSource,\n} from \"../mutator/sharing\";\nimport type { LiveEnvelope, OutgoingShare, PendingShare } from \"./sharing_list\";\nimport {\n createLiveEnvelopesComputable,\n createOutgoingShares,\n createPendingSharesComputable,\n createPendingSharesTree,\n createSharingStateTree,\n} from \"./sharing_list\";\nimport { BlockPackPreparer } from \"../mutator/block-pack/block_pack\";\nimport type { MiLogger, Signer } from \"@milaboratories/ts-helpers\";\nimport { BlockEventDispatcher, cachedDeserialize } from \"@milaboratories/ts-helpers\";\nimport { HmacSha256Signer } from \"@milaboratories/ts-helpers\";\nimport type { Computable, ComputableStableDefined } from \"@milaboratories/computable\";\nimport { WatchableValue } from \"@milaboratories/computable\";\nimport { Project } from \"./project\";\nimport type { MiddleLayerOps, MiddleLayerOpsConstructor } from \"./ops\";\nimport { DefaultMiddleLayerOpsPaths, DefaultMiddleLayerOpsSettings } from \"./ops\";\nimport { randomUUID } from \"node:crypto\";\nimport type { ProjectListEntry } from \"../model\";\nimport type {\n AuthorMarker,\n ProjectMeta,\n BlockPlatform,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { BlockUpdateWatcher } from \"../block_registry/watcher\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { getQuickJS } from \"quickjs-emscripten\";\nimport type { MiddleLayerDriverKit } from \"./driver_kit\";\nimport { initDriverKit } from \"./driver_kit\";\nimport type { BlockCodeFeatureFlags, DriverKit, SupportedRequirement } from \"@platforma-sdk/model\";\nimport { RuntimeCapabilities } from \"@platforma-sdk/model\";\nimport {\n type ModelServiceRegistry,\n registerServiceCapabilities,\n REQUIRES_PFRAMES_VERSION,\n} from \"@milaboratories/pl-model-common\";\nimport { createModelServiceRegistry } from \"../service_factories\";\nimport type { DownloadUrlDriver } from \"@milaboratories/pl-drivers\";\nimport { V2RegistryProvider } from \"../block_registry\";\nimport type { Dispatcher } from \"undici\";\nimport { RetryAgent } from \"undici\";\nimport { getDebugFlags } from \"../debug\";\nimport { ProjectHelper } from \"../model/project_helper\";\n\nexport interface MiddleLayerEnvironment {\n dispose(): Promise<void>;\n readonly pl: PlClient;\n readonly runtimeCapabilities: RuntimeCapabilities;\n readonly logger: MiLogger;\n readonly blockEventDispatcher: BlockEventDispatcher;\n readonly httpDispatcher: Dispatcher;\n readonly retryHttpDispatcher: Dispatcher;\n readonly signer: Signer;\n readonly ops: MiddleLayerOps;\n readonly bpPreparer: BlockPackPreparer;\n readonly frontendDownloadDriver: DownloadUrlDriver;\n readonly blockUpdateWatcher: BlockUpdateWatcher;\n readonly quickJs: QuickJSWASMModule;\n readonly driverKit: MiddleLayerDriverKit;\n readonly serviceRegistry: ModelServiceRegistry;\n readonly projectHelper: ProjectHelper;\n}\n\n/**\n * Main access object to work with pl from UI.\n *\n * It implements an abstraction layer of projects and blocks.\n *\n * As a main entry point inside the pl, this object uses a resource attached\n * via the {@link ProjectsField} to the pl client's root, this resource\n * contains project list.\n *\n * Read about alternative roots, if isolated project lists (working environments)\n * are required.\n * */\nexport class MiddleLayer {\n public readonly pl: PlClient;\n\n private constructor(\n private readonly env: MiddleLayerEnvironment,\n public readonly driverKit: DriverKit,\n public readonly signer: Signer,\n private readonly projectListResourceId: SignedResourceId,\n private readonly sharingOutboxResourceId: SignedResourceId,\n private readonly sharingStateResourceId: SignedResourceId,\n private readonly openedProjectsList: WatchableValue<ProjectId[]>,\n private readonly projectListTree: SynchronizedTreeState,\n private readonly sharingOutboxTree: SynchronizedTreeState,\n private readonly sharingStateTree: SynchronizedTreeState,\n private readonly pendingSharesTree: SynchronizedTreeState,\n public readonly blockRegistryProvider: V2RegistryProvider,\n /** Contains a reactive list of projects along with their meta information. */\n public readonly projectList: ComputableStableDefined<ProjectListEntry[]>,\n /** Reactive view of the donor's outbox — the shares this user has created.\n * v1: API only, no UI. */\n public outgoingShares: Computable<OutgoingShare[] | undefined>,\n /** Envelopes granted to this user, not yet accepted or rejected. Fed by the\n * shared-resource discovery tree. */\n public pendingShares: Computable<PendingShare[] | undefined>,\n /** Internal: the acceptor's currently-live envelopes, read from the same shared-resource\n * discovery tree as {@link pendingShares}. The single source the accept/reject flow resolves\n * live envelopes from — no second discovery path. */\n private readonly liveEnvelopes: Computable<LiveEnvelope[] | undefined>,\n ) {\n this.pl = this.env.pl;\n this.startEnvelopeCleanup();\n }\n\n /**\n * Get the OS where backend is running.\n * For old backend versions returns undefined.\n */\n public get serverPlatform(): BlockPlatform | undefined {\n return this.pl.serverInfo.platform as BlockPlatform | undefined;\n }\n\n /**\n * Runtime capabilities advertised by the connected backend (tokens of\n * the form `<feature>:<version>`, e.g. \"wasm:v1\"). Empty list if the\n * backend predates the capability mechanism — that's the desired\n * fail-closed behaviour for blocks declaring any `requiredCapabilities`.\n */\n public get serverCapabilities(): string[] {\n return this.pl.serverInfo.capabilities ?? [];\n }\n\n /**\n * Login of the authenticated user, for the \"Signed in as\" UI. `null` when the\n * backend has no auth (local/dev mode) — the UI hides the element.\n */\n public get currentUserLogin(): string | null {\n return this.pl.userResources.authUser;\n }\n\n /**\n * Whether the connected backend supports project sharing. Synthetic — computed\n * in the middle layer from the backend capabilities the share flow needs (the\n * cross-color field-reference relaxation the accept flow rests on). It can absorb\n * additional required capabilities later without a UI change.\n */\n public get sharingSupported(): boolean {\n // Sharing does not compose with impersonation (discovery is scoped to the admin's session,\n // decisions attribute to the admin), so it is disabled while impersonating. Admins move\n // projects across roots with duplicateProjectToUser instead.\n return this.serverCapabilities.includes(\"crossTreeRefs:v1\") && !this.impersonating;\n }\n\n /** True when this session is impersonating another user (an admin opened another user's root). */\n public get impersonating(): boolean {\n return this.pl.conf.asUser !== undefined;\n }\n\n /**\n * Role of the authenticated user, from the `GetSessionInfo` RPC surfaced through the\n * pl-client. `null` in no-auth mode (when {@link currentUserLogin} is null).\n */\n public get currentUserRole(): Role | null {\n return this.pl.currentUserRole;\n }\n\n /**\n * Whether the UI offers share-with-everybody — no role policy lives in the UI:\n * serverCapabilities.has(\"publicGrants:v1\") && canGrantToEveryone(currentUserRole)\n * Not a security boundary: a crafted call still hits the backend's role +\n * permission-ceiling gate.\n */\n public get canShareWithEveryone(): boolean {\n return (\n !this.impersonating &&\n this.serverCapabilities.includes(\"publicGrants:v1\") &&\n canGrantToEveryone(this.currentUserRole)\n );\n }\n\n /**\n * Whether the authenticated user may impersonate others (open another user's root). Mirrors\n * the backend's `CanImpersonate` role gate — admin/controller only, never a regular user.\n * Derived from the session role, which stays the authenticated admin's even while\n * impersonating, so this stays true across a switch: the \"return to my root\" affordance must\n * not vanish mid-impersonation. Not a security boundary; the backend re-checks on every call.\n */\n public get currentUserCanImpersonate(): boolean {\n return canImpersonate(this.currentUserRole);\n }\n\n /** Adds a runtime capability to the middle layer. */\n public addRuntimeCapability(\n requirement: SupportedRequirement,\n value: number | boolean = true,\n ): void {\n this.env.runtimeCapabilities.addSupportedRequirement(requirement, value);\n }\n\n /** Checks if the given block feature flags are compatible with the runtime capabilities. */\n public checkBlockCompatibility(featureFlags: BlockCodeFeatureFlags | undefined): boolean {\n return this.env.runtimeCapabilities.checkCompatibility(featureFlags);\n }\n\n /** Returns extended API driver kit used internally by middle layer. */\n public get internalDriverKit(): MiddleLayerDriverKit {\n return this.env.driverKit;\n }\n\n /** Returns the service registry for service introspection. */\n public get serviceRegistry(): ModelServiceRegistry {\n return this.env.serviceRegistry;\n }\n\n //\n // ProjectId ↔ SignedResourceId resolution\n //\n\n private readonly projectIdCache = new LRUCache<ProjectId, SignedResourceId>({ max: 1024 });\n\n /** Resolves a ProjectId to a signed SignedResourceId.\n * Uses LRU cache with TX-scan fallback. */\n private async resolveProjectId(projectId: ProjectId): Promise<SignedResourceId> {\n const cached = this.projectIdCache.get(projectId);\n if (cached !== undefined) return cached;\n\n // Cache miss — scan project list fields to find the matching resource\n const rid = await this.pl.withReadTx(\"ResolveProjectId\", async (tx) => {\n const data = await tx.getResourceData(this.projectListResourceId, true);\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (resourceIdToString(f.value) === (projectId as string)) return f.value;\n }\n throw new Error(`Project ${projectId} not found in project list.`);\n });\n\n this.projectIdCache.set(projectId, rid);\n return rid;\n }\n\n //\n // Project List Manipulation\n //\n\n /** Creates a project with initial state and adds it to project list. */\n public async createProject(meta: ProjectMeta): Promise<ProjectId> {\n let prj: ResourceRef;\n await this.pl.withWriteTx(\"MLCreateProject\", async (tx) => {\n prj = await createProject(tx, meta);\n tx.createField(field(this.projectListResourceId, randomUUID()), \"Dynamic\", prj);\n await tx.commit();\n });\n await this.projectListTree.refreshState();\n\n const signedRid = await prj!.globalId;\n const projectId = resourceIdToString(signedRid) as ProjectId;\n this.projectIdCache.set(projectId, signedRid);\n return projectId;\n }\n\n /** Updates project metadata */\n public async setProjectMeta(\n id: ProjectId,\n meta: ProjectMeta,\n author?: AuthorMarker,\n ): Promise<void> {\n const rid = await this.resolveProjectId(id);\n await withProjectAuthored(\n this.env.projectHelper,\n this.pl,\n rid,\n author,\n (prj) => {\n prj.setMeta(meta);\n },\n { name: \"setProjectMeta\" },\n );\n await this.projectListTree.refreshState();\n }\n\n /** Permanently deletes project from the project list, this will result in\n * destruction of all attached objects, like files, analysis results etc. */\n public async deleteProject(id: ProjectId): Promise<void> {\n await this.pl.withWriteTx(\"MLRemoveProject\", async (tx) => {\n const data = await tx.getResourceData(this.projectListResourceId, true);\n let fieldName: string | undefined;\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (resourceIdToString(f.value) === (id as string)) {\n fieldName = f.name;\n break;\n }\n }\n if (fieldName === undefined) throw new Error(`Project ${id} not found in project list.`);\n tx.removeField(field(this.projectListResourceId, fieldName));\n await tx.commit();\n });\n this.projectIdCache.delete(id);\n await this.projectListTree.refreshState();\n }\n\n /**\n * Duplicates an existing project and adds the copy to this user's project list.\n *\n * @param srcProjectId - project id of the project to duplicate\n * @param rename - optional function that receives the source label and all existing\n * project labels (read within the same transaction), and returns the label for the copy\n */\n public async duplicateProject(\n srcProjectId: ProjectId,\n rename?: (previousLabel: string, existingLabels: string[]) => string,\n ): Promise<ProjectId> {\n const sourceRid = await this.resolveProjectId(srcProjectId);\n\n const newPrj: ResourceRef = await this.pl.withWriteTx(\"MLDuplicateProject\", async (tx) => {\n // Read source project meta\n const sourceMeta = await tx.getKValueJson<ProjectMeta>(sourceRid, ProjectMetaKey);\n\n // Read all existing project labels from the project list (parallel reads)\n const projectListData = await tx.getResourceData(this.projectListResourceId, true);\n const projectRids = projectListData.fields\n .map((f) => f.value)\n .filter(isNotNullSignedResourceId);\n const existingLabels = (\n await Promise.all(\n projectRids.map((rid) => tx.getKValueJson<ProjectMeta>(rid, ProjectMetaKey)),\n )\n ).map((m) => m.label);\n\n // Compute new label\n const newLabel = rename ? rename(sourceMeta.label, existingLabels) : sourceMeta.label;\n\n // Create the duplicate\n const newPrj = await duplicateProject(\n tx,\n sourceRid,\n { label: newLabel },\n this.env.projectHelper,\n );\n\n // Attach to project list with a random UUID field name\n tx.createField(field(this.projectListResourceId, randomUUID()), \"Dynamic\", newPrj);\n await tx.commit();\n\n return newPrj;\n });\n\n await this.projectListTree.refreshState();\n\n const signedRid = await newPrj.globalId;\n const newProjectId = resourceIdToString(signedRid) as ProjectId;\n this.projectIdCache.set(newProjectId, signedRid);\n return newProjectId;\n }\n\n /**\n * Duplicates a project into another user's root, minted in the TARGET user's color so the target\n * owns it. Sibling of {@link duplicateProject}, but writes into a different root. The source\n * project (on the current client root) is referenced cross-color for its block data, kept alive\n * by refcounting, exactly like accepting a shared project. Works both ways: pull (while\n * impersonating a user, copy their project to yourself) and push (from your own root, copy a\n * project to a user). Admin cross-root op; requires the crossTreeRefs:v1 backend capability.\n */\n public async duplicateProjectToUser(\n srcProjectId: ProjectId,\n targetLogin: string,\n rename?: (previousLabel: string, existingLabels: string[]) => string,\n ): Promise<void> {\n if (!this.serverCapabilities.includes(\"crossTreeRefs:v1\"))\n throw new Error(\"duplicateProjectToUser requires the crossTreeRefs:v1 backend capability.\");\n\n const sourceRid = await this.resolveProjectId(srcProjectId);\n const targetRoot = await this.pl.getUserRoot({ login: targetLogin, createIfNotExists: true });\n\n // Run on the target root: the tx default color is the target's, so the new project (and the\n // target's project list, if created here) are minted in the target's color.\n await this.pl.withWriteTxOnRoot(targetRoot, \"MLDuplicateProjectToUser\", async (tx) => {\n // Resolve or lazily create the target root's project list (tx.clientRoot === targetRoot).\n const targetProjectListRid = await ensureProjectListRid(tx);\n\n // Source label + the target's existing labels, for collision-aware renaming.\n const sourceMeta = await tx.getKValueJson<ProjectMeta>(sourceRid, ProjectMetaKey);\n const targetListData = await tx.getResourceData(targetProjectListRid, true);\n const existingLabels = (\n await Promise.all(\n targetListData.fields\n .map((f) => f.value)\n .filter(isNotNullSignedResourceId)\n .map((rid) => tx.getKValueJson<ProjectMeta>(rid, ProjectMetaKey)),\n )\n ).map((m) => m.label);\n const newLabel = rename ? rename(sourceMeta.label, existingLabels) : sourceMeta.label;\n\n const newPrj = await duplicateProject(\n tx,\n sourceRid,\n { label: newLabel },\n this.env.projectHelper,\n );\n tx.createField(field(targetProjectListRid, randomUUID()), \"Dynamic\", newPrj);\n await tx.commit();\n });\n }\n\n //\n // Project Sharing (Copy & Share)\n //\n\n /**\n * Shares the given projects (Copy & Share). Snapshots the projects, creates one envelope, and\n * grants it — all in one atomic write transaction, so a failed grant rolls the whole thing back\n * and the outbox is left as it was.\n *\n * Two variants (see {@link ShareProjectsOptions}):\n * - `{ recipients }` — one writable grant per named recipient; the envelope expires after the\n * default TTL (`sharedAt + envelopeTtlMs`).\n * - `{ everyone: true }` — one make-public grant (backend rewrites the target to the\n * everyone-user); the envelope's `expiresAt` is `null`, so it never expires.\n *\n * v1 always passes `mode: \"copy\"`.\n */\n public async shareProjects(\n projectIds: ProjectId[],\n options: ShareProjectsOptions,\n ): Promise<void> {\n if (projectIds.length === 0) throw new Error(\"shareProjects: no projects given\");\n\n // Everyone + replace: refresh the existing everyone-share of this project under its stable\n // shareId (so recipients who already decided aren't re-prompted), if one exists. Found\n // automatically by project overlap; falls through to a fresh share when none exists.\n if (\"everyone\" in options && options.replace) {\n const priorEveryone = (await this.findSupersedableEnvelopes(projectIds)).find(\n (p) => p.everyone,\n );\n if (priorEveryone !== undefined) {\n await this.changeShare(priorEveryone.shareId, { title: options.title });\n return;\n }\n }\n\n await this.createNewShare(projectIds, options);\n }\n\n /**\n * Mints a fresh share: snapshots the projects into one new envelope (a fresh shareId),\n * supersedes prior shares of the same project, and grants it — all in one atomic write\n * transaction, so a failed grant rolls the whole thing back and the outbox is left as it was.\n * The everyone-refresh path is the {@link changeShare} branch of {@link shareProjects}; this is\n * the mint-a-new-envelope branch.\n */\n private async createNewShare(\n projectIds: ProjectId[],\n options: ShareProjectsOptions,\n ): Promise<void> {\n const everyone = \"everyone\" in options;\n const sources: EnvelopeProjectSource[] = await Promise.all(\n projectIds.map(\n async (id): Promise<EnvelopeProjectSource> => ({\n kind: \"fresh\",\n projectId: id,\n sourceRid: await this.resolveProjectId(id),\n }),\n ),\n );\n const sender = this.currentUserLogin ?? \"\";\n // Targeted share: sharedAt + ttl. Share-with-everybody: never expires (null).\n const expiresAt = everyone ? null : Date.now() + this.env.ops.envelopeTtlMs;\n\n // Supersede prior shares of the same project(s) so they never pile up. Resolved before\n // the write tx (ListGrants is a separate RPC). Everyone-share supersedes a prior\n // everyone-share of the same project; a targeted share pulls each named recipient out of\n // any prior share of that project, deleting that share if it ends up with no recipients.\n const priors = await this.findSupersedableEnvelopes(projectIds);\n\n await this.pl.withWriteTx(\"MLShareProjects\", async (tx) => {\n if (everyone) {\n for (const prior of priors) {\n if (prior.everyone) tx.removeField(field(this.sharingOutboxResourceId, prior.fieldName));\n }\n } else {\n const newRecipients = new Set(options.recipients);\n for (const prior of priors) {\n if (prior.everyone) continue; // a single user can't be pulled from an everyone-grant\n const toRemove = prior.recipients.filter((u) => newRecipients.has(u));\n if (toRemove.length === 0) continue;\n const remaining = prior.recipients.filter((u) => !newRecipients.has(u));\n if (remaining.length === 0) {\n // Nobody left on the old share — drop the whole envelope.\n tx.removeField(field(this.sharingOutboxResourceId, prior.fieldName));\n } else {\n for (const u of toRemove) tx.revokeAccess(prior.rid, u);\n }\n }\n }\n\n const { envelope } = await buildShareEnvelope(tx, this.sharingOutboxResourceId, sources, {\n mode: options.mode,\n sender,\n title: options.title,\n expiresAt,\n });\n\n // Grant in the same transaction (writable: the cross-color accept rule demands a writable\n // grant on the envelope). Atomic with the create.\n const envelopeGid = await envelope.globalId;\n if (everyone) {\n // One everyone-grant: empty/ignored target, ANY_AUTHORISED. The backend rewrites\n // the target to the everyone-user; gated by role + permission ceiling.\n tx.grantAccess(envelopeGid, \"\", { writable: true }, GrantType.ANY_AUTHORISED);\n } else {\n for (const recipient of options.recipients) {\n tx.grantAccess(envelopeGid, recipient, { writable: true });\n }\n }\n\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Changes a share in place (same {@link ShareId}), in one write transaction: re-snapshots live\n * source projects and carries deleted ones' snapshots forward; applies edited recipients/title;\n * transfers already-decided recipients' accept/reject records (they keep their copy and aren't\n * re-prompted); re-grants; drops the old envelope.\n *\n * `opts.recipients` is the full targeted set (decided users are always kept). `opts.title`\n * replaces the title — omit keeps the current one. `opts.everyone` upgrades targeted ->\n * everyone; the reverse is impossible and ignored.\n *\n * `opts.projectActions` is a per-source-project decision, keyed by projectId: `update`\n * re-snapshots the live source (falls back to carry if the source is gone), `keep` carries the\n * existing snapshot (and its timestamp), `remove` drops the project from the pack. A project not\n * in the map defaults to `keep`. Omit the whole map for the legacy auto behavior (live sources\n * updated, gone ones kept) — the everyone-refresh path relies on that.\n */\n public async changeShare(\n shareId: ShareId,\n opts: {\n recipients?: string[];\n everyone?: boolean;\n title?: string;\n projectActions?: Record<ProjectId, ProjectChangeAction>;\n } = {},\n ): Promise<void> {\n await this.pl.withWriteTx(\"MLChangeShare\", async (tx) => {\n const old = await this.resolveOutboxEnvelope(tx, shareId);\n if (old === undefined)\n throw new Error(`changeShare: no live share with id ${shareId} in the outbox.`);\n\n const self = this.currentUserLogin ?? \"\";\n const grants = await tx.listGrants(old.rid);\n // A targeted share may be upgraded to everyone; an everyone-share can't be narrowed back.\n const everyone = grants.some((g) => isEveryoneUserLogin(g.user)) || opts.everyone === true;\n\n // Read the old envelope's project snapshots (uuid -> rid) and accept/reject records.\n const oldRd = await tx.getResourceData(old.rid, true);\n const snapshotByUuid = new Map<string, SignedResourceId>();\n const acceptances: { login: string; acc: EnvelopeAcceptance }[] = [];\n for (const f of oldRd.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (isEnvelopeProjectField(f.name)) {\n snapshotByUuid.set(envelopeProjectFieldUuid(f.name), f.value);\n } else if (isAcceptanceField(f.name)) {\n const raw = (await tx.getResourceData(f.value, false)).data;\n if (raw === undefined) continue;\n acceptances.push({\n login: acceptanceFieldLogin(f.name),\n acc: cachedDeserialize(raw) as EnvelopeAcceptance,\n });\n }\n }\n const decidedLogins = acceptances.map((a) => a.login);\n\n // Everyone-shares ignore recipients; targeted shares keep decided users plus the edited set.\n const priorRecipients = grants\n .filter((g) => !isEveryoneUserLogin(g.user) && g.user !== self)\n .map((g) => g.user);\n const recipients = everyone\n ? []\n : Array.from(new Set([...(opts.recipients ?? priorRecipients), ...decidedLogins]));\n\n // Live source projects by persistable id — these get a fresh snapshot.\n const liveProjects = new Map<string, SignedResourceId>();\n const projList = await tx.getResourceData(this.projectListResourceId, true);\n for (const f of projList.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n liveProjects.set(resourceIdToString(f.value), f.value);\n }\n\n // Per project (keyed by field uuid), apply the caller's decision (default `keep`); with no\n // projectActions map, fall back to the legacy auto behavior: update a live source, keep a gone one.\n const actions = opts.projectActions;\n const sources: EnvelopeProjectSource[] = [];\n for (const uuid of Object.keys(old.data.projects) as ProjectFieldUuid[]) {\n const { label, source, updatedAt } = old.data.projects[uuid];\n const liveRid = liveProjects.get(source);\n\n const action = actions\n ? (actions[source] ?? \"keep\")\n : liveRid !== undefined\n ? \"update\"\n : \"keep\";\n if (action === \"remove\") continue;\n\n if (action === \"update\" && liveRid !== undefined) {\n sources.push({ kind: \"fresh\", projectId: source, sourceRid: liveRid });\n } else {\n // keep, or an \"update\" whose source vanished before commit (deleted meanwhile, e.g. from\n // another client): carry the prior snapshot. Liveness is read inside this write tx — race-safe.\n const snapshotRid = snapshotByUuid.get(uuid);\n if (snapshotRid !== undefined)\n sources.push({ kind: \"carry\", projectId: source, label, snapshotRid, updatedAt });\n }\n }\n\n // Omit (undefined) keeps the current title; a provided value replaces it.\n const title = opts.title === undefined ? old.data.title : opts.title.trim();\n const expiresAt = everyone ? null : Date.now() + this.env.ops.envelopeTtlMs;\n\n // Same shareId, same outbox field name — detach the old field before rebuilding, or they collide.\n tx.removeField(field(this.sharingOutboxResourceId, old.fieldName));\n\n const { envelope } = await buildShareEnvelope(tx, this.sharingOutboxResourceId, sources, {\n mode: old.data.mode,\n sender: self,\n title,\n expiresAt,\n shareId, // SAME shareId — the essence of change\n });\n\n // Transfer the decided users' records onto the new envelope (donor-written copies).\n for (const { login, acc } of acceptances) {\n if (!everyone && !recipients.includes(login)) continue;\n writeEnvelopeAcceptance(tx, envelope, login, acc.action, acc.timestamp);\n }\n\n const gid = await envelope.globalId;\n if (everyone) tx.grantAccess(gid, \"\", { writable: true }, GrantType.ANY_AUTHORISED);\n else for (const r of recipients) tx.grantAccess(gid, r, { writable: true });\n\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Finds the donor's own outgoing envelopes built from any of the given source projects —\n * the supersede candidates for a fresh share of the same project(s). Reads each envelope's\n * recipient set via `ListGrants` so the caller can pull individual recipients or detect an\n * everyone-share.\n */\n private async findSupersedableEnvelopes(projectIds: ProjectId[]): Promise<\n {\n fieldName: string;\n rid: SignedResourceId;\n shareId: ShareId;\n everyone: boolean;\n recipients: string[];\n }[]\n > {\n const wanted = new Set(projectIds);\n\n const matched = await this.pl.withReadTx(\"MLFindSupersede\", async (tx) => {\n const outbox = await tx.getResourceData(this.sharingOutboxResourceId, true);\n const out: { fieldName: string; rid: SignedResourceId; shareId: ShareId }[] = [];\n for (const f of outbox.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const data = decodeEnvelopeData(rd.data);\n if (Object.values(data.projects).some((p) => wanted.has(p.source)))\n out.push({ fieldName: f.name, rid: f.value, shareId: data.shareId });\n }\n return out;\n });\n\n return await Promise.all(\n matched.map(async ({ fieldName, rid, shareId }) => {\n const grants = await this.pl.userResources.listGrants(rid);\n return {\n fieldName,\n rid,\n shareId,\n everyone: grants.some((g) => isEveryoneUserLogin(g.user)),\n recipients: grants.filter((g) => !isEveryoneUserLogin(g.user)).map((g) => g.user),\n };\n }),\n );\n }\n\n /**\n * Revokes and deletes an outgoing share for all recipients: detaches and deletes the envelope, and\n * its grants are revoked along with it. Already-accepted copies are unaffected (ref-counting keeps\n * the adopted resources alive). Idempotent — revoking a share that is already gone is a no-op.\n */\n public async revokeShare(shareId: ShareId): Promise<void> {\n await this.pl.withWriteTx(\"MLRevokeShare\", async (tx) => {\n const target = await this.resolveOutboxEnvelope(tx, shareId);\n if (target === undefined) return;\n tx.removeField(field(this.sharingOutboxResourceId, target.fieldName));\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Resolves a live envelope from the donor's own outbox by its logical `shareId`, returning the\n * outbox field name (for detach), the signed envelope id, and its decoded {@link EnvelopeData}.\n * The outbox is keyed by `{shareId}` directly, but a replaced/legacy share may have drifted, so\n * we match on the decoded `shareId` rather than the field name alone.\n */\n private async resolveOutboxEnvelope(\n tx: PlTransaction,\n shareId: ShareId,\n ): Promise<{ fieldName: string; rid: SignedResourceId; data: EnvelopeData } | undefined> {\n const outboxData = await tx.getResourceData(this.sharingOutboxResourceId, true);\n for (const f of outboxData.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const data = decodeEnvelopeData(rd.data);\n if (data.shareId === shareId) return { fieldName: f.name, rid: f.value, data };\n }\n return undefined;\n }\n\n /**\n * Resolves currently-shared envelopes (granted to this user) to their resource ids, keyed by\n * the envelope's logical `shareId`.\n *\n * Reads the {@link liveEnvelopes} Computable — the same shared-resource discovery tree that\n * feeds {@link pendingShares}. This is the single discovery mechanism: there is no separate\n * `ListUserResources` re-stream on every accept/reject. `refreshState()` is awaited first so a\n * just-granted envelope is observed (the tree's discovery poll may otherwise lag a freshly\n * landed grant). The tree is gRPC-only, so this is empty on a REST-connected client.\n */\n private async resolveLiveEnvelopes(): Promise<Map<ShareId, LiveEnvelope>> {\n await this.pendingSharesTree.refreshState();\n const live = (await this.liveEnvelopes.getValue()) ?? [];\n // Dedup by logical shareId (last writer wins — at most one live envelope per shareId).\n const map = new Map<ShareId, LiveEnvelope>();\n for (const e of live) map.set(e.data.shareId, e);\n return map;\n }\n\n /**\n * Accepts one or more pending shares: duplicates each share's projects into this user's\n * project list, records the decision per share, and (read-write share) writes the donor-visible\n * acceptance onto the envelope. Per-share failures (e.g. an expiry race) are collected, not\n * short-circuited — the rest still get accepted. Accept-all = pass every current pending shareId.\n *\n * `rename` resolves label collisions (same callback contract as {@link duplicateProject}), but\n * the source lives in the envelope tree, so accept calls the low-level mutator directly.\n */\n public async acceptShare(\n shareIds: ShareId[],\n rename?: (previousLabel: string, existingLabels: string[]) => string,\n ): Promise<{ accepted: ProjectId[]; failed: { shareId: ShareId; error: string }[] }> {\n const live = await this.resolveLiveEnvelopes();\n const login = this.currentUserLogin;\n\n const accepted: ProjectId[] = [];\n const failed: { shareId: ShareId; error: string }[] = [];\n\n for (const shareId of shareIds) {\n const envelope = live.get(shareId);\n if (envelope === undefined) {\n failed.push({ shareId, error: \"Share is no longer available.\" });\n continue;\n }\n try {\n const now = Date.now();\n const createdRids = await this.pl.withWriteTx(\"MLAcceptShare\", async (tx) => {\n const created = await copyEnvelopeProjectsIntoList(\n tx,\n envelope.rid,\n this.projectListResourceId,\n rename,\n );\n\n // Record the decision on the acceptor's own SharingState, keyed on shareId.\n writeSharingDecision(tx, this.sharingStateResourceId, shareId, {\n decision: \"accepted\",\n timestamp: now,\n envelopeSharedAt: envelope.data.sharedAt,\n acceptedProjects: resourceIdsToStrings(created),\n });\n\n // Read-write share: write the donor-visible acceptance onto the envelope.\n if (login !== null && envelope.data.mode !== \"read-only\")\n writeEnvelopeAcceptance(tx, envelope.rid, login, \"accepted\", now);\n\n await tx.commit();\n return created;\n });\n for (const rid of createdRids) {\n const projectId = resourceIdToString(rid) as ProjectId;\n this.projectIdCache.set(projectId, rid);\n accepted.push(projectId);\n }\n } catch (e) {\n failed.push({ shareId, error: e instanceof Error ? e.message : String(e) });\n }\n }\n\n await Promise.all([this.projectListTree.refreshState(), this.sharingStateTree.refreshState()]);\n return { accepted, failed };\n }\n\n /** Records rejection of a pending share; it never surfaces again. */\n public async rejectShare(shareId: ShareId): Promise<void> {\n const live = await this.resolveLiveEnvelopes();\n const envelope = live.get(shareId);\n const login = this.currentUserLogin;\n const now = Date.now();\n\n await this.pl.withWriteTx(\"MLRejectShare\", async (tx) => {\n writeSharingDecision(tx, this.sharingStateResourceId, shareId, {\n decision: \"rejected\",\n timestamp: now,\n envelopeSharedAt: envelope?.data.sharedAt ?? now,\n acceptedProjects: [],\n });\n\n // Read-write share: write the donor-visible rejection onto the envelope (if still live).\n if (envelope !== undefined && login !== null && envelope.data.mode !== \"read-only\")\n writeEnvelopeAcceptance(tx, envelope.rid, login, \"rejected\", now);\n\n await tx.commit();\n });\n\n await this.sharingStateTree.refreshState();\n }\n\n //\n // Outbox cleanup (donor side)\n //\n\n private static readonly EnvelopeCleanupIntervalMs = 6 * 3600 * 1000; // every 6h\n private envelopeCleanupTimer: ReturnType<typeof setInterval> | undefined;\n\n /** On ML start and every 6h, delete envelopes whose immutable `expiresAt` has passed. */\n private startEnvelopeCleanup(): void {\n void this.runEnvelopeCleanup();\n this.envelopeCleanupTimer = setInterval(() => {\n void this.runEnvelopeCleanup();\n }, MiddleLayer.EnvelopeCleanupIntervalMs);\n // Don't keep the process alive solely for cleanup.\n this.envelopeCleanupTimer.unref?.();\n }\n\n /** Scans the donor's outbox and deletes expired envelopes (backend auto-revokes their grants).\n * Envelopes with `expiresAt: null` (share-with-everybody) are skipped. */\n private async runEnvelopeCleanup(): Promise<void> {\n try {\n const now = Date.now();\n const expired = await this.pl.withReadTx(\"MLEnvelopeCleanupScan\", async (tx) => {\n const data = await tx.getResourceData(this.sharingOutboxResourceId, true);\n const toDelete: { fieldName: string }[] = [];\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const envData = decodeEnvelopeData(rd.data);\n if (envData.expiresAt === null) continue; // never expires\n if (envData.expiresAt <= now) toDelete.push({ fieldName: f.name });\n }\n return toDelete;\n });\n\n if (expired.length === 0) return;\n\n await this.pl.withWriteTx(\"MLEnvelopeCleanup\", async (tx) => {\n for (const { fieldName } of expired)\n tx.removeField(field(this.sharingOutboxResourceId, fieldName));\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n } catch (e) {\n this.env.logger.warn(\n `envelope cleanup failed: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n }\n\n //\n // Projects\n //\n\n private readonly openedProjects = new Map<ProjectId, Project>();\n\n /** Opens a project, and starts corresponding project maintenance loop. */\n public async openProject(id: ProjectId): Promise<void> {\n if (this.openedProjects.has(id)) throw new Error(`Project ${id} already opened`);\n const rid = await this.resolveProjectId(id);\n this.openedProjects.set(id, await Project.init(this.env, id, rid));\n this.openedProjectsList.setValue([...this.openedProjects.keys()]);\n }\n\n /** Closes the project, and deallocate all corresponding resources. */\n public async closeProject(id: ProjectId): Promise<void> {\n const prj = this.openedProjects.get(id);\n if (prj === undefined) throw new Error(`Project ${id} not found among opened projects`);\n this.openedProjects.delete(id);\n await prj.destroy();\n this.openedProjectsList.setValue([...this.openedProjects.keys()]);\n }\n\n /** Returns a project access object for an opened project. */\n public getOpenedProject(id: ProjectId): Project {\n const prj = this.openedProjects.get(id);\n if (prj === undefined) throw new Error(`Project ${id} not found among opened projects`);\n return prj;\n }\n\n /** Returns true if project with given id is currently opened. */\n public isProjectOpened(id: ProjectId): boolean {\n return this.openedProjects.has(id);\n }\n\n /**\n * Deallocates all runtime resources consumed by this object and awaits\n * actual termination of event loops and other processes associated with\n * them.\n */\n public async close() {\n if (this.envelopeCleanupTimer !== undefined) clearInterval(this.envelopeCleanupTimer);\n await Promise.all([...this.openedProjects.values()].map((prj) => prj.destroy()));\n // this.env.quickJs;\n await Promise.all([\n this.projectListTree.terminate(),\n this.sharingOutboxTree.terminate(),\n this.sharingStateTree.terminate(),\n this.pendingSharesTree.terminate(),\n ]);\n await this.env.dispose();\n await this.pl.close();\n }\n\n /** @deprecated */\n public async closeAndAwaitTermination() {\n await this.close();\n }\n\n /** Generates sufficiently random string to be used as local secret for the\n * middle layer */\n public static generateLocalSecret(): string {\n return HmacSha256Signer.generateSecret();\n }\n\n /** Returns a block event dispatcher, which can be used to listen to block events. */\n public get blockEventDispatcher(): BlockEventDispatcher {\n return this.env.blockEventDispatcher;\n }\n\n /** Initialize middle layer */\n public static async init(\n pl: PlClient,\n workdir: string,\n _ops: MiddleLayerOpsConstructor,\n ): Promise<MiddleLayer> {\n const ops: MiddleLayerOps = {\n ...DefaultMiddleLayerOpsSettings,\n ...DefaultMiddleLayerOpsPaths(workdir),\n ..._ops,\n };\n\n // overriding debug options from environment variables\n ops.defaultTreeOptions.logStat = getDebugFlags().logTreeStats;\n ops.debugOps.dumpInitialTreeState = getDebugFlags().dumpInitialTreeState;\n // apply MI_TREE_TRAVERSAL only when the embedder hasn't set an explicit mode\n if (\n ops.defaultTreeOptions.traversalMode === undefined &&\n getDebugFlags().treeTraversalMode !== undefined\n )\n ops.defaultTreeOptions.traversalMode = getDebugFlags().treeTraversalMode;\n\n const { projects, sharingOutbox, sharingState } = await pl.withWriteTx(\n \"MLInitialization\",\n async (tx) => {\n // Lazily create each clientRoot-attached singleton resource. Returns the existing\n // resource id if the field is already populated, otherwise creates + locks + sets it.\n const lazyInit = async (\n fieldName: string,\n type: { name: string; version: string },\n ): Promise<{ ref?: ResourceRef; existing?: SignedResourceId }> => {\n const f = field(tx.clientRoot, fieldName);\n tx.createField(f, \"Dynamic\");\n const fData = await tx.getField(f);\n if (isNullSignedResourceId(fData.value)) {\n const ref = tx.createEphemeral(type);\n tx.lock(ref);\n tx.setField(f, ref);\n return { ref };\n }\n return { existing: fData.value };\n };\n\n const projectsR = await lazyInit(ProjectsField, ProjectsResourceType);\n const outboxR = await lazyInit(SharingOutboxField, SharingOutboxResourceType);\n const stateR = await lazyInit(SharingStateField, SharingStateResourceType);\n\n await tx.commit();\n\n return {\n projects: projectsR.existing ?? (await projectsR.ref!.globalId),\n sharingState: stateR.existing ?? (await stateR.ref!.globalId),\n sharingOutbox: outboxR.existing ?? (await outboxR.ref!.globalId),\n };\n },\n );\n\n const logger = ops.logger;\n\n const driverKit = await initDriverKit(pl, workdir, ops.frontendDownloadPath, ops);\n\n // passed to components having no own retry logic\n const retryHttpDispatcher = new RetryAgent(pl.httpDispatcher);\n\n const v2RegistryProvider = new V2RegistryProvider(retryHttpDispatcher);\n\n const bpPreparer = new BlockPackPreparer(\n v2RegistryProvider,\n driverKit.signer,\n retryHttpDispatcher,\n );\n\n const quickJs = await getQuickJS();\n\n const runtimeCapabilities = new RuntimeCapabilities();\n // add runtime capabilities of model here\n runtimeCapabilities.addSupportedRequirement(\"requiresModelAPIVersion\", 1);\n runtimeCapabilities.addSupportedRequirement(\"requiresModelAPIVersion\", 2);\n runtimeCapabilities.addSupportedRequirement(\"requiresCreatePTable\", 2);\n runtimeCapabilities.addSupportedRequirement(\"requiresPFramesVersion\", REQUIRES_PFRAMES_VERSION);\n registerServiceCapabilities((flag, value) =>\n runtimeCapabilities.addSupportedRequirement(flag, value),\n );\n // runtime capabilities of the desktop are to be added by the desktop app / test framework\n\n const serviceRegistry = createModelServiceRegistry({ logger });\n\n const env: MiddleLayerEnvironment = {\n pl,\n blockEventDispatcher: new BlockEventDispatcher(),\n signer: driverKit.signer,\n logger,\n httpDispatcher: pl.httpDispatcher,\n retryHttpDispatcher,\n ops,\n bpPreparer,\n frontendDownloadDriver: driverKit.frontendDriver,\n driverKit,\n blockUpdateWatcher: new BlockUpdateWatcher(v2RegistryProvider, logger, {\n minDelay: ops.devBlockUpdateRecheckInterval,\n http: retryHttpDispatcher,\n preferredUpdateChannel: ops.preferredUpdateChannel,\n }),\n runtimeCapabilities,\n serviceRegistry,\n quickJs,\n projectHelper: new ProjectHelper(quickJs, logger),\n dispose: async () => {\n await serviceRegistry.dispose();\n await retryHttpDispatcher.destroy();\n await driverKit.dispose();\n },\n };\n\n const openedProjects = new WatchableValue<ProjectId[]>([]);\n const projectListTC = await createProjectList(pl, projects, openedProjects, env);\n\n // Project sharing trees and reactive views.\n const outgoingTC = await createOutgoingShares(pl, sharingOutbox, env);\n const sharingStateTree = await createSharingStateTree(pl, sharingState, env);\n const pendingSharesTree = await createPendingSharesTree(pl, env);\n const pendingShares = createPendingSharesComputable(\n pendingSharesTree,\n sharingStateTree,\n pl.userResources.authUser,\n );\n const liveEnvelopes = createLiveEnvelopesComputable(pendingSharesTree);\n\n return new MiddleLayer(\n env,\n driverKit,\n driverKit.signer,\n projects,\n sharingOutbox,\n sharingState,\n openedProjects,\n projectListTC.tree,\n outgoingTC.tree,\n sharingStateTree,\n pendingSharesTree,\n v2RegistryProvider,\n projectListTC.computable,\n outgoingTC.computable,\n pendingShares,\n liveEnvelopes,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgIA,IAAa,cAAb,MAAa,YAAY;CAIJ;CACD;CACA;CACC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;CAEA;CAGT;CAGA;CAIU;CA1BnB;CAEA,YACE,KACA,WACA,QACA,uBACA,yBACA,wBACA,oBACA,iBACA,mBACA,kBACA,mBACA,uBAEA,aAGA,gBAGA,eA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B,GAAG;EAG/E,MAAM,aAAa,MAAMC,qBAAAA,qBAAqB,IAAI,eAAe,GAAG;EACpE,MAAM,mBAAmB,MAAMC,qBAAAA,uBAAuB,IAAI,cAAc,GAAG;EAC3E,MAAM,oBAAoB,MAAMC,qBAAAA,wBAAwB,IAAI,GAAG;EAC/D,MAAM,gBAAgBC,qBAAAA,8BACpB,mBACA,kBACA,GAAG,cAAc,QACnB;EACA,MAAM,gBAAgBC,qBAAAA,8BAA8B,iBAAiB;EAErE,OAAO,IAAI,YACT,KACA,WACA,UAAU,QACV,UACA,eACA,cACA,gBACA,cAAc,MACd,WAAW,MACX,kBACA,mBACA,oBACA,cAAc,YACd,WAAW,YACX,eACA,aACF;CACF;AACF"}
1
+ {"version":3,"file":"middle_layer.cjs","names":["canGrantToEveryone","canImpersonate","LRUCache","createProject","withProjectAuthored","withProject","resolveTemplateEntries","kindMismatch","cacheBlockPackTemplate","applyTemplateEntries","TemplateEntryRejected","ProjectMetaKey","isNotNullSignedResourceId","duplicateProject","ensureProjectListRid","buildShareEnvelope","GrantType","isEnvelopeProjectField","envelopeProjectFieldUuid","isAcceptanceField","acceptanceFieldLogin","decodeEnvelopeData","copyEnvelopeProjectsIntoList","resourceIdsToStrings","Project","HmacSha256Signer","DefaultMiddleLayerOpsSettings","DefaultMiddleLayerOpsPaths","getDebugFlags","ProjectsField","ProjectsResourceType","SharingOutboxField","SharingOutboxResourceType","SharingStateField","SharingStateResourceType","initDriverKit","RetryAgent","V2RegistryProvider","BlockPackPreparer","RuntimeCapabilities","REQUIRES_PFRAMES_VERSION","createModelServiceRegistry","BlockEventDispatcher","BlockUpdateWatcher","ProjectHelper","WatchableValue","createProjectList","createOutgoingShares","createSharingStateTree","createPendingSharesTree","createPendingSharesComputable","createLiveEnvelopesComputable"],"sources":["../../src/middle_layer/middle_layer.ts"],"sourcesContent":["import type {\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n Role,\n} from \"@milaboratories/pl-client\";\nimport {\n isEveryoneUserLogin,\n field,\n GrantType,\n isNotNullSignedResourceId,\n isNullSignedResourceId,\n resourceIdToString,\n} from \"@milaboratories/pl-client\";\nimport { LRUCache } from \"lru-cache\";\nimport {\n createProjectList,\n ensureProjectListRid,\n ProjectsField,\n ProjectsResourceType,\n} from \"./project_list\";\nimport {\n createProject,\n duplicateProject,\n withProject,\n withProjectAuthored,\n} from \"../mutator/project\";\nimport type { ProjectTemplateExportOutcome } from \"../model/template_serializer\";\nimport type { ProjectTemplateV1 } from \"@milaboratories/pl-model-common\";\nimport { extractConfig, ensureError } from \"@platforma-sdk/model\";\nimport type { TemplateApplyProblem, TemplateApplyReport } from \"../model/template_apply\";\nimport { TemplateEntryRejected, kindMismatch } from \"../model/template_apply\";\nimport type { BlockPackProvider } from \"../model/template_resolve\";\nimport { resolveTemplateEntries } from \"../model/template_resolve\";\nimport type { PreparedTemplateEntry } from \"../mutator/template_construct\";\nimport { applyTemplateEntries } from \"../mutator/template_construct\";\nimport { throwIfMissingServerCapabilities } from \"./project\";\nimport { cacheBlockPackTemplate } from \"../mutator/template/template_cache\";\nimport { ProjectMetaKey } from \"../model/project_model\";\nimport type { ProjectId } from \"../model/project_model\";\nimport type { SynchronizedTreeState } from \"@milaboratories/pl-tree\";\nimport {\n acceptanceFieldLogin,\n canGrantToEveryone,\n canImpersonate,\n decodeEnvelopeData,\n isAcceptanceField,\n SharingOutboxField,\n SharingOutboxResourceType,\n SharingStateField,\n SharingStateResourceType,\n type EnvelopeAcceptance,\n type EnvelopeData,\n type ProjectChangeAction,\n type ProjectFieldUuid,\n type ShareId,\n type ShareProjectsOptions,\n} from \"../model/sharing_model\";\nimport {\n buildShareEnvelope,\n copyEnvelopeProjectsIntoList,\n envelopeProjectFieldUuid,\n isEnvelopeProjectField,\n resourceIdsToStrings,\n writeEnvelopeAcceptance,\n writeSharingDecision,\n type EnvelopeProjectSource,\n} from \"../mutator/sharing\";\nimport type { LiveEnvelope, OutgoingShare, PendingShare } from \"./sharing_list\";\nimport {\n createLiveEnvelopesComputable,\n createOutgoingShares,\n createPendingSharesComputable,\n createPendingSharesTree,\n createSharingStateTree,\n} from \"./sharing_list\";\nimport { BlockPackPreparer } from \"../mutator/block-pack/block_pack\";\nimport type { MiLogger, Signer } from \"@milaboratories/ts-helpers\";\nimport { BlockEventDispatcher, cachedDeserialize } from \"@milaboratories/ts-helpers\";\nimport { HmacSha256Signer } from \"@milaboratories/ts-helpers\";\nimport type { Computable, ComputableStableDefined } from \"@milaboratories/computable\";\nimport { WatchableValue } from \"@milaboratories/computable\";\nimport { Project } from \"./project\";\nimport type { MiddleLayerOps, MiddleLayerOpsConstructor } from \"./ops\";\nimport { DefaultMiddleLayerOpsPaths, DefaultMiddleLayerOpsSettings } from \"./ops\";\nimport { randomUUID } from \"node:crypto\";\nimport type { ProjectListEntry } from \"../model\";\nimport type {\n AuthorMarker,\n ProjectMeta,\n BlockPlatform,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport type { AppliedEntry } from \"../model/template_apply\";\nimport { BlockUpdateWatcher } from \"../block_registry/watcher\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { getQuickJS } from \"quickjs-emscripten\";\nimport type { MiddleLayerDriverKit } from \"./driver_kit\";\nimport { initDriverKit } from \"./driver_kit\";\nimport type { BlockCodeFeatureFlags, DriverKit, SupportedRequirement } from \"@platforma-sdk/model\";\nimport { RuntimeCapabilities } from \"@platforma-sdk/model\";\nimport {\n type ModelServiceRegistry,\n registerServiceCapabilities,\n REQUIRES_PFRAMES_VERSION,\n} from \"@milaboratories/pl-model-common\";\nimport { createModelServiceRegistry } from \"../service_factories\";\nimport type { DownloadUrlDriver } from \"@milaboratories/pl-drivers\";\nimport { V2RegistryProvider } from \"../block_registry\";\nimport type { Dispatcher } from \"undici\";\nimport { RetryAgent } from \"undici\";\nimport { getDebugFlags } from \"../debug\";\nimport { ProjectHelper } from \"../model/project_helper\";\n\nexport interface MiddleLayerEnvironment {\n dispose(): Promise<void>;\n readonly pl: PlClient;\n readonly runtimeCapabilities: RuntimeCapabilities;\n readonly logger: MiLogger;\n readonly blockEventDispatcher: BlockEventDispatcher;\n readonly httpDispatcher: Dispatcher;\n readonly retryHttpDispatcher: Dispatcher;\n readonly signer: Signer;\n readonly ops: MiddleLayerOps;\n readonly bpPreparer: BlockPackPreparer;\n readonly frontendDownloadDriver: DownloadUrlDriver;\n readonly blockUpdateWatcher: BlockUpdateWatcher;\n readonly quickJs: QuickJSWASMModule;\n readonly driverKit: MiddleLayerDriverKit;\n readonly serviceRegistry: ModelServiceRegistry;\n readonly projectHelper: ProjectHelper;\n}\n\n/**\n * Main access object to work with pl from UI.\n *\n * It implements an abstraction layer of projects and blocks.\n *\n * As a main entry point inside the pl, this object uses a resource attached\n * via the {@link ProjectsField} to the pl client's root, this resource\n * contains project list.\n *\n * Read about alternative roots, if isolated project lists (working environments)\n * are required.\n * */\nexport class MiddleLayer {\n public readonly pl: PlClient;\n\n private constructor(\n private readonly env: MiddleLayerEnvironment,\n public readonly driverKit: DriverKit,\n public readonly signer: Signer,\n private readonly projectListResourceId: SignedResourceId,\n private readonly sharingOutboxResourceId: SignedResourceId,\n private readonly sharingStateResourceId: SignedResourceId,\n private readonly openedProjectsList: WatchableValue<ProjectId[]>,\n private readonly projectListTree: SynchronizedTreeState,\n private readonly sharingOutboxTree: SynchronizedTreeState,\n private readonly sharingStateTree: SynchronizedTreeState,\n private readonly pendingSharesTree: SynchronizedTreeState,\n public readonly blockRegistryProvider: V2RegistryProvider,\n /** Contains a reactive list of projects along with their meta information. */\n public readonly projectList: ComputableStableDefined<ProjectListEntry[]>,\n /** Reactive view of the donor's outbox — the shares this user has created.\n * v1: API only, no UI. */\n public outgoingShares: Computable<OutgoingShare[] | undefined>,\n /** Envelopes granted to this user, not yet accepted or rejected. Fed by the\n * shared-resource discovery tree. */\n public pendingShares: Computable<PendingShare[] | undefined>,\n /** Internal: the acceptor's currently-live envelopes, read from the same shared-resource\n * discovery tree as {@link pendingShares}. The single source the accept/reject flow resolves\n * live envelopes from — no second discovery path. */\n private readonly liveEnvelopes: Computable<LiveEnvelope[] | undefined>,\n ) {\n this.pl = this.env.pl;\n this.startEnvelopeCleanup();\n }\n\n /**\n * Get the OS where backend is running.\n * For old backend versions returns undefined.\n */\n public get serverPlatform(): BlockPlatform | undefined {\n return this.pl.serverInfo.platform as BlockPlatform | undefined;\n }\n\n /**\n * Runtime capabilities advertised by the connected backend (tokens of\n * the form `<feature>:<version>`, e.g. \"wasm:v1\"). Empty list if the\n * backend predates the capability mechanism — that's the desired\n * fail-closed behaviour for blocks declaring any `requiredCapabilities`.\n */\n public get serverCapabilities(): string[] {\n return this.pl.serverInfo.capabilities ?? [];\n }\n\n /**\n * Login of the authenticated user, for the \"Signed in as\" UI. `null` when the\n * backend has no auth (local/dev mode) — the UI hides the element.\n */\n public get currentUserLogin(): string | null {\n return this.pl.userResources.authUser;\n }\n\n /**\n * Whether the connected backend supports project sharing. Synthetic — computed\n * in the middle layer from the backend capabilities the share flow needs (the\n * cross-color field-reference relaxation the accept flow rests on). It can absorb\n * additional required capabilities later without a UI change.\n */\n public get sharingSupported(): boolean {\n // Sharing does not compose with impersonation (discovery is scoped to the admin's session,\n // decisions attribute to the admin), so it is disabled while impersonating. Admins move\n // projects across roots with duplicateProjectToUser instead.\n return this.serverCapabilities.includes(\"crossTreeRefs:v1\") && !this.impersonating;\n }\n\n /** True when this session is impersonating another user (an admin opened another user's root). */\n public get impersonating(): boolean {\n return this.pl.conf.asUser !== undefined;\n }\n\n /**\n * Role of the authenticated user, from the `GetSessionInfo` RPC surfaced through the\n * pl-client. `null` in no-auth mode (when {@link currentUserLogin} is null).\n */\n public get currentUserRole(): Role | null {\n return this.pl.currentUserRole;\n }\n\n /**\n * Whether the UI offers share-with-everybody — no role policy lives in the UI:\n * serverCapabilities.has(\"publicGrants:v1\") && canGrantToEveryone(currentUserRole)\n * Not a security boundary: a crafted call still hits the backend's role +\n * permission-ceiling gate.\n */\n public get canShareWithEveryone(): boolean {\n return (\n !this.impersonating &&\n this.serverCapabilities.includes(\"publicGrants:v1\") &&\n canGrantToEveryone(this.currentUserRole)\n );\n }\n\n /**\n * Whether the authenticated user may impersonate others (open another user's root). Mirrors\n * the backend's `CanImpersonate` role gate — admin/controller only, never a regular user.\n * Derived from the session role, which stays the authenticated admin's even while\n * impersonating, so this stays true across a switch: the \"return to my root\" affordance must\n * not vanish mid-impersonation. Not a security boundary; the backend re-checks on every call.\n */\n public get currentUserCanImpersonate(): boolean {\n return canImpersonate(this.currentUserRole);\n }\n\n /** Adds a runtime capability to the middle layer. */\n public addRuntimeCapability(\n requirement: SupportedRequirement,\n value: number | boolean = true,\n ): void {\n this.env.runtimeCapabilities.addSupportedRequirement(requirement, value);\n }\n\n /** Checks if the given block feature flags are compatible with the runtime capabilities. */\n public checkBlockCompatibility(featureFlags: BlockCodeFeatureFlags | undefined): boolean {\n return this.env.runtimeCapabilities.checkCompatibility(featureFlags);\n }\n\n /** Returns extended API driver kit used internally by middle layer. */\n public get internalDriverKit(): MiddleLayerDriverKit {\n return this.env.driverKit;\n }\n\n /** Returns the service registry for service introspection. */\n public get serviceRegistry(): ModelServiceRegistry {\n return this.env.serviceRegistry;\n }\n\n //\n // ProjectId ↔ SignedResourceId resolution\n //\n\n private readonly projectIdCache = new LRUCache<ProjectId, SignedResourceId>({ max: 1024 });\n\n /** Resolves a ProjectId to a signed SignedResourceId.\n * Uses LRU cache with TX-scan fallback. */\n private async resolveProjectId(projectId: ProjectId): Promise<SignedResourceId> {\n const cached = this.projectIdCache.get(projectId);\n if (cached !== undefined) return cached;\n\n // Cache miss — scan project list fields to find the matching resource\n const rid = await this.pl.withReadTx(\"ResolveProjectId\", async (tx) => {\n const data = await tx.getResourceData(this.projectListResourceId, true);\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (resourceIdToString(f.value) === (projectId as string)) return f.value;\n }\n throw new Error(`Project ${projectId} not found in project list.`);\n });\n\n this.projectIdCache.set(projectId, rid);\n return rid;\n }\n\n //\n // Project List Manipulation\n //\n\n /** Creates a project with initial state and adds it to project list. */\n public async createProject(meta: ProjectMeta): Promise<ProjectId> {\n let prj: ResourceRef;\n await this.pl.withWriteTx(\"MLCreateProject\", async (tx) => {\n prj = await createProject(tx, meta);\n tx.createField(field(this.projectListResourceId, randomUUID()), \"Dynamic\", prj);\n await tx.commit();\n });\n await this.projectListTree.refreshState();\n\n const signedRid = await prj!.globalId;\n const projectId = resourceIdToString(signedRid) as ProjectId;\n this.projectIdCache.set(projectId, signedRid);\n return projectId;\n }\n\n /** Updates project metadata */\n public async setProjectMeta(\n id: ProjectId,\n meta: ProjectMeta,\n author?: AuthorMarker,\n ): Promise<void> {\n const rid = await this.resolveProjectId(id);\n await withProjectAuthored(\n this.env.projectHelper,\n this.pl,\n rid,\n author,\n (prj) => {\n prj.setMeta(meta);\n },\n { name: \"setProjectMeta\" },\n );\n await this.projectListTree.refreshState();\n }\n\n /**\n * Renders a project as a `template-v1` YAML document, or reports every reason it\n * cannot be — the backing call for an \"Export Project as Template…\" command.\n *\n * Takes a project id rather than an open {@link Project} because exporting is a\n * property of the stored project, not of a session with it: the command belongs on\n * a project card, where the project is usually closed. Opening one to read it would\n * spin up trees and watchers for a one-shot read, and then have to decide whether to\n * close them again.\n *\n * Read-only — the underlying mutator touches no field, so the transaction is never\n * committed and the project list needs no refresh.\n *\n * @param id - project id of the project to export\n */\n public async exportProjectAsTemplate(id: ProjectId): Promise<ProjectTemplateExportOutcome> {\n const rid = await this.resolveProjectId(id);\n return await withProject(\n this.env.projectHelper,\n this.pl,\n rid,\n (prj) => prj.exportAsTemplateV1(),\n { name: \"exportProjectAsTemplate\" },\n );\n }\n\n /**\n * Creates the blocks a `template-v1` document describes in an existing project, in the\n * order the document lists them — the backing call for a \"Create Project from Template\n * file…\" command, which is `createProject` followed by this.\n *\n * Takes a project id rather than an open {@link Project}, like\n * {@link exportProjectAsTemplate} and for the same reason: applying a template is a\n * property of the stored project, not of a session with it, and the flow that needs it\n * has just created the project and has no session yet. An already-open session picks the\n * new blocks up through its own refresh loop.\n *\n * Three stages, and their order is the design:\n *\n * 1. **Resolve every entry** to a concrete block pack, through `provider`.\n * 2. **Prepare every block**: fetch it, check it can run against this backend, cache its\n * workflow template, and offer the entry's params to the block's kind for a shape\n * check.\n * 3. **Create the blocks**, in one transaction — each one's params first pointed at this\n * project by the block's own model, since which values in there are references is\n * knowledge only the block has.\n *\n * The first two create nothing, so either of them failing leaves the project exactly as it\n * was. They are also what leaves stage 3 with only in-memory work, and hence able to be a\n * single transaction.\n *\n * **Stage 3 is all or nothing too**, because it is that one transaction: an entry it cannot\n * create throws, the transaction is never committed, and the project keeps none of the\n * blocks the apply had placed. So `problems` non-empty always means `added` is empty, at\n * every stage — a caller never has to reconcile a half-built project, and never has to ask\n * which of the blocks present came from the file.\n *\n * What is NOT checked before the work starts: which entries an entry references. Reading\n * that means reading the params, which only the block can do, and no block exists until\n * stage 2 has fetched one. A file whose entry references one listed below it therefore\n * applies, and the block it creates reports itself as missing references — the same way a\n * reference to a deleted block already behaves.\n *\n * @param id Project to apply into\n * @param document A parsed template document\n * @param provider Where each entry's block comes from\n * @param options `allowUnstable` widens resolution to pre-release implementations, for\n * the whole document\n */\n public async applyTemplateToProject(\n id: ProjectId,\n document: ProjectTemplateV1,\n provider: BlockPackProvider,\n options: { allowUnstable?: boolean; author?: AuthorMarker } = {},\n ): Promise<TemplateApplyReport> {\n const resolution = await resolveTemplateEntries(document, provider, {\n allowUnstable: options.allowUnstable ?? false,\n });\n if (resolution.problems.length > 0) return { added: [], problems: resolution.problems };\n\n // One map, not one per field: resolution reports by entry id, so everything this loop\n // needs about an entry is looked up the same way.\n const byEntryId = new Map(document.blocks.map((entry) => [entry.id, entry]));\n const prepared = new Map<string, PreparedTemplateEntry>();\n const problems: TemplateApplyProblem[] = [];\n\n for (const entry of resolution.resolved) {\n try {\n const documentEntry = byEntryId.get(entry.entryId)!;\n const preparedBp = await this.env.bpPreparer.prepare(entry.spec);\n const blockCfg = extractConfig(preparedBp.config);\n\n // The first question asked of the prepared block: is it the block this entry meant.\n // Everything below is only meaningful once the answer is yes.\n //\n // The locator is appended here rather than inside the check, which names no route:\n // when the file chose the implementation itself, what it chose is the thing to correct.\n const mismatch = kindMismatch(documentEntry.kind, preparedBp.config.kind);\n if (mismatch !== undefined) {\n const locator = documentEntry.location ?? documentEntry.block;\n problems.push({\n entryId: entry.entryId,\n error: locator === undefined ? `${mismatch}.` : `${mismatch} (${locator}).`,\n });\n continue;\n }\n\n // The same two gates `Project.addBlock` applies, for the same reason: a block that\n // cannot run here must not be installed. Here they become per-entry problems\n // rather than throws, so one unusable block reads as one bad entry.\n this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);\n throwIfMissingServerCapabilities(this.pl, preparedBp.requiredCapabilities);\n\n const cachedBp = await cacheBlockPackTemplate(this.pl, preparedBp);\n\n // Offered to the block's kind while nothing has been created yet. Every entry is\n // checked, including one whose file omitted `params` — the parser read that as `{}`,\n // which a kind with required fields rejects, and rightly: it would otherwise apply as\n // a block that looks configured and is not.\n const checked = this.env.projectHelper.validateTemplateParamsInVM(\n blockCfg,\n documentEntry.params,\n );\n if (checked.error !== undefined) {\n problems.push({ entryId: entry.entryId, error: checked.error.message });\n continue;\n }\n\n // The block package's own title, the same thing the add-block UI writes. It is\n // what the user sees for a block whose model derives no title of its own, and it\n // is resolution's to supply — nothing here could reconstruct it.\n prepared.set(entry.entryId, { blockPack: cachedBp, label: entry.title });\n } catch (e) {\n problems.push({\n entryId: entry.entryId,\n error: `This entry's block could not be installed: ${ensureError(e).message}`,\n });\n }\n }\n\n if (problems.length > 0) return { added: [], problems };\n\n const rid = await this.resolveProjectId(id);\n let added: AppliedEntry[] = [];\n try {\n await withProjectAuthored(\n this.env.projectHelper,\n this.pl,\n rid,\n options.author,\n (mut) => {\n added = applyTemplateEntries({\n document,\n placer: mut,\n entries: prepared,\n projectHelper: this.env.projectHelper,\n });\n },\n // Under the same lock an open session's own mutations take, so an apply and a user\n // editing the project cannot interleave.\n { name: \"applyTemplateToProject\", lockId: `project:${id}` },\n );\n } catch (e: unknown) {\n // A statement about the file: the transaction went with the throw, so the project kept\n // none of the blocks the apply had placed, and `added` is empty by construction.\n // Anything else — a backend that refused the write, say — is not about the file and\n // keeps propagating.\n if (!(e instanceof TemplateEntryRejected)) throw e;\n return { added: [], problems: [{ entryId: e.entryId, error: e.message }] };\n }\n\n return { added, problems: [] };\n }\n\n /** Permanently deletes project from the project list, this will result in\n * destruction of all attached objects, like files, analysis results etc. */\n public async deleteProject(id: ProjectId): Promise<void> {\n await this.pl.withWriteTx(\"MLRemoveProject\", async (tx) => {\n const data = await tx.getResourceData(this.projectListResourceId, true);\n let fieldName: string | undefined;\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (resourceIdToString(f.value) === (id as string)) {\n fieldName = f.name;\n break;\n }\n }\n if (fieldName === undefined) throw new Error(`Project ${id} not found in project list.`);\n tx.removeField(field(this.projectListResourceId, fieldName));\n await tx.commit();\n });\n this.projectIdCache.delete(id);\n await this.projectListTree.refreshState();\n }\n\n /**\n * Duplicates an existing project and adds the copy to this user's project list.\n *\n * @param srcProjectId - project id of the project to duplicate\n * @param rename - optional function that receives the source label and all existing\n * project labels (read within the same transaction), and returns the label for the copy\n */\n public async duplicateProject(\n srcProjectId: ProjectId,\n rename?: (previousLabel: string, existingLabels: string[]) => string,\n ): Promise<ProjectId> {\n const sourceRid = await this.resolveProjectId(srcProjectId);\n\n const newPrj: ResourceRef = await this.pl.withWriteTx(\"MLDuplicateProject\", async (tx) => {\n // Read source project meta\n const sourceMeta = await tx.getKValueJson<ProjectMeta>(sourceRid, ProjectMetaKey);\n\n // Read all existing project labels from the project list (parallel reads)\n const projectListData = await tx.getResourceData(this.projectListResourceId, true);\n const projectRids = projectListData.fields\n .map((f) => f.value)\n .filter(isNotNullSignedResourceId);\n const existingLabels = (\n await Promise.all(\n projectRids.map((rid) => tx.getKValueJson<ProjectMeta>(rid, ProjectMetaKey)),\n )\n ).map((m) => m.label);\n\n // Compute new label\n const newLabel = rename ? rename(sourceMeta.label, existingLabels) : sourceMeta.label;\n\n // Create the duplicate\n const newPrj = await duplicateProject(\n tx,\n sourceRid,\n { label: newLabel },\n this.env.projectHelper,\n );\n\n // Attach to project list with a random UUID field name\n tx.createField(field(this.projectListResourceId, randomUUID()), \"Dynamic\", newPrj);\n await tx.commit();\n\n return newPrj;\n });\n\n await this.projectListTree.refreshState();\n\n const signedRid = await newPrj.globalId;\n const newProjectId = resourceIdToString(signedRid) as ProjectId;\n this.projectIdCache.set(newProjectId, signedRid);\n return newProjectId;\n }\n\n /**\n * Duplicates a project into another user's root, minted in the TARGET user's color so the target\n * owns it. Sibling of {@link duplicateProject}, but writes into a different root. The source\n * project (on the current client root) is referenced cross-color for its block data, kept alive\n * by refcounting, exactly like accepting a shared project. Works both ways: pull (while\n * impersonating a user, copy their project to yourself) and push (from your own root, copy a\n * project to a user). Admin cross-root op; requires the crossTreeRefs:v1 backend capability.\n */\n public async duplicateProjectToUser(\n srcProjectId: ProjectId,\n targetLogin: string,\n rename?: (previousLabel: string, existingLabels: string[]) => string,\n ): Promise<void> {\n if (!this.serverCapabilities.includes(\"crossTreeRefs:v1\"))\n throw new Error(\"duplicateProjectToUser requires the crossTreeRefs:v1 backend capability.\");\n\n const sourceRid = await this.resolveProjectId(srcProjectId);\n const targetRoot = await this.pl.getUserRoot({ login: targetLogin, createIfNotExists: true });\n\n // Run on the target root: the tx default color is the target's, so the new project (and the\n // target's project list, if created here) are minted in the target's color.\n await this.pl.withWriteTxOnRoot(targetRoot, \"MLDuplicateProjectToUser\", async (tx) => {\n // Resolve or lazily create the target root's project list (tx.clientRoot === targetRoot).\n const targetProjectListRid = await ensureProjectListRid(tx);\n\n // Source label + the target's existing labels, for collision-aware renaming.\n const sourceMeta = await tx.getKValueJson<ProjectMeta>(sourceRid, ProjectMetaKey);\n const targetListData = await tx.getResourceData(targetProjectListRid, true);\n const existingLabels = (\n await Promise.all(\n targetListData.fields\n .map((f) => f.value)\n .filter(isNotNullSignedResourceId)\n .map((rid) => tx.getKValueJson<ProjectMeta>(rid, ProjectMetaKey)),\n )\n ).map((m) => m.label);\n const newLabel = rename ? rename(sourceMeta.label, existingLabels) : sourceMeta.label;\n\n const newPrj = await duplicateProject(\n tx,\n sourceRid,\n { label: newLabel },\n this.env.projectHelper,\n );\n tx.createField(field(targetProjectListRid, randomUUID()), \"Dynamic\", newPrj);\n await tx.commit();\n });\n }\n\n //\n // Project Sharing (Copy & Share)\n //\n\n /**\n * Shares the given projects (Copy & Share). Snapshots the projects, creates one envelope, and\n * grants it — all in one atomic write transaction, so a failed grant rolls the whole thing back\n * and the outbox is left as it was.\n *\n * Two variants (see {@link ShareProjectsOptions}):\n * - `{ recipients }` — one writable grant per named recipient; the envelope expires after the\n * default TTL (`sharedAt + envelopeTtlMs`).\n * - `{ everyone: true }` — one make-public grant (backend rewrites the target to the\n * everyone-user); the envelope's `expiresAt` is `null`, so it never expires.\n *\n * v1 always passes `mode: \"copy\"`.\n */\n public async shareProjects(\n projectIds: ProjectId[],\n options: ShareProjectsOptions,\n ): Promise<void> {\n if (projectIds.length === 0) throw new Error(\"shareProjects: no projects given\");\n\n // Everyone + replace: refresh the existing everyone-share of this project under its stable\n // shareId (so recipients who already decided aren't re-prompted), if one exists. Found\n // automatically by project overlap; falls through to a fresh share when none exists.\n if (\"everyone\" in options && options.replace) {\n const priorEveryone = (await this.findSupersedableEnvelopes(projectIds)).find(\n (p) => p.everyone,\n );\n if (priorEveryone !== undefined) {\n await this.changeShare(priorEveryone.shareId, { title: options.title });\n return;\n }\n }\n\n await this.createNewShare(projectIds, options);\n }\n\n /**\n * Mints a fresh share: snapshots the projects into one new envelope (a fresh shareId),\n * supersedes prior shares of the same project, and grants it — all in one atomic write\n * transaction, so a failed grant rolls the whole thing back and the outbox is left as it was.\n * The everyone-refresh path is the {@link changeShare} branch of {@link shareProjects}; this is\n * the mint-a-new-envelope branch.\n */\n private async createNewShare(\n projectIds: ProjectId[],\n options: ShareProjectsOptions,\n ): Promise<void> {\n const everyone = \"everyone\" in options;\n const sources: EnvelopeProjectSource[] = await Promise.all(\n projectIds.map(\n async (id): Promise<EnvelopeProjectSource> => ({\n kind: \"fresh\",\n projectId: id,\n sourceRid: await this.resolveProjectId(id),\n }),\n ),\n );\n const sender = this.currentUserLogin ?? \"\";\n // Targeted share: sharedAt + ttl. Share-with-everybody: never expires (null).\n const expiresAt = everyone ? null : Date.now() + this.env.ops.envelopeTtlMs;\n\n // Supersede prior shares of the same project(s) so they never pile up. Resolved before\n // the write tx (ListGrants is a separate RPC). Everyone-share supersedes a prior\n // everyone-share of the same project; a targeted share pulls each named recipient out of\n // any prior share of that project, deleting that share if it ends up with no recipients.\n const priors = await this.findSupersedableEnvelopes(projectIds);\n\n await this.pl.withWriteTx(\"MLShareProjects\", async (tx) => {\n if (everyone) {\n for (const prior of priors) {\n if (prior.everyone) tx.removeField(field(this.sharingOutboxResourceId, prior.fieldName));\n }\n } else {\n const newRecipients = new Set(options.recipients);\n for (const prior of priors) {\n if (prior.everyone) continue; // a single user can't be pulled from an everyone-grant\n const toRemove = prior.recipients.filter((u) => newRecipients.has(u));\n if (toRemove.length === 0) continue;\n const remaining = prior.recipients.filter((u) => !newRecipients.has(u));\n if (remaining.length === 0) {\n // Nobody left on the old share — drop the whole envelope.\n tx.removeField(field(this.sharingOutboxResourceId, prior.fieldName));\n } else {\n for (const u of toRemove) tx.revokeAccess(prior.rid, u);\n }\n }\n }\n\n const { envelope } = await buildShareEnvelope(tx, this.sharingOutboxResourceId, sources, {\n mode: options.mode,\n sender,\n title: options.title,\n expiresAt,\n });\n\n // Grant in the same transaction (writable: the cross-color accept rule demands a writable\n // grant on the envelope). Atomic with the create.\n const envelopeGid = await envelope.globalId;\n if (everyone) {\n // One everyone-grant: empty/ignored target, ANY_AUTHORISED. The backend rewrites\n // the target to the everyone-user; gated by role + permission ceiling.\n tx.grantAccess(envelopeGid, \"\", { writable: true }, GrantType.ANY_AUTHORISED);\n } else {\n for (const recipient of options.recipients) {\n tx.grantAccess(envelopeGid, recipient, { writable: true });\n }\n }\n\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Changes a share in place (same {@link ShareId}), in one write transaction: re-snapshots live\n * source projects and carries deleted ones' snapshots forward; applies edited recipients/title;\n * transfers already-decided recipients' accept/reject records (they keep their copy and aren't\n * re-prompted); re-grants; drops the old envelope.\n *\n * `opts.recipients` is the full targeted set (decided users are always kept). `opts.title`\n * replaces the title — omit keeps the current one. `opts.everyone` upgrades targeted ->\n * everyone; the reverse is impossible and ignored.\n *\n * `opts.projectActions` is a per-source-project decision, keyed by projectId: `update`\n * re-snapshots the live source (falls back to carry if the source is gone), `keep` carries the\n * existing snapshot (and its timestamp), `remove` drops the project from the pack. A project not\n * in the map defaults to `keep`. Omit the whole map for the legacy auto behavior (live sources\n * updated, gone ones kept) — the everyone-refresh path relies on that.\n */\n public async changeShare(\n shareId: ShareId,\n opts: {\n recipients?: string[];\n everyone?: boolean;\n title?: string;\n projectActions?: Record<ProjectId, ProjectChangeAction>;\n } = {},\n ): Promise<void> {\n await this.pl.withWriteTx(\"MLChangeShare\", async (tx) => {\n const old = await this.resolveOutboxEnvelope(tx, shareId);\n if (old === undefined)\n throw new Error(`changeShare: no live share with id ${shareId} in the outbox.`);\n\n const self = this.currentUserLogin ?? \"\";\n const grants = await tx.listGrants(old.rid);\n // A targeted share may be upgraded to everyone; an everyone-share can't be narrowed back.\n const everyone = grants.some((g) => isEveryoneUserLogin(g.user)) || opts.everyone === true;\n\n // Read the old envelope's project snapshots (uuid -> rid) and accept/reject records.\n const oldRd = await tx.getResourceData(old.rid, true);\n const snapshotByUuid = new Map<string, SignedResourceId>();\n const acceptances: { login: string; acc: EnvelopeAcceptance }[] = [];\n for (const f of oldRd.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n if (isEnvelopeProjectField(f.name)) {\n snapshotByUuid.set(envelopeProjectFieldUuid(f.name), f.value);\n } else if (isAcceptanceField(f.name)) {\n const raw = (await tx.getResourceData(f.value, false)).data;\n if (raw === undefined) continue;\n acceptances.push({\n login: acceptanceFieldLogin(f.name),\n acc: cachedDeserialize(raw) as EnvelopeAcceptance,\n });\n }\n }\n const decidedLogins = acceptances.map((a) => a.login);\n\n // Everyone-shares ignore recipients; targeted shares keep decided users plus the edited set.\n const priorRecipients = grants\n .filter((g) => !isEveryoneUserLogin(g.user) && g.user !== self)\n .map((g) => g.user);\n const recipients = everyone\n ? []\n : Array.from(new Set([...(opts.recipients ?? priorRecipients), ...decidedLogins]));\n\n // Live source projects by persistable id — these get a fresh snapshot.\n const liveProjects = new Map<string, SignedResourceId>();\n const projList = await tx.getResourceData(this.projectListResourceId, true);\n for (const f of projList.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n liveProjects.set(resourceIdToString(f.value), f.value);\n }\n\n // Per project (keyed by field uuid), apply the caller's decision (default `keep`); with no\n // projectActions map, fall back to the legacy auto behavior: update a live source, keep a gone one.\n const actions = opts.projectActions;\n const sources: EnvelopeProjectSource[] = [];\n for (const uuid of Object.keys(old.data.projects) as ProjectFieldUuid[]) {\n const { label, source, updatedAt } = old.data.projects[uuid];\n const liveRid = liveProjects.get(source);\n\n const action = actions\n ? (actions[source] ?? \"keep\")\n : liveRid !== undefined\n ? \"update\"\n : \"keep\";\n if (action === \"remove\") continue;\n\n if (action === \"update\" && liveRid !== undefined) {\n sources.push({ kind: \"fresh\", projectId: source, sourceRid: liveRid });\n } else {\n // keep, or an \"update\" whose source vanished before commit (deleted meanwhile, e.g. from\n // another client): carry the prior snapshot. Liveness is read inside this write tx — race-safe.\n const snapshotRid = snapshotByUuid.get(uuid);\n if (snapshotRid !== undefined)\n sources.push({ kind: \"carry\", projectId: source, label, snapshotRid, updatedAt });\n }\n }\n\n // Omit (undefined) keeps the current title; a provided value replaces it.\n const title = opts.title === undefined ? old.data.title : opts.title.trim();\n const expiresAt = everyone ? null : Date.now() + this.env.ops.envelopeTtlMs;\n\n // Same shareId, same outbox field name — detach the old field before rebuilding, or they collide.\n tx.removeField(field(this.sharingOutboxResourceId, old.fieldName));\n\n const { envelope } = await buildShareEnvelope(tx, this.sharingOutboxResourceId, sources, {\n mode: old.data.mode,\n sender: self,\n title,\n expiresAt,\n shareId, // SAME shareId — the essence of change\n });\n\n // Transfer the decided users' records onto the new envelope (donor-written copies).\n for (const { login, acc } of acceptances) {\n if (!everyone && !recipients.includes(login)) continue;\n writeEnvelopeAcceptance(tx, envelope, login, acc.action, acc.timestamp);\n }\n\n const gid = await envelope.globalId;\n if (everyone) tx.grantAccess(gid, \"\", { writable: true }, GrantType.ANY_AUTHORISED);\n else for (const r of recipients) tx.grantAccess(gid, r, { writable: true });\n\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Finds the donor's own outgoing envelopes built from any of the given source projects —\n * the supersede candidates for a fresh share of the same project(s). Reads each envelope's\n * recipient set via `ListGrants` so the caller can pull individual recipients or detect an\n * everyone-share.\n */\n private async findSupersedableEnvelopes(projectIds: ProjectId[]): Promise<\n {\n fieldName: string;\n rid: SignedResourceId;\n shareId: ShareId;\n everyone: boolean;\n recipients: string[];\n }[]\n > {\n const wanted = new Set(projectIds);\n\n const matched = await this.pl.withReadTx(\"MLFindSupersede\", async (tx) => {\n const outbox = await tx.getResourceData(this.sharingOutboxResourceId, true);\n const out: { fieldName: string; rid: SignedResourceId; shareId: ShareId }[] = [];\n for (const f of outbox.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const data = decodeEnvelopeData(rd.data);\n if (Object.values(data.projects).some((p) => wanted.has(p.source)))\n out.push({ fieldName: f.name, rid: f.value, shareId: data.shareId });\n }\n return out;\n });\n\n return await Promise.all(\n matched.map(async ({ fieldName, rid, shareId }) => {\n const grants = await this.pl.userResources.listGrants(rid);\n return {\n fieldName,\n rid,\n shareId,\n everyone: grants.some((g) => isEveryoneUserLogin(g.user)),\n recipients: grants.filter((g) => !isEveryoneUserLogin(g.user)).map((g) => g.user),\n };\n }),\n );\n }\n\n /**\n * Revokes and deletes an outgoing share for all recipients: detaches and deletes the envelope, and\n * its grants are revoked along with it. Already-accepted copies are unaffected (ref-counting keeps\n * the adopted resources alive). Idempotent — revoking a share that is already gone is a no-op.\n */\n public async revokeShare(shareId: ShareId): Promise<void> {\n await this.pl.withWriteTx(\"MLRevokeShare\", async (tx) => {\n const target = await this.resolveOutboxEnvelope(tx, shareId);\n if (target === undefined) return;\n tx.removeField(field(this.sharingOutboxResourceId, target.fieldName));\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n }\n\n /**\n * Resolves a live envelope from the donor's own outbox by its logical `shareId`, returning the\n * outbox field name (for detach), the signed envelope id, and its decoded {@link EnvelopeData}.\n * The outbox is keyed by `{shareId}` directly, but a replaced/legacy share may have drifted, so\n * we match on the decoded `shareId` rather than the field name alone.\n */\n private async resolveOutboxEnvelope(\n tx: PlTransaction,\n shareId: ShareId,\n ): Promise<{ fieldName: string; rid: SignedResourceId; data: EnvelopeData } | undefined> {\n const outboxData = await tx.getResourceData(this.sharingOutboxResourceId, true);\n for (const f of outboxData.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const data = decodeEnvelopeData(rd.data);\n if (data.shareId === shareId) return { fieldName: f.name, rid: f.value, data };\n }\n return undefined;\n }\n\n /**\n * Resolves currently-shared envelopes (granted to this user) to their resource ids, keyed by\n * the envelope's logical `shareId`.\n *\n * Reads the {@link liveEnvelopes} Computable — the same shared-resource discovery tree that\n * feeds {@link pendingShares}. This is the single discovery mechanism: there is no separate\n * `ListUserResources` re-stream on every accept/reject. `refreshState()` is awaited first so a\n * just-granted envelope is observed (the tree's discovery poll may otherwise lag a freshly\n * landed grant). The tree is gRPC-only, so this is empty on a REST-connected client.\n */\n private async resolveLiveEnvelopes(): Promise<Map<ShareId, LiveEnvelope>> {\n await this.pendingSharesTree.refreshState();\n const live = (await this.liveEnvelopes.getValue()) ?? [];\n // Dedup by logical shareId (last writer wins — at most one live envelope per shareId).\n const map = new Map<ShareId, LiveEnvelope>();\n for (const e of live) map.set(e.data.shareId, e);\n return map;\n }\n\n /**\n * Accepts one or more pending shares: duplicates each share's projects into this user's\n * project list, records the decision per share, and (read-write share) writes the donor-visible\n * acceptance onto the envelope. Per-share failures (e.g. an expiry race) are collected, not\n * short-circuited — the rest still get accepted. Accept-all = pass every current pending shareId.\n *\n * `rename` resolves label collisions (same callback contract as {@link duplicateProject}), but\n * the source lives in the envelope tree, so accept calls the low-level mutator directly.\n */\n public async acceptShare(\n shareIds: ShareId[],\n rename?: (previousLabel: string, existingLabels: string[]) => string,\n ): Promise<{ accepted: ProjectId[]; failed: { shareId: ShareId; error: string }[] }> {\n const live = await this.resolveLiveEnvelopes();\n const login = this.currentUserLogin;\n\n const accepted: ProjectId[] = [];\n const failed: { shareId: ShareId; error: string }[] = [];\n\n for (const shareId of shareIds) {\n const envelope = live.get(shareId);\n if (envelope === undefined) {\n failed.push({ shareId, error: \"Share is no longer available.\" });\n continue;\n }\n try {\n const now = Date.now();\n const createdRids = await this.pl.withWriteTx(\"MLAcceptShare\", async (tx) => {\n const created = await copyEnvelopeProjectsIntoList(\n tx,\n envelope.rid,\n this.projectListResourceId,\n rename,\n );\n\n // Record the decision on the acceptor's own SharingState, keyed on shareId.\n writeSharingDecision(tx, this.sharingStateResourceId, shareId, {\n decision: \"accepted\",\n timestamp: now,\n envelopeSharedAt: envelope.data.sharedAt,\n acceptedProjects: resourceIdsToStrings(created),\n });\n\n // Read-write share: write the donor-visible acceptance onto the envelope.\n if (login !== null && envelope.data.mode !== \"read-only\")\n writeEnvelopeAcceptance(tx, envelope.rid, login, \"accepted\", now);\n\n await tx.commit();\n return created;\n });\n for (const rid of createdRids) {\n const projectId = resourceIdToString(rid) as ProjectId;\n this.projectIdCache.set(projectId, rid);\n accepted.push(projectId);\n }\n } catch (e) {\n failed.push({ shareId, error: e instanceof Error ? e.message : String(e) });\n }\n }\n\n await Promise.all([this.projectListTree.refreshState(), this.sharingStateTree.refreshState()]);\n return { accepted, failed };\n }\n\n /** Records rejection of a pending share; it never surfaces again. */\n public async rejectShare(shareId: ShareId): Promise<void> {\n const live = await this.resolveLiveEnvelopes();\n const envelope = live.get(shareId);\n const login = this.currentUserLogin;\n const now = Date.now();\n\n await this.pl.withWriteTx(\"MLRejectShare\", async (tx) => {\n writeSharingDecision(tx, this.sharingStateResourceId, shareId, {\n decision: \"rejected\",\n timestamp: now,\n envelopeSharedAt: envelope?.data.sharedAt ?? now,\n acceptedProjects: [],\n });\n\n // Read-write share: write the donor-visible rejection onto the envelope (if still live).\n if (envelope !== undefined && login !== null && envelope.data.mode !== \"read-only\")\n writeEnvelopeAcceptance(tx, envelope.rid, login, \"rejected\", now);\n\n await tx.commit();\n });\n\n await this.sharingStateTree.refreshState();\n }\n\n //\n // Outbox cleanup (donor side)\n //\n\n private static readonly EnvelopeCleanupIntervalMs = 6 * 3600 * 1000; // every 6h\n private envelopeCleanupTimer: ReturnType<typeof setInterval> | undefined;\n\n /** On ML start and every 6h, delete envelopes whose immutable `expiresAt` has passed. */\n private startEnvelopeCleanup(): void {\n void this.runEnvelopeCleanup();\n this.envelopeCleanupTimer = setInterval(() => {\n void this.runEnvelopeCleanup();\n }, MiddleLayer.EnvelopeCleanupIntervalMs);\n // Don't keep the process alive solely for cleanup.\n this.envelopeCleanupTimer.unref?.();\n }\n\n /** Scans the donor's outbox and deletes expired envelopes (backend auto-revokes their grants).\n * Envelopes with `expiresAt: null` (share-with-everybody) are skipped. */\n private async runEnvelopeCleanup(): Promise<void> {\n try {\n const now = Date.now();\n const expired = await this.pl.withReadTx(\"MLEnvelopeCleanupScan\", async (tx) => {\n const data = await tx.getResourceData(this.sharingOutboxResourceId, true);\n const toDelete: { fieldName: string }[] = [];\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const rd = await tx.getResourceData(f.value, false);\n if (rd.data === undefined) continue;\n const envData = decodeEnvelopeData(rd.data);\n if (envData.expiresAt === null) continue; // never expires\n if (envData.expiresAt <= now) toDelete.push({ fieldName: f.name });\n }\n return toDelete;\n });\n\n if (expired.length === 0) return;\n\n await this.pl.withWriteTx(\"MLEnvelopeCleanup\", async (tx) => {\n for (const { fieldName } of expired)\n tx.removeField(field(this.sharingOutboxResourceId, fieldName));\n await tx.commit();\n });\n\n await this.sharingOutboxTree.refreshState();\n } catch (e) {\n this.env.logger.warn(\n `envelope cleanup failed: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n }\n\n //\n // Projects\n //\n\n private readonly openedProjects = new Map<ProjectId, Project>();\n\n /** Opens a project, and starts corresponding project maintenance loop. */\n public async openProject(id: ProjectId): Promise<void> {\n if (this.openedProjects.has(id)) throw new Error(`Project ${id} already opened`);\n const rid = await this.resolveProjectId(id);\n this.openedProjects.set(id, await Project.init(this.env, id, rid));\n this.openedProjectsList.setValue([...this.openedProjects.keys()]);\n }\n\n /** Closes the project, and deallocate all corresponding resources. */\n public async closeProject(id: ProjectId): Promise<void> {\n const prj = this.openedProjects.get(id);\n if (prj === undefined) throw new Error(`Project ${id} not found among opened projects`);\n this.openedProjects.delete(id);\n await prj.destroy();\n this.openedProjectsList.setValue([...this.openedProjects.keys()]);\n }\n\n /** Returns a project access object for an opened project. */\n public getOpenedProject(id: ProjectId): Project {\n const prj = this.openedProjects.get(id);\n if (prj === undefined) throw new Error(`Project ${id} not found among opened projects`);\n return prj;\n }\n\n /** Returns true if project with given id is currently opened. */\n public isProjectOpened(id: ProjectId): boolean {\n return this.openedProjects.has(id);\n }\n\n /**\n * Deallocates all runtime resources consumed by this object and awaits\n * actual termination of event loops and other processes associated with\n * them.\n */\n public async close() {\n if (this.envelopeCleanupTimer !== undefined) clearInterval(this.envelopeCleanupTimer);\n await Promise.all([...this.openedProjects.values()].map((prj) => prj.destroy()));\n // this.env.quickJs;\n await Promise.all([\n this.projectListTree.terminate(),\n this.sharingOutboxTree.terminate(),\n this.sharingStateTree.terminate(),\n this.pendingSharesTree.terminate(),\n ]);\n await this.env.dispose();\n await this.pl.close();\n }\n\n /** @deprecated */\n public async closeAndAwaitTermination() {\n await this.close();\n }\n\n /** Generates sufficiently random string to be used as local secret for the\n * middle layer */\n public static generateLocalSecret(): string {\n return HmacSha256Signer.generateSecret();\n }\n\n /** Returns a block event dispatcher, which can be used to listen to block events. */\n public get blockEventDispatcher(): BlockEventDispatcher {\n return this.env.blockEventDispatcher;\n }\n\n /** Initialize middle layer */\n public static async init(\n pl: PlClient,\n workdir: string,\n _ops: MiddleLayerOpsConstructor,\n ): Promise<MiddleLayer> {\n const ops: MiddleLayerOps = {\n ...DefaultMiddleLayerOpsSettings,\n ...DefaultMiddleLayerOpsPaths(workdir),\n ..._ops,\n };\n\n // overriding debug options from environment variables\n ops.defaultTreeOptions.logStat = getDebugFlags().logTreeStats;\n ops.debugOps.dumpInitialTreeState = getDebugFlags().dumpInitialTreeState;\n // apply MI_TREE_TRAVERSAL only when the embedder hasn't set an explicit mode\n if (\n ops.defaultTreeOptions.traversalMode === undefined &&\n getDebugFlags().treeTraversalMode !== undefined\n )\n ops.defaultTreeOptions.traversalMode = getDebugFlags().treeTraversalMode;\n\n const { projects, sharingOutbox, sharingState } = await pl.withWriteTx(\n \"MLInitialization\",\n async (tx) => {\n // Lazily create each clientRoot-attached singleton resource. Returns the existing\n // resource id if the field is already populated, otherwise creates + locks + sets it.\n const lazyInit = async (\n fieldName: string,\n type: { name: string; version: string },\n ): Promise<{ ref?: ResourceRef; existing?: SignedResourceId }> => {\n const f = field(tx.clientRoot, fieldName);\n tx.createField(f, \"Dynamic\");\n const fData = await tx.getField(f);\n if (isNullSignedResourceId(fData.value)) {\n const ref = tx.createEphemeral(type);\n tx.lock(ref);\n tx.setField(f, ref);\n return { ref };\n }\n return { existing: fData.value };\n };\n\n const projectsR = await lazyInit(ProjectsField, ProjectsResourceType);\n const outboxR = await lazyInit(SharingOutboxField, SharingOutboxResourceType);\n const stateR = await lazyInit(SharingStateField, SharingStateResourceType);\n\n await tx.commit();\n\n return {\n projects: projectsR.existing ?? (await projectsR.ref!.globalId),\n sharingState: stateR.existing ?? (await stateR.ref!.globalId),\n sharingOutbox: outboxR.existing ?? (await outboxR.ref!.globalId),\n };\n },\n );\n\n const logger = ops.logger;\n\n const driverKit = await initDriverKit(pl, workdir, ops.frontendDownloadPath, ops);\n\n // passed to components having no own retry logic\n const retryHttpDispatcher = new RetryAgent(pl.httpDispatcher);\n\n const v2RegistryProvider = new V2RegistryProvider(retryHttpDispatcher);\n\n const bpPreparer = new BlockPackPreparer(\n v2RegistryProvider,\n driverKit.signer,\n retryHttpDispatcher,\n );\n\n const quickJs = await getQuickJS();\n\n const runtimeCapabilities = new RuntimeCapabilities();\n // add runtime capabilities of model here\n runtimeCapabilities.addSupportedRequirement(\"requiresModelAPIVersion\", 1);\n runtimeCapabilities.addSupportedRequirement(\"requiresModelAPIVersion\", 2);\n runtimeCapabilities.addSupportedRequirement(\"requiresCreatePTable\", 2);\n runtimeCapabilities.addSupportedRequirement(\"requiresPFramesVersion\", REQUIRES_PFRAMES_VERSION);\n registerServiceCapabilities((flag, value) =>\n runtimeCapabilities.addSupportedRequirement(flag, value),\n );\n // runtime capabilities of the desktop are to be added by the desktop app / test framework\n\n const serviceRegistry = createModelServiceRegistry({ logger });\n\n const env: MiddleLayerEnvironment = {\n pl,\n blockEventDispatcher: new BlockEventDispatcher(),\n signer: driverKit.signer,\n logger,\n httpDispatcher: pl.httpDispatcher,\n retryHttpDispatcher,\n ops,\n bpPreparer,\n frontendDownloadDriver: driverKit.frontendDriver,\n driverKit,\n blockUpdateWatcher: new BlockUpdateWatcher(v2RegistryProvider, logger, {\n minDelay: ops.devBlockUpdateRecheckInterval,\n http: retryHttpDispatcher,\n preferredUpdateChannel: ops.preferredUpdateChannel,\n }),\n runtimeCapabilities,\n serviceRegistry,\n quickJs,\n projectHelper: new ProjectHelper(quickJs, logger),\n dispose: async () => {\n await serviceRegistry.dispose();\n await retryHttpDispatcher.destroy();\n await driverKit.dispose();\n },\n };\n\n const openedProjects = new WatchableValue<ProjectId[]>([]);\n const projectListTC = await createProjectList(pl, projects, openedProjects, env);\n\n // Project sharing trees and reactive views.\n const outgoingTC = await createOutgoingShares(pl, sharingOutbox, env);\n const sharingStateTree = await createSharingStateTree(pl, sharingState, env);\n const pendingSharesTree = await createPendingSharesTree(pl, env);\n const pendingShares = createPendingSharesComputable(\n pendingSharesTree,\n sharingStateTree,\n pl.userResources.authUser,\n );\n const liveEnvelopes = createLiveEnvelopesComputable(pendingSharesTree);\n\n return new MiddleLayer(\n env,\n driverKit,\n driverKit.signer,\n projects,\n sharingOutbox,\n sharingState,\n openedProjects,\n projectListTC.tree,\n outgoingTC.tree,\n sharingStateTree,\n pendingSharesTree,\n v2RegistryProvider,\n projectListTC.computable,\n outgoingTC.computable,\n pendingShares,\n liveEnvelopes,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiJA,IAAa,cAAb,MAAa,YAAY;CAIJ;CACD;CACA;CACC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;CAEA;CAGT;CAGA;CAIU;CA1BnB;CAEA,YACE,KACA,WACA,QACA,uBACA,yBACA,wBACA,oBACA,iBACA,mBACA,kBACA,mBACA,uBAEA,aAGA,gBAGA,eAIA,eACA;EAxBiB,KAAA,MAAA;EACD,KAAA,YAAA;EACA,KAAA,SAAA;EACC,KAAA,wBAAA;EACA,KAAA,0BAAA;EACA,KAAA,yBAAA;EACA,KAAA,qBAAA;EACA,KAAA,kBAAA;EACA,KAAA,oBAAA;EACA,KAAA,mBAAA;EACA,KAAA,oBAAA;EACD,KAAA,wBAAA;EAEA,KAAA,cAAA;EAGT,KAAA,iBAAA;EAGA,KAAA,gBAAA;EAIU,KAAA,gBAAA;EAE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../block_registry/registry-v2-provider.js";
2
+ import { TemplateApplyReport } from "../model/template_apply.js";
3
+ import { BlockPackProvider } from "../model/template_resolve.js";
2
4
  import { ProjectId as ProjectId$1, ProjectListEntry as ProjectListEntry$1 } from "../model/project_model.js";
5
+ import { ProjectTemplateExportOutcome } from "../model/template_serializer.js";
3
6
  import { ProjectChangeAction, ShareId, ShareProjectsOptions } from "../model/sharing_model.js";
4
7
  import { OutgoingShare, PendingShare } from "./sharing_list.js";
5
8
  import { BlockPackPreparer } from "../mutator/block-pack/block_pack.js";
@@ -12,11 +15,11 @@ import { BlockCodeFeatureFlags, DriverKit, RuntimeCapabilities, SupportedRequire
12
15
  import { AuthorMarker, BlockPlatform, ProjectMeta } from "@milaboratories/pl-model-middle-layer";
13
16
  import { Dispatcher } from "undici";
14
17
  import { BlockEventDispatcher, MiLogger, Signer } from "@milaboratories/ts-helpers";
18
+ import { ModelServiceRegistry, ProjectTemplateV1 } from "@milaboratories/pl-model-common";
15
19
  import { PlClient, Role } from "@milaboratories/pl-client";
16
20
  import { Computable, ComputableStableDefined } from "@milaboratories/computable";
17
21
  import { DownloadUrlDriver } from "@milaboratories/pl-drivers";
18
22
  import { QuickJSWASMModule } from "quickjs-emscripten";
19
- import { ModelServiceRegistry } from "@milaboratories/pl-model-common";
20
23
 
21
24
  //#region src/middle_layer/middle_layer.d.ts
22
25
  interface MiddleLayerEnvironment {
@@ -138,6 +141,69 @@ declare class MiddleLayer {
138
141
  createProject(meta: ProjectMeta): Promise<ProjectId$1>;
139
142
  /** Updates project metadata */
140
143
  setProjectMeta(id: ProjectId$1, meta: ProjectMeta, author?: AuthorMarker): Promise<void>;
144
+ /**
145
+ * Renders a project as a `template-v1` YAML document, or reports every reason it
146
+ * cannot be — the backing call for an "Export Project as Template…" command.
147
+ *
148
+ * Takes a project id rather than an open {@link Project} because exporting is a
149
+ * property of the stored project, not of a session with it: the command belongs on
150
+ * a project card, where the project is usually closed. Opening one to read it would
151
+ * spin up trees and watchers for a one-shot read, and then have to decide whether to
152
+ * close them again.
153
+ *
154
+ * Read-only — the underlying mutator touches no field, so the transaction is never
155
+ * committed and the project list needs no refresh.
156
+ *
157
+ * @param id - project id of the project to export
158
+ */
159
+ exportProjectAsTemplate(id: ProjectId$1): Promise<ProjectTemplateExportOutcome>;
160
+ /**
161
+ * Creates the blocks a `template-v1` document describes in an existing project, in the
162
+ * order the document lists them — the backing call for a "Create Project from Template
163
+ * file…" command, which is `createProject` followed by this.
164
+ *
165
+ * Takes a project id rather than an open {@link Project}, like
166
+ * {@link exportProjectAsTemplate} and for the same reason: applying a template is a
167
+ * property of the stored project, not of a session with it, and the flow that needs it
168
+ * has just created the project and has no session yet. An already-open session picks the
169
+ * new blocks up through its own refresh loop.
170
+ *
171
+ * Three stages, and their order is the design:
172
+ *
173
+ * 1. **Resolve every entry** to a concrete block pack, through `provider`.
174
+ * 2. **Prepare every block**: fetch it, check it can run against this backend, cache its
175
+ * workflow template, and offer the entry's params to the block's kind for a shape
176
+ * check.
177
+ * 3. **Create the blocks**, in one transaction — each one's params first pointed at this
178
+ * project by the block's own model, since which values in there are references is
179
+ * knowledge only the block has.
180
+ *
181
+ * The first two create nothing, so either of them failing leaves the project exactly as it
182
+ * was. They are also what leaves stage 3 with only in-memory work, and hence able to be a
183
+ * single transaction.
184
+ *
185
+ * **Stage 3 is all or nothing too**, because it is that one transaction: an entry it cannot
186
+ * create throws, the transaction is never committed, and the project keeps none of the
187
+ * blocks the apply had placed. So `problems` non-empty always means `added` is empty, at
188
+ * every stage — a caller never has to reconcile a half-built project, and never has to ask
189
+ * which of the blocks present came from the file.
190
+ *
191
+ * What is NOT checked before the work starts: which entries an entry references. Reading
192
+ * that means reading the params, which only the block can do, and no block exists until
193
+ * stage 2 has fetched one. A file whose entry references one listed below it therefore
194
+ * applies, and the block it creates reports itself as missing references — the same way a
195
+ * reference to a deleted block already behaves.
196
+ *
197
+ * @param id Project to apply into
198
+ * @param document A parsed template document
199
+ * @param provider Where each entry's block comes from
200
+ * @param options `allowUnstable` widens resolution to pre-release implementations, for
201
+ * the whole document
202
+ */
203
+ applyTemplateToProject(id: ProjectId$1, document: ProjectTemplateV1, provider: BlockPackProvider, options?: {
204
+ allowUnstable?: boolean;
205
+ author?: AuthorMarker;
206
+ }): Promise<TemplateApplyReport>;
141
207
  /** Permanently deletes project from the project list, this will result in
142
208
  * destruction of all attached objects, like files, analysis results etc. */
143
209
  deleteProject(id: ProjectId$1): Promise<void>;