@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,182 @@
1
+ import {
2
+ createColumnDiscoveredId,
3
+ createGlobalPObjectId,
4
+ type ColumnUniversalId,
5
+ type PColumnSpec,
6
+ type PTableDefV2,
7
+ type PTableHandle,
8
+ } from "@milaboratories/pl-model-common";
9
+ import { describe, expect, test } from "vitest";
10
+ import { FakeProject, type Columns } from "../test/fake_project";
11
+ import { poolTable, type PoolTableEnv } from "./pool_table";
12
+
13
+ const SPEC: PColumnSpec = {
14
+ kind: "PColumn",
15
+ name: "pl7.app/test/value",
16
+ valueType: "Int",
17
+ axesSpec: [{ name: "sample", type: "String" }],
18
+ };
19
+
20
+ const HANDLE = "a".repeat(64) as PTableHandle;
21
+
22
+ /** A driver that records what it is asked to build and counts the references it gives back. */
23
+ function fakeEnv() {
24
+ const built: string[][] = [];
25
+ const counts = { refs: 0 };
26
+ const env: PoolTableEnv = {
27
+ driverKit: {
28
+ pFrameDriver: {
29
+ createPTableV2: (def) => {
30
+ const ids: string[] = [];
31
+ const visit = (q: unknown): void => {
32
+ if (typeof q !== "object" || q === null) return;
33
+ if ("type" in q && q.type === "column" && "column" in q) {
34
+ const column = q.column;
35
+ if (typeof column === "object" && column !== null && "id" in column)
36
+ ids.push(String(column.id));
37
+ return;
38
+ }
39
+ for (const v of Object.values(q)) visit(v);
40
+ };
41
+ visit(def.query);
42
+ built.push(ids);
43
+ counts.refs++;
44
+ const unref = () => void counts.refs--;
45
+ return { key: HANDLE, resource: {}, unref, [Symbol.dispose]: unref };
46
+ },
47
+ },
48
+ },
49
+ };
50
+ return { env, built, counts };
51
+ }
52
+
53
+ /** A project of two blocks that export one column each, `a` and `b`, as `columns` say. */
54
+ function project(a: Columns[string], b: Columns[string]) {
55
+ const prj = new FakeProject();
56
+ prj.block("one", {
57
+ prodCtx: prj.value("BContext", {}),
58
+ prodUiCtx: prj.frame({ value: a }),
59
+ });
60
+ prj.block("two", {
61
+ prodCtx: prj.value("BContext", {}),
62
+ prodUiCtx: prj.frame({ value: b }),
63
+ });
64
+ return prj;
65
+ }
66
+
67
+ const A = createGlobalPObjectId("one", "value");
68
+ const B = createGlobalPObjectId("two", "value");
69
+
70
+ function join(...ids: ColumnUniversalId[]): PTableDefV2<ColumnUniversalId> {
71
+ return {
72
+ query: {
73
+ type: "innerJoin",
74
+ entries: ids.map((column) => ({ entry: { type: "column", column } })),
75
+ },
76
+ };
77
+ }
78
+
79
+ describe("poolTable", () => {
80
+ test("builds a table over columns of two blocks and releases it on reset", async () => {
81
+ const prj = project({ spec: SPEC, cells: ["1"] }, { spec: SPEC, cells: ["2"] });
82
+ const { env, built, counts } = fakeEnv();
83
+ const table = poolTable(prj.tree().entry(), join(A, B), env);
84
+
85
+ expect(await table.getValue()).toEqual({ type: "ok", handle: HANDLE });
86
+ expect(built).toEqual([[A, B]]);
87
+ expect(counts.refs).toBe(1);
88
+ expect(table.isChanged()).toBe(false);
89
+
90
+ table.resetState();
91
+ expect(counts.refs).toBe(0);
92
+ });
93
+
94
+ test("refuses unknown columns and columns without ready data, building nothing", async () => {
95
+ const prj = project(
96
+ { spec: SPEC, cells: ["1"], data: "notReady" },
97
+ { spec: SPEC, cells: ["2"], data: "missing" },
98
+ );
99
+ const { env, built, counts } = fakeEnv();
100
+ const unknown = createGlobalPObjectId("three", "value");
101
+ const table = poolTable(prj.tree().entry(), join(A, B, unknown), env);
102
+
103
+ expect(await table.getValue()).toEqual({
104
+ type: "refused",
105
+ refused: [
106
+ { columnId: A, issue: "notReady" },
107
+ { columnId: B, issue: "noData" },
108
+ { columnId: unknown, issue: "unknown" },
109
+ ],
110
+ });
111
+ expect(built).toEqual([]);
112
+ expect(counts.refs).toBe(0);
113
+ });
114
+
115
+ test("refuses a column whose data is an error", async () => {
116
+ const prj = project({ spec: SPEC, cells: ["1"] }, { spec: SPEC, cells: ["2"], data: "failed" });
117
+ const { env, built } = fakeEnv();
118
+ const value = await poolTable(prj.tree().entry(), join(A, B), env).getValue();
119
+
120
+ expect(value).toMatchObject({
121
+ type: "refused",
122
+ refused: [{ columnId: B, issue: "failed", message: expect.stringContaining("boom") }],
123
+ });
124
+ expect(built).toEqual([]);
125
+ });
126
+
127
+ test("a discovered id builds through its linker when both are ready", async () => {
128
+ const prj = project({ spec: SPEC, cells: ["1"] }, { spec: SPEC, cells: ["2"] });
129
+ const { env, built } = fakeEnv();
130
+ const discovered = createColumnDiscoveredId({
131
+ column: A,
132
+ path: [{ type: "linker", column: B }],
133
+ });
134
+ const table = poolTable(prj.tree().entry(), join(discovered), env);
135
+
136
+ expect(await table.getValue()).toEqual({ type: "ok", handle: HANDLE });
137
+ // The linker join the id stands for: the linker, then the leaf named by the whole id.
138
+ expect(built).toEqual([[B, discovered]]);
139
+ table.resetState();
140
+ });
141
+
142
+ test("a discovered id is refused by the readiness of its leaf, naming the whole id", async () => {
143
+ const prj = project(
144
+ { spec: SPEC, cells: ["1"], data: "notReady" },
145
+ { spec: SPEC, cells: ["2"] },
146
+ );
147
+ const { env, built } = fakeEnv();
148
+ const discovered = createColumnDiscoveredId({ column: A });
149
+ const value = await poolTable(prj.tree().entry(), join(discovered), env).getValue();
150
+
151
+ expect(value).toEqual({
152
+ type: "refused",
153
+ refused: [{ columnId: discovered, issue: "notReady" }],
154
+ });
155
+ expect(built).toEqual([]);
156
+ });
157
+
158
+ test("a linker a discovered id reads must be ready too", async () => {
159
+ const prj = project(
160
+ { spec: SPEC, cells: ["1"] },
161
+ { spec: SPEC, cells: ["2"], data: "missing" },
162
+ );
163
+ const { env, built } = fakeEnv();
164
+ const discovered = createColumnDiscoveredId({
165
+ column: A,
166
+ path: [{ type: "linker", column: B }],
167
+ });
168
+ const value = await poolTable(prj.tree().entry(), join(discovered), env).getValue();
169
+
170
+ expect(value).toEqual({ type: "refused", refused: [{ columnId: B, issue: "noData" }] });
171
+ expect(built).toEqual([]);
172
+ });
173
+
174
+ test("an empty project has no columns", async () => {
175
+ const prj = new FakeProject();
176
+ const { env } = fakeEnv();
177
+ expect(await poolTable(prj.tree().entry(), join(A), env).getValue()).toEqual({
178
+ type: "refused",
179
+ refused: [{ columnId: A, issue: "unknown" }],
180
+ });
181
+ });
182
+ });
@@ -0,0 +1,98 @@
1
+ import { Computable } from "@milaboratories/computable";
2
+ import type { PlTreeEntry } from "@milaboratories/pl-tree";
3
+ import {
4
+ collectSpecQueryColumns,
5
+ isPColumnSpec,
6
+ mapPTableDefV2,
7
+ PoolEntryGuard,
8
+ type ColumnUniversalId,
9
+ type PObjectId,
10
+ type PTableDefV2,
11
+ type PTableHandle,
12
+ } from "@milaboratories/pl-model-common";
13
+ import {
14
+ buildColumnRegistry,
15
+ resolveColumnSpec,
16
+ resolvePColumnById,
17
+ } from "../js_render/column_registry";
18
+ import { collapseSpecOverrideNode } from "../js_render/spec_override_collapse";
19
+ import type { InternalPFrameDriver } from "../pool/driver";
20
+ import { poolView } from "./pool_columns";
21
+ import { poolColumnProblem, type PoolColumnIssue } from "./pool_frame";
22
+ import { richColumnReferences, richTableDef } from "./rich_column_query";
23
+
24
+ /** Why {@link poolTable} refused a column (see {@link PoolColumnIssue}). */
25
+ export type PoolTableIssue = PoolColumnIssue;
26
+
27
+ /** A column {@link poolTable} refused, and why. */
28
+ export interface PoolTableRefusal {
29
+ /** The id the table names the column by, or the id of a linker column it reads. */
30
+ readonly columnId: ColumnUniversalId;
31
+ readonly issue: PoolTableIssue;
32
+ /** The error of a `failed` column. */
33
+ readonly message?: string;
34
+ }
35
+
36
+ /**
37
+ * What {@link poolTable} computes: the handle of the table, or, with nothing built, the columns
38
+ * it refused.
39
+ */
40
+ export type PoolTable =
41
+ | { readonly type: "ok"; readonly handle: PTableHandle }
42
+ | { readonly type: "refused"; readonly refused: readonly PoolTableRefusal[] };
43
+
44
+ /** What {@link poolTable} uses besides the project tree: the driver that builds the table. */
45
+ export type PoolTableEnv = {
46
+ readonly driverKit: { readonly pFrameDriver: Pick<InternalPFrameDriver, "createPTableV2"> };
47
+ };
48
+
49
+ /**
50
+ * A table over columns of a project's result pool, built by the PFrame driver from `def`, whose
51
+ * columns are pool column ids (those {@link poolColumns} lists, discovered, filtered and
52
+ * overridden ids included): what a block's model gets from `createPTableV2` over the same
53
+ * columns, with no block involved. Each column of a join entry is built into the query its id
54
+ * stands for, with the qualifications of a discovered column, by {@link richTableDef}.
55
+ *
56
+ * Every column must be ready, and so must each linker column a discovered id reads; readiness is
57
+ * that of the exported column an id comes down to. An unknown column, or one whose data is
58
+ * missing, still being calculated or failed, is refused and nothing is built, where a block's
59
+ * model would get an empty column instead.
60
+ *
61
+ * The table is made when the value is first asked for and lives as long as the computable's state:
62
+ * `resetState()` releases it. Ask for the value once. Asking again after the project changed
63
+ * builds a new table and releases the first; {@link Computable.isChanged} tells whether that
64
+ * would happen, i.e. whether what the table was built from may have changed (any change of the
65
+ * project's structure counts too).
66
+ */
67
+ export function poolTable(
68
+ prjEntry: PlTreeEntry,
69
+ def: PTableDefV2<ColumnUniversalId>,
70
+ env: PoolTableEnv,
71
+ ): Computable<PoolTable> {
72
+ return Computable.make((ctx): PoolTable => {
73
+ const registry = buildColumnRegistry({
74
+ upstreamBlockCtxes: poolView(ctx, prjEntry, undefined) ?? [],
75
+ });
76
+ const ids = [...new Set(collectSpecQueryColumns(def.query).flatMap(richColumnReferences))];
77
+ const refused = ids.flatMap((columnId): PoolTableRefusal[] => {
78
+ const problem = poolColumnProblem(registry, columnId);
79
+ return problem === undefined ? [] : [{ columnId, ...problem }];
80
+ });
81
+ if (refused.length > 0) return { type: "refused", refused };
82
+
83
+ const specOf = (leaf: PObjectId) => {
84
+ const spec = resolveColumnSpec(registry, leaf);
85
+ return spec !== undefined && isPColumnSpec(spec) ? spec : undefined;
86
+ };
87
+ using guard = new PoolEntryGuard(
88
+ env.driverKit.pFrameDriver.createPTableV2(
89
+ mapPTableDefV2(richTableDef(def, specOf), {
90
+ column: (id) => resolvePColumnById(registry, id),
91
+ node: collapseSpecOverrideNode,
92
+ }),
93
+ ),
94
+ );
95
+ ctx.addOnDestroy(guard.entry.unref);
96
+ return { type: "ok", handle: guard.keep().key };
97
+ });
98
+ }
@@ -3,7 +3,6 @@ import type {
3
3
  FieldData,
4
4
  Filter,
5
5
  OptionalAnyResourceId,
6
- PlClient,
7
6
  SignedResourceId,
8
7
  } from "@milaboratories/pl-client";
