@onlyflows/servicenow-mcp 2.2.0-dev.6 → 2.2.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 (244) hide show
  1. package/.env.example +6 -3
  2. package/CHANGELOG.md +286 -0
  3. package/README.md +504 -101
  4. package/dist/atf-form.d.ts +3 -15
  5. package/dist/atf-form.d.ts.map +1 -1
  6. package/dist/atf-result-cache.d.ts +23 -59
  7. package/dist/atf-result-cache.d.ts.map +1 -1
  8. package/dist/auth.d.ts +1 -0
  9. package/dist/auth.d.ts.map +1 -1
  10. package/dist/auth.js +17 -0
  11. package/dist/auth.js.map +1 -1
  12. package/dist/batch-limits.d.ts +18 -0
  13. package/dist/batch-limits.d.ts.map +1 -0
  14. package/dist/batch-limits.js +21 -0
  15. package/dist/batch-limits.js.map +1 -0
  16. package/dist/bounded-input.d.ts +49 -0
  17. package/dist/bounded-input.d.ts.map +1 -0
  18. package/dist/bounded-input.js +81 -0
  19. package/dist/bounded-input.js.map +1 -0
  20. package/dist/client.d.ts +25 -0
  21. package/dist/client.d.ts.map +1 -1
  22. package/dist/client.js +92 -18
  23. package/dist/client.js.map +1 -1
  24. package/dist/encoded-query-policy.d.ts +11 -0
  25. package/dist/encoded-query-policy.d.ts.map +1 -1
  26. package/dist/encoded-query-policy.js +10 -1
  27. package/dist/encoded-query-policy.js.map +1 -1
  28. package/dist/field-policy.d.ts +82 -3
  29. package/dist/field-policy.d.ts.map +1 -1
  30. package/dist/field-policy.js +609 -80
  31. package/dist/field-policy.js.map +1 -1
  32. package/dist/html-response.d.ts +34 -0
  33. package/dist/html-response.d.ts.map +1 -0
  34. package/dist/html-response.js +72 -0
  35. package/dist/html-response.js.map +1 -0
  36. package/dist/http-runtime.d.ts.map +1 -1
  37. package/dist/http-runtime.js +8 -0
  38. package/dist/http-runtime.js.map +1 -1
  39. package/dist/incident-journal-policy.d.ts +27 -5
  40. package/dist/incident-journal-policy.d.ts.map +1 -1
  41. package/dist/incident-journal-policy.js +34 -21
  42. package/dist/incident-journal-policy.js.map +1 -1
  43. package/dist/json-shape-limits.d.ts +71 -0
  44. package/dist/json-shape-limits.d.ts.map +1 -0
  45. package/dist/json-shape-limits.js +131 -0
  46. package/dist/json-shape-limits.js.map +1 -0
  47. package/dist/metadata-cache.d.ts +46 -21
  48. package/dist/metadata-cache.d.ts.map +1 -1
  49. package/dist/metadata-cache.js +228 -195
  50. package/dist/metadata-cache.js.map +1 -1
  51. package/dist/policy-card.d.ts +131 -0
  52. package/dist/policy-card.d.ts.map +1 -0
  53. package/dist/policy-card.js +409 -0
  54. package/dist/policy-card.js.map +1 -0
  55. package/dist/profile-manager.d.ts +7 -3
  56. package/dist/profile-manager.d.ts.map +1 -1
  57. package/dist/profile-manager.js +66 -3
  58. package/dist/profile-manager.js.map +1 -1
  59. package/dist/record-identifier-policy.d.ts +2 -8
  60. package/dist/record-identifier-policy.d.ts.map +1 -1
  61. package/dist/risky-grants.d.ts +25 -0
  62. package/dist/risky-grants.d.ts.map +1 -0
  63. package/dist/risky-grants.js +77 -0
  64. package/dist/risky-grants.js.map +1 -0
  65. package/dist/server.d.ts.map +1 -1
  66. package/dist/server.js +26 -5
  67. package/dist/server.js.map +1 -1
  68. package/dist/setup-prompts.js +1 -0
  69. package/dist/setup-prompts.js.map +1 -1
  70. package/dist/setup.d.ts +1 -1
  71. package/dist/setup.d.ts.map +1 -1
  72. package/dist/setup.js +300 -58
  73. package/dist/setup.js.map +1 -1
  74. package/dist/stdio-runtime.d.ts +15 -0
  75. package/dist/stdio-runtime.d.ts.map +1 -1
  76. package/dist/stdio-runtime.js +60 -0
  77. package/dist/stdio-runtime.js.map +1 -1
  78. package/dist/structured-query.d.ts +100 -115
  79. package/dist/structured-query.d.ts.map +1 -1
  80. package/dist/structured-query.js +132 -16
  81. package/dist/structured-query.js.map +1 -1
  82. package/dist/table-policy.d.ts +10 -4
  83. package/dist/table-policy.d.ts.map +1 -1
  84. package/dist/table-policy.js +1 -1
  85. package/dist/table-policy.js.map +1 -1
  86. package/dist/tool-error.d.ts +18 -0
  87. package/dist/tool-error.d.ts.map +1 -1
  88. package/dist/tool-error.js +69 -0
  89. package/dist/tool-error.js.map +1 -1
  90. package/dist/tool-table-access.d.ts.map +1 -1
  91. package/dist/tool-table-access.js +32 -2
  92. package/dist/tool-table-access.js.map +1 -1
  93. package/dist/tools/aggregate.d.ts +13 -19
  94. package/dist/tools/aggregate.d.ts.map +1 -1
  95. package/dist/tools/aggregate.js +2 -3
  96. package/dist/tools/aggregate.js.map +1 -1
  97. package/dist/tools/all-fields-cap.d.ts.map +1 -1
  98. package/dist/tools/all-fields-cap.js +3 -38
  99. package/dist/tools/all-fields-cap.js.map +1 -1
  100. package/dist/tools/atf-author-module.d.ts +28 -7
  101. package/dist/tools/atf-author-module.d.ts.map +1 -1
  102. package/dist/tools/atf-author-module.js +4 -2
  103. package/dist/tools/atf-author-module.js.map +1 -1
  104. package/dist/tools/atf-contracts.d.ts +135 -829
  105. package/dist/tools/atf-contracts.d.ts.map +1 -1
  106. package/dist/tools/atf-shared.js +2 -2
  107. package/dist/tools/atf-shared.js.map +1 -1
  108. package/dist/tools/atf-step-catalog.d.ts +3 -7
  109. package/dist/tools/atf-step-catalog.d.ts.map +1 -1
  110. package/dist/tools/atf-step-catalog.js +12 -5
  111. package/dist/tools/atf-step-catalog.js.map +1 -1
  112. package/dist/tools/atf.d.ts +8 -24
  113. package/dist/tools/atf.d.ts.map +1 -1
  114. package/dist/tools/atf.js +2 -2
  115. package/dist/tools/atf.js.map +1 -1
  116. package/dist/tools/attach.d.ts +6 -22
  117. package/dist/tools/attach.d.ts.map +1 -1
  118. package/dist/tools/batch.d.ts +18 -71
  119. package/dist/tools/batch.d.ts.map +1 -1
  120. package/dist/tools/batch.js +544 -96
  121. package/dist/tools/batch.js.map +1 -1
  122. package/dist/tools/catalog.d.ts +2 -2
  123. package/dist/tools/catalog.d.ts.map +1 -1
  124. package/dist/tools/catalog.js +7 -1
  125. package/dist/tools/catalog.js.map +1 -1
  126. package/dist/tools/codesearch.d.ts +1 -13
  127. package/dist/tools/codesearch.d.ts.map +1 -1
  128. package/dist/tools/create-module.d.ts +9 -14
  129. package/dist/tools/create-module.d.ts.map +1 -1
  130. package/dist/tools/create-module.js +4 -8
  131. package/dist/tools/create-module.js.map +1 -1
  132. package/dist/tools/delete.d.ts +1 -9
  133. package/dist/tools/delete.d.ts.map +1 -1
  134. package/dist/tools/delete.js +2 -3
  135. package/dist/tools/delete.js.map +1 -1
  136. package/dist/tools/discover.d.ts +6 -14
  137. package/dist/tools/discover.d.ts.map +1 -1
  138. package/dist/tools/flow-view-contracts.d.ts +1023 -0
  139. package/dist/tools/flow-view-contracts.d.ts.map +1 -0
  140. package/dist/tools/flow-view-contracts.js +570 -0
  141. package/dist/tools/flow-view-contracts.js.map +1 -0
  142. package/dist/tools/flow-view-graph.d.ts +86 -0
  143. package/dist/tools/flow-view-graph.d.ts.map +1 -0
  144. package/dist/tools/flow-view-graph.js +993 -0
  145. package/dist/tools/flow-view-graph.js.map +1 -0
  146. package/dist/tools/flow-view-gzip.d.ts +52 -0
  147. package/dist/tools/flow-view-gzip.d.ts.map +1 -0
  148. package/dist/tools/flow-view-gzip.js +179 -0
  149. package/dist/tools/flow-view-gzip.js.map +1 -0
  150. package/dist/tools/flow-view-mermaid.d.ts +37 -0
  151. package/dist/tools/flow-view-mermaid.d.ts.map +1 -0
  152. package/dist/tools/flow-view-mermaid.js +337 -0
  153. package/dist/tools/flow-view-mermaid.js.map +1 -0
  154. package/dist/tools/flow-view-module.d.ts +61 -0
  155. package/dist/tools/flow-view-module.d.ts.map +1 -0
  156. package/dist/tools/flow-view-module.js +378 -0
  157. package/dist/tools/flow-view-module.js.map +1 -0
  158. package/dist/tools/flow-view-policy.d.ts +106 -0
  159. package/dist/tools/flow-view-policy.d.ts.map +1 -0
  160. package/dist/tools/flow-view-policy.js +461 -0
  161. package/dist/tools/flow-view-policy.js.map +1 -0
  162. package/dist/tools/flow-view-renderers.d.ts +68 -0
  163. package/dist/tools/flow-view-renderers.d.ts.map +1 -0
  164. package/dist/tools/flow-view-renderers.js +513 -0
  165. package/dist/tools/flow-view-renderers.js.map +1 -0
  166. package/dist/tools/flow-view-table.d.ts +115 -0
  167. package/dist/tools/flow-view-table.d.ts.map +1 -0
  168. package/dist/tools/flow-view-table.js +1002 -0
  169. package/dist/tools/flow-view-table.js.map +1 -0
  170. package/dist/tools/get-module.d.ts +36 -42
  171. package/dist/tools/get-module.d.ts.map +1 -1
  172. package/dist/tools/health.d.ts +9 -6
  173. package/dist/tools/health.d.ts.map +1 -1
  174. package/dist/tools/incident-journal-module.d.ts +8 -7
  175. package/dist/tools/incident-journal-module.d.ts.map +1 -1
  176. package/dist/tools/index.d.ts +4 -4
  177. package/dist/tools/index.d.ts.map +1 -1
  178. package/dist/tools/index.js +43 -6
  179. package/dist/tools/index.js.map +1 -1
  180. package/dist/tools/markdown.d.ts +27 -0
  181. package/dist/tools/markdown.d.ts.map +1 -1
  182. package/dist/tools/markdown.js +104 -1
  183. package/dist/tools/markdown.js.map +1 -1
  184. package/dist/tools/nl.d.ts +1 -11
  185. package/dist/tools/nl.d.ts.map +1 -1
  186. package/dist/tools/profile.d.ts +1 -1
  187. package/dist/tools/profile.d.ts.map +1 -1
  188. package/dist/tools/profile.js +19 -1
  189. package/dist/tools/profile.js.map +1 -1
  190. package/dist/tools/query-module.d.ts +59 -71
  191. package/dist/tools/query-module.d.ts.map +1 -1
  192. package/dist/tools/query-module.js +2 -2
  193. package/dist/tools/query-module.js.map +1 -1
  194. package/dist/tools/record-write-shared.d.ts.map +1 -1
  195. package/dist/tools/record-write-shared.js +19 -2
  196. package/dist/tools/record-write-shared.js.map +1 -1
  197. package/dist/tools/relationships.d.ts +6 -22
  198. package/dist/tools/relationships.d.ts.map +1 -1
  199. package/dist/tools/result-envelope.d.ts +2255 -1357
  200. package/dist/tools/result-envelope.d.ts.map +1 -1
  201. package/dist/tools/result-envelope.js +24 -2
  202. package/dist/tools/result-envelope.js.map +1 -1
  203. package/dist/tools/schema-module.d.ts +36 -21
  204. package/dist/tools/schema-module.d.ts.map +1 -1
  205. package/dist/tools/schema-module.js +106 -65
  206. package/dist/tools/schema-module.js.map +1 -1
  207. package/dist/tools/script.d.ts +1 -11
  208. package/dist/tools/script.d.ts.map +1 -1
  209. package/dist/tools/syslog.d.ts +11 -18
  210. package/dist/tools/syslog.d.ts.map +1 -1
  211. package/dist/tools/syslog.js +2 -3
  212. package/dist/tools/syslog.js.map +1 -1
  213. package/dist/tools/table-hierarchy.d.ts +35 -0
  214. package/dist/tools/table-hierarchy.d.ts.map +1 -0
  215. package/dist/tools/table-hierarchy.js +74 -0
  216. package/dist/tools/table-hierarchy.js.map +1 -0
  217. package/dist/tools/tool-module.d.ts +40 -15
  218. package/dist/tools/tool-module.d.ts.map +1 -1
  219. package/dist/tools/tool-module.js +755 -205
  220. package/dist/tools/tool-module.js.map +1 -1
  221. package/dist/tools/update-module.d.ts +11 -17
  222. package/dist/tools/update-module.d.ts.map +1 -1
  223. package/dist/tools/update-module.js +10 -12
  224. package/dist/tools/update-module.js.map +1 -1
  225. package/dist/version.d.ts +1 -1
  226. package/dist/version.d.ts.map +1 -1
  227. package/dist/version.js +1 -1
  228. package/dist/version.js.map +1 -1
  229. package/dist/write-value-policy.d.ts +20 -12
  230. package/dist/write-value-policy.d.ts.map +1 -1
  231. package/dist/write-value-policy.js +179 -67
  232. package/dist/write-value-policy.js.map +1 -1
  233. package/docs/ADDING-TOOLS.md +22 -13
  234. package/docs/CLIENT-SETUP.md +110 -52
  235. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +2 -2
  236. package/docs/FLOW-VIEW.md +214 -0
  237. package/docs/PRODUCTION-SECURITY.md +154 -25
  238. package/docs/RELEASE-VALIDATION.md +2 -2
  239. package/docs/TESTING-OAUTH.md +1 -1
  240. package/docs/V2-MIGRATION.md +404 -30
  241. package/package.json +20 -6
  242. package/scripts/release-validate.mjs +56 -0
  243. package/server.json +22 -0
  244. package/tools/inspector/package-lock.json +163 -201
