@milaboratories/pl-middle-layer 2.10.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/dist/block_registry/registry-v2-provider.cjs +8 -1
  2. package/dist/block_registry/registry-v2-provider.cjs.map +1 -1
  3. package/dist/block_registry/registry-v2-provider.d.ts.map +1 -1
  4. package/dist/block_registry/registry-v2-provider.js +8 -1
  5. package/dist/block_registry/registry-v2-provider.js.map +1 -1
  6. package/dist/index.cjs +25 -1
  7. package/dist/index.d.ts +12 -5
  8. package/dist/index.js +5 -3
  9. package/dist/js_render/bundle_bytecode_cache.cjs +6 -1
  10. package/dist/js_render/bundle_bytecode_cache.cjs.map +1 -1
  11. package/dist/js_render/bundle_bytecode_cache.js +6 -1
  12. package/dist/js_render/bundle_bytecode_cache.js.map +1 -1
  13. package/dist/js_render/column_registry.cjs +17 -0
  14. package/dist/js_render/column_registry.cjs.map +1 -1
  15. package/dist/js_render/column_registry.js +16 -1
  16. package/dist/js_render/column_registry.js.map +1 -1
  17. package/dist/js_render/computable_context.cjs +1 -1
  18. package/dist/js_render/computable_context.js +1 -1
  19. package/dist/js_render/context.cjs +3 -2
  20. package/dist/js_render/context.cjs.map +1 -1
  21. package/dist/js_render/context.js +3 -2
  22. package/dist/js_render/context.js.map +1 -1
  23. package/dist/js_render/index.cjs +1 -1
  24. package/dist/js_render/index.cjs.map +1 -1
  25. package/dist/js_render/index.js +1 -1
  26. package/dist/js_render/index.js.map +1 -1
  27. package/dist/js_render/service_injectors.cjs +2 -9
  28. package/dist/js_render/service_injectors.cjs.map +1 -1
  29. package/dist/js_render/service_injectors.js +2 -9
  30. package/dist/js_render/service_injectors.js.map +1 -1
  31. package/dist/middle_layer/block.cjs +48 -0
  32. package/dist/middle_layer/block.cjs.map +1 -1
  33. package/dist/middle_layer/block.js +51 -4
  34. package/dist/middle_layer/block.js.map +1 -1
  35. package/dist/middle_layer/block_pack_description.cjs +80 -0
  36. package/dist/middle_layer/block_pack_description.cjs.map +1 -0
  37. package/dist/middle_layer/block_pack_description.d.ts +36 -0
  38. package/dist/middle_layer/block_pack_description.d.ts.map +1 -0
  39. package/dist/middle_layer/block_pack_description.js +78 -0
  40. package/dist/middle_layer/block_pack_description.js.map +1 -0
  41. package/dist/middle_layer/build_stamp.cjs +1 -1
  42. package/dist/middle_layer/build_stamp.js +1 -1
  43. package/dist/middle_layer/index.cjs +11 -0
  44. package/dist/middle_layer/index.d.ts +8 -2
  45. package/dist/middle_layer/index.js +3 -1
  46. package/dist/middle_layer/legacy_project_holds.cjs +61 -0
  47. package/dist/middle_layer/legacy_project_holds.cjs.map +1 -0
  48. package/dist/middle_layer/legacy_project_holds.js +61 -0
  49. package/dist/middle_layer/legacy_project_holds.js.map +1 -0
  50. package/dist/middle_layer/middle_layer.cjs +22 -24
  51. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  52. package/dist/middle_layer/middle_layer.d.ts +13 -3
  53. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  54. package/dist/middle_layer/middle_layer.js +21 -23
  55. package/dist/middle_layer/middle_layer.js.map +1 -1
  56. package/dist/middle_layer/pool_columns.cjs +160 -0
  57. package/dist/middle_layer/pool_columns.cjs.map +1 -0
  58. package/dist/middle_layer/pool_columns.d.ts +59 -0
  59. package/dist/middle_layer/pool_columns.d.ts.map +1 -0
  60. package/dist/middle_layer/pool_columns.js +157 -0
  61. package/dist/middle_layer/pool_columns.js.map +1 -0
  62. package/dist/middle_layer/pool_frame.cjs +82 -0
  63. package/dist/middle_layer/pool_frame.cjs.map +1 -0
  64. package/dist/middle_layer/pool_frame.d.ts +37 -0
  65. package/dist/middle_layer/pool_frame.d.ts.map +1 -0
  66. package/dist/middle_layer/pool_frame.js +81 -0
  67. package/dist/middle_layer/pool_frame.js.map +1 -0
  68. package/dist/middle_layer/pool_table.cjs +66 -0
  69. package/dist/middle_layer/pool_table.cjs.map +1 -0
  70. package/dist/middle_layer/pool_table.d.ts +27 -0
  71. package/dist/middle_layer/pool_table.d.ts.map +1 -0
  72. package/dist/middle_layer/pool_table.js +66 -0
  73. package/dist/middle_layer/pool_table.js.map +1 -0
  74. package/dist/middle_layer/project.cjs +89 -23
  75. package/dist/middle_layer/project.cjs.map +1 -1
  76. package/dist/middle_layer/project.d.ts +70 -4
  77. package/dist/middle_layer/project.d.ts.map +1 -1
  78. package/dist/middle_layer/project.js +89 -22
  79. package/dist/middle_layer/project.js.map +1 -1
  80. package/dist/middle_layer/rich_column_query.cjs +180 -0
  81. package/dist/middle_layer/rich_column_query.cjs.map +1 -0
  82. package/dist/middle_layer/rich_column_query.d.ts +34 -0
  83. package/dist/middle_layer/rich_column_query.d.ts.map +1 -0
  84. package/dist/middle_layer/rich_column_query.js +176 -0
  85. package/dist/middle_layer/rich_column_query.js.map +1 -0
  86. package/dist/model/args.cjs +23 -0
  87. package/dist/model/args.cjs.map +1 -1
  88. package/dist/model/args.js +24 -2
  89. package/dist/model/args.js.map +1 -1
  90. package/dist/model/args_derivation.cjs +60 -2
  91. package/dist/model/args_derivation.cjs.map +1 -1
  92. package/dist/model/args_derivation.d.ts +73 -3
  93. package/dist/model/args_derivation.d.ts.map +1 -1
  94. package/dist/model/args_derivation.js +60 -3
  95. package/dist/model/args_derivation.js.map +1 -1
  96. package/dist/model/block_pack_spec.cjs.map +1 -1
  97. package/dist/model/block_pack_spec.d.ts +3 -3
  98. package/dist/model/block_pack_spec.d.ts.map +1 -1
  99. package/dist/model/block_pack_spec.js.map +1 -1
  100. package/dist/model/block_params_model.cjs +42 -0
  101. package/dist/model/block_params_model.cjs.map +1 -0
  102. package/dist/model/block_params_model.d.ts +45 -0
  103. package/dist/model/block_params_model.d.ts.map +1 -0
  104. package/dist/model/block_params_model.js +42 -0
  105. package/dist/model/block_params_model.js.map +1 -0
  106. package/dist/model/index.d.ts +3 -1
  107. package/dist/model/project_helper.cjs +50 -6
  108. package/dist/model/project_helper.cjs.map +1 -1
  109. package/dist/model/project_helper.d.ts +25 -1
  110. package/dist/model/project_helper.d.ts.map +1 -1
  111. package/dist/model/project_helper.js +51 -7
  112. package/dist/model/project_helper.js.map +1 -1
  113. package/dist/model/template_spec.d.ts +18 -0
  114. package/dist/model/template_spec.d.ts.map +1 -1
  115. package/dist/mutator/block-pack/block_pack.cjs +90 -3
  116. package/dist/mutator/block-pack/block_pack.cjs.map +1 -1
  117. package/dist/mutator/block-pack/block_pack.d.ts +16 -0
  118. package/dist/mutator/block-pack/block_pack.d.ts.map +1 -1
  119. package/dist/mutator/block-pack/block_pack.js +91 -5
  120. package/dist/mutator/block-pack/block_pack.js.map +1 -1
  121. package/dist/mutator/block-pack/required_capabilities.cjs +16 -0
  122. package/dist/mutator/block-pack/required_capabilities.cjs.map +1 -1
  123. package/dist/mutator/block-pack/required_capabilities.js +16 -1
  124. package/dist/mutator/block-pack/required_capabilities.js.map +1 -1
  125. package/dist/mutator/project.cjs +4 -0
  126. package/dist/mutator/project.cjs.map +1 -1
  127. package/dist/mutator/project.d.ts +1 -1
  128. package/dist/mutator/project.d.ts.map +1 -1
  129. package/dist/mutator/project.js +4 -0
  130. package/dist/mutator/project.js.map +1 -1
  131. package/dist/mutator/template/template_cache.cjs +8 -1
  132. package/dist/mutator/template/template_cache.cjs.map +1 -1
  133. package/dist/mutator/template/template_cache.d.ts +7 -3
  134. package/dist/mutator/template/template_cache.d.ts.map +1 -1
  135. package/dist/mutator/template/template_cache.js +8 -1
  136. package/dist/mutator/template/template_cache.js.map +1 -1
  137. package/package.json +9 -9
  138. package/src/block_registry/registry-v2-provider.test.ts +23 -0
  139. package/src/block_registry/registry-v2-provider.ts +11 -1
  140. package/src/index.ts +2 -0
  141. package/src/js_render/bundle_bytecode_cache.ts +15 -4
  142. package/src/js_render/column_registry.ts +24 -3
  143. package/src/js_render/context.ts +4 -3
  144. package/src/js_render/index.ts +3 -2
  145. package/src/js_render/service_injectors.ts +2 -11
  146. package/src/middle_layer/block.ts +61 -2
  147. package/src/middle_layer/block_pack_description.test.ts +235 -0
  148. package/src/middle_layer/block_pack_description.ts +143 -0
  149. package/src/middle_layer/index.ts +9 -1
  150. package/src/middle_layer/legacy_project_holds.test.ts +133 -0
  151. package/src/middle_layer/legacy_project_holds.ts +73 -0
  152. package/src/middle_layer/middle_layer.ts +27 -28
  153. package/src/middle_layer/pool_columns.test.ts +217 -0
  154. package/src/middle_layer/pool_columns.ts +250 -0
  155. package/src/middle_layer/pool_frame.test.ts +144 -0
  156. package/src/middle_layer/pool_frame.ts +127 -0
  157. package/src/middle_layer/pool_table.test.ts +182 -0
  158. package/src/middle_layer/pool_table.ts +98 -0
  159. package/src/middle_layer/project.ts +135 -32
  160. package/src/middle_layer/rich_column_query.test.ts +311 -0
  161. package/src/middle_layer/rich_column_query.ts +214 -0
  162. package/src/model/args.test.ts +23 -1
  163. package/src/model/args.ts +29 -1
  164. package/src/model/args_derivation.test.ts +129 -12
  165. package/src/model/args_derivation.ts +112 -8
  166. package/src/model/block_pack_spec.ts +3 -2
  167. package/src/model/block_params_model.test.ts +194 -0
  168. package/src/model/block_params_model.ts +117 -0
  169. package/src/model/index.ts +6 -0
  170. package/src/model/project_helper.ts +101 -20
  171. package/src/model/template_spec.ts +21 -0
  172. package/src/mutator/block-pack/block_pack.test.ts +10 -1
  173. package/src/mutator/block-pack/block_pack.ts +102 -2
  174. package/src/mutator/block-pack/block_pack_load.test.ts +52 -0
  175. package/src/mutator/block-pack/required_capabilities.ts +25 -0
  176. package/src/mutator/project-v3.test.ts +27 -16
  177. package/src/mutator/project.ts +5 -0
  178. package/src/mutator/template/template_cache.ts +26 -3
  179. package/src/pool/result_pool_markers.test.ts +47 -0
  180. package/src/test/block_packs.ts +12 -0
  181. package/src/test/fake_project.ts +33 -6
