@milaboratories/pl-mcp-server 54.0.0 → 55.0.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.
- package/README.md +15 -25
- package/dist/_virtual/_rolldown/runtime.cjs +22 -0
- package/dist/agent-tables.cjs +116 -0
- package/dist/agent-tables.cjs.map +1 -0
- package/dist/agent-tables.js +115 -0
- package/dist/agent-tables.js.map +1 -0
- package/dist/instructions.cjs +15 -12
- package/dist/instructions.cjs.map +1 -1
- package/dist/instructions.js +15 -12
- package/dist/instructions.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/project-holds.cjs +58 -8
- package/dist/project-holds.cjs.map +1 -1
- package/dist/project-holds.js +58 -8
- package/dist/project-holds.js.map +1 -1
- package/dist/project-list.cjs +16 -0
- package/dist/project-list.cjs.map +1 -0
- package/dist/project-list.js +16 -0
- package/dist/project-list.js.map +1 -0
- package/dist/server-log.cjs +40 -18
- package/dist/server-log.cjs.map +1 -1
- package/dist/server-log.js +40 -19
- package/dist/server-log.js.map +1 -1
- package/dist/server.cjs +48 -18
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +21 -20
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +48 -18
- package/dist/server.js.map +1 -1
- package/dist/tools/agent-tables.cjs +424 -0
- package/dist/tools/agent-tables.cjs.map +1 -0
- package/dist/tools/agent-tables.js +417 -0
- package/dist/tools/agent-tables.js.map +1 -0
- package/dist/tools/await.cjs +216 -73
- package/dist/tools/await.cjs.map +1 -1
- package/dist/tools/await.js +212 -75
- package/dist/tools/await.js.map +1 -1
- package/dist/tools/block-action-context.cjs +3 -0
- package/dist/tools/block-action-context.cjs.map +1 -1
- package/dist/tools/block-action-context.js +3 -0
- package/dist/tools/block-action-context.js.map +1 -1
- package/dist/tools/block-api.cjs +17 -2
- package/dist/tools/block-api.cjs.map +1 -1
- package/dist/tools/block-api.js +17 -3
- package/dist/tools/block-api.js.map +1 -1
- package/dist/tools/block-params.cjs +272 -4
- package/dist/tools/block-params.cjs.map +1 -1
- package/dist/tools/block-params.js +270 -6
- package/dist/tools/block-params.js.map +1 -1
- package/dist/tools/block-state.cjs +323 -42
- package/dist/tools/block-state.cjs.map +1 -1
- package/dist/tools/block-state.js +317 -46
- package/dist/tools/block-state.js.map +1 -1
- package/dist/tools/block-storage.cjs +153 -0
- package/dist/tools/block-storage.cjs.map +1 -0
- package/dist/tools/block-storage.js +147 -0
- package/dist/tools/block-storage.js.map +1 -0
- package/dist/tools/block-updates.cjs +405 -0
- package/dist/tools/block-updates.cjs.map +1 -0
- package/dist/tools/block-updates.js +397 -0
- package/dist/tools/block-updates.js.map +1 -0
- package/dist/tools/blocks.cjs +183 -70
- package/dist/tools/blocks.cjs.map +1 -1
- package/dist/tools/blocks.js +177 -70
- package/dist/tools/blocks.js.map +1 -1
- package/dist/tools/data-query.cjs +451 -113
- package/dist/tools/data-query.cjs.map +1 -1
- package/dist/tools/data-query.js +446 -118
- package/dist/tools/data-query.js.map +1 -1
- package/dist/tools/errors.cjs +21 -0
- package/dist/tools/errors.cjs.map +1 -0
- package/dist/tools/errors.js +20 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/files.cjs +643 -0
- package/dist/tools/files.cjs.map +1 -0
- package/dist/tools/files.js +613 -0
- package/dist/tools/files.js.map +1 -0
- package/dist/tools/ids.cjs +56 -0
- package/dist/tools/ids.cjs.map +1 -1
- package/dist/tools/ids.js +51 -2
- package/dist/tools/ids.js.map +1 -1
- package/dist/tools/imports.cjs +195 -0
- package/dist/tools/imports.cjs.map +1 -0
- package/dist/tools/imports.js +186 -0
- package/dist/tools/imports.js.map +1 -0
- package/dist/tools/logs.cjs +98 -19
- package/dist/tools/logs.cjs.map +1 -1
- package/dist/tools/logs.js +95 -20
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/paging.cjs +27 -0
- package/dist/tools/paging.cjs.map +1 -0
- package/dist/tools/paging.js +26 -0
- package/dist/tools/paging.js.map +1 -0
- package/dist/tools/params-merge.cjs +106 -0
- package/dist/tools/params-merge.cjs.map +1 -0
- package/dist/tools/params-merge.js +106 -0
- package/dist/tools/params-merge.js.map +1 -0
- package/dist/tools/project-template.cjs +75 -0
- package/dist/tools/project-template.cjs.map +1 -0
- package/dist/tools/project-template.js +72 -0
- package/dist/tools/project-template.js.map +1 -0
- package/dist/tools/projects.cjs +66 -19
- package/dist/tools/projects.cjs.map +1 -1
- package/dist/tools/projects.js +66 -20
- package/dist/tools/projects.js.map +1 -1
- package/dist/tools/readiness.cjs +104 -0
- package/dist/tools/readiness.cjs.map +1 -0
- package/dist/tools/readiness.js +99 -0
- package/dist/tools/readiness.js.map +1 -0
- package/dist/tools/result-pool.cjs +260 -0
- package/dist/tools/result-pool.cjs.map +1 -0
- package/dist/tools/result-pool.js +252 -0
- package/dist/tools/result-pool.js.map +1 -0
- package/dist/tools/sandbox.cjs +112 -14
- package/dist/tools/sandbox.cjs.map +1 -1
- package/dist/tools/sandbox.js +110 -15
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/sdk-types.cjs +24 -0
- package/dist/tools/sdk-types.cjs.map +1 -0
- package/dist/tools/sdk-types.js +24 -0
- package/dist/tools/sdk-types.js.map +1 -0
- package/dist/tools/settle.cjs +155 -0
- package/dist/tools/settle.cjs.map +1 -0
- package/dist/tools/settle.js +148 -0
- package/dist/tools/settle.js.map +1 -0
- package/dist/tools/tokens.cjs +49 -8
- package/dist/tools/tokens.cjs.map +1 -1
- package/dist/tools/tokens.js +45 -9
- package/dist/tools/tokens.js.map +1 -1
- package/dist/tools/types.cjs +62 -11
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js +60 -12
- package/dist/tools/types.js.map +1 -1
- package/dist/tools/value-outline.cjs +119 -0
- package/dist/tools/value-outline.cjs.map +1 -0
- package/dist/tools/value-outline.js +117 -0
- package/dist/tools/value-outline.js.map +1 -0
- package/package.json +9 -8
- package/src/agent-tables.test.ts +246 -0
- package/src/agent-tables.ts +145 -0
- package/src/instructions.ts +15 -12
- package/src/project-holds.test.ts +179 -0
- package/src/project-holds.ts +114 -12
- package/src/project-list.test.ts +38 -0
- package/src/project-list.ts +25 -0
- package/src/server-log.test.ts +54 -1
- package/src/server-log.ts +49 -27
- package/src/server.logging.test.ts +38 -46
- package/src/server.test.ts +151 -17
- package/src/server.ts +62 -34
- package/src/tools/agent-tables.test.ts +650 -0
- package/src/tools/agent-tables.ts +673 -0
- package/src/tools/await.test.ts +287 -0
- package/src/tools/await.ts +393 -123
- package/src/tools/block-action-context.ts +3 -0
- package/src/tools/block-api.ts +19 -4
- package/src/tools/block-params.test.ts +828 -0
- package/src/tools/block-params.ts +623 -8
- package/src/tools/block-state.test.ts +480 -0
- package/src/tools/block-state.ts +659 -66
- package/src/tools/block-storage.test.ts +270 -0
- package/src/tools/block-storage.ts +195 -0
- package/src/tools/block-updates.test.ts +605 -0
- package/src/tools/block-updates.ts +751 -0
- package/src/tools/blocks.test.ts +169 -22
- package/src/tools/blocks.ts +336 -105
- package/src/tools/data-query.test.ts +641 -0
- package/src/tools/data-query.ts +807 -157
- package/src/tools/errors.test.ts +33 -0
- package/src/tools/errors.ts +23 -0
- package/src/tools/files.test.ts +842 -0
- package/src/tools/files.ts +990 -0
- package/src/tools/ids.test.ts +87 -0
- package/src/tools/ids.ts +67 -0
- package/src/tools/imports.ts +304 -0
- package/src/tools/logs.test.ts +70 -0
- package/src/tools/logs.ts +130 -21
- package/src/tools/paging.test.ts +39 -0
- package/src/tools/paging.ts +39 -0
- package/src/tools/params-merge.test.ts +274 -0
- package/src/tools/params-merge.ts +149 -0
- package/src/tools/project-template.test.ts +230 -0
- package/src/tools/project-template.ts +135 -0
- package/src/tools/projects.test.ts +122 -0
- package/src/tools/projects.ts +135 -25
- package/src/tools/readiness.test.ts +195 -0
- package/src/tools/readiness.ts +189 -0
- package/src/tools/result-pool.test.ts +377 -0
- package/src/tools/result-pool.ts +483 -0
- package/src/tools/sandbox.test.ts +128 -10
- package/src/tools/sandbox.ts +132 -18
- package/src/tools/sdk-types.ts +54 -0
- package/src/tools/settle.test.ts +340 -0
- package/src/tools/settle.ts +312 -0
- package/src/tools/tokens.ts +74 -9
- package/src/tools/types.ts +77 -12
- package/src/tools/value-outline.ts +143 -0
- package/dist/tools/screenshot.cjs +0 -44
- package/dist/tools/screenshot.cjs.map +0 -1
- package/dist/tools/screenshot.js +0 -44
- package/dist/tools/screenshot.js.map +0 -1
- package/dist/tools/ui-interaction.cjs +0 -140
- package/dist/tools/ui-interaction.cjs.map +0 -1
- package/dist/tools/ui-interaction.js +0 -140
- package/dist/tools/ui-interaction.js.map +0 -1
- package/src/tools/screenshot.ts +0 -61
- package/src/tools/ui-interaction.ts +0 -184
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
let zod = require("zod");
|
|
2
|
+
// src/tools/paging.ts
|
|
3
|
+
/**
|
|
4
|
+
* The `limit` and `offset` arguments of a tool that lists items page by page, so a caller can
|
|
5
|
+
* always reach every item (and its id), however many there are.
|
|
6
|
+
*/
|
|
7
|
+
function pagingArgs(what, defaultLimit, maxLimit) {
|
|
8
|
+
return {
|
|
9
|
+
limit: zod.z.number().int().min(1).max(maxLimit).optional().describe(`The most ${what} to return (default ${defaultLimit}, at most ${maxLimit}).`),
|
|
10
|
+
offset: zod.z.number().int().min(0).optional().describe(`How many ${what} to skip (default 0); with \`limit\`, pages through them.`)
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/** One page of `items`: the items, how many there are in all and whether more follow. */
|
|
14
|
+
function page(items, offset, limit) {
|
|
15
|
+
const start = offset ?? 0;
|
|
16
|
+
const slice = items.slice(start, start + limit);
|
|
17
|
+
return {
|
|
18
|
+
items: slice,
|
|
19
|
+
total: items.length,
|
|
20
|
+
offset: start,
|
|
21
|
+
hasMore: start + slice.length < items.length
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
exports.page = page;
|
|
25
|
+
exports.pagingArgs = pagingArgs;
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=paging.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paging.cjs","names":["z"],"sources":["../../src/tools/paging.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * The `limit` and `offset` arguments of a tool that lists items page by page, so a caller can\n * always reach every item (and its id), however many there are.\n */\nexport function pagingArgs(what: string, defaultLimit: number, maxLimit: number) {\n return {\n limit: z\n .number()\n .int()\n .min(1)\n .max(maxLimit)\n .optional()\n .describe(`The most ${what} to return (default ${defaultLimit}, at most ${maxLimit}).`),\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(`How many ${what} to skip (default 0); with \\`limit\\`, pages through them.`),\n };\n}\n\n/** One page of `items`: the items, how many there are in all and whether more follow. */\nexport function page<T>(\n items: readonly T[],\n offset: number | undefined,\n limit: number,\n): { items: T[]; total: number; offset: number; hasMore: boolean } {\n const start = offset ?? 0;\n const slice = items.slice(start, start + limit);\n return {\n items: slice,\n total: items.length,\n offset: start,\n hasMore: start + slice.length < items.length,\n };\n}\n"],"mappings":";;;;;;AAMA,SAAgB,WAAW,MAAc,cAAsB,UAAkB;CAC/E,OAAO;EACL,OAAOA,IAAAA,EACJ,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,IAAI,QAAQ,CAAC,CACb,SAAS,CAAC,CACV,SAAS,YAAY,KAAK,sBAAsB,aAAa,YAAY,SAAS,GAAG;EACxF,QAAQA,IAAAA,EACL,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,SAAS,CAAC,CACV,SAAS,YAAY,KAAK,0DAA0D;CACzF;AACF;;AAGA,SAAgB,KACd,OACA,QACA,OACiE;CACjE,MAAM,QAAQ,UAAU;CACxB,MAAM,QAAQ,MAAM,MAAM,OAAO,QAAQ,KAAK;CAC9C,OAAO;EACL,OAAO;EACP,OAAO,MAAM;EACb,QAAQ;EACR,SAAS,QAAQ,MAAM,SAAS,MAAM;CACxC;AACF"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
// src/tools/paging.ts
|
|
3
|
+
/**
|
|
4
|
+
* The `limit` and `offset` arguments of a tool that lists items page by page, so a caller can
|
|
5
|
+
* always reach every item (and its id), however many there are.
|
|
6
|
+
*/
|
|
7
|
+
function pagingArgs(what, defaultLimit, maxLimit) {
|
|
8
|
+
return {
|
|
9
|
+
limit: z.number().int().min(1).max(maxLimit).optional().describe(`The most ${what} to return (default ${defaultLimit}, at most ${maxLimit}).`),
|
|
10
|
+
offset: z.number().int().min(0).optional().describe(`How many ${what} to skip (default 0); with \`limit\`, pages through them.`)
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/** One page of `items`: the items, how many there are in all and whether more follow. */
|
|
14
|
+
function page(items, offset, limit) {
|
|
15
|
+
const start = offset ?? 0;
|
|
16
|
+
const slice = items.slice(start, start + limit);
|
|
17
|
+
return {
|
|
18
|
+
items: slice,
|
|
19
|
+
total: items.length,
|
|
20
|
+
offset: start,
|
|
21
|
+
hasMore: start + slice.length < items.length
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export { page, pagingArgs };
|
|
25
|
+
|
|
26
|
+
//# sourceMappingURL=paging.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paging.js","names":[],"sources":["../../src/tools/paging.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * The `limit` and `offset` arguments of a tool that lists items page by page, so a caller can\n * always reach every item (and its id), however many there are.\n */\nexport function pagingArgs(what: string, defaultLimit: number, maxLimit: number) {\n return {\n limit: z\n .number()\n .int()\n .min(1)\n .max(maxLimit)\n .optional()\n .describe(`The most ${what} to return (default ${defaultLimit}, at most ${maxLimit}).`),\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(`How many ${what} to skip (default 0); with \\`limit\\`, pages through them.`),\n };\n}\n\n/** One page of `items`: the items, how many there are in all and whether more follow. */\nexport function page<T>(\n items: readonly T[],\n offset: number | undefined,\n limit: number,\n): { items: T[]; total: number; offset: number; hasMore: boolean } {\n const start = offset ?? 0;\n const slice = items.slice(start, start + limit);\n return {\n items: slice,\n total: items.length,\n offset: start,\n hasMore: start + slice.length < items.length,\n };\n}\n"],"mappings":";;;;;;AAMA,SAAgB,WAAW,MAAc,cAAsB,UAAkB;CAC/E,OAAO;EACL,OAAO,EACJ,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,IAAI,QAAQ,CAAC,CACb,SAAS,CAAC,CACV,SAAS,YAAY,KAAK,sBAAsB,aAAa,YAAY,SAAS,GAAG;EACxF,QAAQ,EACL,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,SAAS,CAAC,CACV,SAAS,YAAY,KAAK,0DAA0D;CACzF;AACF;;AAGA,SAAgB,KACd,OACA,QACA,OACiE;CACjE,MAAM,QAAQ,UAAU;CACxB,MAAM,QAAQ,MAAM,MAAM,OAAO,QAAQ,KAAK;CAC9C,OAAO;EACL,OAAO;EACP,OAAO,MAAM;EACb,QAAQ;EACR,SAAS,QAAQ,MAAM,SAAS,MAAM;CACxC;AACF"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
const require_block_storage = require("./block-storage.cjs");
|
|
2
|
+
let _milaboratories_helpers = require("@milaboratories/helpers");
|
|
3
|
+
let node_util = require("node:util");
|
|
4
|
+
// src/tools/params-merge.ts
|
|
5
|
+
/** A key, or an element, a version does not have. */
|
|
6
|
+
const ABSENT = Symbol("absent");
|
|
7
|
+
/**
|
|
8
|
+
* Three-way merge of a block's data for set_block_params (D-040, Q-047): `base` is the data the
|
|
9
|
+
* block's model builds from the current params, `theirs` the data it builds from the new params,
|
|
10
|
+
* `ours` the block's current data.
|
|
11
|
+
*
|
|
12
|
+
* Where `theirs` differs from `base`, the params changed that part, and `theirs` is taken;
|
|
13
|
+
* elsewhere `ours` is kept, so view state and everything params do not drive stays. Objects merge
|
|
14
|
+
* key by key. Arrays of objects that all carry a unique `id` (string or number) merge element by
|
|
15
|
+
* element, matched by `id`: an element follows its id wherever the new params move it. The new
|
|
16
|
+
* params own such an array's membership and order: an element they drop goes even when `ours`
|
|
17
|
+
* changed it (its per-element state, e.g. the per-sample values of a metadata column, goes with
|
|
18
|
+
* it), an element only `ours` has is kept after its neighbour. Other arrays and values merge as
|
|
19
|
+
* whole values.
|
|
20
|
+
*
|
|
21
|
+
* A conflict is a path where all three differ and neither rule applies; the merge then reports
|
|
22
|
+
* every such path and its `merged` is not to be written.
|
|
23
|
+
*/
|
|
24
|
+
function mergeThreeWay(base, theirs, ours) {
|
|
25
|
+
const conflicts = [];
|
|
26
|
+
const merged = mergeAt("", base, theirs, ours, conflicts);
|
|
27
|
+
return {
|
|
28
|
+
merged: merged === ABSENT ? void 0 : merged,
|
|
29
|
+
conflicts
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function same(a, b) {
|
|
33
|
+
if (a === ABSENT || b === ABSENT) return a === b;
|
|
34
|
+
return (0, node_util.isDeepStrictEqual)(a, b);
|
|
35
|
+
}
|
|
36
|
+
function mergeAt(path, base, theirs, ours, conflicts) {
|
|
37
|
+
if (same(base, theirs)) return ours;
|
|
38
|
+
if (same(base, ours) || same(theirs, ours)) return theirs;
|
|
39
|
+
if ((0, _milaboratories_helpers.isPlainObject)(base) && (0, _milaboratories_helpers.isPlainObject)(theirs) && (0, _milaboratories_helpers.isPlainObject)(ours)) return mergeRecords(path, base, theirs, ours, conflicts);
|
|
40
|
+
if (Array.isArray(base) && Array.isArray(theirs) && Array.isArray(ours)) {
|
|
41
|
+
const [b, t, o] = [
|
|
42
|
+
base,
|
|
43
|
+
theirs,
|
|
44
|
+
ours
|
|
45
|
+
].map(byId);
|
|
46
|
+
if (b !== void 0 && t !== void 0 && o !== void 0) return mergeById(path, b, t, o, conflicts);
|
|
47
|
+
}
|
|
48
|
+
conflicts.push(path === "" ? "(root)" : path);
|
|
49
|
+
return ours;
|
|
50
|
+
}
|
|
51
|
+
/** The value of `key` in `obj`, or {@link ABSENT}: a key holding `undefined` is no key in JSON. */
|
|
52
|
+
function slotOf(obj, key) {
|
|
53
|
+
const value = require_block_storage.ownValue(obj, key);
|
|
54
|
+
return value === void 0 ? ABSENT : value;
|
|
55
|
+
}
|
|
56
|
+
function mergeRecords(path, base, theirs, ours, conflicts) {
|
|
57
|
+
const keys = [...Object.keys(ours), ...Object.keys(theirs).filter((k) => !Object.hasOwn(ours, k))];
|
|
58
|
+
const entries = [];
|
|
59
|
+
for (const key of keys) {
|
|
60
|
+
const value = mergeAt(require_block_storage.childPath(path, key), slotOf(base, key), slotOf(theirs, key), slotOf(ours, key), conflicts);
|
|
61
|
+
if (value !== ABSENT) entries.push([key, value]);
|
|
62
|
+
}
|
|
63
|
+
return Object.fromEntries(entries);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* `xs` keyed by the `id` of its elements, or `undefined` when an element is not an object, has no
|
|
67
|
+
* string or numeric `id`, or shares its id with another. The key tells `1` from `"1"`.
|
|
68
|
+
*/
|
|
69
|
+
function byId(xs) {
|
|
70
|
+
const keyed = {
|
|
71
|
+
order: [],
|
|
72
|
+
ids: /* @__PURE__ */ new Map(),
|
|
73
|
+
elements: /* @__PURE__ */ new Map()
|
|
74
|
+
};
|
|
75
|
+
for (const x of xs) {
|
|
76
|
+
if (!(0, _milaboratories_helpers.isPlainObject)(x)) return void 0;
|
|
77
|
+
const id = require_block_storage.ownValue(x, "id");
|
|
78
|
+
if (typeof id !== "string" && typeof id !== "number") return void 0;
|
|
79
|
+
const key = `${typeof id}:${id}`;
|
|
80
|
+
if (keyed.elements.has(key)) return void 0;
|
|
81
|
+
keyed.order.push(key);
|
|
82
|
+
keyed.ids.set(key, id);
|
|
83
|
+
keyed.elements.set(key, x);
|
|
84
|
+
}
|
|
85
|
+
return keyed;
|
|
86
|
+
}
|
|
87
|
+
function mergeById(path, base, theirs, ours, conflicts) {
|
|
88
|
+
const result = /* @__PURE__ */ new Map();
|
|
89
|
+
for (const key of /* @__PURE__ */ new Set([...theirs.order, ...ours.order])) {
|
|
90
|
+
const inTheirs = theirs.elements.has(key);
|
|
91
|
+
if (!inTheirs && base.elements.has(key)) continue;
|
|
92
|
+
const id = theirs.ids.get(key) ?? ours.ids.get(key);
|
|
93
|
+
const value = mergeAt(`${path}[id=${JSON.stringify(id)}]`, base.elements.get(key) ?? ABSENT, inTheirs ? theirs.elements.get(key) : ABSENT, ours.elements.get(key) ?? ABSENT, conflicts);
|
|
94
|
+
if (value !== ABSENT) result.set(key, value);
|
|
95
|
+
}
|
|
96
|
+
const order = theirs.order.filter((key) => result.has(key));
|
|
97
|
+
ours.order.forEach((key, i) => {
|
|
98
|
+
if (!result.has(key) || order.includes(key)) return;
|
|
99
|
+
const before = ours.order.slice(0, i).reverse().find((k) => order.includes(k));
|
|
100
|
+
order.splice(before === void 0 ? 0 : order.indexOf(before) + 1, 0, key);
|
|
101
|
+
});
|
|
102
|
+
return order.map((key) => result.get(key));
|
|
103
|
+
}
|
|
104
|
+
exports.mergeThreeWay = mergeThreeWay;
|
|
105
|
+
|
|
106
|
+
//# sourceMappingURL=params-merge.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"params-merge.cjs","names":["isDeepStrictEqual","isPlainObject","ownValue","childPath"],"sources":["../../src/tools/params-merge.ts"],"sourcesContent":["import { isDeepStrictEqual } from \"node:util\";\nimport { isPlainObject } from \"@milaboratories/helpers\";\nimport { childPath, ownValue } from \"./block-storage\";\n\n/** The outcome of {@link mergeThreeWay}. */\nexport type MergeOutcome = {\n /** The merged value; meaningless when there are conflicts. */\n merged: unknown;\n /** The paths where base, theirs and ours all differ, in the form of reported changes. */\n conflicts: string[];\n};\n\n/** A key, or an element, a version does not have. */\nconst ABSENT: unique symbol = Symbol(\"absent\");\ntype Slot = unknown;\n\n/**\n * Three-way merge of a block's data for set_block_params (D-040, Q-047): `base` is the data the\n * block's model builds from the current params, `theirs` the data it builds from the new params,\n * `ours` the block's current data.\n *\n * Where `theirs` differs from `base`, the params changed that part, and `theirs` is taken;\n * elsewhere `ours` is kept, so view state and everything params do not drive stays. Objects merge\n * key by key. Arrays of objects that all carry a unique `id` (string or number) merge element by\n * element, matched by `id`: an element follows its id wherever the new params move it. The new\n * params own such an array's membership and order: an element they drop goes even when `ours`\n * changed it (its per-element state, e.g. the per-sample values of a metadata column, goes with\n * it), an element only `ours` has is kept after its neighbour. Other arrays and values merge as\n * whole values.\n *\n * A conflict is a path where all three differ and neither rule applies; the merge then reports\n * every such path and its `merged` is not to be written.\n */\nexport function mergeThreeWay(base: unknown, theirs: unknown, ours: unknown): MergeOutcome {\n const conflicts: string[] = [];\n const merged = mergeAt(\"\", base, theirs, ours, conflicts);\n return { merged: merged === ABSENT ? undefined : merged, conflicts };\n}\n\nfunction same(a: Slot, b: Slot): boolean {\n if (a === ABSENT || b === ABSENT) return a === b;\n return isDeepStrictEqual(a, b);\n}\n\nfunction mergeAt(path: string, base: Slot, theirs: Slot, ours: Slot, conflicts: string[]): Slot {\n if (same(base, theirs)) return ours;\n if (same(base, ours) || same(theirs, ours)) return theirs;\n if (isPlainObject(base) && isPlainObject(theirs) && isPlainObject(ours))\n return mergeRecords(path, base, theirs, ours, conflicts);\n if (Array.isArray(base) && Array.isArray(theirs) && Array.isArray(ours)) {\n const keyed = [base, theirs, ours].map(byId);\n const [b, t, o] = keyed;\n if (b !== undefined && t !== undefined && o !== undefined)\n return mergeById(path, b, t, o, conflicts);\n }\n conflicts.push(path === \"\" ? \"(root)\" : path);\n return ours;\n}\n\n/** The value of `key` in `obj`, or {@link ABSENT}: a key holding `undefined` is no key in JSON. */\nfunction slotOf(obj: Record<string, unknown>, key: string): Slot {\n const value = ownValue(obj, key);\n return value === undefined ? ABSENT : value;\n}\n\nfunction mergeRecords(\n path: string,\n base: Record<string, unknown>,\n theirs: Record<string, unknown>,\n ours: Record<string, unknown>,\n conflicts: string[],\n): Record<string, unknown> {\n // Ours' key order, then the keys the new params add.\n const keys = [\n ...Object.keys(ours),\n ...Object.keys(theirs).filter((k) => !Object.hasOwn(ours, k)),\n ];\n const entries: [string, unknown][] = [];\n for (const key of keys) {\n const value = mergeAt(\n childPath(path, key),\n slotOf(base, key),\n slotOf(theirs, key),\n slotOf(ours, key),\n conflicts,\n );\n if (value !== ABSENT) entries.push([key, value]);\n }\n // `Object.fromEntries` defines own keys, so a key such as `__proto__` stays a key.\n return Object.fromEntries(entries);\n}\n\n/** An array of objects keyed by their `id`: ids in array order and the element of each. */\ntype Keyed = { order: string[]; ids: Map<string, unknown>; elements: Map<string, unknown> };\n\n/**\n * `xs` keyed by the `id` of its elements, or `undefined` when an element is not an object, has no\n * string or numeric `id`, or shares its id with another. The key tells `1` from `\"1\"`.\n */\nfunction byId(xs: unknown[]): Keyed | undefined {\n const keyed: Keyed = { order: [], ids: new Map(), elements: new Map() };\n for (const x of xs) {\n if (!isPlainObject(x)) return undefined;\n const id = ownValue(x, \"id\");\n if (typeof id !== \"string\" && typeof id !== \"number\") return undefined;\n const key = `${typeof id}:${id}`;\n if (keyed.elements.has(key)) return undefined;\n keyed.order.push(key);\n keyed.ids.set(key, id);\n keyed.elements.set(key, x);\n }\n return keyed;\n}\n\nfunction mergeById(\n path: string,\n base: Keyed,\n theirs: Keyed,\n ours: Keyed,\n conflicts: string[],\n): unknown[] {\n const result = new Map<string, unknown>();\n for (const key of new Set([...theirs.order, ...ours.order])) {\n const inTheirs = theirs.elements.has(key);\n // Dropped by the new params: the element goes, whatever ours holds in it.\n if (!inTheirs && base.elements.has(key)) continue;\n const id = theirs.ids.get(key) ?? ours.ids.get(key);\n const value = mergeAt(\n `${path}[id=${JSON.stringify(id)}]`,\n base.elements.get(key) ?? ABSENT,\n inTheirs ? theirs.elements.get(key) : ABSENT,\n ours.elements.get(key) ?? ABSENT,\n conflicts,\n );\n if (value !== ABSENT) result.set(key, value);\n }\n\n // Theirs' order; an element only ours has goes after the element before it in ours.\n const order = theirs.order.filter((key) => result.has(key));\n ours.order.forEach((key, i) => {\n if (!result.has(key) || order.includes(key)) return;\n const before = ours.order\n .slice(0, i)\n .reverse()\n .find((k) => order.includes(k));\n order.splice(before === undefined ? 0 : order.indexOf(before) + 1, 0, key);\n });\n return order.map((key) => result.get(key));\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { childPath, ownValue } from "./block-storage.js";
|
|
2
|
+
import { isPlainObject } from "@milaboratories/helpers";
|
|
3
|
+
import { isDeepStrictEqual } from "node:util";
|
|
4
|
+
// src/tools/params-merge.ts
|
|
5
|
+
/** A key, or an element, a version does not have. */
|
|
6
|
+
const ABSENT = Symbol("absent");
|
|
7
|
+
/**
|
|
8
|
+
* Three-way merge of a block's data for set_block_params (D-040, Q-047): `base` is the data the
|
|
9
|
+
* block's model builds from the current params, `theirs` the data it builds from the new params,
|
|
10
|
+
* `ours` the block's current data.
|
|
11
|
+
*
|
|
12
|
+
* Where `theirs` differs from `base`, the params changed that part, and `theirs` is taken;
|
|
13
|
+
* elsewhere `ours` is kept, so view state and everything params do not drive stays. Objects merge
|
|
14
|
+
* key by key. Arrays of objects that all carry a unique `id` (string or number) merge element by
|
|
15
|
+
* element, matched by `id`: an element follows its id wherever the new params move it. The new
|
|
16
|
+
* params own such an array's membership and order: an element they drop goes even when `ours`
|
|
17
|
+
* changed it (its per-element state, e.g. the per-sample values of a metadata column, goes with
|
|
18
|
+
* it), an element only `ours` has is kept after its neighbour. Other arrays and values merge as
|
|
19
|
+
* whole values.
|
|
20
|
+
*
|
|
21
|
+
* A conflict is a path where all three differ and neither rule applies; the merge then reports
|
|
22
|
+
* every such path and its `merged` is not to be written.
|
|
23
|
+
*/
|
|
24
|
+
function mergeThreeWay(base, theirs, ours) {
|
|
25
|
+
const conflicts = [];
|
|
26
|
+
const merged = mergeAt("", base, theirs, ours, conflicts);
|
|
27
|
+
return {
|
|
28
|
+
merged: merged === ABSENT ? void 0 : merged,
|
|
29
|
+
conflicts
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function same(a, b) {
|
|
33
|
+
if (a === ABSENT || b === ABSENT) return a === b;
|
|
34
|
+
return isDeepStrictEqual(a, b);
|
|
35
|
+
}
|
|
36
|
+
function mergeAt(path, base, theirs, ours, conflicts) {
|
|
37
|
+
if (same(base, theirs)) return ours;
|
|
38
|
+
if (same(base, ours) || same(theirs, ours)) return theirs;
|
|
39
|
+
if (isPlainObject(base) && isPlainObject(theirs) && isPlainObject(ours)) return mergeRecords(path, base, theirs, ours, conflicts);
|
|
40
|
+
if (Array.isArray(base) && Array.isArray(theirs) && Array.isArray(ours)) {
|
|
41
|
+
const [b, t, o] = [
|
|
42
|
+
base,
|
|
43
|
+
theirs,
|
|
44
|
+
ours
|
|
45
|
+
].map(byId);
|
|
46
|
+
if (b !== void 0 && t !== void 0 && o !== void 0) return mergeById(path, b, t, o, conflicts);
|
|
47
|
+
}
|
|
48
|
+
conflicts.push(path === "" ? "(root)" : path);
|
|
49
|
+
return ours;
|
|
50
|
+
}
|
|
51
|
+
/** The value of `key` in `obj`, or {@link ABSENT}: a key holding `undefined` is no key in JSON. */
|
|
52
|
+
function slotOf(obj, key) {
|
|
53
|
+
const value = ownValue(obj, key);
|
|
54
|
+
return value === void 0 ? ABSENT : value;
|
|
55
|
+
}
|
|
56
|
+
function mergeRecords(path, base, theirs, ours, conflicts) {
|
|
57
|
+
const keys = [...Object.keys(ours), ...Object.keys(theirs).filter((k) => !Object.hasOwn(ours, k))];
|
|
58
|
+
const entries = [];
|
|
59
|
+
for (const key of keys) {
|
|
60
|
+
const value = mergeAt(childPath(path, key), slotOf(base, key), slotOf(theirs, key), slotOf(ours, key), conflicts);
|
|
61
|
+
if (value !== ABSENT) entries.push([key, value]);
|
|
62
|
+
}
|
|
63
|
+
return Object.fromEntries(entries);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* `xs` keyed by the `id` of its elements, or `undefined` when an element is not an object, has no
|
|
67
|
+
* string or numeric `id`, or shares its id with another. The key tells `1` from `"1"`.
|
|
68
|
+
*/
|
|
69
|
+
function byId(xs) {
|
|
70
|
+
const keyed = {
|
|
71
|
+
order: [],
|
|
72
|
+
ids: /* @__PURE__ */ new Map(),
|
|
73
|
+
elements: /* @__PURE__ */ new Map()
|
|
74
|
+
};
|
|
75
|
+
for (const x of xs) {
|
|
76
|
+
if (!isPlainObject(x)) return void 0;
|
|
77
|
+
const id = ownValue(x, "id");
|
|
78
|
+
if (typeof id !== "string" && typeof id !== "number") return void 0;
|
|
79
|
+
const key = `${typeof id}:${id}`;
|
|
80
|
+
if (keyed.elements.has(key)) return void 0;
|
|
81
|
+
keyed.order.push(key);
|
|
82
|
+
keyed.ids.set(key, id);
|
|
83
|
+
keyed.elements.set(key, x);
|
|
84
|
+
}
|
|
85
|
+
return keyed;
|
|
86
|
+
}
|
|
87
|
+
function mergeById(path, base, theirs, ours, conflicts) {
|
|
88
|
+
const result = /* @__PURE__ */ new Map();
|
|
89
|
+
for (const key of /* @__PURE__ */ new Set([...theirs.order, ...ours.order])) {
|
|
90
|
+
const inTheirs = theirs.elements.has(key);
|
|
91
|
+
if (!inTheirs && base.elements.has(key)) continue;
|
|
92
|
+
const id = theirs.ids.get(key) ?? ours.ids.get(key);
|
|
93
|
+
const value = mergeAt(`${path}[id=${JSON.stringify(id)}]`, base.elements.get(key) ?? ABSENT, inTheirs ? theirs.elements.get(key) : ABSENT, ours.elements.get(key) ?? ABSENT, conflicts);
|
|
94
|
+
if (value !== ABSENT) result.set(key, value);
|
|
95
|
+
}
|
|
96
|
+
const order = theirs.order.filter((key) => result.has(key));
|
|
97
|
+
ours.order.forEach((key, i) => {
|
|
98
|
+
if (!result.has(key) || order.includes(key)) return;
|
|
99
|
+
const before = ours.order.slice(0, i).reverse().find((k) => order.includes(k));
|
|
100
|
+
order.splice(before === void 0 ? 0 : order.indexOf(before) + 1, 0, key);
|
|
101
|
+
});
|
|
102
|
+
return order.map((key) => result.get(key));
|
|
103
|
+
}
|
|
104
|
+
export { mergeThreeWay };
|
|
105
|
+
|
|
106
|
+
//# sourceMappingURL=params-merge.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"params-merge.js","names":[],"sources":["../../src/tools/params-merge.ts"],"sourcesContent":["import { isDeepStrictEqual } from \"node:util\";\nimport { isPlainObject } from \"@milaboratories/helpers\";\nimport { childPath, ownValue } from \"./block-storage\";\n\n/** The outcome of {@link mergeThreeWay}. */\nexport type MergeOutcome = {\n /** The merged value; meaningless when there are conflicts. */\n merged: unknown;\n /** The paths where base, theirs and ours all differ, in the form of reported changes. */\n conflicts: string[];\n};\n\n/** A key, or an element, a version does not have. */\nconst ABSENT: unique symbol = Symbol(\"absent\");\ntype Slot = unknown;\n\n/**\n * Three-way merge of a block's data for set_block_params (D-040, Q-047): `base` is the data the\n * block's model builds from the current params, `theirs` the data it builds from the new params,\n * `ours` the block's current data.\n *\n * Where `theirs` differs from `base`, the params changed that part, and `theirs` is taken;\n * elsewhere `ours` is kept, so view state and everything params do not drive stays. Objects merge\n * key by key. Arrays of objects that all carry a unique `id` (string or number) merge element by\n * element, matched by `id`: an element follows its id wherever the new params move it. The new\n * params own such an array's membership and order: an element they drop goes even when `ours`\n * changed it (its per-element state, e.g. the per-sample values of a metadata column, goes with\n * it), an element only `ours` has is kept after its neighbour. Other arrays and values merge as\n * whole values.\n *\n * A conflict is a path where all three differ and neither rule applies; the merge then reports\n * every such path and its `merged` is not to be written.\n */\nexport function mergeThreeWay(base: unknown, theirs: unknown, ours: unknown): MergeOutcome {\n const conflicts: string[] = [];\n const merged = mergeAt(\"\", base, theirs, ours, conflicts);\n return { merged: merged === ABSENT ? undefined : merged, conflicts };\n}\n\nfunction same(a: Slot, b: Slot): boolean {\n if (a === ABSENT || b === ABSENT) return a === b;\n return isDeepStrictEqual(a, b);\n}\n\nfunction mergeAt(path: string, base: Slot, theirs: Slot, ours: Slot, conflicts: string[]): Slot {\n if (same(base, theirs)) return ours;\n if (same(base, ours) || same(theirs, ours)) return theirs;\n if (isPlainObject(base) && isPlainObject(theirs) && isPlainObject(ours))\n return mergeRecords(path, base, theirs, ours, conflicts);\n if (Array.isArray(base) && Array.isArray(theirs) && Array.isArray(ours)) {\n const keyed = [base, theirs, ours].map(byId);\n const [b, t, o] = keyed;\n if (b !== undefined && t !== undefined && o !== undefined)\n return mergeById(path, b, t, o, conflicts);\n }\n conflicts.push(path === \"\" ? \"(root)\" : path);\n return ours;\n}\n\n/** The value of `key` in `obj`, or {@link ABSENT}: a key holding `undefined` is no key in JSON. */\nfunction slotOf(obj: Record<string, unknown>, key: string): Slot {\n const value = ownValue(obj, key);\n return value === undefined ? ABSENT : value;\n}\n\nfunction mergeRecords(\n path: string,\n base: Record<string, unknown>,\n theirs: Record<string, unknown>,\n ours: Record<string, unknown>,\n conflicts: string[],\n): Record<string, unknown> {\n // Ours' key order, then the keys the new params add.\n const keys = [\n ...Object.keys(ours),\n ...Object.keys(theirs).filter((k) => !Object.hasOwn(ours, k)),\n ];\n const entries: [string, unknown][] = [];\n for (const key of keys) {\n const value = mergeAt(\n childPath(path, key),\n slotOf(base, key),\n slotOf(theirs, key),\n slotOf(ours, key),\n conflicts,\n );\n if (value !== ABSENT) entries.push([key, value]);\n }\n // `Object.fromEntries` defines own keys, so a key such as `__proto__` stays a key.\n return Object.fromEntries(entries);\n}\n\n/** An array of objects keyed by their `id`: ids in array order and the element of each. */\ntype Keyed = { order: string[]; ids: Map<string, unknown>; elements: Map<string, unknown> };\n\n/**\n * `xs` keyed by the `id` of its elements, or `undefined` when an element is not an object, has no\n * string or numeric `id`, or shares its id with another. The key tells `1` from `\"1\"`.\n */\nfunction byId(xs: unknown[]): Keyed | undefined {\n const keyed: Keyed = { order: [], ids: new Map(), elements: new Map() };\n for (const x of xs) {\n if (!isPlainObject(x)) return undefined;\n const id = ownValue(x, \"id\");\n if (typeof id !== \"string\" && typeof id !== \"number\") return undefined;\n const key = `${typeof id}:${id}`;\n if (keyed.elements.has(key)) return undefined;\n keyed.order.push(key);\n keyed.ids.set(key, id);\n keyed.elements.set(key, x);\n }\n return keyed;\n}\n\nfunction mergeById(\n path: string,\n base: Keyed,\n theirs: Keyed,\n ours: Keyed,\n conflicts: string[],\n): unknown[] {\n const result = new Map<string, unknown>();\n for (const key of new Set([...theirs.order, ...ours.order])) {\n const inTheirs = theirs.elements.has(key);\n // Dropped by the new params: the element goes, whatever ours holds in it.\n if (!inTheirs && base.elements.has(key)) continue;\n const id = theirs.ids.get(key) ?? ours.ids.get(key);\n const value = mergeAt(\n `${path}[id=${JSON.stringify(id)}]`,\n base.elements.get(key) ?? ABSENT,\n inTheirs ? theirs.elements.get(key) : ABSENT,\n ours.elements.get(key) ?? ABSENT,\n conflicts,\n );\n if (value !== ABSENT) result.set(key, value);\n }\n\n // Theirs' order; an element only ours has goes after the element before it in ours.\n const order = theirs.order.filter((key) => result.has(key));\n ours.order.forEach((key, i) => {\n if (!result.has(key) || order.includes(key)) return;\n const before = ours.order\n .slice(0, i)\n .reverse()\n .find((k) => order.includes(k));\n order.splice(before === undefined ? 0 : order.indexOf(before) + 1, 0, key);\n });\n return order.map((key) => result.get(key));\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
|
|
2
|
+
const require_types = require("./types.cjs");
|
|
3
|
+
const require_paging = require("./paging.cjs");
|
|
4
|
+
const require_files = require("./files.cjs");
|
|
5
|
+
let _milaboratories_pl_middle_layer = require("@milaboratories/pl-middle-layer");
|
|
6
|
+
let _milaboratories_pl_model_common = require("@milaboratories/pl-model-common");
|
|
7
|
+
let node_fs_promises = require("node:fs/promises");
|
|
8
|
+
let node_path = require("node:path");
|
|
9
|
+
node_path = require_runtime.__toESM(node_path, 1);
|
|
10
|
+
// src/tools/project-template.ts
|
|
11
|
+
/** The file a handle names, decoded by the drivers' own parsers. */
|
|
12
|
+
function fileOf(handle) {
|
|
13
|
+
try {
|
|
14
|
+
if ((0, _milaboratories_pl_model_common.isImportFileHandleUpload)(handle)) return { localPath: (0, _milaboratories_pl_middle_layer.parseUploadHandle)(handle).localPath };
|
|
15
|
+
if ((0, _milaboratories_pl_model_common.isImportFileHandleIndex)(handle)) {
|
|
16
|
+
const { storageId, path } = (0, _milaboratories_pl_middle_layer.parseIndexHandle)(handle);
|
|
17
|
+
return {
|
|
18
|
+
storage: storageId,
|
|
19
|
+
storagePath: path
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
} catch {}
|
|
23
|
+
return { error: "The handle does not parse." };
|
|
24
|
+
}
|
|
25
|
+
/** Every import file handle in the params of the exported blocks, in block order. */
|
|
26
|
+
function templateFileHandles(blocks) {
|
|
27
|
+
return blocks.flatMap((block) => require_files.importHandlesIn(block.params).map(({ path, handle }) => ({
|
|
28
|
+
blockId: block.id,
|
|
29
|
+
paramsPath: path,
|
|
30
|
+
handle,
|
|
31
|
+
...fileOf(handle)
|
|
32
|
+
})));
|
|
33
|
+
}
|
|
34
|
+
/** One line of a refusal: the block by label and id, and what stands in its way. */
|
|
35
|
+
function problemLine(problem) {
|
|
36
|
+
return `- ${JSON.stringify(problem.blockLabel)} (${problem.blockId}): ${problem.error}`;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* `export_project_template`: writes the project, as the `template-v1` YAML the application's
|
|
40
|
+
* "Export Project as Template…" writes, to `savePath`, a new file (one that exists is never
|
|
41
|
+
* overwritten), and lists a page of the import file handles its params hold. When any block
|
|
42
|
+
* cannot be written, nothing is written and the refusal names every such block and why. Each call
|
|
43
|
+
* exports anew; a call without `savePath` only lists the handles.
|
|
44
|
+
*/
|
|
45
|
+
async function exportProjectTemplate(deps, input) {
|
|
46
|
+
const { projectId, savePath } = input;
|
|
47
|
+
if (savePath !== void 0 && !node_path.isAbsolute(savePath)) return require_types.errorResult(`Not an absolute path: ${savePath}. Nothing was exported.`);
|
|
48
|
+
const entry = await deps.resolveProject(projectId);
|
|
49
|
+
const outcome = await deps.exportProjectAsTemplate(entry.id);
|
|
50
|
+
if (!outcome.ok) {
|
|
51
|
+
const n = outcome.problems.length;
|
|
52
|
+
return require_types.errorResult(`Nothing was exported: ${n} block${n === 1 ? "" : "s"} of project ${projectId} cannot be written to a template.\n${outcome.problems.map(problemLine).join("\n")}`, "Each line names a block and the reason. A block whose version cannot be written to a template, or that declares no kind, needs a newer version: update_block, then export again. A block that cannot give its params may need its data fixed (get_block_state).");
|
|
53
|
+
}
|
|
54
|
+
const { yaml } = outcome;
|
|
55
|
+
if (savePath !== void 0) try {
|
|
56
|
+
await (0, node_fs_promises.writeFile)(savePath, yaml, { flag: "wx" });
|
|
57
|
+
} catch (e) {
|
|
58
|
+
return require_types.errorResult(`Could not write the template: ${e instanceof Error ? e.message : String(e)}`, "Check that the folder exists and is writable and that no file exists at the path; a file is never overwritten.");
|
|
59
|
+
}
|
|
60
|
+
const handles = templateFileHandles(outcome.document.blocks);
|
|
61
|
+
const { items, total, ...paging } = require_paging.page(handles, input.offset, input.limit ?? 50);
|
|
62
|
+
return require_types.textResult({
|
|
63
|
+
...savePath !== void 0 ? {
|
|
64
|
+
path: savePath,
|
|
65
|
+
bytes: Buffer.byteLength(yaml, "utf8")
|
|
66
|
+
} : {},
|
|
67
|
+
fileHandlesTotal: total,
|
|
68
|
+
...paging,
|
|
69
|
+
fileHandles: items
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
exports.exportProjectTemplate = exportProjectTemplate;
|
|
73
|
+
exports.templateFileHandles = templateFileHandles;
|
|
74
|
+
|
|
75
|
+
//# sourceMappingURL=project-template.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"project-template.cjs","names":["isImportFileHandleUpload","parseUploadHandle","isImportFileHandleIndex","parseIndexHandle","importHandlesIn","path","errorResult","writeFile","page","textResult"],"sources":["../../src/tools/project-template.ts"],"sourcesContent":["import { writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport type {\n ProjectId,\n ProjectTemplateExportOutcome,\n TemplateExportProblem,\n} from \"@milaboratories/pl-middle-layer\";\nimport { parseIndexHandle, parseUploadHandle } from \"@milaboratories/pl-middle-layer\";\nimport {\n type ImportFileHandle,\n isImportFileHandleIndex,\n isImportFileHandleUpload,\n} from \"@milaboratories/pl-model-common\";\nimport { importHandlesIn } from \"./files\";\nimport { page } from \"./paging\";\nimport { errorResult, textResult } from \"./types\";\n\n/** What `export_project_template` uses of the middle layer and the server. */\nexport type ExportProjectTemplateDeps = {\n resolveProject: (projectId: ProjectId) => Promise<{ id: ProjectId }>;\n exportProjectAsTemplate: (projectId: ProjectId) => Promise<ProjectTemplateExportOutcome>;\n};\n\n/**\n * One import file handle the exported params hold: the block, where in its params, the handle as\n * the file has it, and the file it names. A handle names a file of the computer that made it\n * (`localPath`) or a file in a storage (`storage`, an id list_files takes, and `storagePath`).\n */\nexport type TemplateFileHandle = {\n blockId: string;\n /** Where in the block's params: `inputHandle`, `files[2].handle`. */\n paramsPath: string;\n handle: ImportFileHandle;\n} & ({ localPath: string } | { storage: string; storagePath: string } | { error: string });\n\n/** The file a handle names, decoded by the drivers' own parsers. */\nfunction fileOf(\n handle: ImportFileHandle,\n): { localPath: string } | { storage: string; storagePath: string } | { error: string } {\n try {\n if (isImportFileHandleUpload(handle)) return { localPath: parseUploadHandle(handle).localPath };\n if (isImportFileHandleIndex(handle)) {\n const { storageId, path } = parseIndexHandle(handle);\n return { storage: storageId, storagePath: path };\n }\n } catch {\n // reported below\n }\n return { error: \"The handle does not parse.\" };\n}\n\n/** Every import file handle in the params of the exported blocks, in block order. */\nexport function templateFileHandles(\n blocks: readonly { id: string; params: Record<string, unknown> }[],\n): TemplateFileHandle[] {\n return blocks.flatMap((block) =>\n importHandlesIn(block.params).map(({ path, handle }): TemplateFileHandle => ({\n blockId: block.id,\n paramsPath: path,\n handle,\n ...fileOf(handle),\n })),\n );\n}\n\n/** One line of a refusal: the block by label and id, and what stands in its way. */\nfunction problemLine(problem: TemplateExportProblem): string {\n return `- ${JSON.stringify(problem.blockLabel)} (${problem.blockId}): ${problem.error}`;\n}\n\n/** File handles one `export_project_template` answer lists by default. */\nexport const TEMPLATE_HANDLES_DEFAULT = 50;\n/** The most file handles one `export_project_template` answer lists. */\nexport const TEMPLATE_HANDLES_MAX = 100;\n\n/** Input of {@link exportProjectTemplate}. */\nexport type ExportProjectTemplateInput = {\n projectId: ProjectId;\n /** Absolute path of a new file to write the YAML to; left out, nothing is written. */\n savePath?: string;\n offset?: number;\n limit?: number;\n};\n\n/**\n * `export_project_template`: writes the project, as the `template-v1` YAML the application's\n * \"Export Project as Template…\" writes, to `savePath`, a new file (one that exists is never\n * overwritten), and lists a page of the import file handles its params hold. When any block\n * cannot be written, nothing is written and the refusal names every such block and why. Each call\n * exports anew; a call without `savePath` only lists the handles.\n */\nexport async function exportProjectTemplate(\n deps: ExportProjectTemplateDeps,\n input: ExportProjectTemplateInput,\n) {\n const { projectId, savePath } = input;\n if (savePath !== undefined && !path.isAbsolute(savePath))\n return errorResult(`Not an absolute path: ${savePath}. Nothing was exported.`);\n const entry = await deps.resolveProject(projectId);\n const outcome = await deps.exportProjectAsTemplate(entry.id);\n if (!outcome.ok) {\n const n = outcome.problems.length;\n return errorResult(\n `Nothing was exported: ${n} block${n === 1 ? \"\" : \"s\"} of project ${projectId} cannot be ` +\n `written to a template.\\n${outcome.problems.map(problemLine).join(\"\\n\")}`,\n \"Each line names a block and the reason. A block whose version cannot be written to a \" +\n \"template, or that declares no kind, needs a newer version: update_block, then export \" +\n \"again. A block that cannot give its params may need its data fixed (get_block_state).\",\n );\n }\n const { yaml } = outcome;\n if (savePath !== undefined) {\n try {\n await writeFile(savePath, yaml, { flag: \"wx\" });\n } catch (e: unknown) {\n return errorResult(\n `Could not write the template: ${e instanceof Error ? e.message : String(e)}`,\n \"Check that the folder exists and is writable and that no file exists at the path; a \" +\n \"file is never overwritten.\",\n );\n }\n }\n const handles = templateFileHandles(outcome.document.blocks);\n const { items, total, ...paging } = page(\n handles,\n input.offset,\n input.limit ?? TEMPLATE_HANDLES_DEFAULT,\n );\n return textResult({\n ...(savePath !== undefined ? { path: savePath, bytes: Buffer.byteLength(yaml, \"utf8\") } : {}),\n fileHandlesTotal: total,\n ...paging,\n fileHandles: items,\n });\n}\n"],"mappings":";;;;;;;;;;;AAoCA,SAAS,OACP,QACsF;CACtF,IAAI;EACF,KAAA,GAAIA,gCAAAA,yBAAAA,CAAyB,MAAM,GAAG,OAAO,EAAE,YAAA,GAAWC,gCAAAA,kBAAAA,CAAkB,MAAM,CAAC,CAAC,UAAU;EAC9F,KAAA,GAAIC,gCAAAA,wBAAAA,CAAwB,MAAM,GAAG;GACnC,MAAM,EAAE,WAAW,UAAA,GAASC,gCAAAA,iBAAAA,CAAiB,MAAM;GACnD,OAAO;IAAE,SAAS;IAAW,aAAa;GAAK;EACjD;CACF,QAAQ,CAER;CACA,OAAO,EAAE,OAAO,6BAA6B;AAC/C;;AAGA,SAAgB,oBACd,QACsB;CACtB,OAAO,OAAO,SAAS,UACrBC,cAAAA,gBAAgB,MAAM,MAAM,CAAC,CAAC,KAAK,EAAE,MAAM,cAAkC;EAC3E,SAAS,MAAM;EACf,YAAY;EACZ;EACA,GAAG,OAAO,MAAM;CAClB,EAAE,CACJ;AACF;;AAGA,SAAS,YAAY,SAAwC;CAC3D,OAAO,KAAK,KAAK,UAAU,QAAQ,UAAU,EAAE,IAAI,QAAQ,QAAQ,KAAK,QAAQ;AAClF;;;;;;;;AAuBA,eAAsB,sBACpB,MACA,OACA;CACA,MAAM,EAAE,WAAW,aAAa;CAChC,IAAI,aAAa,KAAA,KAAa,CAACC,UAAK,WAAW,QAAQ,GACrD,OAAOC,cAAAA,YAAY,yBAAyB,SAAS,wBAAwB;CAC/E,MAAM,QAAQ,MAAM,KAAK,eAAe,SAAS;CACjD,MAAM,UAAU,MAAM,KAAK,wBAAwB,MAAM,EAAE;CAC3D,IAAI,CAAC,QAAQ,IAAI;EACf,MAAM,IAAI,QAAQ,SAAS;EAC3B,OAAOA,cAAAA,YACL,yBAAyB,EAAE,QAAQ,MAAM,IAAI,KAAK,IAAI,cAAc,UAAU,qCACjD,QAAQ,SAAS,IAAI,WAAW,CAAC,CAAC,KAAK,IAAI,KACxE,iQAGF;CACF;CACA,MAAM,EAAE,SAAS;CACjB,IAAI,aAAa,KAAA,GACf,IAAI;EACF,OAAA,GAAMC,iBAAAA,UAAAA,CAAU,UAAU,MAAM,EAAE,MAAM,KAAK,CAAC;CAChD,SAAS,GAAY;EACnB,OAAOD,cAAAA,YACL,iCAAiC,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,KAC1E,gHAEF;CACF;CAEF,MAAM,UAAU,oBAAoB,QAAQ,SAAS,MAAM;CAC3D,MAAM,EAAE,OAAO,OAAO,GAAG,WAAWE,eAAAA,KAClC,SACA,MAAM,QACN,MAAM,SAAA,EACR;CACA,OAAOC,cAAAA,WAAW;EAChB,GAAI,aAAa,KAAA,IAAY;GAAE,MAAM;GAAU,OAAO,OAAO,WAAW,MAAM,MAAM;EAAE,IAAI,CAAC;EAC3F,kBAAkB;EAClB,GAAG;EACH,aAAa;CACf,CAAC;AACH"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { errorResult, textResult } from "./types.js";
|
|
2
|
+
import { page } from "./paging.js";
|
|
3
|
+
import { importHandlesIn } from "./files.js";
|
|
4
|
+
import { parseIndexHandle, parseUploadHandle } from "@milaboratories/pl-middle-layer";
|
|
5
|
+
import { isImportFileHandleIndex, isImportFileHandleUpload } from "@milaboratories/pl-model-common";
|
|
6
|
+
import { writeFile } from "node:fs/promises";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
// src/tools/project-template.ts
|
|
9
|
+
/** The file a handle names, decoded by the drivers' own parsers. */
|
|
10
|
+
function fileOf(handle) {
|
|
11
|
+
try {
|
|
12
|
+
if (isImportFileHandleUpload(handle)) return { localPath: parseUploadHandle(handle).localPath };
|
|
13
|
+
if (isImportFileHandleIndex(handle)) {
|
|
14
|
+
const { storageId, path } = parseIndexHandle(handle);
|
|
15
|
+
return {
|
|
16
|
+
storage: storageId,
|
|
17
|
+
storagePath: path
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
} catch {}
|
|
21
|
+
return { error: "The handle does not parse." };
|
|
22
|
+
}
|
|
23
|
+
/** Every import file handle in the params of the exported blocks, in block order. */
|
|
24
|
+
function templateFileHandles(blocks) {
|
|
25
|
+
return blocks.flatMap((block) => importHandlesIn(block.params).map(({ path, handle }) => ({
|
|
26
|
+
blockId: block.id,
|
|
27
|
+
paramsPath: path,
|
|
28
|
+
handle,
|
|
29
|
+
...fileOf(handle)
|
|
30
|
+
})));
|
|
31
|
+
}
|
|
32
|
+
/** One line of a refusal: the block by label and id, and what stands in its way. */
|
|
33
|
+
function problemLine(problem) {
|
|
34
|
+
return `- ${JSON.stringify(problem.blockLabel)} (${problem.blockId}): ${problem.error}`;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* `export_project_template`: writes the project, as the `template-v1` YAML the application's
|
|
38
|
+
* "Export Project as Template…" writes, to `savePath`, a new file (one that exists is never
|
|
39
|
+
* overwritten), and lists a page of the import file handles its params hold. When any block
|
|
40
|
+
* cannot be written, nothing is written and the refusal names every such block and why. Each call
|
|
41
|
+
* exports anew; a call without `savePath` only lists the handles.
|
|
42
|
+
*/
|
|
43
|
+
async function exportProjectTemplate(deps, input) {
|
|
44
|
+
const { projectId, savePath } = input;
|
|
45
|
+
if (savePath !== void 0 && !path.isAbsolute(savePath)) return errorResult(`Not an absolute path: ${savePath}. Nothing was exported.`);
|
|
46
|
+
const entry = await deps.resolveProject(projectId);
|
|
47
|
+
const outcome = await deps.exportProjectAsTemplate(entry.id);
|
|
48
|
+
if (!outcome.ok) {
|
|
49
|
+
const n = outcome.problems.length;
|
|
50
|
+
return errorResult(`Nothing was exported: ${n} block${n === 1 ? "" : "s"} of project ${projectId} cannot be written to a template.\n${outcome.problems.map(problemLine).join("\n")}`, "Each line names a block and the reason. A block whose version cannot be written to a template, or that declares no kind, needs a newer version: update_block, then export again. A block that cannot give its params may need its data fixed (get_block_state).");
|
|
51
|
+
}
|
|
52
|
+
const { yaml } = outcome;
|
|
53
|
+
if (savePath !== void 0) try {
|
|
54
|
+
await writeFile(savePath, yaml, { flag: "wx" });
|
|
55
|
+
} catch (e) {
|
|
56
|
+
return errorResult(`Could not write the template: ${e instanceof Error ? e.message : String(e)}`, "Check that the folder exists and is writable and that no file exists at the path; a file is never overwritten.");
|
|
57
|
+
}
|
|
58
|
+
const handles = templateFileHandles(outcome.document.blocks);
|
|
59
|
+
const { items, total, ...paging } = page(handles, input.offset, input.limit ?? 50);
|
|
60
|
+
return textResult({
|
|
61
|
+
...savePath !== void 0 ? {
|
|
62
|
+
path: savePath,
|
|
63
|
+
bytes: Buffer.byteLength(yaml, "utf8")
|
|
64
|
+
} : {},
|
|
65
|
+
fileHandlesTotal: total,
|
|
66
|
+
...paging,
|
|
67
|
+
fileHandles: items
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
export { exportProjectTemplate, templateFileHandles };
|
|
71
|
+
|
|
72
|
+
//# sourceMappingURL=project-template.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"project-template.js","names":[],"sources":["../../src/tools/project-template.ts"],"sourcesContent":["import { writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport type {\n ProjectId,\n ProjectTemplateExportOutcome,\n TemplateExportProblem,\n} from \"@milaboratories/pl-middle-layer\";\nimport { parseIndexHandle, parseUploadHandle } from \"@milaboratories/pl-middle-layer\";\nimport {\n type ImportFileHandle,\n isImportFileHandleIndex,\n isImportFileHandleUpload,\n} from \"@milaboratories/pl-model-common\";\nimport { importHandlesIn } from \"./files\";\nimport { page } from \"./paging\";\nimport { errorResult, textResult } from \"./types\";\n\n/** What `export_project_template` uses of the middle layer and the server. */\nexport type ExportProjectTemplateDeps = {\n resolveProject: (projectId: ProjectId) => Promise<{ id: ProjectId }>;\n exportProjectAsTemplate: (projectId: ProjectId) => Promise<ProjectTemplateExportOutcome>;\n};\n\n/**\n * One import file handle the exported params hold: the block, where in its params, the handle as\n * the file has it, and the file it names. A handle names a file of the computer that made it\n * (`localPath`) or a file in a storage (`storage`, an id list_files takes, and `storagePath`).\n */\nexport type TemplateFileHandle = {\n blockId: string;\n /** Where in the block's params: `inputHandle`, `files[2].handle`. */\n paramsPath: string;\n handle: ImportFileHandle;\n} & ({ localPath: string } | { storage: string; storagePath: string } | { error: string });\n\n/** The file a handle names, decoded by the drivers' own parsers. */\nfunction fileOf(\n handle: ImportFileHandle,\n): { localPath: string } | { storage: string; storagePath: string } | { error: string } {\n try {\n if (isImportFileHandleUpload(handle)) return { localPath: parseUploadHandle(handle).localPath };\n if (isImportFileHandleIndex(handle)) {\n const { storageId, path } = parseIndexHandle(handle);\n return { storage: storageId, storagePath: path };\n }\n } catch {\n // reported below\n }\n return { error: \"The handle does not parse.\" };\n}\n\n/** Every import file handle in the params of the exported blocks, in block order. */\nexport function templateFileHandles(\n blocks: readonly { id: string; params: Record<string, unknown> }[],\n): TemplateFileHandle[] {\n return blocks.flatMap((block) =>\n importHandlesIn(block.params).map(({ path, handle }): TemplateFileHandle => ({\n blockId: block.id,\n paramsPath: path,\n handle,\n ...fileOf(handle),\n })),\n );\n}\n\n/** One line of a refusal: the block by label and id, and what stands in its way. */\nfunction problemLine(problem: TemplateExportProblem): string {\n return `- ${JSON.stringify(problem.blockLabel)} (${problem.blockId}): ${problem.error}`;\n}\n\n/** File handles one `export_project_template` answer lists by default. */\nexport const TEMPLATE_HANDLES_DEFAULT = 50;\n/** The most file handles one `export_project_template` answer lists. */\nexport const TEMPLATE_HANDLES_MAX = 100;\n\n/** Input of {@link exportProjectTemplate}. */\nexport type ExportProjectTemplateInput = {\n projectId: ProjectId;\n /** Absolute path of a new file to write the YAML to; left out, nothing is written. */\n savePath?: string;\n offset?: number;\n limit?: number;\n};\n\n/**\n * `export_project_template`: writes the project, as the `template-v1` YAML the application's\n * \"Export Project as Template…\" writes, to `savePath`, a new file (one that exists is never\n * overwritten), and lists a page of the import file handles its params hold. When any block\n * cannot be written, nothing is written and the refusal names every such block and why. Each call\n * exports anew; a call without `savePath` only lists the handles.\n */\nexport async function exportProjectTemplate(\n deps: ExportProjectTemplateDeps,\n input: ExportProjectTemplateInput,\n) {\n const { projectId, savePath } = input;\n if (savePath !== undefined && !path.isAbsolute(savePath))\n return errorResult(`Not an absolute path: ${savePath}. Nothing was exported.`);\n const entry = await deps.resolveProject(projectId);\n const outcome = await deps.exportProjectAsTemplate(entry.id);\n if (!outcome.ok) {\n const n = outcome.problems.length;\n return errorResult(\n `Nothing was exported: ${n} block${n === 1 ? \"\" : \"s\"} of project ${projectId} cannot be ` +\n `written to a template.\\n${outcome.problems.map(problemLine).join(\"\\n\")}`,\n \"Each line names a block and the reason. A block whose version cannot be written to a \" +\n \"template, or that declares no kind, needs a newer version: update_block, then export \" +\n \"again. A block that cannot give its params may need its data fixed (get_block_state).\",\n );\n }\n const { yaml } = outcome;\n if (savePath !== undefined) {\n try {\n await writeFile(savePath, yaml, { flag: \"wx\" });\n } catch (e: unknown) {\n return errorResult(\n `Could not write the template: ${e instanceof Error ? e.message : String(e)}`,\n \"Check that the folder exists and is writable and that no file exists at the path; a \" +\n \"file is never overwritten.\",\n );\n }\n }\n const handles = templateFileHandles(outcome.document.blocks);\n const { items, total, ...paging } = page(\n handles,\n input.offset,\n input.limit ?? TEMPLATE_HANDLES_DEFAULT,\n );\n return textResult({\n ...(savePath !== undefined ? { path: savePath, bytes: Buffer.byteLength(yaml, \"utf8\") } : {}),\n fileHandlesTotal: total,\n ...paging,\n fileHandles: items,\n });\n}\n"],"mappings":";;;;;;;;;AAoCA,SAAS,OACP,QACsF;CACtF,IAAI;EACF,IAAI,yBAAyB,MAAM,GAAG,OAAO,EAAE,WAAW,kBAAkB,MAAM,CAAC,CAAC,UAAU;EAC9F,IAAI,wBAAwB,MAAM,GAAG;GACnC,MAAM,EAAE,WAAW,SAAS,iBAAiB,MAAM;GACnD,OAAO;IAAE,SAAS;IAAW,aAAa;GAAK;EACjD;CACF,QAAQ,CAER;CACA,OAAO,EAAE,OAAO,6BAA6B;AAC/C;;AAGA,SAAgB,oBACd,QACsB;CACtB,OAAO,OAAO,SAAS,UACrB,gBAAgB,MAAM,MAAM,CAAC,CAAC,KAAK,EAAE,MAAM,cAAkC;EAC3E,SAAS,MAAM;EACf,YAAY;EACZ;EACA,GAAG,OAAO,MAAM;CAClB,EAAE,CACJ;AACF;;AAGA,SAAS,YAAY,SAAwC;CAC3D,OAAO,KAAK,KAAK,UAAU,QAAQ,UAAU,EAAE,IAAI,QAAQ,QAAQ,KAAK,QAAQ;AAClF;;;;;;;;AAuBA,eAAsB,sBACpB,MACA,OACA;CACA,MAAM,EAAE,WAAW,aAAa;CAChC,IAAI,aAAa,KAAA,KAAa,CAAC,KAAK,WAAW,QAAQ,GACrD,OAAO,YAAY,yBAAyB,SAAS,wBAAwB;CAC/E,MAAM,QAAQ,MAAM,KAAK,eAAe,SAAS;CACjD,MAAM,UAAU,MAAM,KAAK,wBAAwB,MAAM,EAAE;CAC3D,IAAI,CAAC,QAAQ,IAAI;EACf,MAAM,IAAI,QAAQ,SAAS;EAC3B,OAAO,YACL,yBAAyB,EAAE,QAAQ,MAAM,IAAI,KAAK,IAAI,cAAc,UAAU,qCACjD,QAAQ,SAAS,IAAI,WAAW,CAAC,CAAC,KAAK,IAAI,KACxE,iQAGF;CACF;CACA,MAAM,EAAE,SAAS;CACjB,IAAI,aAAa,KAAA,GACf,IAAI;EACF,MAAM,UAAU,UAAU,MAAM,EAAE,MAAM,KAAK,CAAC;CAChD,SAAS,GAAY;EACnB,OAAO,YACL,iCAAiC,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,KAC1E,gHAEF;CACF;CAEF,MAAM,UAAU,oBAAoB,QAAQ,SAAS,MAAM;CAC3D,MAAM,EAAE,OAAO,OAAO,GAAG,WAAW,KAClC,SACA,MAAM,QACN,MAAM,SAAA,EACR;CACA,OAAO,WAAW;EAChB,GAAI,aAAa,KAAA,IAAY;GAAE,MAAM;GAAU,OAAO,OAAO,WAAW,MAAM,MAAM;EAAE,IAAI,CAAC;EAC3F,kBAAkB;EAClB,GAAG;EACH,aAAa;CACf,CAAC;AACH"}
|
package/dist/tools/projects.cjs
CHANGED
|
@@ -1,23 +1,54 @@
|
|
|
1
1
|
const require_types = require("./types.cjs");
|
|
2
2
|
const require_ids = require("./ids.cjs");
|
|
3
|
+
const require_paging = require("./paging.cjs");
|
|
4
|
+
const require_project_template = require("./project-template.cjs");
|
|
3
5
|
let _milaboratories_pl_middle_layer = require("@milaboratories/pl-middle-layer");
|
|
4
6
|
let zod = require("zod");
|
|
5
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Deletes a project, unless it is in use: by a holder that is not this server (an agent of
|
|
9
|
+
* another server, the user in the application), or by another call of this server still running
|
|
10
|
+
* on it (an agent of this server). This server's kept hold does not count: it ends with the
|
|
11
|
+
* delete. The check of this server's calls is made inside the middle layer's check, where no
|
|
12
|
+
* acquire comes in between, and once before it for a call that has not got its hold yet.
|
|
13
|
+
*/
|
|
14
|
+
async function deleteProject(deps, projectId) {
|
|
15
|
+
const entry = await deps.resolveProject(projectId);
|
|
16
|
+
const inUse = () => require_types.errorResult(`Project ${projectId} was not deleted: it is still in use by another agent or by the user in the application.`);
|
|
17
|
+
if (deps.callsInFlight(entry.id) > 0) return inUse();
|
|
18
|
+
try {
|
|
19
|
+
await deps.deleteProject(entry.id, { refuseIfHeldBy: (holder) => holder !== deps.projectHolder || deps.callsInFlight(entry.id) > 0 });
|
|
20
|
+
} catch (e) {
|
|
21
|
+
if (!(0, _milaboratories_pl_middle_layer.isProjectInUseError)(e)) throw e;
|
|
22
|
+
return inUse();
|
|
23
|
+
}
|
|
24
|
+
await deps.onDeleted?.(projectId);
|
|
25
|
+
return require_types.textResult({ ok: true });
|
|
26
|
+
}
|
|
6
27
|
function registerProjectTools(server, ctx) {
|
|
7
28
|
server.registerTool("list_projects", {
|
|
8
29
|
title: "List Projects",
|
|
9
30
|
annotations: require_types.hints.read,
|
|
10
|
-
description:
|
|
11
|
-
|
|
31
|
+
description: `List projects with their IDs, labels, and creation and modification times, 100 at a time. Result: \`{ projects, total, offset, hasMore }\`; page with \`offset\` and \`limit\`, or narrow with \`nameContains\`.`,
|
|
32
|
+
inputSchema: zod.z.object({
|
|
33
|
+
...require_paging.pagingArgs("projects", 100, 500),
|
|
34
|
+
nameContains: zod.z.string().optional().describe("Only projects whose label contains this text (case-insensitive).")
|
|
35
|
+
})
|
|
36
|
+
}, async ({ limit, offset, nameContains }) => {
|
|
12
37
|
const ml = ctx.requireMl();
|
|
13
38
|
await ml.projectList.refreshState();
|
|
14
39
|
const projects = await ml.projectList.awaitStableValue();
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
40
|
+
const needle = nameContains?.toLowerCase();
|
|
41
|
+
const matching = needle === void 0 ? projects : projects.filter((p) => p.meta.label.toLowerCase().includes(needle));
|
|
42
|
+
const { items, ...paging } = require_paging.page(matching, offset, limit ?? 100);
|
|
43
|
+
return require_types.textResult({
|
|
44
|
+
projects: items.map((p) => ({
|
|
45
|
+
projectId: p.id,
|
|
46
|
+
label: p.meta.label,
|
|
47
|
+
created: p.created.toISOString(),
|
|
48
|
+
lastModified: p.lastModified.toISOString()
|
|
49
|
+
})),
|
|
50
|
+
...paging
|
|
51
|
+
}, { hint: "Ask for fewer projects: a smaller `limit` with `offset` to page, or `nameContains` to narrow by label." });
|
|
21
52
|
});
|
|
22
53
|
server.registerTool("create_project", {
|
|
23
54
|
title: "Create Project",
|
|
@@ -32,20 +63,36 @@ function registerProjectTools(server, ctx) {
|
|
|
32
63
|
server.registerTool("delete_project", {
|
|
33
64
|
title: "Delete Project",
|
|
34
65
|
annotations: require_types.hints.destructive,
|
|
35
|
-
description: "Delete a project permanently, with all its blocks and results. Refused while the project is in use by another agent or by the user in the application.",
|
|
66
|
+
description: "Delete a project permanently, with all its blocks and results. Refused while the project is in use by another agent (another call working on it, through this server or another) or by the user in the application.",
|
|
36
67
|
inputSchema: zod.z.object({ projectId: require_ids.projectIdInput.describe("Project ID") })
|
|
37
68
|
}, async ({ projectId }) => {
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
69
|
+
const ml = ctx.requireMl();
|
|
70
|
+
return await deleteProject({
|
|
71
|
+
resolveProject: (id) => ctx.resolveProject(id),
|
|
72
|
+
deleteProject: (id, ops) => ml.deleteProject(id, ops),
|
|
73
|
+
projectHolder: ctx.projectHolder,
|
|
74
|
+
callsInFlight: (id) => ctx.callsInFlight(id),
|
|
75
|
+
onDeleted: ctx.callbacks.onProjectDeleted
|
|
76
|
+
}, projectId);
|
|
77
|
+
});
|
|
78
|
+
server.registerTool("export_project_template", {
|
|
79
|
+
title: "Export Project Template",
|
|
80
|
+
annotations: require_types.hints.additive,
|
|
81
|
+
description: "Export a project as a template file, to hand it over or reproduce it elsewhere: writes the `template-v1` YAML the application's Export Project as Template… writes, unchanged, to `savePath`, a new file (an existing one is never overwritten), so the application's import reads it. All or nothing: when any block cannot be written, nothing is written and the error names every such block (id, label, reason). read_file reads the file.\n\nReturns `{ path, bytes, fileHandlesTotal, offset, hasMore, fileHandles }`: a page of the file handles the params hold, each with `blockId`, `paramsPath`, `handle`, and the file it names (`localPath`, or `storage` and `storagePath`). Page on without `savePath`. Handles work only on the desktop that made them; on another, replace each with a handle of the file there (get_file_handles).",
|
|
82
|
+
inputSchema: zod.z.object({
|
|
83
|
+
projectId: require_ids.projectIdInput.describe("Project ID"),
|
|
84
|
+
savePath: zod.z.string().optional().describe("Absolute path of the new file to write. Omit to list the file handles only."),
|
|
85
|
+
...require_paging.pagingArgs("file handles", 50, 100)
|
|
86
|
+
})
|
|
87
|
+
}, async (input) => {
|
|
88
|
+
const ml = ctx.requireMl();
|
|
89
|
+
return await require_project_template.exportProjectTemplate({
|
|
90
|
+
resolveProject: (id) => ctx.resolveProject(id),
|
|
91
|
+
exportProjectAsTemplate: (id) => ml.exportProjectAsTemplate(id)
|
|
92
|
+
}, input);
|
|
47
93
|
});
|
|
48
94
|
}
|
|
95
|
+
exports.deleteProject = deleteProject;
|
|
49
96
|
exports.registerProjectTools = registerProjectTools;
|
|
50
97
|
|
|
51
98
|
//# sourceMappingURL=projects.cjs.map
|