@@ -0,0 +1,1002 @@
1
+ "use strict";
2
+ /**
3
+ * Table API loader for `sn_flow_view`, the only flow source.
4
+ *
5
+ * Reads the `sys_hub_*` closure of one flow through `/api/now/table/<table>`
6
+ * GETs only, sequentially and in a fixed order, and returns a
7
+ * NormalizedFlowDefinition whose every value has already passed the
8
+ * flow-view field policy. Flow Designer's internal ProcessFlow API is never
9
+ * called: its flow GET writes a Workflow Studio history row.
10
+ *
11
+ * Reads for one flow load (each: `sysparm_exclude_reference_link=true`,
12
+ * `sysparm_limit=501` sentinel; `sysparm_display_value=all` unless noted).
13
+ * Independent reads are issued together and the client bounds how many run
14
+ * at once; results are always processed in this fixed order:
15
+ * wave 1, together:
16
+ * 0. `sys_hub_flow` label_cache, raw (only with inputs, and only when the
17
+ * caller did not already read it with the header)
18
+ * 1. trigger V1, trigger V2
19
+ * 2. action V1, action V2; logic V1, logic V2; subflow V1, subflow V2
20
+ * 3. flow variables, inputs, outputs (`model=<flow>`)
21
+ * wave 2, together, each only when there is something to look up:
22
+ * 4. `sys_hub_flow_snapshot` by `sys_idIN` for subflow call targets
23
+ * 5. the compressed value column of each non-empty V2 table, raw
24
+ * (`sysparm_display_value=false`: its display value is the same
25
+ * blob, which would double the bytes)
26
+ * 6. `sys_variable_value` by `document_keyIN<≤100 ids>` (V1 values),
27
+ * paged with `sysparm_offset`, then `var_dictionary` by
28
+ * `sys_idIN<≤100 ids>` (V1 input names and types)
29
+ * Reads 0, 5 and 6 happen only with `include_inputs`. A missing `_v2` table
30
+ * (HTTP 400) reads as zero rows.
31
+ *
32
+ * @module tools/flow-view-table
33
+ */
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ exports.FLOW_LABEL_CACHE_MAX_CHARS = exports.FLOW_LABEL_CACHE_MAX_ENTRIES = exports.FLOW_AMBIGUOUS_CANDIDATES = exports.FLOW_NAME_LOOKUP_LIMIT = exports.FLOW_TABLE_ROW_LIMIT = void 0;
36
+ exports.resolveFlowRecord = resolveFlowRecord;
37
+ exports.resolveSubflowTarget = resolveSubflowTarget;
38
+ exports.loadFlowFromTables = loadFlowFromTables;
39
+ exports.parseFlowOrder = parseFlowOrder;
40
+ const field_policy_js_1 = require("../field-policy.js");
41
+ const metadata_cache_js_1 = require("../metadata-cache.js");
42
+ const servicenow_identifiers_js_1 = require("../servicenow-identifiers.js");
43
+ const tool_error_js_1 = require("../tool-error.js");
44
+ const utils_js_1 = require("../utils.js");
45
+ const flow_view_contracts_js_1 = require("./flow-view-contracts.js");
46
+ const flow_view_policy_js_1 = require("./flow-view-policy.js");
47
+ const flow_view_gzip_js_1 = require("./flow-view-gzip.js");
48
+ /** Rows kept per table read; one more is requested as the overflow sentinel. */
49
+ exports.FLOW_TABLE_ROW_LIMIT = flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_ROWS_PER_TABLE;
50
+ /** Exact-name lookups request this many rows (5 candidates + 1). */
51
+ exports.FLOW_NAME_LOOKUP_LIMIT = 6;
52
+ /** Most sys_ids reported for an ambiguous name. */
53
+ exports.FLOW_AMBIGUOUS_CANDIDATES = 5;
54
+ /** Entries kept from one flow's label_cache. */
55
+ exports.FLOW_LABEL_CACHE_MAX_ENTRIES = 1_000;
56
+ /** Longest label_cache JSON text parsed (plain JSON, not gzip). */
57
+ exports.FLOW_LABEL_CACHE_MAX_CHARS = flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_GZIP_OUTPUT_BYTES;
58
+ /**
59
+ * Of a load's 1 MiB response scope, the most that its wave-1 reads plus its
60
+ * V1 value reads may use; the rest is left for the `var_dictionary` reads
61
+ * that follow and for estimate error. V1 value reads (every page of every
62
+ * chunk after the first) stop when the next one, assumed as large as the
63
+ * last, would pass it, and report `input_values_incomplete`. A flow with
64
+ * very many V1 values then keeps the values it read instead of overflowing
65
+ * its scope and losing all of them to the retry without inputs.
66
+ */
67
+ const V1_VALUE_SCOPE_BYTES = 896 * 1024;
68
+ /** Name of the input that marks a blob that could not be decoded. */
69
+ const DECODE_FAILED_NAMES = Object.freeze({
70
+ values: "values",
71
+ trigger_inputs: "trigger_inputs",
72
+ subflow_inputs: "subflow_inputs",
73
+ });
74
+ /**
75
+ * Resolve the `sys_hub_flow` record for a selector.
76
+ *
77
+ * - `sys_id`: `sys_id=<hex>^typeINflow,subflow`.
78
+ * - `name`: `name=<escaped>^typeINflow,subflow^ORDERBYsys_id` with
79
+ * `sysparm_limit=6`, then an exact, case-sensitive post-filter. A name that
80
+ * contains `^` cannot match (`escapeQueryValue` strips it, and the
81
+ * post-filter compares the original text).
82
+ *
83
+ * The header is policy-projected. `label_cache` is requested only with
84
+ * `withLabelCache` on a sys_id selector.
85
+ */
86
+ async function resolveFlowRecord(ops, plan, selector, options = {}) {
87
+ const reader = (0, metadata_cache_js_1.uncachedOperations)(ops);
88
+ let fields = fieldsFor(plan, "sys_hub_flow", { exclude: ["label_cache"] });
89
+ let withLabels = false;
90
+ let matches;
91
+ if (isSysIdSelector(selector)) {
92
+ const id = sysIdOf(selector.sys_id);
93
+ if (id === null)
94
+ return { status: "not_found" };
95
+ withLabels =
96
+ options.withLabelCache?.include_inputs === true &&
97
+ (0, flow_view_policy_js_1.inputsIncluded)(plan) &&
98
+ (0, flow_view_policy_js_1.canShow)(plan, "pill_labels");
99
+ if (withLabels)
100
+ fields = `${fields},label_cache`;
101
+ const { rows } = await readTable(reader, "sys_hub_flow", `sys_id=${id}^typeINflow,subflow`, fields, {
102
+ maxRows: 1,
103
+ });
104
+ matches = rows.filter((row) => sysIdOf(scalar(row.sys_id)) === id && isFlowType(row));
105
+ }
106
+ else {
107
+ const name = typeof selector.name === "string" ? selector.name : "";
108
+ if (name.trim() === "" || name.length > flow_view_contracts_js_1.FLOW_VIEW_MAX_FLOW_SELECTOR_CHARS) {
109
+ return { status: "not_found" };
110
+ }
111
+ const { rows } = await readTable(reader, "sys_hub_flow", `name=${(0, utils_js_1.escapeQueryValue)(name)}^typeINflow,subflow^ORDERBYsys_id`, fields, { maxRows: exports.FLOW_NAME_LOOKUP_LIMIT - 1 });
112
+ matches = rows.filter((row) => scalar(row.name) === name && isFlowType(row) && sysIdOf(scalar(row.sys_id)) !== null);
113
+ }
114
+ if (matches.length === 0)
115
+ return { status: "not_found" };
116
+ if (matches.length > 1) {
117
+ const candidates = matches
118
+ .map((row) => sysIdOf(scalar(row.sys_id)))
119
+ .filter((id) => id !== null);
120
+ return { status: "ambiguous", candidates: [...new Set(candidates)].slice(0, exports.FLOW_AMBIGUOUS_CANDIDATES) };
121
+ }
122
+ const row = matches[0];
123
+ const header = headerFrom(plan, row, sysIdOf(scalar(row.sys_id)));
124
+ return withLabels ? { status: "found", header, label_cache: scalar(row.label_cache) } : { status: "found", header };
125
+ }
126
+ /**
127
+ * The flow a subflow call targets. `sys_hub_sub_flow_instance(_v2).subflow`
128
+ * references a `sys_hub_flow_snapshot` row; its `parent_flow` is the flow.
129
+ * Returns null when the reference is not a sys_id, the snapshot is not
130
+ * readable or not found, or its parent is not a sys_id.
131
+ */
132
+ async function resolveSubflowTarget(ops, plan, ref) {
133
+ const id = sysIdOf(ref);
134
+ if (id === null)
135
+ return null;
136
+ const targets = await resolveSubflowTargets((0, metadata_cache_js_1.uncachedOperations)(ops), plan, [id]);
137
+ return targets.get(id) ?? null;
138
+ }
139
+ /**
140
+ * Load one flow's definition from the Table API. Every value is projected
141
+ * through the flow-view policy before it is returned. Decoding failures
142
+ * never throw; they mark the affected inputs `decode_failed`. Upstream
143
+ * errors (other than a missing `_v2` table) and cancellations propagate.
144
+ */
145
+ async function loadFlowFromTables(ops, header, plan, options) {
146
+ const flowId = sysIdOf(header?.sys_id);
147
+ if (flowId === null)
148
+ throw (0, tool_error_js_1.createToolError)("internal", "do_not_retry");
149
+ const reader = (0, metadata_cache_js_1.uncachedOperations)(ops);
150
+ const load = {
151
+ plan,
152
+ reader,
153
+ flowId,
154
+ includeInputs: options?.include_inputs === true && (0, flow_view_policy_js_1.inputsIncluded)(plan),
155
+ budget: (0, flow_view_gzip_js_1.createDecompressionBudget)(),
156
+ warnings: new Set(),
157
+ limits: new Set(),
158
+ dropped: 0,
159
+ blobs: new Map(),
160
+ readBytes: 0,
161
+ };
162
+ const knownLabels = typeof options?.label_cache === "string" ? options.label_cache : undefined;
163
+ // Wave 1: every read that depends only on the flow id, issued together.
164
+ const triggerTables = ["sys_hub_trigger_instance", "sys_hub_trigger_instance_v2"];
165
+ const [labelText, triggerReads, stepReads, variableReads] = await Promise.all([
166
+ load.includeInputs && knownLabels === undefined ? readLabelCacheText(load) : Promise.resolve(knownLabels),
167
+ Promise.all(triggerTables.map((table) => readTriggerTable(load, table))),
168
+ Promise.all(STEP_SPECS.map((spec) => readTable(reader, spec.table, `flow=${flowId}^ORDERBYorder^ORDERBYsys_id`, fieldsFor(plan, spec.table, { values: false }), { missingIsEmpty: spec.v2 }))),
169
+ readVariableTables(load),
170
+ ]);
171
+ load.readBytes =
172
+ Buffer.byteLength(labelText ?? "") +
173
+ [...triggerReads, ...stepReads, ...variableReads].reduce((sum, read) => sum + (read?.bytes ?? 0), 0);
174
+ // 0. Pill labels.
175
+ const labelCache = load.includeInputs ? parseLabelCache(load, labelText) : [];
176
+ // 1. Trigger.
177
+ const triggerRows = collectTriggerRows(load, triggerTables, triggerReads);
178
+ // 2. Steps.
179
+ const steps = new Map();
180
+ STEP_SPECS.forEach((spec, index) => {
181
+ const { rows, truncated } = stepReads[index];
182
+ if (truncated)
183
+ load.limits.add("rows_per_table");
184
+ for (const row of rows)
185
+ addStep(load, steps, spec, row);
186
+ });
187
+ normalizeStructure(load, steps);
188
+ // 3. Flow variables, inputs and outputs.
189
+ const variables = collectVariables(load, variableReads);
190
+ // Trigger choice: V2 over V1, first row of each.
191
+ const trigger = triggerRows.v2[0] ?? triggerRows.v1[0];
192
+ // Wave 2: lookups keyed by what wave 1 returned, issued together.
193
+ const snapshotIds = [...steps.values()]
194
+ .map((step) => (step.spec.kind === "subflow" ? sysIdOf(scalar(step.row.subflow)) : null))
195
+ .filter((id) => id !== null);
196
+ const v1Documents = [
197
+ ...(trigger && !trigger.v2 ? [{ table: trigger.table, sysId: trigger.sysId }] : []),
198
+ ...[...steps.values()].filter((step) => !step.spec.v2).map((step) => ({ table: step.spec.table, sysId: step.sysId })),
199
+ ];
200
+ const blobTables = load.includeInputs ? blobReadsFor(load, triggerRows, steps) : [];
201
+ const [targets, blobReads, v1Values] = await Promise.all([
202
+ snapshotIds.length > 0 ? resolveSubflowTargets(reader, plan, snapshotIds) : Promise.resolve(new Map()),
203
+ Promise.all(blobTables.map((blob) => readBlobColumn(load, blob))),
204
+ load.includeInputs ? readV1Values(load, v1Documents) : Promise.resolve(new Map()),
205
+ ]);
206
+ blobTables.forEach((blob, index) => {
207
+ const { rows, truncated } = blobReads[index];
208
+ if (truncated)
209
+ load.limits.add("rows_per_table");
210
+ for (const row of rows) {
211
+ const sysId = sysIdOf(scalar(row.sys_id));
212
+ if (sysId !== null)
213
+ load.blobs.set(`${blob.table}:${sysId}`, scalar(row[blob.column]));
214
+ }
215
+ });
216
+ // Blobs decode in display order (trigger, then steps by order), sharing one budget.
217
+ const normalizedTrigger = trigger ? assembleTrigger(load, trigger, v1Values) : null;
218
+ const normalizedSteps = assembleSteps(load, steps, targets, v1Values);
219
+ return {
220
+ source: "table",
221
+ header,
222
+ trigger: normalizedTrigger,
223
+ steps: normalizedSteps,
224
+ label_cache: labelCache,
225
+ variables,
226
+ warnings: [...load.warnings].slice(0, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_WARNINGS),
227
+ limits_hit: [...load.limits],
228
+ items_dropped: load.dropped,
229
+ };
230
+ }
231
+ /**
232
+ * Parse a step `order`. V2 orders are integers; V1 orders can be arrow paths
233
+ * such as `2➛3` (the parent's order, then the step's own), whose last number
234
+ * orders the step. Anything else is null; the step is kept.
235
+ */
236
+ function parseFlowOrder(raw) {
237
+ const text = typeof raw === "number" ? String(raw) : typeof raw === "string" ? raw.trim() : "";
238
+ if (text === "" || text.length > MAX_ORDER_CHARS)
239
+ return null;
240
+ if (/^-?\d{1,15}(?:\.\d{1,6})?$/u.test(text))
241
+ return Number(text);
242
+ const path = /^\d{1,15}(?:\s*➛\s*\d{1,15})+$/u;
243
+ if (!path.test(text))
244
+ return null;
245
+ const parts = text.split("➛");
246
+ return Number(parts[parts.length - 1].trim());
247
+ }
248
+ const TABLE_PATH = "/api/now/table/";
249
+ const MAX_ORDER_CHARS = 64;
250
+ const SHORT_TEXT_CHARS = flow_view_contracts_js_1.FLOW_GRAPH_SCHEMA_BOUNDS.MAX_SHORT_CHARS;
251
+ const CONDITION_KINDS = new Set(["if", "else_if", "do_until"]);
252
+ const BRANCH_KINDS = new Set(["else", "else_if", "catch"]);
253
+ const BRANCH_HEAD_KINDS = new Set(["if", "try"]);
254
+ const ROOT_KINDS = new Set(["top_level_try", "top_level_catch"]);
255
+ const TRIGGER_TABLE_INPUTS = Object.freeze(["table"]);
256
+ const TRIGGER_CONDITION_INPUTS = Object.freeze(["condition"]);
257
+ /** Best effort: no scheduled trigger was captured. */
258
+ const TRIGGER_SCHEDULE_INPUTS = Object.freeze(["schedule", "run_in", "repeat", "run_at", "run_time", "time"]);
259
+ const LOGIC_CONDITION_INPUTS = Object.freeze(["condition_name", "condition"]);
260
+ function stepSpec(table, kind, v2, valueColumn) {
261
+ const names = {
262
+ action: ["action_inputs", "action_title", "action_annotation"],
263
+ logic: ["logic_inputs", "logic_title", "logic_annotation"],
264
+ subflow: ["subflow_inputs", "subflow_title", "subflow_annotation"],
265
+ };
266
+ const [inputs, title, annotation] = names[kind];
267
+ return Object.freeze({
268
+ table,
269
+ kind,
270
+ v2,
271
+ valueColumn,
272
+ valueShape: kind === "logic" ? "logic" : "list",
273
+ inputs,
274
+ title,
275
+ annotation,
276
+ });
277
+ }
278
+ /** Fixed read order: action, logic, subflow; V1 before V2. */
279
+ const STEP_SPECS = Object.freeze([
280
+ stepSpec("sys_hub_action_instance", "action", false, null),
281
+ stepSpec("sys_hub_action_instance_v2", "action", true, "values"),
282
+ stepSpec("sys_hub_flow_logic", "logic", false, null),
283
+ stepSpec("sys_hub_flow_logic_instance_v2", "logic", true, "values"),
284
+ stepSpec("sys_hub_sub_flow_instance", "subflow", false, null),
285
+ stepSpec("sys_hub_sub_flow_instance_v2", "subflow", true, "subflow_inputs"),
286
+ ]);
287
+ function isSysIdSelector(selector) {
288
+ return typeof selector === "object" && selector !== null && Object.hasOwn(selector, "sys_id");
289
+ }
290
+ function ownData(candidate, key) {
291
+ if (typeof candidate !== "object" || candidate === null)
292
+ return undefined;
293
+ try {
294
+ const descriptor = Object.getOwnPropertyDescriptor(candidate, key);
295
+ return descriptor && "value" in descriptor ? descriptor.value : undefined;
296
+ }
297
+ catch {
298
+ return undefined;
299
+ }
300
+ }
301
+ function scalarText(candidate) {
302
+ if (typeof candidate === "string")
303
+ return candidate;
304
+ if (typeof candidate === "number" && Number.isFinite(candidate))
305
+ return String(candidate);
306
+ if (typeof candidate === "boolean")
307
+ return String(candidate);
308
+ return null;
309
+ }
310
+ /** The internal value of a cell: `value` of a `{value, display_value}` pair, or the scalar. */
311
+ function scalar(cell) {
312
+ const direct = scalarText(cell);
313
+ if (direct !== null)
314
+ return direct;
315
+ return scalarText(ownData(cell, "value")) ?? "";
316
+ }
317
+ /** The display value of a cell, falling back to its value. */
318
+ function display(cell) {
319
+ const direct = scalarText(cell);
320
+ if (direct !== null)
321
+ return direct;
322
+ const shown = scalarText(ownData(cell, "display_value"));
323
+ return shown !== null && shown !== "" ? shown : scalar(cell);
324
+ }
325
+ /** The display value of a cell only; null when it is empty. */
326
+ function displayOnly(cell) {
327
+ const shown = scalarText(cell) ?? scalarText(ownData(cell, "display_value"));
328
+ return shown === null || shown.trim() === "" ? null : shown;
329
+ }
330
+ /** A content cell, validated by the shared raw schema; null when it does not parse. */
331
+ function content(cell) {
332
+ const parsed = flow_view_contracts_js_1.rawFlowContentSchema.safeParse(cell === undefined ? null : cell);
333
+ return parsed.success ? parsed.data : null;
334
+ }
335
+ function sysIdOf(candidate) {
336
+ const parsed = servicenow_identifiers_js_1.serviceNowSysIdSchema.safeParse(candidate);
337
+ return parsed.success ? parsed.data : null;
338
+ }
339
+ function uidOf(candidate) {
340
+ const parsed = flow_view_contracts_js_1.rawFlowUidSchema.safeParse(candidate);
341
+ return parsed.success ? parsed.data.toLowerCase() : null;
342
+ }
343
+ function isFlowType(row) {
344
+ const type = scalar(row.type);
345
+ return type === "flow" || type === "subflow";
346
+ }
347
+ /** Control-free, trimmed, cut single line; null when empty. */
348
+ function line(text, max) {
349
+ if (text === null)
350
+ return null;
351
+ const clean = text.replace(/[\u0000-\u001F\u007F-\u009F]/gu, "").trim();
352
+ if (clean === "")
353
+ return null;
354
+ if (clean.length <= max)
355
+ return clean;
356
+ const last = clean.charCodeAt(max - 1);
357
+ return clean.slice(0, last >= 0xd800 && last <= 0xdbff ? max - 1 : max);
358
+ }
359
+ /**
360
+ * `sysparm_fields` for one table: the prepared readable set (via
361
+ * sysparmFieldsFor), minus value fields when inputs are not requested, or the
362
+ * subset of `only` that is readable.
363
+ */
364
+ function fieldsFor(plan, table, options = {}) {
365
+ const spec = flow_view_contracts_js_1.FLOW_TABLE_FIELDS[table];
366
+ const readable = plan.readable.get(table);
367
+ if (options.only) {
368
+ const fields = options.only.filter((field) => readable?.has(field) === true && !(0, field_policy_js_1.isSensitiveFieldName)(field));
369
+ if (fields.length !== options.only.length)
370
+ throw (0, tool_error_js_1.createToolError)("internal", "do_not_retry");
371
+ return fields.join(",");
372
+ }
373
+ const excluded = new Set([...(options.exclude ?? []), ...(options.values === false ? spec.values : [])]);
374
+ const fields = (0, flow_view_policy_js_1.sysparmFieldsFor)(plan, table)
375
+ .split(",")
376
+ .filter((field) => !excluded.has(field));
377
+ if (fields.length === 0)
378
+ throw (0, tool_error_js_1.createToolError)("internal", "do_not_retry");
379
+ return fields.join(",");
380
+ }
381
+ /**
382
+ * A trusted upstream rejection that is neither a 5xx nor one of the mapped
383
+ * 4xx statuses: what the Table API returns (HTTP 400) for a table that does
384
+ * not exist. The client exposes only the category, so this is the narrowest
385
+ * test available without the status. An error with a `reason` (a 200 body
386
+ * that is not JSON, an HTML page, a redirect, a hibernating instance) is a
387
+ * bad response, not a missing table: it fails the call instead of silently
388
+ * dropping that table's steps.
389
+ */
390
+ function isMissingTableError(error) {
391
+ const descriptor = (0, tool_error_js_1.trustedToolErrorDescriptor)(error);
392
+ return (descriptor?.category === "upstream" &&
393
+ descriptor.retry === "do_not_retry" &&
394
+ descriptor.reason === undefined);
395
+ }
396
+ /**
397
+ * One Table API read. Requests `maxRows + 1` rows: an extra row means the
398
+ * table has more than the bound, reported as `truncated` (the extra row is
399
+ * discarded). Rows pass `filterReadableRecord` against the requested fields.
400
+ */
401
+ async function readTable(reader, table, query, fields, options = {}) {
402
+ const maxRows = options.maxRows ?? exports.FLOW_TABLE_ROW_LIMIT;
403
+ let response;
404
+ try {
405
+ response = await reader.get(`${TABLE_PATH}${table}`, {
406
+ sysparm_query: query,
407
+ sysparm_fields: fields,
408
+ sysparm_display_value: options.raw === true ? "false" : "all",
409
+ sysparm_exclude_reference_link: "true",
410
+ sysparm_limit: String(maxRows + 1),
411
+ ...(options.offset !== undefined && options.offset > 0 ? { sysparm_offset: String(options.offset) } : {}),
412
+ });
413
+ }
414
+ catch (error) {
415
+ if (options.missingIsEmpty === true && isMissingTableError(error)) {
416
+ return { rows: [], truncated: false, bytes: 0 };
417
+ }
418
+ throw error;
419
+ }
420
+ const result = ownData(response, "result");
421
+ if (!Array.isArray(result))
422
+ throw (0, tool_error_js_1.createToolError)("upstream", "do_not_retry");
423
+ const bytes = Buffer.byteLength(JSON.stringify(result));
424
+ const filtered = (0, field_policy_js_1.filterReadableRecord)(result, fields.split(","));
425
+ if (!Array.isArray(filtered))
426
+ throw (0, tool_error_js_1.createToolError)("upstream", "do_not_retry");
427
+ const rows = filtered.filter((row) => typeof row === "object" && row !== null && !Array.isArray(row));
428
+ return rows.length > maxRows
429
+ ? { rows: rows.slice(0, maxRows), truncated: true, bytes }
430
+ : { rows, truncated: false, bytes };
431
+ }
432
+ /**
433
+ * Sort clause for a table whose `order` column is optional: by `order` only
434
+ * when the profile may read it, so a hidden column cannot leak through the
435
+ * order of the results; by `sys_id` alone otherwise.
436
+ */
437
+ function orderBy(plan, table) {
438
+ return plan.readable.get(table)?.has("order") === true ? "ORDERBYorder^ORDERBYsys_id" : "ORDERBYsys_id";
439
+ }
440
+ function chunks(items, size) {
441
+ const output = [];
442
+ for (let index = 0; index < items.length; index += size)
443
+ output.push(items.slice(index, index + size));
444
+ return output;
445
+ }
446
+ function drop(load) {
447
+ load.dropped += 1;
448
+ load.warnings.add("items_dropped_invalid");
449
+ return null;
450
+ }
451
+ // --- Header ----------------------------------------------------------------
452
+ function shortText(plan, element, raw) {
453
+ return line((0, flow_view_policy_js_1.policyText)(plan, element, raw, SHORT_TEXT_CHARS).text, SHORT_TEXT_CHARS);
454
+ }
455
+ function headerFrom(plan, row, sysId) {
456
+ const type = scalar(row.type);
457
+ const active = scalar(row.active);
458
+ return {
459
+ sys_id: sysId,
460
+ name: (0, flow_view_policy_js_1.policyText)(plan, "flow_name", content(row.name), flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_TITLE_CHARS),
461
+ description: (0, flow_view_policy_js_1.policyText)(plan, "flow_description", content(row.description), flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_INPUT_VALUE_CHARS),
462
+ type: (0, flow_view_policy_js_1.canShow)(plan, "flow_type") && (type === "flow" || type === "subflow") ? type : null,
463
+ active: (0, flow_view_policy_js_1.canShow)(plan, "flow_active") ? (active === "true" ? true : active === "false" ? false : null) : null,
464
+ status: shortText(plan, "flow_status", scalar(row.status)),
465
+ version: shortText(plan, "flow_version", scalar(row.version)),
466
+ scope: shortText(plan, "flow_scope", content(row.sys_scope)),
467
+ };
468
+ }
469
+ // --- Label cache -------------------------------------------------------------
470
+ /** The raw `label_cache` text; undefined when pill labels are not readable. */
471
+ async function readLabelCacheText(load) {
472
+ if (!(0, flow_view_policy_js_1.canShow)(load.plan, "pill_labels"))
473
+ return undefined;
474
+ const { rows } = await readTable(load.reader, "sys_hub_flow", `sys_id=${load.flowId}`, fieldsFor(load.plan, "sys_hub_flow", { only: ["sys_id", "label_cache"] }),
475
+ // The display value of label_cache is the same JSON text.
476
+ { maxRows: 1, raw: true });
477
+ const row = rows.find((candidate) => sysIdOf(scalar(candidate.sys_id)) === load.flowId);
478
+ return row ? scalar(row.label_cache) : "";
479
+ }
480
+ function parseLabelCache(load, text) {
481
+ const { plan } = load;
482
+ if (text === undefined || !(0, flow_view_policy_js_1.canShow)(plan, "pill_labels")) {
483
+ load.warnings.add("label_cache_unavailable");
484
+ return [];
485
+ }
486
+ if (text.trim() === "")
487
+ return [];
488
+ const parsed = text.length > exports.FLOW_LABEL_CACHE_MAX_CHARS ? null : (0, flow_view_gzip_js_1.parseBoundedJson)(text);
489
+ if (!parsed?.ok || !Array.isArray(parsed.value)) {
490
+ load.warnings.add("label_cache_unavailable");
491
+ return [];
492
+ }
493
+ const output = [];
494
+ const seen = new Set();
495
+ for (const entry of parsed.value) {
496
+ const item = flow_view_contracts_js_1.rawLabelCacheEntrySchema.safeParse(entry);
497
+ if (!item.success) {
498
+ drop(load);
499
+ continue;
500
+ }
501
+ const token = line(item.data.name, Number.MAX_SAFE_INTEGER);
502
+ if (token === null || token.length > flow_view_contracts_js_1.FLOW_GRAPH_SCHEMA_BOUNDS.MAX_PILL_TOKEN_CHARS) {
503
+ drop(load);
504
+ continue;
505
+ }
506
+ if (seen.has(token))
507
+ continue;
508
+ const label = line((0, flow_view_policy_js_1.policyText)(plan, "pill_labels", item.data.label ?? null, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_PILL_LABEL_CHARS).text, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_PILL_LABEL_CHARS);
509
+ if (label === null)
510
+ continue;
511
+ if (output.length >= exports.FLOW_LABEL_CACHE_MAX_ENTRIES) {
512
+ load.limits.add("pills");
513
+ break;
514
+ }
515
+ seen.add(token);
516
+ output.push(Object.freeze([token, label]));
517
+ }
518
+ return output;
519
+ }
520
+ // --- Triggers ----------------------------------------------------------------
521
+ function readTriggerTable(load, table) {
522
+ return readTable(load.reader, table, `flow=${load.flowId}^ORDERBYsys_id`, fieldsFor(load.plan, table, { values: false }), { missingIsEmpty: table.endsWith("_v2") });
523
+ }
524
+ function collectTriggerRows(load, tables, reads) {
525
+ const output = { v1: [], v2: [] };
526
+ for (const [index, table] of tables.entries()) {
527
+ const v2 = table.endsWith("_v2");
528
+ const { rows, truncated } = reads[index];
529
+ if (truncated)
530
+ load.limits.add("rows_per_table");
531
+ for (const row of rows) {
532
+ const sysId = sysIdOf(scalar(row.sys_id));
533
+ if (sysId === null || sysIdOf(scalar(row.flow)) !== load.flowId) {
534
+ drop(load);
535
+ continue;
536
+ }
537
+ (v2 ? output.v2 : output.v1).push({ table, v2, row, sysId });
538
+ }
539
+ }
540
+ return output;
541
+ }
542
+ function assembleTrigger(load, trigger, v1Values) {
543
+ const { plan } = load;
544
+ const output = {
545
+ type: (0, flow_view_policy_js_1.policyText)(plan, "trigger_type", content(trigger.row.trigger_type), flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_TITLE_CHARS),
546
+ table: notRequested(),
547
+ condition: notRequested(),
548
+ schedule: notRequested(),
549
+ };
550
+ if (!load.includeInputs)
551
+ return output;
552
+ const inputs = trigger.v2
553
+ ? decodeInputs(load, load.blobs.get(`${trigger.table}:${trigger.sysId}`), "list", "trigger_inputs", "trigger_inputs")
554
+ : projectV1(load, "trigger_inputs", v1Values.get(trigger.sysId) ?? []);
555
+ output.inputs = inputs;
556
+ output.table = fromInputs(plan, "trigger_inputs", inputs, TRIGGER_TABLE_INPUTS, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_INPUT_VALUE_CHARS);
557
+ output.condition = fromInputs(plan, "trigger_inputs", inputs, TRIGGER_CONDITION_INPUTS, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_INPUT_VALUE_CHARS);
558
+ output.schedule = fromInputs(plan, "trigger_inputs", inputs, TRIGGER_SCHEDULE_INPUTS, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_INPUT_VALUE_CHARS);
559
+ return output;
560
+ }
561
+ /** The FlowText for a value element when inputs were not requested. */
562
+ function notRequested() {
563
+ return { text: null, redacted: "not_requested" };
564
+ }
565
+ /**
566
+ * Text derived from an already-projected input, carrying its redaction. The
567
+ * first named input with a value wins; a redacted one is reported as such.
568
+ */
569
+ function fromInputs(plan, element, inputs, names, maxChars) {
570
+ for (const name of names) {
571
+ const input = inputs.find((candidate) => candidate.name === name);
572
+ if (!input)
573
+ continue;
574
+ if (input.redacted)
575
+ return { text: null, redacted: input.redacted };
576
+ const text = line(input.value, Number.MAX_SAFE_INTEGER);
577
+ if (text === null)
578
+ continue;
579
+ if (text.length <= maxChars && input.original_length === undefined)
580
+ return { text };
581
+ return { text: line(text, maxChars), original_length: input.original_length ?? text.length };
582
+ }
583
+ return (0, flow_view_policy_js_1.canShow)(plan, element) ? { text: null } : { text: null, redacted: "field_policy" };
584
+ }
585
+ /**
586
+ * One raw read per V2 table that returned rows and whose value column is
587
+ * readable. The structural reads leave the column out, because with
588
+ * `sysparm_display_value=all` it would come back twice.
589
+ */
590
+ function blobReadsFor(load, triggers, steps) {
591
+ const readable = (table, column) => load.plan.readable.get(table)?.has(column) === true;
592
+ const output = [];
593
+ if (triggers.v2.length > 0 && readable("sys_hub_trigger_instance_v2", "trigger_inputs")) {
594
+ output.push({
595
+ table: "sys_hub_trigger_instance_v2",
596
+ column: "trigger_inputs",
597
+ query: `flow=${load.flowId}^ORDERBYsys_id`,
598
+ });
599
+ }
600
+ const kept = new Set([...steps.values()].map((step) => step.spec.table));
601
+ for (const spec of STEP_SPECS) {
602
+ if (spec.valueColumn === null || !kept.has(spec.table) || !readable(spec.table, spec.valueColumn))
603
+ continue;
604
+ output.push({
605
+ table: spec.table,
606
+ column: spec.valueColumn,
607
+ query: `flow=${load.flowId}^ORDERBYorder^ORDERBYsys_id`,
608
+ });
609
+ }
610
+ return output;
611
+ }
612
+ function readBlobColumn(load, blob) {
613
+ return readTable(load.reader, blob.table, blob.query, fieldsFor(load.plan, blob.table, { only: ["sys_id", blob.column] }), { raw: true });
614
+ }
615
+ // --- Steps -------------------------------------------------------------------
616
+ function addStep(load, steps, spec, row) {
617
+ const sysId = sysIdOf(scalar(row.sys_id));
618
+ const uid = uidOf(scalar(row.ui_id));
619
+ if (sysId === null || uid === null || sysIdOf(scalar(row.flow)) !== load.flowId) {
620
+ drop(load);
621
+ return;
622
+ }
623
+ const parentText = scalar(row.parent_ui_id).trim();
624
+ const parentUid = parentText === "" ? null : uidOf(parentText);
625
+ if (parentText !== "" && parentUid === null) {
626
+ drop(load);
627
+ return;
628
+ }
629
+ let logicKind;
630
+ let connectedUid = null;
631
+ if (spec.kind === "logic") {
632
+ logicKind = (0, flow_view_policy_js_1.canShow)(load.plan, "logic_title") ? (0, flow_view_contracts_js_1.flowLogicKindFromName)(display(row.logic_definition)) : "other";
633
+ if (logicKind === "other")
634
+ load.warnings.add("unknown_logic_type");
635
+ const connectedText = scalar(row.connected_to).trim();
636
+ connectedUid = connectedText === "" ? null : uidOf(connectedText);
637
+ }
638
+ const step = {
639
+ spec,
640
+ row,
641
+ sysId,
642
+ uid,
643
+ parentUid,
644
+ connectedUid,
645
+ order: parseFlowOrder(scalar(row.order)),
646
+ logicKind,
647
+ };
648
+ const existing = steps.get(uid);
649
+ if (!existing) {
650
+ steps.set(uid, step);
651
+ return;
652
+ }
653
+ // The same step stored in both V1 and V2 tables: V2 is the current copy.
654
+ if (!existing.spec.v2 && spec.v2 && existing.spec.kind === spec.kind) {
655
+ steps.set(uid, step);
656
+ return;
657
+ }
658
+ drop(load);
659
+ }
660
+ /**
661
+ * Apply the capture's structural rules, then make the parent links a forest:
662
+ * - Top Level Try and Top Level Catch are roots.
663
+ * - Else, Else If and Catch pair with their head If or Try through
664
+ * `connected_to` and take the head's parent.
665
+ * - Every other step has no `connected_uid`.
666
+ * - A parent that is not a loaded step, or a parent cycle, makes the step a
667
+ * root with the `orphan_steps` warning.
668
+ */
669
+ function normalizeStructure(load, steps) {
670
+ for (const step of steps.values()) {
671
+ const kind = step.logicKind;
672
+ if (kind !== undefined && ROOT_KINDS.has(kind))
673
+ step.parentUid = null;
674
+ if (kind === undefined || !BRANCH_KINDS.has(kind)) {
675
+ step.connectedUid = null;
676
+ continue;
677
+ }
678
+ const head = step.connectedUid === null ? undefined : steps.get(step.connectedUid);
679
+ if (!head || head.logicKind === undefined || !BRANCH_HEAD_KINDS.has(head.logicKind)) {
680
+ if (step.connectedUid !== null)
681
+ load.warnings.add("orphan_steps");
682
+ step.connectedUid = null;
683
+ continue;
684
+ }
685
+ step.parentUid = head.parentUid;
686
+ }
687
+ for (const step of steps.values()) {
688
+ if (step.parentUid !== null && (step.parentUid === step.uid || !steps.has(step.parentUid))) {
689
+ step.parentUid = null;
690
+ load.warnings.add("orphan_steps");
691
+ }
692
+ }
693
+ const status = new Map();
694
+ for (const start of steps.values()) {
695
+ const path = [];
696
+ let current = start;
697
+ while (current && !status.has(current.uid)) {
698
+ status.set(current.uid, 1);
699
+ path.push(current);
700
+ current = current.parentUid === null ? undefined : steps.get(current.parentUid);
701
+ }
702
+ if (current && status.get(current.uid) === 1) {
703
+ path[path.length - 1].parentUid = null;
704
+ load.warnings.add("orphan_steps");
705
+ }
706
+ for (const node of path)
707
+ status.set(node.uid, 2);
708
+ }
709
+ // A branch whose head lost its parent above no longer shares it: unpair it
710
+ // rather than move it (moving could close a new cycle).
711
+ for (const step of steps.values()) {
712
+ if (step.connectedUid === null)
713
+ continue;
714
+ if (steps.get(step.connectedUid)?.parentUid !== step.parentUid) {
715
+ step.connectedUid = null;
716
+ load.warnings.add("orphan_steps");
717
+ }
718
+ }
719
+ }
720
+ function compareSteps(left, right) {
721
+ const a = left.order ?? Number.POSITIVE_INFINITY;
722
+ const b = right.order ?? Number.POSITIVE_INFINITY;
723
+ if (a !== b)
724
+ return a < b ? -1 : 1;
725
+ return left.uid < right.uid ? -1 : left.uid > right.uid ? 1 : 0;
726
+ }
727
+ function assembleSteps(load, steps, targets, v1Values) {
728
+ const { plan } = load;
729
+ return [...steps.values()].sort(compareSteps).map((raw) => {
730
+ const { spec, row } = raw;
731
+ const titleCell = spec.kind === "action" ? row.action_type : spec.kind === "logic" ? row.logic_definition : row.subflow;
732
+ const title = (0, flow_view_policy_js_1.policyText)(plan, spec.title, content(titleCell), flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_TITLE_CHARS);
733
+ const step = {
734
+ uid: raw.uid,
735
+ parent_uid: raw.parentUid,
736
+ order: raw.order,
737
+ connected_uid: raw.connectedUid,
738
+ kind: spec.kind,
739
+ title,
740
+ annotation: (0, flow_view_policy_js_1.policyText)(plan, spec.annotation, content(row.comment), flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_INPUT_VALUE_CHARS),
741
+ inputs: [],
742
+ ref: { table: spec.table, sys_id: raw.sysId },
743
+ };
744
+ if (raw.logicKind !== undefined)
745
+ step.logic_kind = raw.logicKind;
746
+ if (load.includeInputs) {
747
+ step.inputs =
748
+ spec.valueColumn !== null
749
+ ? decodeInputs(load, load.blobs.get(`${spec.table}:${raw.sysId}`), spec.valueShape, spec.inputs, spec.valueColumn)
750
+ : projectV1(load, spec.inputs, v1Values.get(raw.sysId) ?? []);
751
+ }
752
+ if (raw.logicKind !== undefined && CONDITION_KINDS.has(raw.logicKind)) {
753
+ step.condition = load.includeInputs
754
+ ? fromInputs(plan, spec.inputs, step.inputs, LOGIC_CONDITION_INPUTS, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_TITLE_CHARS)
755
+ : notRequested();
756
+ }
757
+ if (spec.kind === "subflow") {
758
+ const snapshot = sysIdOf(scalar(row.subflow));
759
+ step.subflow = {
760
+ flow_sys_id: (0, flow_view_policy_js_1.canShow)(plan, "subflow_title") && snapshot !== null ? targets.get(snapshot) ?? null : null,
761
+ name: title,
762
+ };
763
+ }
764
+ return step;
765
+ });
766
+ }
767
+ // --- Inputs ------------------------------------------------------------------
768
+ function decodeFailed(column) {
769
+ return { name: DECODE_FAILED_NAMES[column], label: null, type: null, value: null, redacted: "decode_failed" };
770
+ }
771
+ /** Decode one V2 blob and project its inputs; failures become one `decode_failed` input. */
772
+ function decodeInputs(load, cell, shape, element, column) {
773
+ const blob = scalar(cell);
774
+ if (blob.trim() === "")
775
+ return [];
776
+ const decoded = (0, flow_view_gzip_js_1.decodeCompressedJson)(blob, load.budget);
777
+ if (!decoded.ok) {
778
+ load.warnings.add("gzip_decode_failed");
779
+ return [decodeFailed(column)];
780
+ }
781
+ let entries;
782
+ if (shape === "logic") {
783
+ const parsed = flow_view_contracts_js_1.rawFlowLogicValuesSchema.safeParse(decoded.value);
784
+ if (!parsed.success) {
785
+ load.warnings.add("gzip_decode_failed");
786
+ return [decodeFailed(column)];
787
+ }
788
+ entries = [...(parsed.data.inputs ?? []), ...(parsed.data.variables ?? [])];
789
+ }
790
+ else {
791
+ const parsed = flow_view_contracts_js_1.rawFlowInputListSchema.safeParse(decoded.value);
792
+ if (!parsed.success) {
793
+ load.warnings.add("gzip_decode_failed");
794
+ return [decodeFailed(column)];
795
+ }
796
+ entries = parsed.data;
797
+ }
798
+ const raws = [];
799
+ const seen = new Set();
800
+ for (const entry of entries) {
801
+ const parsed = flow_view_contracts_js_1.rawFlowInputSchema.safeParse(entry);
802
+ if (!parsed.success) {
803
+ drop(load);
804
+ continue;
805
+ }
806
+ const input = parsed.data;
807
+ // Logic `variables` repeat the `inputs` entry of the same name (Set Flow Variables).
808
+ if (seen.has(input.name))
809
+ continue;
810
+ seen.add(input.name);
811
+ raws.push({
812
+ name: input.name,
813
+ label: input.parameter?.label ?? input.label ?? null,
814
+ type: input.parameter?.type ?? input.internalType ?? null,
815
+ value: input.value,
816
+ displayValue: input.displayValue,
817
+ ...(input.scriptActive === true ? { script: true } : {}),
818
+ });
819
+ }
820
+ return projectInputs(load, element, raws);
821
+ }
822
+ function projectV1(load, element, raws) {
823
+ return projectInputs(load, element, raws);
824
+ }
825
+ function projectInputs(load, element, raws) {
826
+ const output = [];
827
+ for (const raw of raws) {
828
+ if (output.length >= flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_INPUTS_PER_NODE) {
829
+ load.limits.add("inputs_per_node");
830
+ break;
831
+ }
832
+ output.push((0, flow_view_policy_js_1.policyInput)(load.plan, element, {
833
+ name: raw.name,
834
+ label: raw.label,
835
+ type: raw.type,
836
+ value: raw.value,
837
+ displayValue: raw.displayValue,
838
+ ...(raw.script === true ? { script: true } : {}),
839
+ }));
840
+ }
841
+ return output;
842
+ }
843
+ /**
844
+ * V1 values: `sys_variable_value` rows of the kept V1 rows (chunks of 100
845
+ * document keys), then the `var_dictionary` rows that name and type them.
846
+ * Returns the values of each V1 row by its sys_id, in instance order.
847
+ */
848
+ async function readV1Values(load, documents) {
849
+ const output = new Map();
850
+ if (documents.length === 0)
851
+ return output;
852
+ const tableOf = new Map(documents.map((document) => [document.sysId, document.table]));
853
+ const fields = fieldsFor(load.plan, "sys_variable_value", { values: true });
854
+ const values = [];
855
+ let lastReadBytes;
856
+ let budgetSpent = false;
857
+ for (const chunk of chunks([...tableOf.keys()], flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_SYS_ID_IN_CHUNK)) {
858
+ if (budgetSpent)
859
+ break;
860
+ const keys = new Set(chunk);
861
+ const rows = [];
862
+ // Page past the row cap, up to what MAX_INPUTS_PER_NODE values per step
863
+ // can use, and while the scope allows; anything beyond that is
864
+ // reported, never dropped silently.
865
+ const pages = Math.max(1, Math.ceil((chunk.length * flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_INPUTS_PER_NODE) / exports.FLOW_TABLE_ROW_LIMIT));
866
+ for (let page = 0; page < pages; page += 1) {
867
+ if (lastReadBytes !== undefined && load.readBytes + lastReadBytes > V1_VALUE_SCOPE_BYTES) {
868
+ load.limits.add("rows_per_table");
869
+ load.warnings.add("input_values_incomplete");
870
+ budgetSpent = true;
871
+ break;
872
+ }
873
+ const read = await readTable(load.reader, "sys_variable_value", `document_keyIN${chunk.join(",")}^${orderBy(load.plan, "sys_variable_value")}`, fields, { offset: page * exports.FLOW_TABLE_ROW_LIMIT });
874
+ rows.push(...read.rows);
875
+ load.readBytes += read.bytes;
876
+ lastReadBytes = read.bytes;
877
+ if (!read.truncated)
878
+ break;
879
+ if (page === pages - 1) {
880
+ load.limits.add("rows_per_table");
881
+ load.warnings.add("input_values_incomplete");
882
+ }
883
+ }
884
+ for (const row of rows) {
885
+ const key = sysIdOf(scalar(row.document_key));
886
+ const variable = sysIdOf(scalar(row.variable));
887
+ if (sysIdOf(scalar(row.sys_id)) === null ||
888
+ key === null ||
889
+ variable === null ||
890
+ !keys.has(key) ||
891
+ tableOf.get(key) !== scalar(row.document)) {
892
+ drop(load);
893
+ continue;
894
+ }
895
+ values.push({ key, variable, row });
896
+ }
897
+ }
898
+ const definitions = await readDefinitions(load, [...new Set(values.map((value) => value.variable))]);
899
+ for (const { key, variable, row } of values) {
900
+ const definition = definitions.get(variable);
901
+ const list = output.get(key) ?? [];
902
+ list.push({
903
+ // Without a readable definition the name is unknown: policyInput fails closed.
904
+ name: definition?.element ?? "",
905
+ label: displayOnly(row.variable),
906
+ type: definition?.type ?? null,
907
+ value: scalar(row.value),
908
+ displayValue: display(row.value),
909
+ });
910
+ output.set(key, list);
911
+ }
912
+ return output;
913
+ }
914
+ async function readDefinitions(load, ids) {
915
+ const output = new Map();
916
+ const readable = load.plan.readable.get("var_dictionary");
917
+ if (ids.length === 0 || !readable?.has("element"))
918
+ return output;
919
+ const fields = fieldsFor(load.plan, "var_dictionary", { values: true });
920
+ for (const chunk of chunks(ids, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_SYS_ID_IN_CHUNK)) {
921
+ const wanted = new Set(chunk);
922
+ const { rows, truncated } = await readTable(load.reader, "var_dictionary", `sys_idIN${chunk.join(",")}^ORDERBYsys_id`, fields);
923
+ if (truncated)
924
+ load.limits.add("rows_per_table");
925
+ for (const row of rows) {
926
+ const id = sysIdOf(scalar(row.sys_id));
927
+ if (id === null || !wanted.has(id)) {
928
+ drop(load);
929
+ continue;
930
+ }
931
+ const element = scalar(row.element);
932
+ if (element.trim() === "")
933
+ continue;
934
+ const type = scalar(row.internal_type);
935
+ output.set(id, { element, type: type === "" ? null : type });
936
+ }
937
+ }
938
+ return output;
939
+ }
940
+ // --- Subflow targets ---------------------------------------------------------
941
+ async function resolveSubflowTargets(reader, plan, refs) {
942
+ const output = new Map();
943
+ const readable = plan.readable.get("sys_hub_flow_snapshot");
944
+ if (!(0, flow_view_policy_js_1.canShow)(plan, "subflow_title") || !readable?.has("sys_id") || !readable.has("parent_flow")) {
945
+ return output;
946
+ }
947
+ const ids = [...new Set(refs.map((ref) => sysIdOf(ref)).filter((id) => id !== null))];
948
+ const fields = fieldsFor(plan, "sys_hub_flow_snapshot", { only: ["sys_id", "parent_flow"] });
949
+ for (const chunk of chunks(ids, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_SYS_ID_IN_CHUNK)) {
950
+ const wanted = new Set(chunk);
951
+ const { rows } = await readTable(reader, "sys_hub_flow_snapshot", `sys_idIN${chunk.join(",")}^ORDERBYsys_id`, fields);
952
+ for (const row of rows) {
953
+ const id = sysIdOf(scalar(row.sys_id));
954
+ const parent = sysIdOf(scalar(row.parent_flow));
955
+ if (id !== null && parent !== null && wanted.has(id))
956
+ output.set(id, parent);
957
+ }
958
+ }
959
+ return output;
960
+ }
961
+ // --- Variables ---------------------------------------------------------------
962
+ const VARIABLE_TABLES = Object.freeze([
963
+ ["sys_hub_flow_variable", "variable", "flow_variables"],
964
+ ["sys_hub_flow_input", "input", "flow_inputs"],
965
+ ["sys_hub_flow_output", "output", "flow_outputs"],
966
+ ]);
967
+ /** The variable, input and output reads whose element is showable; null where skipped. */
968
+ function readVariableTables(load) {
969
+ return Promise.all(VARIABLE_TABLES.map(([table, , element]) => (0, flow_view_policy_js_1.canShow)(load.plan, element)
970
+ ? readTable(load.reader, table, `model=${load.flowId}^${orderBy(load.plan, table)}`, fieldsFor(load.plan, table))
971
+ : Promise.resolve(null)));
972
+ }
973
+ function collectVariables(load, reads) {
974
+ const output = [];
975
+ for (const [index, [, scope, element]] of VARIABLE_TABLES.entries()) {
976
+ const read = reads[index];
977
+ if (!read)
978
+ continue;
979
+ const { rows, truncated } = read;
980
+ if (truncated)
981
+ load.limits.add("rows_per_table");
982
+ for (const row of rows) {
983
+ if (sysIdOf(scalar(row.sys_id)) === null || sysIdOf(scalar(row.model)) !== load.flowId) {
984
+ drop(load);
985
+ continue;
986
+ }
987
+ const name = line((0, flow_view_policy_js_1.policyText)(load.plan, element, scalar(row.element), flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_NAME_CHARS).text, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_NAME_CHARS);
988
+ if (name === null) {
989
+ drop(load);
990
+ continue;
991
+ }
992
+ output.push({
993
+ scope,
994
+ name,
995
+ label: line((0, flow_view_policy_js_1.policyText)(load.plan, element, content(row.label), flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_TITLE_CHARS).text, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_TITLE_CHARS),
996
+ type: line((0, flow_view_policy_js_1.policyText)(load.plan, element, scalar(row.internal_type), flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_NAME_CHARS).text, flow_view_contracts_js_1.FLOW_VIEW_LIMITS.MAX_NAME_CHARS),
997
+ });
998
+ }
999
+ }
1000
+ return output;
1001
+ }
1002
+ //# sourceMappingURL=flow-view-table.js.map