@@ -0,0 +1,117 @@
1
+ import type { BlockId } from "@milaboratories/pl-model-common";
2
+ import { ModelAPIVersionMismatchError } from "@milaboratories/pl-errors";
3
+ import type { BlockConfig, ResultOrError } from "@platforma-sdk/model";
4
+ import {
5
+ BLOCK_STORAGE_FACADE_VERSION,
6
+ BlockStorageFacadeCallbacks,
7
+ createBlockStorage,
8
+ isBlockStorage,
9
+ } from "@platforma-sdk/model";
10
+ import type { ProjectHelper } from "./project_helper";
11
+
12
+ /** A block's data with the version of the block's data model it is written in. */
13
+ export type VersionedBlockData = {
14
+ dataVersion: string;
15
+ data: unknown;
16
+ };
17
+
18
+ /**
19
+ * A block's model as functions between its kind's initialization params and its data: the data
20
+ * model's `init(params)`, its inverse `templateParams(data)` and, when the block declares it,
21
+ * `applyParams(data, params)`. Each runs the block's own model code in the VM, each call on its
22
+ * own; no block is created and nothing is read from or written to the project.
23
+ */
24
+ export interface BlockParamsModel {
25
+ /**
26
+ * Whether the model has both functions. A model built before blocks gave params has neither
27
+ * callback; its calls answer with an error.
28
+ */
29
+ readonly givesParams: boolean;
30
+
31
+ /**
32
+ * `templateParams(data)`: the params the block's model derives from `data`. The data is not
33
+ * migrated first (the SDK does not), so it should be in the version {@link dataOf} produces.
34
+ */
35
+ paramsOf(data: VersionedBlockData): ResultOrError<unknown>;
36
+
37
+ /**
38
+ * `init(params)`: the data the block's model builds from `params`, after the kind's parser has
39
+ * accepted them, with the version of the data model it is in. References in `params` are taken
40
+ * as they are: they name blocks of this project.
41
+ */
42
+ dataOf(params: unknown): ResultOrError<VersionedBlockData>;
43
+
44
+ /**
45
+ * Whether the block declares `applyParams`, putting its params onto live data
46
+ * itself. For such a block {@link dataOf} is `applyParams(defaults, params)`.
47
+ */
48
+ readonly appliesParams: boolean;
49
+
50
+ /**
51
+ * `applyParams(data, params)`: `data` with `params` put onto it by the block's own model, after
52
+ * the kind's parser has accepted them, with the version of the data model it is in. The model
53
+ * refuses data at another version than its current one, the version {@link dataOf} produces.
54
+ * A model that does not apply params ({@link appliesParams} false) answers with an error.
55
+ */
56
+ applyParams(data: VersionedBlockData, params: unknown): ResultOrError<VersionedBlockData>;
57
+ }
58
+
59
+ /** No template entries: live params already name the blocks of the project. */
60
+ const NO_BLOCK_IDS: ReadonlyMap<string, string> = new Map();
61
+
62
+ /**
63
+ * The {@link BlockParamsModel} of block `blockId` with model `config`.
64
+ *
65
+ * @throws {ModelAPIVersionMismatchError} when the block is not on BlockModelV3: such a model has
66
+ * no storage facade and no params
67
+ */
68
+ export function blockParamsModel(
69
+ helper: ProjectHelper,
70
+ blockId: BlockId,
71
+ config: BlockConfig,
72
+ ): BlockParamsModel {
73
+ if (config.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION)
74
+ throw new ModelAPIVersionMismatchError(
75
+ blockId,
76
+ BLOCK_STORAGE_FACADE_VERSION,
77
+ config.modelAPIVersion,
78
+ );
79
+ const callbacks = config.blockLifecycleCallbacks;
80
+ return {
81
+ givesParams:
82
+ callbacks[BlockStorageFacadeCallbacks.InitializationParamsDerive] !== undefined &&
83
+ callbacks[BlockStorageFacadeCallbacks.StorageInitialFromParams] !== undefined,
84
+
85
+ paramsOf: ({ dataVersion, data }) =>
86
+ helper.deriveTemplateParamsFromStorage(
87
+ config,
88
+ JSON.stringify(createBlockStorage(data, dataVersion)),
89
+ ),
90
+
91
+ dataOf: (params) => {
92
+ const storage = helper.getInitialStorageFromParamsInVM(config, params, NO_BLOCK_IDS);
93
+ if (storage.error !== undefined) return storage;
94
+ return parseVersionedData(storage.value);
95
+ },
96
+
97
+ appliesParams: callbacks[BlockStorageFacadeCallbacks.StorageApplyParams] !== undefined,
98
+
99
+ applyParams: ({ dataVersion, data }, params) => {
100
+ const storage = helper.applyParamsInVM(
101
+ config,
102
+ JSON.stringify(createBlockStorage(data, dataVersion)),
103
+ params,
104
+ );
105
+ if (storage.error !== undefined) return storage;
106
+ return parseVersionedData(storage.value);
107
+ },
108
+ };
109
+ }
110
+
111
+ /** The data and its version out of a block storage the model built, as JSON text. */
112
+ function parseVersionedData(storageJson: string): ResultOrError<VersionedBlockData> {
113
+ const storage: unknown = JSON.parse(storageJson);
114
+ if (!isBlockStorage(storage) || typeof storage.__dataVersion !== "string")
115
+ return { error: new Error("The block's model built its data in an unknown storage format") };
116
+ return { value: { dataVersion: storage.__dataVersion, data: storage.__data } };
117
+ }
@@ -1,5 +1,11 @@
1
1
  export * from "./block_pack_spec";
