@milaboratories/pl-mcp-server 53.1.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.
Files changed (208) hide show
  1. package/README.md +30 -37
  2. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  3. package/dist/agent-tables.cjs +116 -0
  4. package/dist/agent-tables.cjs.map +1 -0
  5. package/dist/agent-tables.js +115 -0
  6. package/dist/agent-tables.js.map +1 -0
  7. package/dist/instructions.cjs +16 -12
  8. package/dist/instructions.cjs.map +1 -1
  9. package/dist/instructions.js +16 -12
  10. package/dist/instructions.js.map +1 -1
  11. package/dist/package.cjs +1 -1
  12. package/dist/package.js +1 -1
  13. package/dist/project-holds.cjs +122 -0
  14. package/dist/project-holds.cjs.map +1 -0
  15. package/dist/project-holds.js +122 -0
  16. package/dist/project-holds.js.map +1 -0
  17. package/dist/project-list.cjs +16 -0
  18. package/dist/project-list.cjs.map +1 -0
  19. package/dist/project-list.js +16 -0
  20. package/dist/project-list.js.map +1 -0
  21. package/dist/server-log.cjs +48 -18
  22. package/dist/server-log.cjs.map +1 -1
  23. package/dist/server-log.js +48 -19
  24. package/dist/server-log.js.map +1 -1
  25. package/dist/server.cjs +71 -18
  26. package/dist/server.cjs.map +1 -1
  27. package/dist/server.d.ts +37 -24
  28. package/dist/server.d.ts.map +1 -1
  29. package/dist/server.js +71 -19
  30. package/dist/server.js.map +1 -1
  31. package/dist/tools/agent-tables.cjs +424 -0
  32. package/dist/tools/agent-tables.cjs.map +1 -0
  33. package/dist/tools/agent-tables.js +417 -0
  34. package/dist/tools/agent-tables.js.map +1 -0
  35. package/dist/tools/await.cjs +216 -72
  36. package/dist/tools/await.cjs.map +1 -1
  37. package/dist/tools/await.js +212 -74
  38. package/dist/tools/await.js.map +1 -1
  39. package/dist/tools/block-action-context.cjs +14 -9
  40. package/dist/tools/block-action-context.cjs.map +1 -1
  41. package/dist/tools/block-action-context.js +14 -9
  42. package/dist/tools/block-action-context.js.map +1 -1
  43. package/dist/tools/block-api.cjs +17 -2
  44. package/dist/tools/block-api.cjs.map +1 -1
  45. package/dist/tools/block-api.js +17 -3
  46. package/dist/tools/block-api.js.map +1 -1
  47. package/dist/tools/block-params.cjs +275 -6
  48. package/dist/tools/block-params.cjs.map +1 -1
  49. package/dist/tools/block-params.js +273 -8
  50. package/dist/tools/block-params.js.map +1 -1
  51. package/dist/tools/block-state.cjs +343 -57
  52. package/dist/tools/block-state.cjs.map +1 -1
  53. package/dist/tools/block-state.js +337 -61
  54. package/dist/tools/block-state.js.map +1 -1
  55. package/dist/tools/block-storage.cjs +153 -0
  56. package/dist/tools/block-storage.cjs.map +1 -0
  57. package/dist/tools/block-storage.js +147 -0
  58. package/dist/tools/block-storage.js.map +1 -0
  59. package/dist/tools/block-updates.cjs +405 -0
  60. package/dist/tools/block-updates.cjs.map +1 -0
  61. package/dist/tools/block-updates.js +397 -0
  62. package/dist/tools/block-updates.js.map +1 -0
  63. package/dist/tools/blocks.cjs +199 -76
  64. package/dist/tools/blocks.cjs.map +1 -1
  65. package/dist/tools/blocks.js +193 -76
  66. package/dist/tools/blocks.js.map +1 -1
  67. package/dist/tools/data-query.cjs +470 -101
  68. package/dist/tools/data-query.cjs.map +1 -1
  69. package/dist/tools/data-query.js +465 -106
  70. package/dist/tools/data-query.js.map +1 -1
  71. package/dist/tools/errors.cjs +21 -0
  72. package/dist/tools/errors.cjs.map +1 -0
  73. package/dist/tools/errors.js +20 -0
  74. package/dist/tools/errors.js.map +1 -0
  75. package/dist/tools/files.cjs +643 -0
  76. package/dist/tools/files.cjs.map +1 -0
  77. package/dist/tools/files.js +613 -0
  78. package/dist/tools/files.js.map +1 -0
  79. package/dist/tools/ids.cjs +72 -0
  80. package/dist/tools/ids.cjs.map +1 -1
  81. package/dist/tools/ids.js +63 -2
  82. package/dist/tools/ids.js.map +1 -1
  83. package/dist/tools/imports.cjs +195 -0
  84. package/dist/tools/imports.cjs.map +1 -0
  85. package/dist/tools/imports.js +186 -0
  86. package/dist/tools/imports.js.map +1 -0
  87. package/dist/tools/logs.cjs +111 -30
  88. package/dist/tools/logs.cjs.map +1 -1
  89. package/dist/tools/logs.js +108 -31
  90. package/dist/tools/logs.js.map +1 -1
  91. package/dist/tools/paging.cjs +27 -0
  92. package/dist/tools/paging.cjs.map +1 -0
  93. package/dist/tools/paging.js +26 -0
  94. package/dist/tools/paging.js.map +1 -0
  95. package/dist/tools/params-merge.cjs +106 -0
  96. package/dist/tools/params-merge.cjs.map +1 -0
  97. package/dist/tools/params-merge.js +106 -0
  98. package/dist/tools/params-merge.js.map +1 -0
  99. package/dist/tools/project-template.cjs +75 -0
  100. package/dist/tools/project-template.cjs.map +1 -0
  101. package/dist/tools/project-template.js +72 -0
  102. package/dist/tools/project-template.js.map +1 -0
  103. package/dist/tools/projects.cjs +68 -38
  104. package/dist/tools/projects.cjs.map +1 -1
  105. package/dist/tools/projects.js +69 -40
  106. package/dist/tools/projects.js.map +1 -1
  107. package/dist/tools/readiness.cjs +104 -0
  108. package/dist/tools/readiness.cjs.map +1 -0
  109. package/dist/tools/readiness.js +99 -0
  110. package/dist/tools/readiness.js.map +1 -0
  111. package/dist/tools/result-pool.cjs +260 -0
  112. package/dist/tools/result-pool.cjs.map +1 -0
  113. package/dist/tools/result-pool.js +252 -0
  114. package/dist/tools/result-pool.js.map +1 -0
  115. package/dist/tools/sandbox.cjs +112 -14
  116. package/dist/tools/sandbox.cjs.map +1 -1
  117. package/dist/tools/sandbox.js +110 -15
  118. package/dist/tools/sandbox.js.map +1 -1
  119. package/dist/tools/sdk-types.cjs +24 -0
  120. package/dist/tools/sdk-types.cjs.map +1 -0
  121. package/dist/tools/sdk-types.js +24 -0
  122. package/dist/tools/sdk-types.js.map +1 -0
  123. package/dist/tools/settle.cjs +155 -0
  124. package/dist/tools/settle.cjs.map +1 -0
  125. package/dist/tools/settle.js +148 -0
  126. package/dist/tools/settle.js.map +1 -0
  127. package/dist/tools/tokens.cjs +49 -8
  128. package/dist/tools/tokens.cjs.map +1 -1
  129. package/dist/tools/tokens.js +45 -9
  130. package/dist/tools/tokens.js.map +1 -1
  131. package/dist/tools/types.cjs +62 -11
  132. package/dist/tools/types.cjs.map +1 -1
  133. package/dist/tools/types.js +60 -12
  134. package/dist/tools/types.js.map +1 -1
  135. package/dist/tools/value-outline.cjs +119 -0
  136. package/dist/tools/value-outline.cjs.map +1 -0
  137. package/dist/tools/value-outline.js +117 -0
  138. package/dist/tools/value-outline.js.map +1 -0
  139. package/package.json +9 -8
  140. package/src/agent-tables.test.ts +246 -0
  141. package/src/agent-tables.ts +145 -0
  142. package/src/instructions.ts +16 -12
  143. package/src/project-holds.test.ts +362 -0
  144. package/src/project-holds.ts +207 -0
  145. package/src/project-list.test.ts +38 -0
  146. package/src/project-list.ts +25 -0
  147. package/src/server-log.test.ts +71 -6
  148. package/src/server-log.ts +58 -27
  149. package/src/server.logging.test.ts +46 -51
  150. package/src/server.test.ts +166 -22
  151. package/src/server.ts +97 -37
  152. package/src/tools/agent-tables.test.ts +650 -0
  153. package/src/tools/agent-tables.ts +673 -0
  154. package/src/tools/await.test.ts +287 -0
  155. package/src/tools/await.ts +393 -122
  156. package/src/tools/block-action-context.ts +17 -13
  157. package/src/tools/block-api.ts +19 -4
  158. package/src/tools/block-params.test.ts +828 -0
  159. package/src/tools/block-params.ts +626 -10
  160. package/src/tools/block-state.test.ts +480 -0
  161. package/src/tools/block-state.ts +678 -83
  162. package/src/tools/block-storage.test.ts +270 -0
  163. package/src/tools/block-storage.ts +195 -0
  164. package/src/tools/block-updates.test.ts +605 -0
  165. package/src/tools/block-updates.ts +751 -0
  166. package/src/tools/blocks.test.ts +169 -22
  167. package/src/tools/blocks.ts +354 -113
  168. package/src/tools/data-query.test.ts +641 -0
  169. package/src/tools/data-query.ts +839 -145
  170. package/src/tools/errors.test.ts +33 -0
  171. package/src/tools/errors.ts +23 -0
  172. package/src/tools/files.test.ts +842 -0
  173. package/src/tools/files.ts +990 -0
  174. package/src/tools/ids.test.ts +87 -0
  175. package/src/tools/ids.ts +89 -1
  176. package/src/tools/imports.ts +304 -0
  177. package/src/tools/logs.test.ts +70 -0
  178. package/src/tools/logs.ts +154 -44
  179. package/src/tools/paging.test.ts +39 -0
  180. package/src/tools/paging.ts +39 -0
  181. package/src/tools/params-merge.test.ts +274 -0
  182. package/src/tools/params-merge.ts +149 -0
  183. package/src/tools/project-template.test.ts +230 -0
  184. package/src/tools/project-template.ts +135 -0
  185. package/src/tools/projects.test.ts +122 -0
  186. package/src/tools/projects.ts +136 -48
  187. package/src/tools/readiness.test.ts +195 -0
  188. package/src/tools/readiness.ts +189 -0
  189. package/src/tools/result-pool.test.ts +377 -0
  190. package/src/tools/result-pool.ts +483 -0
  191. package/src/tools/sandbox.test.ts +128 -10
  192. package/src/tools/sandbox.ts +132 -18
  193. package/src/tools/sdk-types.ts +54 -0
  194. package/src/tools/settle.test.ts +340 -0
  195. package/src/tools/settle.ts +312 -0
  196. package/src/tools/tokens.ts +74 -9
  197. package/src/tools/types.ts +84 -12
  198. package/src/tools/value-outline.ts +143 -0
  199. package/dist/tools/screenshot.cjs +0 -44
  200. package/dist/tools/screenshot.cjs.map +0 -1
  201. package/dist/tools/screenshot.js +0 -44
  202. package/dist/tools/screenshot.js.map +0 -1
  203. package/dist/tools/ui-interaction.cjs +0 -140
  204. package/dist/tools/ui-interaction.cjs.map +0 -1
  205. package/dist/tools/ui-interaction.js +0 -140
  206. package/dist/tools/ui-interaction.js.map +0 -1
  207. package/src/tools/screenshot.ts +0 -61
  208. package/src/tools/ui-interaction.ts +0 -184