9
8
  import {
@@ -42,7 +41,8 @@ import type { TreeSnapshotStore } from "./tree_snapshot_store";
42
41
  import { setTimeout } from "node:timers/promises";
43
42
  import { frontendData } from "./frontend_path";
44
43
  import type { NavigationState } from "@milaboratories/pl-model-common";
45
- import { getBlockParameters, blockOutputs } from "./block";
44
+ import { getBlockParameters, blockOutputs, blockReadiness } from "./block";
45
+ import type { BlockReadiness } from "../model/args_derivation";
46
46
  import type { BlockActionContextMode, BlockActionContextNode } from "./block_action_context";
47
47
  import { readBlockActionContextTree } from "./block_action_context";
48
48
  import { getBlockPackInfo } from "./util";
@@ -70,8 +70,23 @@ import type {
70
70
  BlockSettings,
71
71
  BlockStateInternalV3,
72
72
  } from "@milaboratories/pl-model-middle-layer";
73
- import type { BlockId, ColumnLink } from "@milaboratories/pl-model-common";
73
+ import {
74
+ asBlockId,
75
+ type BlockId,
76
+ type ColumnLink,
77
+ type ColumnUniversalId,
78
+ type PTableDefV2,
79
+ } from "@milaboratories/pl-model-common";
74
80
  import { activeConfigs } from "./active_cfg";
81
+ import {
82
+ poolColumns,
83
+ poolColumnsById,
84
+ type PoolColumn,
85
+ type PoolColumns,
86
+ type PoolColumnsQuery,
87
+ } from "./pool_columns";
88
+ import { poolFrame, type PoolFrame } from "./pool_frame";
89
+ import { poolTable, type PoolTable } from "./pool_table";
75
90
  import { NavigationStates } from "./navigation_states";
76
91
  import {
77
92
  checkBlockFlag,
@@ -89,10 +104,14 @@ import canonicalize from "canonicalize";
89
104
  import type { ProjectOverviewLight } from "./project_overview_light";
90
105
  import { projectOverviewLight } from "./project_overview_light";
91
106
  import { applyProjectMigrations } from "../mutator/migration";
107
+ import { blockParamsModel, type BlockParamsModel } from "../model/block_params_model";
92
108
  import { cacheBlockPackTemplate } from "../mutator/template/template_cache";
109
+ import { throwIfMissingServerCapabilities } from "../mutator/block-pack/required_capabilities";
93
110
 
94
111
  type BlockStateComputables = {
95
112
  readonly fullState: Computable<BlockStateInternalV3>;
113
+ /** Lazy: the block's model runs only when the readiness is asked for. Not in the full state. */
114
+ readonly readiness: Computable<BlockReadiness | undefined>;
96
115
  /** Column links of the block, nested into its full state. */
97
116
  readonly dependencies: Computable<ColumnLink[] | undefined>;
98
117
  readonly dependents: Computable<ColumnLink[] | undefined>;
@@ -125,6 +144,7 @@ function stringifyForDump(object: unknown): string {
125
144
  /** Releases what the computables of a block hold. */
126
145
  function resetBlockState(computables: BlockStateComputables): void {
127
146
  computables.fullState.resetState();
147
+ computables.readiness.resetState();
128
148
  computables.dependencies.resetState();
129
149
  computables.dependents.resetState();
130
150
  }
@@ -150,6 +170,12 @@ export type AddBlockOps = {
150
170
  requireModelAPIVersion?: number;
151
171
  };
152
172
 
173
+ /** Options of {@link Project.updateBlockPack}. */
174
+ export type UpdateBlockPackOps = {
175
+ /** Refuse a block pack whose model API version differs from this one. */
176
+ requireModelAPIVersion?: number;
177
+ };
178
+
153
179
  /** Data access object, to manipulate and read single opened (!) project data. */
154
180
  export class Project {
155
181
  /** Data for the left panel, contain basic information about block status. */
@@ -495,7 +521,9 @@ export class Project {
495
521
  }
496
522
 
497
523
  // Pre-materialize template via cache (separate transaction(s))
498
- const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);
524
+ const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp, {
525
+ preparer: this.env.bpPreparer,
526
+ });
499
527
 
500
528
  // Build NewBlockSpec based on model API version
501
529
  const newBlockSpec =
@@ -575,21 +603,37 @@ export class Project {
575
603
  /**
576
604
  * Update block to new block pack, optionally resetting args and ui state to
577
605
  * initial values
606
+ *
607
+ * @throws ModelAPIVersionMismatchError when `ops.requireModelAPIVersion` differs from the
608
+ * model API version of the new block pack; nothing is changed
578
609
  * */
579
610
  public async updateBlockPack(
580
611
  blockId: string,
581
612
  blockPackSpec: BlockPackSpecAny,
582
613
  resetArgs: boolean = false,
583
614
  author?: AuthorMarker,
615
+ ops: UpdateBlockPackOps = {},
584
616
  ): Promise<void> {
585
617
  const preparedBp = await this.env.bpPreparer.prepare(blockPackSpec);
586
618
  const blockCfg = extractConfig(preparedBp.config);
587
619
 
620
+ if (
621
+ ops.requireModelAPIVersion !== undefined &&
622
+ blockCfg.modelAPIVersion !== ops.requireModelAPIVersion
623
+ )
624
+ throw new ModelAPIVersionMismatchError(
625
+ blockId,
626
+ ops.requireModelAPIVersion,
627
+ blockCfg.modelAPIVersion,
628
+ );
629
+
588
630
  this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);
589
631
  throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);
590
632
 
591
633
  // Pre-materialize template via cache (separate transaction(s))
592
- const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp);
634
+ const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp, {
635
+ preparer: this.env.bpPreparer,
636
+ });
593
637
 
594
638
  // resetState signals to mutator to reset storage
595
639
  // For v2+ blocks: mutator gets initial storage directly via getInitialStorageInVM
@@ -671,16 +715,20 @@ export class Project {
671
715
  * Renders production part of the block starting all connected heavy computations.
672
716
  * Upstream blocks of the specified block will be started automatically if in
673
717
  * stale state.
718
+ *
719
+ * @returns the ids of the blocks whose production was started, in project order; empty when
720
+ * the block and the blocks above it were up to date and nothing was started
674
721
  * */
675
- public async runBlock(blockId: string): Promise<void> {
676
- await withProject(
722
+ public async runBlock(blockId: string): Promise<BlockId[]> {
723
+ const started = await withProject(
677
724
  this.env.projectHelper,
678
725
  this.env.pl,
679
726
  this.rid,
680
- (mut) => mut.renderProduction([blockId], true),
727
+ (mut) => [...mut.renderProduction([blockId], true)].map(asBlockId),
681
728
  { name: "runBlock", lockId: this.projectLockId },
682
729
  );
683
730
  await this.refreshAfterWrite();
731
+ return started;
684
732
  }
685
733
 
686
734
  /**
@@ -827,6 +875,27 @@ export class Project {
827
875
  );
828
876
  }
829
877
 
878
+ /**
879
+ * The block's model as functions between its kind's params and its data: `init(params)` and
880
+ * `templateParams(data)` of the model of the block's current pack (see {@link BlockParamsModel}).
881
+ * One read transaction finds the model; each call of the result then runs it in the VM on its
882
+ * own, with no block created and nothing written. A caller writes what it computed with
883
+ * {@link mutateBlockStorage}.
884
+ *
885
+ * @throws when the project has no such block
886
+ * @throws {ModelAPIVersionMismatchError} when the block is not on BlockModelV3
887
+ */
888
+ public async getBlockParamsModel(blockId: BlockId): Promise<BlockParamsModel> {
889
+ const config = await withProject(
890
+ this.env.projectHelper,
891
+ this.env.pl,
892
+ this.rid,
893
+ (prj) => prj.getBlockConfig(blockId),
894
+ { name: "getBlockParamsModel", lockId: this.projectLockId },
895
+ );
896
+ return blockParamsModel(this.env.projectHelper, blockId, config);
897
+ }
898
+
830
899
  /** Update block settings */
831
900
  public async setBlockSettings(blockId: string, newValue: BlockSettings) {
832
901
  await withProjectAuthored(
@@ -941,6 +1010,7 @@ export class Project {
941
1010
 
942
1011
  const computables: BlockStateComputables = {
943
1012
  fullState: fullState.withPreCalculatedValueTree(),
1013
+ readiness: blockReadiness(this.projectTree.entry(), asBlockId(blockId), this.env),
944
1014
  dependencies,
945
1015
  dependents,
946
1016
  };
@@ -1088,6 +1158,63 @@ export class Project {
1088
1158
  return this.getBlockComputables(blockId).fullState;
1089
1159
  }
1090
1160
 
1161
+ /**
1162
+ * Returns a computable of what keeps the block from running or from being staged: the issues
1163
+ * its model finds in its current data and the references to blocks it cannot read from (see
1164
+ * {@link BlockReadiness}). The block's model runs when the value is asked for, not before, and
1165
+ * again only after the project changed. `undefined` for a block not on model API version 2.
1166
+ */
1167
+ public getBlockReadiness(blockId: BlockId): Computable<BlockReadiness | undefined> {
1168
+ return this.getBlockComputables(blockId).readiness;
1169
+ }
1170
+
1171
+ /**
1172
+ * Returns a computable of the project's result-pool columns, specs and refs with no data: as the
1173
+ * block `query.viewAs` sees them (the block and the blocks above it), or as the last block sees
1174
+ * them, which is every block's, and filtered by the selectors a block model passes to
1175
+ * `ColumnsCollection.filter`. Nothing is computed before the value is asked for, and the
1176
+ * computable is not kept by the project: each call makes a new one.
1177
+ */
1178
+ public getPoolColumns(query: PoolColumnsQuery = {}): Computable<PoolColumns> {
1179
+ return poolColumns(this.projectTree.entry(), query, this.env);
1180
+ }
1181
+
1182
+ /**
1183
+ * Returns a computable of the result-pool columns `ids` stand for, in their order, as the block
1184
+ * `viewAs` sees the pool (default: every block's); `undefined` for an id that is no column of
1185
+ * it. Each id is looked up directly, so it finds a column {@link getPoolColumns} leaves out for
1186
+ * having the same spec as another (see {@link poolColumnsById}). Not kept by the project.
1187
+ */
1188
+ public getPoolColumnsById(
1189
+ ids: readonly ColumnUniversalId[],
1190
+ viewAs?: BlockId,
1191
+ ): Computable<(PoolColumn | undefined)[]> {
1192
+ return poolColumnsById(this.projectTree.entry(), ids, viewAs);
1193
+ }
1194
+
1195
+ /**
1196
+ * Returns a computable of a PFrame over result-pool columns of the project, by their ids (see
1197
+ * {@link poolFrame}): what the values of a pool column are read from. A column that is unknown,
1198
+ * not ready, without data or failed, or whose id filters an axis, is refused, and nothing is
1199
+ * built. The frame is built when the value is asked for and released by the computable's
1200
+ * `resetState()`; the computable is not kept by the project, so its owner must reset it.
1201
+ */
1202
+ public createPoolFrame(ids: readonly ColumnUniversalId[]): Computable<PoolFrame> {
1203
+ return poolFrame(this.projectTree.entry(), ids, this.env);
1204
+ }
1205
+
1206
+ /**
1207
+ * Returns a computable of a table over result-pool columns of the project, built by the PFrame
1208
+ * driver from `def`, whose columns are the ids {@link getPoolColumns} lists, discovered ones
1209
+ * included (see {@link poolTable}): the query of a rich id is built on the host. An unknown
1210
+ * column, or one whose data is missing or not ready, is refused, and nothing is built. The table is built when the value is asked for and released by the
1211
+ * computable's `resetState()`; the computable is not kept by the project, so its owner must
1212
+ * reset it.
1213
+ */
1214
+ public createPoolTable(def: PTableDefV2<ColumnUniversalId>): Computable<PoolTable> {
1215
+ return poolTable(this.projectTree.entry(), def, this.env);
1216
+ }
1217
+
1091
1218
  /**
1092
1219
  * Returns a computable, that can be used to retrieve and watch path of the
1093
1220
  * folder containing frontend code.
@@ -1384,27 +1511,3 @@ function convertErrorsToStrings(
1384
1511
 
1385
1512
  return result;
1386
1513
  }
1387
-
1388
- /** Throws when the connected backend doesn't advertise every capability the
1389
- * block-pack requires (as declared in `meta.requiredCapabilities`).
1390
- *
1391
- * The matching set is the desktop's install gate moved server-side so both
1392
- * the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's
1393
- * `add_block` tool, programmatic block installs, tests) reject incompatible
1394
- * blocks consistently. */
1395
- export function throwIfMissingServerCapabilities(
1396
- pl: PlClient,
1397
- requiredCapabilities: readonly string[] | undefined,
1398
- ): void {
1399
- if (!requiredCapabilities || requiredCapabilities.length === 0) return;
1400
- const advertised = (pl.serverInfo.capabilities ?? []) as readonly string[];
1401
- const filterFn = (c: string) => !advertised.includes(c);
1402
- if (!requiredCapabilities.some(filterFn)) return;
1403
- const missing = requiredCapabilities.filter(filterFn);
1404
- throw new Error(
1405
- `Block cannot be added: connected backend does not advertise capabilities ` +
1406
- `${JSON.stringify(missing)}. ` +
1407
- `Backend advertises ${JSON.stringify(advertised)}. ` +
1408
- `Upgrade the backend or remove the requirement from the block manifest.`,
1409
- );
1410
- }