2
+ export type {
3
+ BlockReadiness,
4
+ DerivedPrerunArgsSummary,
5
+ MissingBlockReference,
6
+ } from "./args_derivation";
2
7
  export { type ProjectId, type ProjectListEntry, type ProjectField } from "./project_model";
8
+ export type { BlockParamsModel, VersionedBlockData } from "./block_params_model";
3
9
 
4
10
  export {
5
11
  ProjectMetaKey,
@@ -13,7 +13,12 @@ import { executeSingleLambda } from "../js_render";
13
13
  import type { SignedResourceId } from "@milaboratories/pl-client";
14
14
  import { ConsoleLoggerAdapter, type MiLogger } from "@milaboratories/ts-helpers";
15
15
  import { getDebugFlags } from "../debug";
16
- import { parseArgsDeriveResult, type DerivedArgs } from "./args_derivation";
16
+ import {
17
+ parseArgsDeriveResult,
18
+ parsePrerunArgsDeriveResult,
19
+ type DerivedArgs,
20
+ type DerivedPrerunArgs,
21
+ } from "./args_derivation";
17
22
 
18
23
  type EnrichmentTargetsRequest = {
19
24
  blockConfig: () => BlockConfig;
@@ -37,14 +42,13 @@ export type MigrationResult =
37
42
 
38
43
  /**
39
44
  * Result of a derivation from storage that either produced a value or failed.
40
- * Returned by the __pl_prerunArgs_derive and __pl_initializationParams_derive VM callbacks; a
41
- * newer model adds the issues found in the prerun args, which are not read here.
45
+ * Returned by the __pl_initializationParams_derive VM callback.
42
46
  */
43
47
  type DeriveResult = { error: string } | { error?: undefined; value: unknown };
44
48
 
45
49
  /**
46
- * Result of building initial storage from params.
47
- * Returned by the __pl_storage_initialFromParams VM callback.
50
+ * Result of building storage from params.
51
+ * Returned by the __pl_storage_initialFromParams and __pl_storage_applyParams VM callbacks.
48
52
  */
49
53
  type ParamsStorageResult =
50
54
  | { error: string }
@@ -135,23 +139,44 @@ export class ProjectHelper {
135
139
  if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {
136
140
  throw new Error("derivePrerunArgsFromStorage is only supported for model API version 2");
137
141
  }
142
+ const derived = this.derivePrerunArgsDetailedFromStorage(blockConfig, storageJson);
143
+ // Anything but staged args skips the block in staging.
144
+ return derived.type === "staged" ? derived.args : undefined;
145
+ }
138
146
 
139
- try {
140
- const result = executeSingleLambda(
141
- this.quickJs,
142
- blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.PrerunArgsDerive],
143
- extractCodeWithInfo(blockConfig),
144
- storageJson,
145
- ) as DeriveResult;
147
+ /**
148
+ * {@link derivePrerunArgsFromStorage} with the reason when there are no prerun args to stage:
149
+ * the issues found in them, the error of a lambda that threw, or a `prerunArgs()` that returned
150
+ * nothing. Never throws; a failure of the derivation itself is `failed`.
151
+ *
152
+ * @param blockConfig The block configuration (provides the model code)
153
+ * @param storageJson Storage as JSON string
154
+ */
155
+ public derivePrerunArgsDetailedFromStorage(
156
+ blockConfig: BlockConfig,
157
+ storageJson: string,
158
+ ): DerivedPrerunArgs {
159
+ if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {
160
+ return {
161
+ type: "failed",
162
+ error: "Prerun args derivation from storage is only supported for model API version 2",
163
+ };
164
+ }
146
165
 
147
- if (result.error !== undefined) {
148
- // Return undefined if derivation fails (skip block in staging)
149
- return undefined;
150
- }
151
- return result.value;
152
- } catch {
153
- // Return undefined if derivation fails (skip block in staging)
154
- return undefined;
166
+ try {
167
+ return parsePrerunArgsDeriveResult(
168
+ executeSingleLambda(
169
+ this.quickJs,
170
+ blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.PrerunArgsDerive],
171
+ extractCodeWithInfo(blockConfig),
172
+ storageJson,
173
+ ),
174
+ );
175
+ } catch (e) {
176
+ return {
177
+ type: "failed",
178
+ error: `Prerun args derivation from storage failed: ${ensureError(e).message}`,
179
+ };
155
180
  }
156
181
  }
157
182
 
@@ -458,6 +483,62 @@ export class ProjectHelper {
458
483
  }
459
484
  }