@@ -1 +1 @@
1
- {"version":3,"file":"logs.js","names":[],"sources":["../../src/tools/logs.ts"],"sourcesContent":["import { isAnyLogHandle } from \"@milaboratories/pl-model-common\";\nimport type { AnyLogHandle } from \"@milaboratories/pl-model-common\";\nimport { z } from \"zod\";\nimport { projectIdInput, blockIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { errorResult, hints, textResult } from \"./types\";\n\nexport function registerLogTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_logs\",\n {\n title: \"Get Block Logs\",\n annotations: hints.read,\n description:\n \"Read execution logs for a block. Extracts log handles from block outputs and reads log content. Returns logs keyed by sample/run ID.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n lines: z.number().optional().default(100).describe(\"Number of lines per log (default 100)\"),\n sampleId: z\n .string()\n .optional()\n .describe(\"Specific sample/key to read logs for (reads all if omitted)\"),\n }),\n },\n async ({ projectId, blockId, lines, sampleId }) => {\n const project = await ctx.getOpenedProject(projectId);\n const state = await project.getBlockState(blockId).getValue();\n if (!state.outputs)\n return errorResult(\n \"Block has no outputs yet.\",\n \"The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.\",\n );\n\n // Scan all outputs for log handles (log+ready:// or log+live://)\n const outputs = state.outputs as Record<\n string,\n { ok?: boolean; value?: { data?: { key: string[]; value: unknown }[] } }\n >;\n const logEntries: { outputKey: string; key: string[]; handle: AnyLogHandle }[] = [];\n for (const [outputKey, output] of Object.entries(outputs)) {\n if (!output?.ok || !output.value?.data) continue;\n for (const entry of output.value.data) {\n if (isAnyLogHandle(entry.value)) {\n logEntries.push({ outputKey, key: entry.key, handle: entry.value });\n }\n }\n }\n\n if (logEntries.length === 0) {\n return errorResult(\n \"No log handles found in block outputs.\",\n \"This block may not produce logs, or it hasn't run yet. Use get_block_outputs to inspect available output types.\",\n );\n }\n\n const logDriver = ctx.requireMl().driverKit.logDriver;\n const results: Record<string, string> = {};\n\n for (const entry of logEntries) {\n const key = entry.key.join(\"/\");\n if (sampleId && !entry.key.includes(sampleId)) continue;\n try {\n const response = await logDriver.lastLines(entry.handle, lines);\n if (response.shouldUpdateHandle) {\n results[key] = \"[log handle stale — block may still be running, retry later]\";\n } else {\n results[key] = new TextDecoder().decode(response.data);\n }\n } catch (err) {\n results[key] = `Error reading log: ${err}`;\n }\n }\n\n return textResult(results);\n },\n );\n\n server.registerTool(\n \"get_app_log\",\n {\n title: \"Get Application Log\",\n annotations: hints.read,\n description: \"Read recent lines from the application log. Useful for debugging errors.\",\n inputSchema: z.object({\n lines: z.number().optional().default(50).describe(\"Number of lines to return (default 50)\"),\n search: z.string().optional().describe(\"Filter lines containing this substring\"),\n }),\n },\n async ({ lines, search }) => {\n if (!ctx.callbacks.readAppLog) {\n return errorResult(\n \"App log reading is not available.\",\n \"This feature requires the desktop app integration.\",\n );\n }\n const log = await ctx.callbacks.readAppLog(lines, search);\n return textResult({ log });\n },\n );\n}\n"],"mappings":";;;;;AAOA,SAAgB,iBAAiB,QAAuB,KAAwB;CAC9E,OAAO,aACL,kBACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aACE;EACF,aAAa,EAAE,OAAO;GACpB,WAAW,eAAe,SAAS,YAAY;GAC/C,SAAS,aAAa,SAAS,UAAU;GACzC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,SAAS,uCAAuC;GAC1F,UAAU,EACP,OAAO,CAAC,CACR,SAAS,CAAC,CACV,SAAS,6DAA6D;EAC3E,CAAC;CACH,GACA,OAAO,EAAE,WAAW,SAAS,OAAO,eAAe;EAEjD,MAAM,QAAQ,OAAM,MADE,IAAI,iBAAiB,SAAS,EAAA,CACxB,cAAc,OAAO,CAAC,CAAC,SAAS;EAC5D,IAAI,CAAC,MAAM,SACT,OAAO,YACL,6BACA,qHACF;EAGF,MAAM,UAAU,MAAM;EAItB,MAAM,aAA2E,CAAC;EAClF,KAAK,MAAM,CAAC,WAAW,WAAW,OAAO,QAAQ,OAAO,GAAG;GACzD,IAAI,CAAC,QAAQ,MAAM,CAAC,OAAO,OAAO,MAAM;GACxC,KAAK,MAAM,SAAS,OAAO,MAAM,MAC/B,IAAI,eAAe,MAAM,KAAK,GAC5B,WAAW,KAAK;IAAE;IAAW,KAAK,MAAM;IAAK,QAAQ,MAAM;GAAM,CAAC;EAGxE;EAEA,IAAI,WAAW,WAAW,GACxB,OAAO,YACL,0CACA,iHACF;EAGF,MAAM,YAAY,IAAI,UAAU,CAAC,CAAC,UAAU;EAC5C,MAAM,UAAkC,CAAC;EAEzC,KAAK,MAAM,SAAS,YAAY;GAC9B,MAAM,MAAM,MAAM,IAAI,KAAK,GAAG;GAC9B,IAAI,YAAY,CAAC,MAAM,IAAI,SAAS,QAAQ,GAAG;GAC/C,IAAI;IACF,MAAM,WAAW,MAAM,UAAU,UAAU,MAAM,QAAQ,KAAK;IAC9D,IAAI,SAAS,oBACX,QAAQ,OAAO;SAEf,QAAQ,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,SAAS,IAAI;GAEzD,SAAS,KAAK;IACZ,QAAQ,OAAO,sBAAsB;GACvC;EACF;EAEA,OAAO,WAAW,OAAO;CAC3B,CACF;CAEA,OAAO,aACL,eACA;EACE,OAAO;EACP,aAAa,MAAM;EACnB,aAAa;EACb,aAAa,EAAE,OAAO;GACpB,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,SAAS,wCAAwC;GAC1F,QAAQ,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,wCAAwC;EACjF,CAAC;CACH,GACA,OAAO,EAAE,OAAO,aAAa;EAC3B,IAAI,CAAC,IAAI,UAAU,YACjB,OAAO,YACL,qCACA,oDACF;EAEF,MAAM,MAAM,MAAM,IAAI,UAAU,WAAW,OAAO,MAAM;EACxD,OAAO,WAAW,EAAE,IAAI,CAAC;CAC3B,CACF;AACF"}
1
+ {"version":3,"file":"logs.js","names":[],"sources":["../../src/tools/logs.ts"],"sourcesContent":["import { isAnyLogHandle } from \"@milaboratories/pl-model-common\";\nimport type { AnyLogHandle } from \"@milaboratories/pl-model-common\";\nimport { z } from \"zod\";\nimport { isPlainObject } from \"@milaboratories/helpers\";\nimport { projectIdInput, blockIdInput } from \"./ids\";\nimport type { ToolContext, ToolRegistrar } from \"./types\";\nimport { errorResult, hints, textResult } from \"./types\";\nimport { findBlock } from \"./readiness\";\nimport { page, pagingArgs } from \"./paging\";\n\n/** How many logs get_block_logs reads when the caller does not say. */\nexport const LOGS_DEFAULT_LIMIT = 10;\n/** The most logs one get_block_logs call reads. */\nexport const LOGS_MAX_LIMIT = 100;\n\n/** How deep into an output value log handles are looked for. */\nconst MAX_DEPTH = 8;\n\n/** The most arrays and objects of one output walked when looking for log handles. */\nexport const MAX_NODES = 20_000;\n\n/** One log a block's outputs carry. */\nexport type LogEntry = {\n /** The output that carries the log handle. */\n outputKey: string;\n /**\n * Where in the output's value: the key of a `{ data: [{ key, value }] }` entry (a sample, a\n * run), or the keys and indices leading to the handle; empty for a handle that is the value.\n */\n path: string[];\n handle: AnyLogHandle;\n};\n\n/** The key a log is given in the result: the output key, then its path, joined by `/`. */\nexport function logKey(entry: Pick<LogEntry, \"outputKey\" | \"path\">): string {\n return [entry.outputKey, ...entry.path].join(\"/\");\n}\n\n/** The log handles of a block's outputs, and the outputs whose walk stopped at a limit. */\nexport type FoundLogs = { entries: LogEntry[]; cutOutputs: string[] };\n\n/**\n * Finds every log handle in a block's outputs (output key → `{ok, value}`), in output order:\n * the value itself, an entry of a `{ data: [{ key, value }] }` map (named by its key), or any\n * other place in arrays and objects. Failed outputs, entries that are not objects and keys that\n * are not arrays are passed over. The walk of each output stops at {@link MAX_DEPTH} and at\n * {@link MAX_NODES} arrays and objects; values that cannot hold a handle (numbers, other strings)\n * are not counted. An output whose walk stopped is in `cutOutputs`.\n */\nexport function collectLogHandles(outputs: Record<string, unknown>): FoundLogs {\n const entries: LogEntry[] = [];\n const cutOutputs: string[] = [];\n let nodes = 0;\n let cut = false;\n\n const walk = (outputKey: string, v: unknown, path: string[], depth: number): void => {\n if (isAnyLogHandle(v)) {\n entries.push({ outputKey, path, handle: v });\n return;\n }\n const isArray = Array.isArray(v);\n if (!isArray && !isPlainObject(v)) return;\n if (++nodes > MAX_NODES || depth > MAX_DEPTH) {\n cut = true;\n return;\n }\n if (isArray) {\n v.forEach((item, i) => walk(outputKey, item, [...path, String(i)], depth + 1));\n return;\n }\n for (const [key, item] of Object.entries(v)) {\n if (key === \"data\" && Array.isArray(item)) {\n item.forEach((entry, i) => {\n if (isPlainObject(entry) && Array.isArray(entry.key))\n walk(outputKey, entry.value, [...path, ...entry.key.map(String)], depth + 1);\n else walk(outputKey, entry, [...path, \"data\", String(i)], depth + 1);\n });\n } else walk(outputKey, item, [...path, key], depth + 1);\n }\n };\n\n for (const [outputKey, output] of Object.entries(outputs)) {\n if (!isPlainObject(output) || output.ok !== true) continue;\n nodes = 0;\n cut = false;\n walk(outputKey, output.value, [], 0);\n if (cut) cutOutputs.push(outputKey);\n }\n return { entries, cutOutputs };\n}\n\n/** What the result says of outputs whose walk stopped at a limit. */\nexport function cutNote(cutOutputs: string[]): string {\n const [noun, verb, owner] =\n cutOutputs.length > 1 ? [\"Outputs\", \"are\", \"their\"] : [\"Output\", \"is\", \"its\"];\n return (\n `${noun} ${cutOutputs.join(\", \")} ${verb} too large or too deep to search whole: some of ` +\n `${owner} logs may be missed.`\n );\n}\n\nexport function registerLogTools(server: ToolRegistrar, ctx: ToolContext): void {\n server.registerTool(\n \"get_block_logs\",\n {\n title: \"Get Block Logs\",\n annotations: hints.read,\n description:\n \"Read execution logs for a block. Finds the log handles in the block's outputs (an \" +\n \"output that is a log, or holds logs per sample or run, at any depth) and reads them, \" +\n `${LOGS_DEFAULT_LIMIT} logs at a time. Result: \\`{ logs, total, offset, hasMore }\\`, ` +\n \"`logs` keyed `<output key>/<sample or run id>` (the output key alone for an output \" +\n \"that is one log); page with `offset` and `limit`.\",\n inputSchema: z.object({\n projectId: projectIdInput.describe(\"Project ID\"),\n blockId: blockIdInput.describe(\"Block ID\"),\n lines: z.number().optional().default(100).describe(\"Number of lines per log (default 100)\"),\n sampleId: z\n .string()\n .optional()\n .describe(\n \"Only the logs of this sample or run id, or of this output key (reads all if omitted)\",\n ),\n ...pagingArgs(\"logs\", LOGS_DEFAULT_LIMIT, LOGS_MAX_LIMIT),\n }),\n },\n async ({ projectId, blockId, lines, sampleId, limit, offset }) => {\n return await ctx.withProject(projectId, async (project) => {\n const { error } = await findBlock(project, projectId, blockId);\n if (error) return error;\n const state = await project.getBlockState(blockId).getValue();\n if (!state.outputs)\n return errorResult(\n \"Block has no outputs yet.\",\n \"The block may not have been run. Use get_project_overview to check its calculationStatus, then run_block if needed.\",\n );\n\n // Scan all outputs for log handles (log+ready:// or log+live://)\n const { entries: logEntries, cutOutputs } = collectLogHandles(state.outputs);\n\n if (logEntries.length === 0) {\n return errorResult(\n \"No log handles found in block outputs.\" +\n (cutOutputs.length > 0 ? ` ${cutNote(cutOutputs)}` : \"\"),\n \"This block may not produce logs, or it hasn't run yet. Use get_block_outputs to inspect available output types.\",\n );\n }\n\n const logDriver = ctx.requireMl().driverKit.logDriver;\n const results: Record<string, string> = {};\n const { items, ...paging } = page(\n sampleId\n ? logEntries.filter((e) => e.path.includes(sampleId) || e.outputKey === sampleId)\n : logEntries,\n offset,\n limit ?? LOGS_DEFAULT_LIMIT,\n );\n\n for (const entry of items) {\n const key = logKey(entry);\n try {\n const response = await logDriver.lastLines(entry.handle, lines);\n if (response.shouldUpdateHandle) {\n results[key] = \"[log handle stale — block may still be running, retry later]\";\n } else {\n results[key] = new TextDecoder().decode(response.data);\n }\n } catch (err) {\n results[key] = `Error reading log: ${err}`;\n }\n }\n\n return textResult(\n {\n logs: results,\n ...paging,\n ...(cutOutputs.length > 0 ? { note: cutNote(cutOutputs) } : {}),\n },\n {\n hint:\n \"Ask for less: fewer `lines`, a smaller `limit` with `offset` to page, or \" +\n \"`sampleId` for one sample's log.\",\n },\n );\n });\n },\n );\n\n server.registerTool(\n \"get_app_log\",\n {\n title: \"Get Application Log\",\n annotations: hints.read,\n description: \"Read recent lines from the application log. Useful for debugging errors.\",\n inputSchema: z.object({\n lines: z.number().optional().default(50).describe(\"Number of lines to return (default 50)\"),\n search: z.string().optional().describe(\"Filter lines containing this substring\"),\n }),\n },\n async ({ lines, search }) => {\n if (!ctx.callbacks.readAppLog) {\n return errorResult(\n \"App log reading is not available.\",\n \"This feature requires the desktop app integration.\",\n );\n }\n const log = await ctx.callbacks.readAppLog(lines, search);\n return textResult({ log });\n },\n );\n}\n"],"mappings":";;;;;;;;AAgBA,MAAM,YAAY;;AAGlB,MAAa,YAAY;;AAezB,SAAgB,OAAO,OAAqD;CAC1E,OAAO,CAAC,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,CAAC,KAAK,GAAG;AAClD;;;;;;;;;AAaA,SAAgB,kBAAkB,SAA6C;CAC7E,MAAM,UAAsB,CAAC;CAC7B,MAAM,aAAuB,CAAC;CAC9B,IAAI,QAAQ;CACZ,IAAI,MAAM;CAEV,MAAM,QAAQ,WAAmB,GAAY,MAAgB,UAAwB;EACnF,IAAI,eAAe,CAAC,GAAG;GACrB,QAAQ,KAAK;IAAE;IAAW;IAAM,QAAQ;GAAE,CAAC;GAC3C;EACF;EACA,MAAM,UAAU,MAAM,QAAQ,CAAC;EAC/B,IAAI,CAAC,WAAW,CAAC,cAAc,CAAC,GAAG;EACnC,IAAI,EAAE,QAAA,OAAqB,QAAQ,WAAW;GAC5C,MAAM;GACN;EACF;EACA,IAAI,SAAS;GACX,EAAE,SAAS,MAAM,MAAM,KAAK,WAAW,MAAM,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC;GAC7E;EACF;EACA,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,CAAC,GACxC,IAAI,QAAQ,UAAU,MAAM,QAAQ,IAAI,GACtC,KAAK,SAAS,OAAO,MAAM;GACzB,IAAI,cAAc,KAAK,KAAK,MAAM,QAAQ,MAAM,GAAG,GACjD,KAAK,WAAW,MAAM,OAAO,CAAC,GAAG,MAAM,GAAG,MAAM,IAAI,IAAI,MAAM,CAAC,GAAG,QAAQ,CAA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E,OAAO,aAAa;EAC3B,IAAI,CAAC,IAAI,UAAU,YACjB,OAAO,YACL,qCACA,oDACF;EAEF,MAAM,MAAM,MAAM,IAAI,UAAU,WAAW,OAAO,MAAM;EACxD,OAAO,WAAW,EAAE,IAAI,CAAC;CAC3B,CACF;AACF"}
@@ -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":";;;;;AAaA,MAAM,SAAwB,OAAO,Q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AAG,GAAG;EACzC,MAAM,KAAK,OAAO,IAAI,IAAI,GAAG,KAAK,KAAK,IAAI,IAAI,GAAG;EAClD,MAAM,QAAQ,QACZ,GAAG,KAAK,MAAM,KAAK,UAAU,EAAE,EAAE,IACjC,KAAK,SAAS,IAAI,GAAG,KAAK,QAC1B,WAAW,OAAO,SAAS,IAAI,GAAG,IAAI,QACtC,KAAK,SAAS,IAAI,GAAG,KAAK,QAC1B,SACF;EACA,IAAI,UAAU,QAAQ,OAAO,IAAI,KAAK,KAAK;CAC7C;CAGA,MAAM,QAAQ,OAAO,MAAM,QAAQ,QAAQ,OAAO,IAAI,GAAG,CAAC;CAC1D,KAAK,MAAM,SAAS,KAAK,MAAM;EAC7B,IAAI,CAAC,OAAO,IAAI,GAAG,KAAK,MAAM,SAAS,GAAG,GAAG;EAC7C,MAAM,SAAS,KAAK,MACjB,MAAM,GAAG,CAAC,CAAC,CACX,QAAQ,CAAC,CACT,MAAM,MAAM,MAAM,SAAS,CAAC,CAAC;EAChC,MAAM,OAAO,WAAW,KAAA,IAAY,IAAI,MAAM,QAAQ,MAAM,IAAI,GAAG,GAAG,GAAG;CAC3E,CAAC;CACD,OAAO,MAAM,KAAK,QAAQ,OAAO,IAAI,GAAG,CAAC;AAC3C"}
@@ -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":";;;;;AAaA,MAAM,SAAwB,OAAO,QAAQ;;;;;;;;;;;;;;;;;;AAoB7C,SAAgB,cAAc,MAAe,QAAiB,MAA6B;CACzF,MAAM,YAAsB,CAAC;CAC7B,MAAM,SAAS,QAAQ,IAAI,MAAM,QAAQ,MAAM,SAAS;CACxD,OAAO;EAAE,QAAQ,WAAW,SAAS,KAAA,IAAY;EAAQ;CAAU;AACrE;AAEA,SAAS,KAAK,GAAS,GAAkB;CACvC,IAAI,MAAM,UAAU,MAAM,QAAQ,OAAO,MAAM;CAC/C,OAAO,kBAAkB,GAAG,CAAC;AAC/B;AAEA,SAAS,QAAQ,MAAc,MAAY,QAAc,MAAY,WAA2B;CAC9F,IAAI,KAAK,MAAM,MAAM,GAAG,OAAO;CAC/B,IAAI,KAAK,MAAM,IAAI,KAAK,KAAK,QAAQ,IAAI,GAAG,OAAO;CACnD,IAAI,cAAc,IAAI,KAAK,cAAc,MAAM,KAAK,cAAc,IAAI,GACpE,OAAO,aAAa,MAAM,MAAM,QAAQ,MAAM,SAAS;CACzD,IAAI,MAAM,QAAQ,IAAI,KAAK,MAAM,QAAQ,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
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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Ac,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,wBAAw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