460
485
 
486
+ /**
487
+ * Puts params onto a block's live data with the block's own `applyParams`, through the VM
488
+ * callback `__pl_storage_applyParams`. Nothing is written: the storage comes back as JSON.
489
+ *
490
+ * The callback runs the kind's params check first, as
491
+ * {@link getInitialStorageFromParamsInVM} does, and refuses data that is not at the data
492
+ * model's current version. Params are live: their references name blocks of this project and
493
+ * are not relocated.
494
+ *
495
+ * @param blockConfig The block configuration (provides the model code)
496
+ * @param storageJson The block's current storage as JSON string
497
+ * @param params The new params, whole
498
+ * @returns The storage with the params applied as JSON string, or why there is none
499
+ */
500
+ public applyParamsInVM(
501
+ blockConfig: BlockConfig,
502
+ storageJson: string,
503
+ params: unknown,
504
+ ): ResultOrError<string> {
505
+ if (blockConfig.modelAPIVersion !== BLOCK_STORAGE_FACADE_VERSION) {
506
+ return {
507
+ error: new Error("applyParamsInVM is only supported for model API version 2"),
508
+ };
509
+ }
510
+
511
+ // Registered only by a block that declares `applyParams`; anything else builds data
512
+ // from params with `init` instead, which is the caller's call to make.
513
+ const callback =
514
+ blockConfig.blockLifecycleCallbacks[BlockStorageFacadeCallbacks.StorageApplyParams];
515
+ if (callback === undefined) {
516
+ return {
517
+ error: new Error("This version of the block does not put params onto its data itself."),
518
+ };
519
+ }
520
+
521
+ try {
522
+ const result = executeSingleLambda(
523
+ this.quickJs,
524
+ callback,
525
+ extractCodeWithInfo(blockConfig),
526
+ storageJson,
527
+ JSON.stringify(params ?? {}),
528
+ ) as ParamsStorageResult;
529
+
530
+ if (result.error !== undefined) return { error: new Error(result.error) };
531
+ return { value: result.storageJson };
532
+ } catch (e) {
533
+ const cause = ensureError(e);
534
+ return {
535
+ error: new Error(`Applying params to the block's data failed: ${cause.message}`, {
536
+ cause,
537
+ }),
538
+ };
539
+ }
540
+ }
541
+
461
542
  /**
462
543
  * Applies a state update using VM-based transformation.
463
544
  * This calls the model's `__pl_storage_applyUpdate` callback which:
@@ -10,6 +10,8 @@ export interface TemplateFromRegistry {
10
10
  export interface ExplicitTemplate {
11
11
  readonly type: "explicit";
12
12
  content: Uint8Array;
13
+ /** The pack file `content` was read from, for local dev blocks. */
14
+ localPath?: string;
13
15
  }
14
16
 
15
17
  export interface PreparedTemplate {
@@ -17,6 +19,25 @@ export interface PreparedTemplate {
17
19
  data: TemplateData | CompiledTemplateV3;
18
20
  }
19
21
 
22
+ /** A registry pack not yet downloaded: it is fetched from `url` when installed. */
23
+ export interface RegistryPackTemplate {
24
+ readonly type: "registry-pack";
25
+ url: string;
26
+ /** Lowercase hex sha256 of the gzipped pack, from the registry manifest. */
27
+ sha256: string;
28
+ }
29
+
30
+ /** A local dev pack: it is read from `path` when installed. */
31
+ export interface LocalPackTemplate {
32
+ readonly type: "local-pack";
33
+ path: string;
34
+ /** Lowercase hex sha256 of the gzipped pack file. */
35
+ sha256: string;
36
+ }
37
+
38
+ /** A pack not yet loaded: `cacheBlockPackTemplate` installs it. */
39
+ export type InstallablePackTemplate = RegistryPackTemplate | LocalPackTemplate;
40
+
20
41
  export interface CachedTemplate {
21
42
  readonly type: "cached";
22
43
  readonly resourceId: SignedResourceId;
@@ -10,6 +10,7 @@ import path from "node:path";
10
10
  import { expect, test } from "vitest";
11
11
  import { V2RegistryProvider } from "../../block_registry/registry-v2-provider";
12
12
  import { BlockPackSpecAny } from "../../model";
13
+ import { cacheBlockPackTemplate } from "../template/template_cache";
13
14
  import { BlockPackPreparer, createBlockPack } from "./block_pack";
14
15
 
15
16
  const preparation = new BlockPackPreparer(
@@ -29,6 +30,13 @@ test.each([
29
30
  },
30
31
  } as BlockPackSpecAny,
31
32
  },
33
+ {
34
+ spec: {
35
+ type: "from-registry-v2",
36
+ registryUrl: "https://blocks.pl-open.science",
37
+ id: { organization: "milaboratories", name: "gpu-test", version: "0.9.0" },
38
+ } as BlockPackSpecAny,
39
+ },
32
40
  {
33
41
  spec: {
34
42
  type: "dev-v1",
@@ -43,11 +51,12 @@ test.each([
43
51
  const specPrepared = await preparation.prepare(spec);
44
52
 
45
53
  await TestHelpers.withTempRoot(async (pl) => {
54
+ const cachedBp = await cacheBlockPackTemplate(pl, specPrepared, { preparer: preparation });
46
55
  const f0 = { resourceId: pl.clientRoot, fieldName: "test0" };
47
56
 
48
57
  const bp = await pl.withWriteTx("test", async (tx) => {
49
58
  tx.createField(f0, "Dynamic");
50
- const bp = createBlockPack(tx, specPrepared);
59
+ const bp = createBlockPack(tx, cachedBp);
51
60
  tx.setField(f0, bp);
52
61
  await tx.commit();
53
62
  return await toGlobalResourceId(bp);
@@ -3,9 +3,10 @@ import { field } from "@milaboratories/pl-client";
3
3
  import { loadTemplate } from "../template/template_loading";
4
4
  import type { BlockPackExplicit, BlockPackSpecAny, BlockPackSpecPrepared } from "../../model";
5
5
  import type { Signer } from "@milaboratories/ts-helpers";
6
- import { assertNever } from "@milaboratories/ts-helpers";
6
+ import { assertNever, notEmpty } from "@milaboratories/ts-helpers";
7
7
  import type { Branded } from "@milaboratories/pl-model-common";
8
8
  import fs from "node:fs";
9
+ import { createHash } from "node:crypto";
9
10
  import { fileURLToPath } from "node:url";
10
11
  import type { Dispatcher } from "undici";
11
12
  import { request } from "undici";
@@ -19,12 +20,13 @@ import {
19
20
  RegistryV1,
20
21
  } from "@platforma-sdk/block-tools";
21
22
  import type { BlockPackInfo } from "../../model/block_pack";
23
+ import type { InstallablePackTemplate, PreparedTemplate } from "../../model/template_spec";
22
24
  import { resolveDevPacket } from "../../dev_env";
23
25
  import { getDevV2PacketMtime, getFromPackV2Mtime } from "../../block_registry";
24
26
  import type { V2RegistryProvider } from "../../block_registry/registry-v2-provider";
25
27
  import { LRUCache } from "lru-cache";
26
28
  import canonicalize from "canonicalize";
27
- import type { BlockPackSpec } from "@milaboratories/pl-model-middle-layer";
29
+ import type { BlockPackFromRegistryV2, BlockPackSpec } from "@milaboratories/pl-model-middle-layer";
28
30
  import { WorkerManager } from "../../worker/WorkerManager";
29
31
  import { z } from "zod";
30
32
 
@@ -75,6 +77,9 @@ export class BlockPackPreparer {
75
77
  sizeCalculation: (value) => value.byteLength,
76
78
  });
77
79
 
80
+ /** Parsed packs by sha256, so adding a block again does not parse its workflow again. */
81
+ private readonly loadedPackCache = new LRUCache<string, LoadedPack>({ max: 50 });
82
+
78
83
  /** Cache of prepared block packs for registry specs (immutable by version). */
79
84
  private readonly preparedCache = new LRUCache<PreparedCacheKey, BlockPackSpecPrepared>({
80
85
  max: 50,
@@ -156,8 +161,24 @@ export class BlockPackPreparer {
156
161
  if (cached) return cached;
157
162
  }
158
163
 
164
+ const registryPack =
165
+ spec.type === "from-registry-v2" ? await this.prepareRegistryPack(spec) : undefined;
166
+ if (registryPack !== undefined) {
167
+ if (key) this.preparedCache.set(key, registryPack);
168
+ return registryPack;
169
+ }
170
+
159
171
  const explicit = await this.prepareWithoutUnpacking(spec);
160
172
 
173
+ // Local dev packs are parsed when installed, which also checks their required capabilities.
174
+ const { localPath, content } = explicit.template;
175
+ if (localPath !== undefined)
176
+ return {
177
+ ...explicit,
178
+ type: "prepared",
179
+ template: { type: "local-pack", path: localPath, sha256: packSha256(content) },
180
+ };
181
+
161
182
  await using workerManager = new WorkerManager();
162
183
 
163
184
  const parsed = await workerManager.process("parseTemplate", explicit.template.content);
@@ -179,6 +200,73 @@ export class BlockPackPreparer {
179
200
  return result;
180
201
  }
181
202
 
203
+ /**
204
+ * Prepares a v2 registry block from its manifest alone, without downloading the workflow.
205
+ * Undefined when the manifest does not list the workflow pack's sha256.
206
+ */
207
+ private async prepareRegistryPack(
208
+ spec: BlockPackFromRegistryV2,
209
+ ): Promise<BlockPackSpecPrepared | undefined> {
210
+ const registry = this.v2RegistryProvider.getRegistry(spec.registryUrl);
211
+ const [manifest, components] = await Promise.all([
212
+ registry.getManifest(spec.id),
213
+ registry.getComponents(spec.id),
214
+ ]);
215
+ const workflowPath = manifest.description.components.workflow.main.path;
216
+ const workflowFile = manifest.files.find((f) => f.name === workflowPath);
217
+ if (workflowFile === undefined) return undefined;
218
+
219
+ return {
220
+ type: "prepared",
221
+ template: {
222
+ type: "registry-pack",
223
+ url: components.workflow.main.url,
224
+ sha256: workflowFile.sha256.toLowerCase(),
225
+ },
226
+ config: parseBufferConfig(await this.remoteContentCache.forceFetch(components.model.url)),
227
+ frontend: { type: "url", url: components.ui.url },
228
+ source: spec,
229
+ requiredCapabilities: manifest.description.meta.requiredCapabilities,
230
+ };
231
+ }
232
+
233
+ /** Downloads or reads a pack, checks its sha256 and parses it. */
234
+ public async loadPack(template: InstallablePackTemplate): Promise<LoadedPack> {
235
+ let content: Uint8Array | undefined;
236
+ if (template.type === "local-pack") {
237
+ // A rebuild after prepare would pair this config with another build's workflow.
238
+ content = await fs.promises.readFile(template.path);
239
+ if (packSha256(content) !== template.sha256)
240
+ throw new Error(
241
+ `workflow pack ${template.path} changed after the block was prepared; add the block again`,
242
+ );
243
+ }
244
+
245
+ const cached = this.loadedPackCache.get(template.sha256);
246
+ if (cached !== undefined) return cached;
247
+
248
+ if (content === undefined && template.type === "registry-pack") {
249
+ content = new Uint8Array(await this.remoteContentCache.forceFetch(template.url));
250
+ const sha256 = packSha256(content);
251
+ if (sha256 !== template.sha256) {
252
+ // Do not keep a broken download for the next attempt.
253
+ this.remoteContentCache.delete(template.url);
254
+ throw new Error(
255
+ `workflow pack ${template.url} has sha256 ${sha256}, expected ${template.sha256}`,
256
+ );
257
+ }
258
+ }
259
+
260
+ await using workerManager = new WorkerManager();
261
+ const parsed = await workerManager.process("parseTemplate", notEmpty(content));
262
+ const loaded: LoadedPack = {
263
+ template: { type: "prepared", data: parsed },
264
+ requiredCapabilities: requiredCapabilitiesFromTemplate(parsed),
265
+ };
266
+ this.loadedPackCache.set(template.sha256, loaded);
267
+ return loaded;
268
+ }
269
+
182
270
  private async prepareWithoutUnpacking(
183
271
  spec: BlockPackExplicit | BlockPackSpec,
184
272
  ): Promise<BlockPackExplicit> {
@@ -234,6 +322,7 @@ export class BlockPackPreparer {
234
322
  template: {
235
323
  type: "explicit",
236
324
  content: workflowContent,
325
+ localPath: description.components.workflow.main.file,
237
326
  },
238
327
  config,
239
328
  frontend: {
@@ -276,6 +365,7 @@ export class BlockPackPreparer {
276
365
  template: {
277
366
  type: "explicit",
278
367
  content: workflowContent,
368
+ localPath: description.components.workflow.main.file,
279
369
  },
280
370
  config,
281
371
  frontend: {
@@ -349,7 +439,17 @@ export class BlockPackPreparer {
349
439
  }
350
440
  }
351
441
 
442
+ /** A pack parsed on the client, with the capabilities it declares. */
443
+ type LoadedPack = { template: PreparedTemplate; requiredCapabilities?: string[] };
444
+
445
+ /** Lowercase hex sha256 of a gzipped workflow pack, the key the backend installs it by. */
446
+ export function packSha256(content: Uint8Array): string {
447
+ return createHash("sha256").update(content).digest("hex");
448
+ }
449
+
352
450
  function createCustomBlockPack(tx: PlTransaction, spec: BlockPackSpecPrepared): AnyResourceRef {
451
+ if (spec.template.type === "registry-pack" || spec.template.type === "local-pack")
452
+ throw new Error("BUG: a pack must be installed by cacheBlockPackTemplate first");
353
453
  const blockPackInfo: BlockPackInfo = { config: spec.config, source: spec.source };
354
454
  const bp = tx.createStruct(BlockPackCustomType, JSON.stringify(blockPackInfo));
355
455
  tx.createField(field(bp, BlockPackTemplateField), "Input", loadTemplate(tx, spec.template));
@@ -0,0 +1,52 @@
1
+ import { defaultHttpDispatcher } from "@milaboratories/pl-http";
2
+ import { HmacSha256Signer } from "@milaboratories/ts-helpers";
3
+ import fs from "node:fs/promises";
4
+ import http from "node:http";
5
+ import type { AddressInfo } from "node:net";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { expect, test } from "vitest";
9
+ import { V2RegistryProvider } from "../../block_registry/registry-v2-provider";
10
+ import { BlockPackPreparer, packSha256 } from "./block_pack";
11
+
12
+ const newPreparer = () =>
13
+ new BlockPackPreparer(
14
+ new V2RegistryProvider(defaultHttpDispatcher()),
15
+ new HmacSha256Signer(HmacSha256Signer.generateSecret()),
16
+ );
17
+
18
+ test("loadPack drops a download with the wrong sha256, so the next attempt fetches again", async () => {
19
+ let requests = 0;
20
+ const server = http.createServer((_req, res) => {
21
+ requests++;
22
+ res.end("not the pack");
23
+ });
24
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
25
+ try {
26
+ const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/main.plj.gz`;
27
+ const preparer = newPreparer();
28
+ const template = { type: "registry-pack" as const, url, sha256: "0".repeat(64) };
29
+
30
+ await expect(preparer.loadPack(template)).rejects.toThrow(/expected 0{64}/);
31
+ await expect(preparer.loadPack(template)).rejects.toThrow(/expected 0{64}/);
32
+ expect(requests).toBe(2);
33
+ } finally {
34
+ server.close();
35
+ }
36
+ });
37
+
38
+ test("loadPack refuses a local pack rebuilt after prepare", async () => {
39
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "pack-"));
40
+ try {
41
+ const packPath = path.join(dir, "main.plj.gz");
42
+ await fs.writeFile(packPath, "build 1");
43
+ const sha256 = packSha256(new TextEncoder().encode("build 1"));
44
+ await fs.writeFile(packPath, "build 2");
45
+
46
+ await expect(
47
+ newPreparer().loadPack({ type: "local-pack", path: packPath, sha256 }),
48
+ ).rejects.toThrow(/changed after the block was prepared/);
49
+ } finally {
50
+ await fs.rm(dir, { recursive: true, force: true });
51
+ }
52
+ });
@@ -1,5 +1,6 @@
1
1
  import { gunzipSync } from "node:zlib";
2
2
  import type { CompiledTemplateV3, TemplateData } from "@milaboratories/pl-model-backend";
3
+ import type { PlClient } from "@milaboratories/pl-client";
3
4
 
4
5
  /**
5
6
  * Reads the capability tokens a template declares it requires via
@@ -42,3 +43,27 @@ export function deriveRequiredCapabilities(
42
43
  }
43
44
  return requiredCapabilitiesFromTemplate(parsed as TemplateData | CompiledTemplateV3);
44
45
  }
46
+
47
+ /** Throws when the connected backend doesn't advertise every capability the
48
+ * block-pack requires (as declared in `meta.requiredCapabilities`).
49
+ *
50
+ * The matching set is the desktop's install gate moved server-side so both
51
+ * the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's
52
+ * `add_block` tool, programmatic block installs, tests) reject incompatible
53
+ * blocks consistently. */
54
+ export function throwIfMissingServerCapabilities(
55
+ pl: PlClient,
56
+ requiredCapabilities: readonly string[] | undefined,
57
+ ): void {
58
+ if (!requiredCapabilities || requiredCapabilities.length === 0) return;
59
+ const advertised = (pl.serverInfo.capabilities ?? []) as readonly string[];
60
+ const filterFn = (c: string) => !advertised.includes(c);
61
+ if (!requiredCapabilities.some(filterFn)) return;
62
+ const missing = requiredCapabilities.filter(filterFn);
63
+ throw new Error(
64
+ `Block cannot be added: connected backend does not advertise capabilities ` +
65
+ `${JSON.stringify(missing)}. ` +
66
+ `Backend advertises ${JSON.stringify(advertised)}. ` +
67
+ `Upgrade the backend or remove the requirement from the block manifest.`,
68
+ );
69
+ }