@onlyflows/servicenow-mcp 2.3.0-rc.2 → 2.3.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 (46) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +28 -1
  3. package/dist/field-policy.d.ts +13 -3
  4. package/dist/field-policy.d.ts.map +1 -1
  5. package/dist/field-policy.js +316 -23
  6. package/dist/field-policy.js.map +1 -1
  7. package/dist/policy-card.d.ts.map +1 -1
  8. package/dist/policy-card.js +2 -0
  9. package/dist/policy-card.js.map +1 -1
  10. package/dist/risky-grants.d.ts +6 -2
  11. package/dist/risky-grants.d.ts.map +1 -1
  12. package/dist/risky-grants.js +57 -5
  13. package/dist/risky-grants.js.map +1 -1
  14. package/dist/tools/platform-view-contracts.d.ts +2 -2
  15. package/dist/tools/platform-view-evaluate.d.ts +214 -6
  16. package/dist/tools/platform-view-evaluate.d.ts.map +1 -1
  17. package/dist/tools/platform-view-evaluate.js +1337 -10
  18. package/dist/tools/platform-view-evaluate.js.map +1 -1
  19. package/dist/update-set-eval/engine.d.ts +29 -0
  20. package/dist/update-set-eval/engine.d.ts.map +1 -0
  21. package/dist/update-set-eval/engine.js +405 -0
  22. package/dist/update-set-eval/engine.js.map +1 -0
  23. package/dist/update-set-eval/prepare.d.ts +72 -0
  24. package/dist/update-set-eval/prepare.d.ts.map +1 -0
  25. package/dist/update-set-eval/prepare.js +216 -0
  26. package/dist/update-set-eval/prepare.js.map +1 -0
  27. package/dist/update-set-eval/rules.d.ts +126 -0
  28. package/dist/update-set-eval/rules.d.ts.map +1 -0
  29. package/dist/update-set-eval/rules.js +927 -0
  30. package/dist/update-set-eval/rules.js.map +1 -0
  31. package/dist/update-set-eval/script-scan.d.ts +65 -0
  32. package/dist/update-set-eval/script-scan.d.ts.map +1 -0
  33. package/dist/update-set-eval/script-scan.js +378 -0
  34. package/dist/update-set-eval/script-scan.js.map +1 -0
  35. package/dist/update-set-eval/secret-patterns.js +2 -2
  36. package/dist/update-set-eval/secret-patterns.js.map +1 -1
  37. package/dist/update-set-eval/types.d.ts +181 -0
  38. package/dist/update-set-eval/types.d.ts.map +1 -0
  39. package/dist/update-set-eval/types.js +20 -0
  40. package/dist/update-set-eval/types.js.map +1 -0
  41. package/dist/version.d.ts +1 -1
  42. package/dist/version.d.ts.map +1 -1
  43. package/dist/version.js +1 -1
  44. package/dist/version.js.map +1 -1
  45. package/package.json +1 -1
  46. package/server.json +2 -2
@@ -1,19 +1,1346 @@
1
1
  "use strict";
2
2
  /**
3
- * `sn_platform_view`, view `evaluate`: a stub. It returns a fixed tool error
4
- * until the view is implemented. The dispatcher
5
- * (`platform-view-module.ts`) and the schema (`platform-view-contracts.ts`)
6
- * need no change when it does.
3
+ * `sn_platform_view`, view `evaluate`: runs the update set evaluator
4
+ * (`update-set-eval/engine.ts`) over a scope the view reads itself, inside the
5
+ * view's access plan.
6
+ *
7
+ * Scope, from exactly one selector:
8
+ * - `update_set` (sys_id or exact name): a local set, with its descendants
9
+ * unless `include_children: false`;
10
+ * - `batch_root` (sys_id): a local batch, the root and every descendant;
11
+ * - `remote_update_set` (sys_id): a retrieved set's rows, with its descendant
12
+ * remote sets unless `include_children: false`. This is the input a commit
13
+ * plan evaluates: what will actually be committed.
14
+ *
15
+ * Reads, each group in its own 1 MiB response scope, at most
16
+ * {@link EVALUATE_LIMITS}.MAX_SCOPES (12) scopes per call:
17
+ * 1. resolve: the set (`sys_update_set` or `sys_remote_update_set`), its
18
+ * descendants one level per read through `parent` (depth and count
19
+ * capped, cycle-safe; a level too large for the scope stops the descent
20
+ * and makes the result partial), one Aggregate API count of its rows per
21
+ * set, and one read of the sys_ids that have a description (set reads
22
+ * never ask for the description itself);
23
+ * 2. rows: `sys_update_xml` pages with `payload`, keyed on `sys_id`, one
24
+ * scope per page. The first page is 10 rows; later pages grow (at least
25
+ * doubling, up to 50) while the measured payloads fit. A page too large
26
+ * for its scope is read again at half the size, and that size becomes a
27
+ * ceiling. A single row too large for a scope is read without its
28
+ * payload and counts as not scanned. Rows stop at `max_updates`
29
+ * (effectively 400 when not given) or when only the scopes the next steps
30
+ * need are left;
31
+ * 3. context, one scope: the tables the rows write to, from `sys_db_object`
32
+ * one level per read (the parent's name is a declared one-hop dot-walk),
33
+ * and the hidden-typed fields from one `sys_dictionary` read. These feed
34
+ * the shared credential-table list and type helper, so the type read stays
35
+ * inside this view's plan (`fieldTypesFromRows`). A table whose hierarchy
36
+ * is not known in full is treated as a possible credential table: its
37
+ * rows are not scanned, and the result is partial. When the `bp` group
38
+ * runs, the update versions of the rows' names (BP005, at most 500 names)
39
+ * are counted in this scope too;
40
+ * 4. when the `bp` group runs, one more scope: the preview problems of a
41
+ * remote scope, or, for a local scope, the same update names in other
42
+ * open sets (BP004).
43
+ *
44
+ * Update names go into a `nameIN` list only when they are plain names with
45
+ * no script prefix ({@link isListableName}); any other name is not checked,
46
+ * and is counted.
47
+ *
48
+ * Payload: only `sys_update_xml.payload` is read, always by name in an
49
+ * explicit field list, and only when field policy allows that field.
50
+ * `sys_update_version` (which also carries payloads) is counted through the
51
+ * Aggregate API, never read as rows. A row on a credential table, or on a
52
+ * table that extends one, is never scanned: the engine keeps its metadata and
53
+ * reports SEC010.
54
+ *
55
+ * A fact that could not be read, in full or in part, is counted in
56
+ * `coverage.checks_unavailable` and makes the result `partial`; it never
57
+ * reads as clean. A payload that field policy hides runs the metadata rules
58
+ * only (`metadata_only`).
59
+ *
60
+ * Text: the engine's messages are fixed sentences and its findings carry no
61
+ * payload text. Row and set names, target names, types and SEC011's table are
62
+ * instance text: they are bounded here and rendered by
63
+ * {@link renderEvaluateText} inside an `untrustedBlock`, never as markdown.
64
+ * Every warning and hint is a fixed sentence. A throw from the engine is
65
+ * replaced by a fixed internal error.
7
66
  *
8
67
  * @module tools/platform-view-evaluate
9
68
  */
10
69
  Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.handleEvaluate = void 0;
70
+ exports.handleEvaluate = exports.EVALUATE_DOT_WALKS = exports.EVALUATE_FIELD_PLAN = exports.EVALUATE_WARNINGS = exports.EVALUATE_METADATA_ONLY = exports.EVALUATE_AMBIGUOUS_HINT = exports.EVALUATE_NOT_FOUND_HINT = exports.EVALUATE_UNAVAILABLE_HINT = exports.EVALUATE_DENIED_HINT = exports.EVALUATE_NOTE = exports.EVALUATE_LIMITS = void 0;
71
+ exports.outsideCdataAndComments = outsideCdataAndComments;
72
+ exports.candidateTables = candidateTables;
73
+ exports.collectCandidateTables = collectCandidateTables;
74
+ exports.isListableName = isListableName;
75
+ exports.createEvaluateHandler = createEvaluateHandler;
76
+ exports.renderEvaluateText = renderEvaluateText;
77
+ const client_js_1 = require("../client.js");
78
+ const credential_tables_js_1 = require("../credential-tables.js");
79
+ const hidden_values_js_1 = require("../hidden-values.js");
80
+ const metadata_cache_js_1 = require("../metadata-cache.js");
12
81
  const tool_error_js_1 = require("../tool-error.js");
13
- const handleEvaluate = async () => {
14
- // Not implemented: the `internal` category is the fixed error the dispatcher
15
- // passes through, and no argument or instance text is part of it.
16
- throw (0, tool_error_js_1.createToolError)("internal", "do_not_retry");
82
+ const utils_js_1 = require("../utils.js");
83
+ const engine_js_1 = require("../update-set-eval/engine.js");
84
+ const flow_view_module_js_1 = require("./flow-view-module.js");
85
+ const markdown_js_1 = require("./markdown.js");
86
+ const platform_view_upgrades_js_1 = require("./platform-view-upgrades.js");
87
+ // ---------------------------------------------------------------------------
88
+ // Limits and fixed text
89
+ // ---------------------------------------------------------------------------
90
+ exports.EVALUATE_LIMITS = Object.freeze({
91
+ /** Response scopes per call, each under the client's 1 MiB cap. */
92
+ MAX_SCOPES: 12,
93
+ /** Rows per `sys_update_xml` page, payload included, at most. */
94
+ PAGE_ROWS: 50,
95
+ /** The first page's rows; later pages grow while their payloads fit. */
96
+ FIRST_PAGE_ROWS: 10,
97
+ /** Payload characters a page is sized to, well under the 1 MiB scope. */
98
+ PAGE_TARGET_CHARS: 600_000,
99
+ /**
100
+ * `max_updates` when the caller sets none. The schema says 1,000, but the
101
+ * scope budget reaches about 400 rows (9 pages), so 400 is the effective
102
+ * default: an explicit `max_updates` warning, not the scope budget, says
103
+ * what was left out.
104
+ */
105
+ DEFAULT_MAX_UPDATES: 400,
106
+ /** Sets in one scope (a set and its descendants). */
107
+ MAX_SETS: 100,
108
+ /** Levels of descendants read through `parent`. */
109
+ MAX_DEPTH: 10,
110
+ /** Distinct tables whose hierarchy and field types are read. */
111
+ MAX_CONTEXT_TABLES: 200,
112
+ /** Distinct record-element tables taken from one row's payload. */
113
+ MAX_RECORD_TABLES_PER_ROW: 16,
114
+ /** Work, in ms, spent finding record-element tables before the rest are left unknown. */
115
+ CANDIDATE_BUDGET_MS: 100,
116
+ /** `sys_db_object` levels read to build those hierarchies. */
117
+ MAX_CHAIN_LEVELS: 8,
118
+ /** Update names per `nameIN` read. */
119
+ NAME_CHUNK: 100,
120
+ /** Update names checked for collisions in other open sets (BP004, local). */
121
+ MAX_COLLISION_NAMES: 500,
122
+ /** Update names checked against `sys_update_version` (BP005). */
123
+ MAX_BASELINE_NAMES: 500,
124
+ /** Preview problems read for a remote scope. */
125
+ MAX_PROBLEMS: 1_000,
126
+ /** Sets listed in the summary. */
127
+ SHOWN_SETS: 50,
128
+ /** Reads of one fact group in flight at once. */
129
+ CONCURRENCY: 2,
130
+ });
131
+ const L = exports.EVALUATE_LIMITS;
132
+ /** Bounds on instance text the view returns. */
133
+ const MAX_NAME_CHARS = 200;
134
+ const MAX_STATE_CHARS = 40;
135
+ /** The sentence every result carries: what the evaluator is, and is not. */
136
+ exports.EVALUATE_NOTE = "Heuristic rules over the rows read; a clean result is not an approval. Names are untrusted instance data.";
137
+ exports.EVALUATE_DENIED_HINT = "Reading update sets was denied for this account.";
138
+ exports.EVALUATE_UNAVAILABLE_HINT = "The update set tables are not available on this instance.";
139
+ exports.EVALUATE_NOT_FOUND_HINT = "No update set matches. Pass its sys_id, or check the name.";
140
+ exports.EVALUATE_AMBIGUOUS_HINT = "More than one update set has this name. Pass update_set as a sys_id.";
141
+ exports.EVALUATE_METADATA_ONLY = "Field policy hides payload: payload rules did not run, only metadata rules.";
142
+ /** Fixed warnings; nothing in them comes from the instance. */
143
+ exports.EVALUATE_WARNINGS = Object.freeze({
144
+ scope_budget: "The upstream scope budget ran out before every row was read; the rows left were not evaluated.",
145
+ max_updates: "max_updates was reached before every row was read; the rows left were not evaluated.",
146
+ sets_capped: `The scope has more than ${L.MAX_SETS} sets or deeper than ${L.MAX_DEPTH} levels; only the first were evaluated.`,
147
+ children_unreadable: "Field policy hides the parent field, so descendants were not included.",
148
+ counts_unavailable: "Row counts per set were not readable; set-size rules could not run.",
149
+ row_too_large: "A row was too large to read with its payload; it was evaluated on metadata only.",
150
+ rows_unreadable: "Some rows had no valid sys_id and were not evaluated.",
151
+ context_tables_capped: `The rows write to more than ${L.MAX_CONTEXT_TABLES} tables; the rest have no type or hierarchy facts.`,
152
+ hierarchy_unavailable: "Table hierarchies could not be read in full; some table checks were not made.",
153
+ field_types_unavailable: "Field types could not be read; password-typed field checks were not made.",
154
+ problems_unavailable: "Preview problems could not be read; the commit-blocking check was not made.",
155
+ problems_capped: `More than ${L.MAX_PROBLEMS} preview problems; the commit-blocking check is incomplete.`,
156
+ collisions_unavailable: "Other open update sets could not be checked in full for the same updates.",
157
+ baseline_unavailable: "Update versions could not be read in full; the baseline-record check is incomplete.",
158
+ descriptions_unavailable: "Set descriptions could not be checked; the missing-description check was not made.",
159
+ names_unlistable: "Some update names cannot be used in a query; their collision and baseline checks were not made.",
160
+ context_tables_budget: "Finding the tables nested in payloads ran out of time; rows with unknown nested tables were not scanned.",
161
+ });
162
+ // ---------------------------------------------------------------------------
163
+ // Fields
164
+ // ---------------------------------------------------------------------------
165
+ const LOCAL_SET_FIELDS = Object.freeze([
166
+ "sys_id", "name", "state", "is_default", "application", "parent", "description",
167
+ ]);
168
+ const REMOTE_SET_FIELDS = Object.freeze(["sys_id", "name", "state", "parent", "description"]);
169
+ /**
170
+ * Set reads never ask for `description`: it can be long, and a batch of long
171
+ * ones would fill the resolve scope. Whether a set has one is a separate read
172
+ * of sys_ids only (`descriptionISNOTEMPTY`).
173
+ */
174
+ const withoutDescription = (fields) => fields.filter((field) => field !== "description");
175
+ /** Never `payload_diff`. `payload` is added only when field policy allows it. */
176
+ const ROW_FIELDS = Object.freeze([
177
+ "sys_id", "name", "type", "target_name", "action", "table", "application", "replace_on_upgrade",
178
+ ]);
179
+ const PROBLEM_FIELDS = Object.freeze(["sys_id", "remote_update", "status", "type"]);
180
+ const DICTIONARY_FIELDS = Object.freeze(["name", "element", "internal_type"]);
181
+ /** The parent's name, a one-hop dot-walk from `sys_db_object` to itself. */
182
+ const PARENT_NAME = "super_class.name";
183
+ /**
184
+ * Every field this view may request or filter on, by table, for the module's
185
+ * field-policy preparation. `super_class` and `update_set` are also the heads
186
+ * of the view's two dot-walks, both into tables of its own plan.
187
+ */
188
+ exports.EVALUATE_FIELD_PLAN = Object.freeze({
189
+ sys_update_set: [...LOCAL_SET_FIELDS],
190
+ sys_remote_update_set: [...REMOTE_SET_FIELDS],
191
+ sys_update_xml: [...ROW_FIELDS, "payload", "update_set", "remote_update_set"],
192
+ sys_update_preview_problem: [...PROBLEM_FIELDS, "remote_update_set"],
193
+ sys_update_version: ["name", "source_table"],
194
+ sys_db_object: ["name", "super_class"],
195
+ sys_dictionary: [...DICTIONARY_FIELDS],
196
+ });
197
+ /** The dot-walks this view makes; each target is in its plan. */
198
+ exports.EVALUATE_DOT_WALKS = Object.freeze([
199
+ Object.freeze({ from: "sys_db_object", field: "super_class", target: "sys_db_object" }),
200
+ Object.freeze({ from: "sys_update_xml", field: "update_set", target: "sys_update_set" }),
201
+ ]);
202
+ /** Version sources that are the customer's own changes; any other named source is a baseline. */
203
+ const CUSTOMER_VERSION_SOURCES = new Set(["sys_update_set", "sys_remote_update_set"]);
204
+ const TABLE_NAME = /^[a-z][a-z0-9_]{0,79}$/u;
205
+ /** `<table>_<sys_id>`, the usual update name. */
206
+ const UPDATE_NAME_TABLE = /^([a-z][a-z0-9_]{0,79})_[0-9a-f]{32}$/u;
207
+ /** An update name that is safe in a `nameIN` list: no comma, no query syntax. */
208
+ const LISTABLE_NAME = /^[A-Za-z0-9_.:-]{1,200}$/u;
209
+ /**
210
+ * A script prefix ServiceNow evaluates in a query value, in any case and with
211
+ * any spacing before the colon. Update names are instance text (from another
212
+ * instance, for a retrieved set), so a name holding it is never listed.
213
+ */
214
+ const SCRIPT_PREFIX = /javascript\s*:/iu;
215
+ /** The payload's declared table, read from its first bytes only. */
216
+ const ROOT_TABLE = /<record_update\b[^>]{0,400}?\btable="([a-z][a-z0-9_]{0,79})"/u;
217
+ const ROOT_HEAD_CHARS = 1_024;
218
+ /** A record element: a table-named element with an `action` attribute. */
219
+ const RECORD_ELEMENT = /<([a-z][a-z0-9_]{0,79})\s+action="/gu;
220
+ /** The base table of all metadata, which extends nothing. */
221
+ const METADATA_ROOT = "sys_metadata";
222
+ /** The credential check's answer for a table whose hierarchy is not known. */
223
+ const UNKNOWN_TABLE = "unknown";
224
+ /** Raised inside a step for a fixed `denied` or `unavailable` result. */
225
+ class ViewStop {
226
+ status;
227
+ hint;
228
+ constructor(status, hint) {
229
+ this.status = status;
230
+ this.hint = hint;
231
+ }
232
+ }
233
+ function isCancellation(error, signal) {
234
+ return signal?.aborted === true || (0, client_js_1.isServiceNowRequestCancellation)(error);
235
+ }
236
+ function isTooLarge(error) {
237
+ return (0, client_js_1.isServiceNowResponseTooLarge)(error) || (0, platform_view_upgrades_js_1.errorCategory)(error) === "too_large";
238
+ }
239
+ /** Run `operation` in a new response scope, or return undefined when none is left. */
240
+ async function inScope(reader, operation) {
241
+ if (!reader.scopes.take())
242
+ return undefined;
243
+ return { value: await (0, platform_view_upgrades_js_1.inOwnScope)(reader.signal, operation) };
244
+ }
245
+ function chunks(items, size) {
246
+ const out = [];
247
+ for (let start = 0; start < items.length; start += size)
248
+ out.push(items.slice(start, start + size));
249
+ return out;
250
+ }
251
+ /** Map with at most `limit` calls in flight; results keep input order. */
252
+ async function mapLimited(items, limit, run) {
253
+ const results = new Array(items.length);
254
+ let next = 0;
255
+ const worker = async () => {
256
+ while (next < items.length) {
257
+ const index = next;
258
+ next += 1;
259
+ results[index] = await run(items[index]);
260
+ }
261
+ };
262
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
263
+ return results;
264
+ }
265
+ const lowerId = (value) => {
266
+ const id = (0, platform_view_upgrades_js_1.scalar)(value)?.trim().toLowerCase();
267
+ return id !== undefined && platform_view_upgrades_js_1.SYS_ID.test(id) ? id : undefined;
17
268
  };
18
- exports.handleEvaluate = handleEvaluate;
269
+ const textOrNull = (value) => (0, platform_view_upgrades_js_1.scalar)(value) ?? null;
270
+ // ---------------------------------------------------------------------------
271
+ // Selector
272
+ // ---------------------------------------------------------------------------
273
+ /** Exactly one of `update_set`, `batch_root` or `remote_update_set`. */
274
+ function selectorOf(args) {
275
+ const given = [args.update_set, args.batch_root, args.remote_update_set].filter((value) => value !== undefined);
276
+ if (given.length !== 1)
277
+ throw (0, tool_error_js_1.createToolError)("conflict", "retry_after_correction");
278
+ if (args.batch_root !== undefined) {
279
+ // A batch is the root with its descendants; leaving them out is a different question.
280
+ if (args.include_children === false)
281
+ throw (0, tool_error_js_1.createToolError)("conflict", "retry_after_correction");
282
+ return { source: "local", id: args.batch_root, children: true };
283
+ }
284
+ const children = args.include_children !== false;
285
+ if (args.remote_update_set !== undefined)
286
+ return { source: "remote", id: args.remote_update_set, children };
287
+ const value = args.update_set;
288
+ return platform_view_upgrades_js_1.SYS_ID.test(value) ? { source: "local", id: value, children } : { source: "local", name: value, children };
289
+ }
290
+ function setTable(source) {
291
+ return source === "local" ? "sys_update_set" : "sys_remote_update_set";
292
+ }
293
+ /** The `sys_update_xml` column that names a row's set. */
294
+ function rowSetField(source) {
295
+ return source === "local" ? "update_set" : "remote_update_set";
296
+ }
297
+ function projectSet(source, row, count, description) {
298
+ const sysId = lowerId(row.sys_id);
299
+ if (sysId === undefined)
300
+ return undefined;
301
+ return {
302
+ sys_id: sysId,
303
+ name: (0, platform_view_upgrades_js_1.cleanText)(row.name, MAX_NAME_CHARS) ?? "",
304
+ state: (0, platform_view_upgrades_js_1.cleanText)(row.state, MAX_STATE_CHARS) ?? null,
305
+ ...(source === "local" && (0, platform_view_upgrades_js_1.flag)(row.is_default) !== undefined ? { is_default: (0, platform_view_upgrades_js_1.flag)(row.is_default) } : {}),
306
+ ...(description === undefined ? {} : { has_description: description }),
307
+ application: source === "local" ? lowerId(row.application) ?? null : null,
308
+ parent: lowerId(row.parent) ?? null,
309
+ update_count: count,
310
+ };
311
+ }
312
+ async function resolveScope(reader, access, selector, warnings) {
313
+ const tableName = setTable(selector.source);
314
+ const fields = withoutDescription((0, platform_view_upgrades_js_1.readableOf)(access, tableName, selector.source === "local" ? LOCAL_SET_FIELDS : REMOTE_SET_FIELDS));
315
+ const descriptionReadable = access.canRead(tableName, "description");
316
+ const required = ["sys_id", ...(selector.name !== undefined ? ["name"] : [])];
317
+ if ((0, platform_view_upgrades_js_1.firstUnreadable)(access, tableName, required) !== undefined)
318
+ throw new ViewStop("denied", platform_view_upgrades_js_1.FIELD_POLICY_HINT);
319
+ const setField = rowSetField(selector.source);
320
+ if ((0, platform_view_upgrades_js_1.firstUnreadable)(access, "sys_update_xml", ["sys_id", setField]) !== undefined) {
321
+ throw new ViewStop("denied", platform_view_upgrades_js_1.FIELD_POLICY_HINT);
322
+ }
323
+ const children = selector.children && access.canRead(tableName, "parent");
324
+ if (selector.children && !children)
325
+ warnings.add("children_unreadable");
326
+ const read = await inScope(reader, async () => {
327
+ const path = `${platform_view_upgrades_js_1.TABLE_PATH}${tableName}`;
328
+ const first = (0, platform_view_upgrades_js_1.rowsOf)(await reader.ops.get(path, (0, platform_view_upgrades_js_1.listParams)({
329
+ fields,
330
+ query: selector.id !== undefined ? `sys_id=${selector.id}` : `name=${selector.name}^ORDERBYsys_id`,
331
+ limit: selector.id !== undefined ? 1 : 2,
332
+ }))).map((row) => (0, platform_view_upgrades_js_1.readableRow)(access, tableName, row, fields));
333
+ if (first.length === 0)
334
+ return { kind: "not_found" };
335
+ if (first.length > 1) {
336
+ return {
337
+ kind: "ambiguous",
338
+ candidates: first.flatMap((row) => {
339
+ const id = lowerId(row.sys_id);
340
+ return id === undefined ? [] : [{ sys_id: id, state: (0, platform_view_upgrades_js_1.cleanText)(row.state, MAX_STATE_CHARS) ?? null }];
341
+ }),
342
+ };
343
+ }
344
+ const rootRow = first[0];
345
+ const root = lowerId(rootRow.sys_id);
346
+ if (root === undefined)
347
+ return { kind: "not_found" };
348
+ // Descendants, one level per read, cycle-safe and capped. The descent
349
+ // stops at the first cap, and a level too large for the scope is a cap
350
+ // too: the sets read so far are evaluated and the result is partial.
351
+ const rows = new Map([[root, rootRow]]);
352
+ let capped = false;
353
+ if (children) {
354
+ let frontier = [root];
355
+ for (let depth = 0; frontier.length > 0 && !capped; depth += 1) {
356
+ if (depth >= L.MAX_DEPTH) {
357
+ capped = true;
358
+ break;
359
+ }
360
+ let level;
361
+ try {
362
+ level = (0, platform_view_upgrades_js_1.rowsOf)(await reader.ops.get(path, (0, platform_view_upgrades_js_1.listParams)({
363
+ fields,
364
+ query: `parentIN${frontier.join(",")}^ORDERBYsys_id`,
365
+ limit: L.MAX_SETS + 1,
366
+ }))).map((row) => (0, platform_view_upgrades_js_1.readableRow)(access, tableName, row, fields));
367
+ }
368
+ catch (error) {
369
+ if (!isTooLarge(error))
370
+ throw error;
371
+ capped = true;
372
+ break;
373
+ }
374
+ const next = [];
375
+ for (const row of level) {
376
+ const id = lowerId(row.sys_id);
377
+ if (id === undefined || rows.has(id))
378
+ continue;
379
+ if (rows.size >= L.MAX_SETS) {
380
+ capped = true;
381
+ break;
382
+ }
383
+ rows.set(id, row);
384
+ next.push(id);
385
+ }
386
+ frontier = next;
387
+ }
388
+ }
389
+ // Row counts per set; an absent group is 0.
390
+ const ids = [...rows.keys()];
391
+ const counts = new Map();
392
+ let countsKnown = true;
393
+ try {
394
+ const stats = (0, platform_view_upgrades_js_1.rowsOf)(await reader.ops.get(`${platform_view_upgrades_js_1.STATS_PATH}sys_update_xml`, {
395
+ sysparm_query: `${setField}IN${ids.join(",")}`,
396
+ sysparm_group_by: setField,
397
+ sysparm_count: "true",
398
+ }));
399
+ for (const group of stats) {
400
+ const by = Array.isArray(group.groupby_fields) ? group.groupby_fields : [];
401
+ const id = lowerId((0, platform_view_upgrades_js_1.asRecord)(by.find((entry) => (0, platform_view_upgrades_js_1.asRecord)(entry).field === setField)).value);
402
+ const count = (0, platform_view_upgrades_js_1.wholeNumber)((0, platform_view_upgrades_js_1.asRecord)(group.stats).count);
403
+ if (id !== undefined && count !== undefined && count >= 0)
404
+ counts.set(id, count);
405
+ }
406
+ }
407
+ catch (error) {
408
+ if (isCancellation(error, reader.signal))
409
+ throw error;
410
+ countsKnown = false;
411
+ }
412
+ // Which sets have a description: their sys_ids only, never the text.
413
+ let described;
414
+ let descriptionsKnown = false;
415
+ if (descriptionReadable) {
416
+ try {
417
+ described = new Set((0, platform_view_upgrades_js_1.rowsOf)(await reader.ops.get(path, (0, platform_view_upgrades_js_1.listParams)({ fields: ["sys_id"], query: `sys_idIN${ids.join(",")}^descriptionISNOTEMPTY`, limit: ids.length }))).flatMap((row) => {
418
+ const id = lowerId((0, platform_view_upgrades_js_1.readableRow)(access, tableName, row, ["sys_id"]).sys_id);
419
+ return id === undefined ? [] : [id];
420
+ }));
421
+ descriptionsKnown = true;
422
+ }
423
+ catch (error) {
424
+ if (isCancellation(error, reader.signal))
425
+ throw error;
426
+ }
427
+ }
428
+ const sets = ids.flatMap((id) => {
429
+ const set = projectSet(selector.source, rows.get(id), countsKnown ? counts.get(id) ?? 0 : Number.NaN, described === undefined ? undefined : described.has(id));
430
+ return set === undefined ? [] : [set];
431
+ });
432
+ const total = countsKnown ? sets.reduce((sum, set) => sum + set.update_count, 0) : Number.NaN;
433
+ return {
434
+ kind: "scope",
435
+ scope: { source: selector.source, root, sets, setsCapped: capped, countsKnown, descriptionsKnown, total },
436
+ };
437
+ });
438
+ // The first scope of a call always exists.
439
+ if (read === undefined)
440
+ throw (0, tool_error_js_1.createToolError)("internal", "do_not_retry");
441
+ if (read.value.kind === "scope") {
442
+ if (read.value.scope.setsCapped)
443
+ warnings.add("sets_capped");
444
+ if (!read.value.scope.countsKnown)
445
+ warnings.add("counts_unavailable");
446
+ if (!read.value.scope.descriptionsKnown)
447
+ warnings.add("descriptions_unavailable");
448
+ }
449
+ return read.value;
450
+ }
451
+ function projectRow(source, row, withPayload) {
452
+ const sysId = lowerId(row.sys_id);
453
+ const set = lowerId(row[rowSetField(source)]);
454
+ if (sysId === undefined || set === undefined)
455
+ return undefined;
456
+ return {
457
+ sys_id: sysId,
458
+ name: (0, platform_view_upgrades_js_1.scalar)(row.name) ?? "",
459
+ type: textOrNull(row.type),
460
+ target_name: textOrNull(row.target_name),
461
+ update_set: set,
462
+ action: textOrNull(row.action),
463
+ table: textOrNull(row.table),
464
+ application: lowerId(row.application) ?? null,
465
+ replace_on_upgrade: (0, platform_view_upgrades_js_1.flag)(row.replace_on_upgrade) === true,
466
+ // Only a string is a payload; anything else reads as absent (not scanned).
467
+ payload: withPayload && typeof row.payload === "string" ? row.payload : null,
468
+ };
469
+ }
470
+ async function readRows(reader, access, scope, options, warnings) {
471
+ const setField = rowSetField(scope.source);
472
+ const base = (0, platform_view_upgrades_js_1.readableOf)(access, "sys_update_xml", [...ROW_FIELDS, setField]);
473
+ const withPayload = [...base, "payload"];
474
+ const ids = scope.sets.map((set) => set.sys_id);
475
+ const known = Number.isFinite(scope.total) ? scope.total : Number.POSITIVE_INFINITY;
476
+ const wanted = Math.min(options.maxUpdates, known);
477
+ const updates = [];
478
+ let last;
479
+ // The page starts small and grows while its payloads fit. A page too large
480
+ // for its scope sets a ceiling the size never climbs back over, so large
481
+ // payloads do not keep failing and spending scopes.
482
+ let pageSize = L.FIRST_PAGE_ROWS;
483
+ let ceiling = L.PAGE_ROWS;
484
+ /** The largest page size read with payloads so far. */
485
+ let lastGood = 0;
486
+ let scopeBudgetHit = false;
487
+ let exhausted = false;
488
+ let invalid = 0;
489
+ const page = (size, fields) => (0, platform_view_upgrades_js_1.listParams)({
490
+ fields,
491
+ query: `${setField}IN${ids.join(",")}${last === undefined ? "" : `^sys_id>${last}`}^ORDERBYsys_id`,
492
+ limit: size,
493
+ });
494
+ while (updates.length + invalid < wanted && !exhausted) {
495
+ if (reader.scopes.max - reader.scopes.opened <= options.reserved) {
496
+ scopeBudgetHit = true;
497
+ break;
498
+ }
499
+ const size = Math.min(pageSize, wanted - updates.length - invalid);
500
+ let rows;
501
+ let payloadRead = options.payload;
502
+ try {
503
+ const read = await inScope(reader, () => reader.ops.get(`${platform_view_upgrades_js_1.TABLE_PATH}sys_update_xml`, page(size, options.payload ? withPayload : base)));
504
+ if (read === undefined) {
505
+ scopeBudgetHit = true;
506
+ break;
507
+ }
508
+ rows = (0, platform_view_upgrades_js_1.rowsOf)(read.value);
509
+ if (options.payload)
510
+ lastGood = Math.max(lastGood, size);
511
+ }
512
+ catch (error) {
513
+ if (!options.payload || !isTooLarge(error))
514
+ throw error;
515
+ if (size > 1) {
516
+ // A page of large payloads: the same rows again, half as many at a time.
517
+ pageSize = Math.ceil(size / 2);
518
+ ceiling = pageSize;
519
+ continue;
520
+ }
521
+ // One row too large for a scope: its metadata only, so paging can go on.
522
+ if (reader.scopes.max - reader.scopes.opened <= options.reserved) {
523
+ scopeBudgetHit = true;
524
+ break;
525
+ }
526
+ const single = await inScope(reader, () => reader.ops.get(`${platform_view_upgrades_js_1.TABLE_PATH}sys_update_xml`, page(1, base)));
527
+ if (single === undefined) {
528
+ scopeBudgetHit = true;
529
+ break;
530
+ }
531
+ rows = (0, platform_view_upgrades_js_1.rowsOf)(single.value);
532
+ payloadRead = false;
533
+ warnings.add("row_too_large");
534
+ // That one row set the ceiling to 1; the rows after it may fit as many
535
+ // as the largest page that has fitted.
536
+ ceiling = Math.max(1, lastGood);
537
+ }
538
+ if (rows.length < size)
539
+ exhausted = true;
540
+ let pageChars = 0;
541
+ let lastOfPage;
542
+ for (const raw of rows) {
543
+ const id = lowerId(raw.sys_id);
544
+ if (id !== undefined && (lastOfPage === undefined || id > lastOfPage))
545
+ lastOfPage = id;
546
+ const fields = payloadRead ? withPayload : base;
547
+ const update = projectRow(scope.source, (0, platform_view_upgrades_js_1.readableRow)(access, "sys_update_xml", raw, fields), payloadRead);
548
+ if (update === undefined)
549
+ invalid += 1;
550
+ else
551
+ updates.push(update);
552
+ pageChars += update?.payload?.length ?? 0;
553
+ }
554
+ // Keyset paging: without a valid sys_id there is no next key.
555
+ if (lastOfPage === undefined || (last !== undefined && lastOfPage <= last))
556
+ exhausted = true;
557
+ last = lastOfPage;
558
+ // Grow: at least double, or straight to what the measured payloads say
559
+ // fits; never past the ceiling.
560
+ const perRow = rows.length === 0 ? 0 : pageChars / rows.length;
561
+ const fits = perRow === 0 ? L.PAGE_ROWS : Math.floor(L.PAGE_TARGET_CHARS / perRow);
562
+ pageSize = Math.max(1, Math.min(ceiling, Math.max(pageSize * 2, fits)));
563
+ }
564
+ if (invalid > 0)
565
+ warnings.add("rows_unreadable");
566
+ const maxUpdatesHit = !exhausted && !scopeBudgetHit && updates.length + invalid >= options.maxUpdates && known > options.maxUpdates;
567
+ if (scopeBudgetHit)
568
+ warnings.add("scope_budget");
569
+ if (maxUpdatesHit)
570
+ warnings.add("max_updates");
571
+ return { updates, scopeBudgetHit, maxUpdatesHit };
572
+ }
573
+ /**
574
+ * The text of a payload with its CDATA sections and comments removed, so
575
+ * markup-like text inside a script is never read as a record. An
576
+ * unterminated section drops the rest of the text.
577
+ *
578
+ * Linear: the next opener of each kind is searched for again only once the
579
+ * scan has passed the last one found, so a kind that does not occur is
580
+ * searched for once, and every character is read a bounded number of times.
581
+ */
582
+ function outsideCdataAndComments(text) {
583
+ const parts = [];
584
+ let at = 0;
585
+ let cdata = text.indexOf("<![CDATA[");
586
+ let comment = text.indexOf("<!--");
587
+ while (at < text.length) {
588
+ if (cdata >= 0 && cdata < at)
589
+ cdata = text.indexOf("<![CDATA[", at);
590
+ if (comment >= 0 && comment < at)
591
+ comment = text.indexOf("<!--", at);
592
+ const next = cdata < 0 ? comment : comment < 0 ? cdata : Math.min(cdata, comment);
593
+ if (next < 0) {
594
+ parts.push(text.slice(at));
595
+ break;
596
+ }
597
+ parts.push(text.slice(at, next));
598
+ const close = next === cdata ? text.indexOf("]]>", next + 9) : text.indexOf("-->", next + 4);
599
+ if (close < 0)
600
+ break;
601
+ at = close + 3;
602
+ parts.push(" ");
603
+ }
604
+ return parts.join("");
605
+ }
606
+ /**
607
+ * Tables a row may write to, most certain first, so the table cap is filled
608
+ * by the tables every row names before any payload can add more:
609
+ * 1. each row's `table` column, update-name prefix and payload root table;
610
+ * 2. record elements (a table-named element with an `action` attribute)
611
+ * found outside CDATA and comments, in the part of the payload the engine
612
+ * reads, at most {@link EVALUATE_LIMITS}.MAX_RECORD_TABLES_PER_ROW per
613
+ * row, taken one per row in turn, so one row cannot crowd out the rest.
614
+ * A table missed here has no facts, so the credential check treats it as
615
+ * unknown and its rows are not scanned: a miss fails closed, for those rows.
616
+ */
617
+ function candidateTables(updates, maxPayloadChars = engine_js_1.ENGINE_LIMITS.maxPayloadBytes) {
618
+ const direct = new Set();
619
+ const nested = [];
620
+ for (const update of updates) {
621
+ directTables(update, direct);
622
+ nested.push(recordTables(update, maxPayloadChars));
623
+ }
624
+ return mergeTables(direct, nested);
625
+ }
626
+ /** Priority 1 for one row: its `table` column, update-name prefix and payload root. Cheap. */
627
+ function directTables(update, into) {
628
+ if (typeof update.table === "string" && TABLE_NAME.test(update.table))
629
+ into.add(update.table);
630
+ const named = UPDATE_NAME_TABLE.exec(update.name);
631
+ if (named !== null)
632
+ into.add(named[1]);
633
+ if (update.payload === null)
634
+ return;
635
+ const declared = ROOT_TABLE.exec(update.payload.slice(0, ROOT_HEAD_CHARS));
636
+ if (declared !== null)
637
+ into.add(declared[1]);
638
+ }
639
+ /** Priority 2 for one row: its record elements outside CDATA and comments, capped. Linear in the payload. */
640
+ function recordTables(update, maxPayloadChars) {
641
+ if (update.payload === null)
642
+ return [];
643
+ const own = new Set();
644
+ for (const match of outsideCdataAndComments(update.payload.slice(0, maxPayloadChars)).matchAll(RECORD_ELEMENT)) {
645
+ own.add(match[1]);
646
+ if (own.size >= L.MAX_RECORD_TABLES_PER_ROW)
647
+ break;
648
+ }
649
+ return [...own];
650
+ }
651
+ function mergeTables(direct, nested) {
652
+ const tables = new Set(direct);
653
+ for (let round = 0; round < L.MAX_RECORD_TABLES_PER_ROW; round += 1) {
654
+ for (const own of nested)
655
+ if (own[round] !== undefined)
656
+ tables.add(own[round]);
657
+ }
658
+ return [...tables];
659
+ }
660
+ /**
661
+ * {@link candidateTables} as the handler runs it: it yields to the event loop
662
+ * after {@link YIELD_AFTER_MS} of work, as the engine does, and stops reading
663
+ * record elements once {@link EVALUATE_LIMITS}.CANDIDATE_BUDGET_MS of work is
664
+ * spent. Rows left then keep only their direct tables; a nested record they
665
+ * hold is unknown, so those rows fail closed, and `budgetHit` says so.
666
+ */
667
+ async function collectCandidateTables(updates, hooks = {}, maxPayloadChars = engine_js_1.ENGINE_LIMITS.maxPayloadBytes) {
668
+ const now = hooks.now ?? (() => performance.now());
669
+ const yieldToLoop = hooks.yieldToLoop ?? (() => new Promise((resolve) => setImmediate(resolve)));
670
+ const direct = new Set();
671
+ const nested = [];
672
+ let spent = 0;
673
+ let segmentStart = now();
674
+ let budgetHit = false;
675
+ for (const update of updates) {
676
+ directTables(update, direct);
677
+ if (budgetHit)
678
+ continue;
679
+ let elapsed = now() - segmentStart;
680
+ if (elapsed >= engine_js_1.YIELD_AFTER_MS) {
681
+ spent += elapsed;
682
+ await yieldToLoop();
683
+ segmentStart = now();
684
+ elapsed = 0;
685
+ }
686
+ if (spent + elapsed >= L.CANDIDATE_BUDGET_MS) {
687
+ budgetHit = true;
688
+ continue;
689
+ }
690
+ nested.push(recordTables(update, maxPayloadChars));
691
+ }
692
+ return { tables: mergeTables(direct, nested), budgetHit };
693
+ }
694
+ /**
695
+ * `parents` maps a table to its parent's name, to null when it extends
696
+ * nothing, or to undefined when its row named no usable parent. A table with
697
+ * no entry had no `sys_db_object` row, or was not read.
698
+ */
699
+ function chainOf(table, parents) {
700
+ if (!parents.has(table))
701
+ return undefined;
702
+ const tables = [table];
703
+ let current = parents.get(table);
704
+ while (current !== null) {
705
+ if (current === undefined || tables.includes(current) || tables.length >= 16) {
706
+ return { tables, complete: false };
707
+ }
708
+ tables.push(current);
709
+ current = parents.has(current) ? parents.get(current) : undefined;
710
+ }
711
+ return { tables, complete: true };
712
+ }
713
+ /**
714
+ * The context reads, in one scope. `extra` (the update-version counts, small
715
+ * like these) runs in the same scope, alongside them; it handles its own
716
+ * failures and is told when no scope was left.
717
+ */
718
+ async function readContext(reader, access, updates, warnings, extra) {
719
+ const { tables: all, budgetHit } = await collectCandidateTables(updates, reader.hooks);
720
+ if (budgetHit)
721
+ warnings.add("context_tables_budget");
722
+ if (all.length > L.MAX_CONTEXT_TABLES)
723
+ warnings.add("context_tables_capped");
724
+ // The cap keeps the most certain tables; the reads list them sorted.
725
+ const tables = all.slice(0, L.MAX_CONTEXT_TABLES).sort();
726
+ /** See {@link chainOf}. `sys_metadata` extends nothing, so it is never read. */
727
+ const parents = new Map([[METADATA_ROOT, null]]);
728
+ let dictionaryRows;
729
+ let hierarchyRead = true;
730
+ const canChain = (0, platform_view_upgrades_js_1.firstUnreadable)(access, "sys_db_object", ["name", "super_class"]) === undefined;
731
+ const canType = (0, platform_view_upgrades_js_1.firstUnreadable)(access, "sys_dictionary", DICTIONARY_FIELDS) === undefined;
732
+ const readChains = async () => {
733
+ if (!canChain) {
734
+ hierarchyRead = false;
735
+ return;
736
+ }
737
+ let pending = tables.filter((table) => !parents.has(table));
738
+ for (let level = 0; pending.length > 0; level += 1) {
739
+ if (level >= L.MAX_CHAIN_LEVELS) {
740
+ hierarchyRead = false;
741
+ return;
742
+ }
743
+ const rows = (0, platform_view_upgrades_js_1.rowsOf)(await reader.meta.get(`${platform_view_upgrades_js_1.TABLE_PATH}sys_db_object`, {
744
+ sysparm_query: `nameIN${pending.join(",")}`,
745
+ sysparm_fields: ["name", PARENT_NAME].join(","),
746
+ sysparm_limit: String(pending.length),
747
+ sysparm_display_value: "false",
748
+ sysparm_exclude_reference_link: "true",
749
+ }));
750
+ const next = new Set();
751
+ for (const row of rows) {
752
+ const name = (0, platform_view_upgrades_js_1.scalar)(row.name)?.trim().toLowerCase();
753
+ if (name === undefined || !pending.includes(name))
754
+ continue;
755
+ const parent = (0, platform_view_upgrades_js_1.scalar)(row[PARENT_NAME])?.trim().toLowerCase() ?? "";
756
+ if (parent === "")
757
+ parents.set(name, null);
758
+ else if (TABLE_NAME.test(parent)) {
759
+ parents.set(name, parent);
760
+ if (!parents.has(parent))
761
+ next.add(parent);
762
+ }
763
+ else {
764
+ // A parent that is not a table name: the chain stops, unknown.
765
+ parents.set(name, undefined);
766
+ }
767
+ }
768
+ pending = [...next].filter((table) => !parents.has(table));
769
+ }
770
+ };
771
+ const readTypes = async () => {
772
+ if (!canType)
773
+ return;
774
+ const response = await reader.meta.getWithMeta(`${platform_view_upgrades_js_1.TABLE_PATH}sys_dictionary`, {
775
+ sysparm_query: `internal_typeIN${hidden_values_js_1.HIDDEN_FIELD_TYPES.join(",")}^ORDERBYname^ORDERBYelement`,
776
+ sysparm_fields: DICTIONARY_FIELDS.join(","),
777
+ sysparm_limit: String(hidden_values_js_1.MAX_HIDDEN_DICTIONARY_ROWS),
778
+ sysparm_display_value: "false",
779
+ sysparm_exclude_reference_link: "true",
780
+ });
781
+ const rows = response.status === 200 ? (0, platform_view_upgrades_js_1.rowsOf)(response.data) : [];
782
+ // No rows means they are hidden from this account (every instance has
783
+ // password-typed fields), and a full page may be cut short: both are
784
+ // unavailable, never "no hidden fields".
785
+ if (rows.length === 0 || rows.length >= hidden_values_js_1.MAX_HIDDEN_DICTIONARY_ROWS)
786
+ return;
787
+ dictionaryRows = rows.flatMap((row) => {
788
+ const entry = (0, platform_view_upgrades_js_1.readableRow)(access, "sys_dictionary", row, DICTIONARY_FIELDS);
789
+ const tableName = (0, platform_view_upgrades_js_1.scalar)(entry.name);
790
+ const element = (0, platform_view_upgrades_js_1.scalar)(entry.element);
791
+ const type = (0, platform_view_upgrades_js_1.scalar)(entry.internal_type);
792
+ // Hidden-typed rows only, as the shared loader keeps: a row of any other
793
+ // type the server returned must not override an inherited hidden field.
794
+ return tableName === undefined || element === undefined || !(0, hidden_values_js_1.isHiddenFieldType)(type)
795
+ ? []
796
+ : [{ table: tableName, element, internal_type: type }];
797
+ });
798
+ };
799
+ if (tables.length > 0 || extra !== undefined) {
800
+ const read = await inScope(reader, async () => {
801
+ // The reads do not depend on each other. A failure costs the facts it
802
+ // would have given, never the call; a cancellation ends the call.
803
+ await Promise.all([
804
+ tables.length === 0
805
+ ? undefined
806
+ : readChains().catch((error) => {
807
+ if (isCancellation(error, reader.signal))
808
+ throw error;
809
+ hierarchyRead = false;
810
+ }),
811
+ tables.length === 0
812
+ ? undefined
813
+ : readTypes().catch((error) => {
814
+ if (isCancellation(error, reader.signal))
815
+ throw error;
816
+ dictionaryRows = undefined;
817
+ }),
818
+ extra?.run(),
819
+ ]);
820
+ });
821
+ if (read === undefined) {
822
+ hierarchyRead = false;
823
+ extra?.noScope();
824
+ }
825
+ }
826
+ const chains = new Map();
827
+ for (const tableName of tables) {
828
+ const chain = chainOf(tableName, parents);
829
+ if (chain !== undefined)
830
+ chains.set(tableName, chain);
831
+ }
832
+ const hierarchies = {};
833
+ for (const [tableName, chain] of chains)
834
+ if (chain.complete)
835
+ hierarchies[tableName] = chain.tables;
836
+ const fieldTypes = dictionaryRows === undefined ? hidden_values_js_1.FIELD_TYPES_UNAVAILABLE : (0, hidden_values_js_1.fieldTypesFromRows)(dictionaryRows, hierarchies);
837
+ if (!hierarchyRead || tables.some((tableName) => chains.get(tableName)?.complete !== true)) {
838
+ warnings.add("hierarchy_unavailable");
839
+ }
840
+ if (fieldTypes.state === "unavailable" && tables.length > 0)
841
+ warnings.add("field_types_unavailable");
842
+ const context = {
843
+ isCredentialTable(tableName) {
844
+ if ((0, credential_tables_js_1.isCredentialTable)(tableName))
845
+ return true;
846
+ const chain = chains.get(tableName);
847
+ if (chain !== undefined && (0, credential_tables_js_1.isCredentialTableHierarchy)(chain.tables))
848
+ return true;
849
+ if (chain?.complete === true)
850
+ return false;
851
+ // No row, an incomplete chain, a failed read or a table past the cap:
852
+ // it may extend a credential table. The engine reads an answer that is
853
+ // not a boolean as "credential" and counts it, so the row is not
854
+ // scanned and the result is partial.
855
+ return UNKNOWN_TABLE;
856
+ },
857
+ hiddenFieldNames(tableName) {
858
+ return (0, hidden_values_js_1.hiddenTypedFields)(fieldTypes, tableName) ?? "unavailable";
859
+ },
860
+ extendsMetadata(tableName) {
861
+ if (tableName === METADATA_ROOT)
862
+ return true;
863
+ const chain = chains.get(tableName);
864
+ if (chain === undefined)
865
+ return "unknown";
866
+ if (chain.tables.includes(METADATA_ROOT))
867
+ return true;
868
+ return chain.complete ? false : "unknown";
869
+ },
870
+ };
871
+ return {
872
+ context,
873
+ hierarchyComplete: !warnings.has("hierarchy_unavailable"),
874
+ fieldTypes: fieldTypes.state,
875
+ collectionBudgetHit: budgetHit,
876
+ };
877
+ }
878
+ /**
879
+ * True when an update name may go into a `nameIN` list as it is: only the
880
+ * allowed characters, no script prefix, and nothing `escapeQueryValue` would
881
+ * change. Any other name is not checked, and is counted.
882
+ */
883
+ function isListableName(name) {
884
+ return LISTABLE_NAME.test(name) && !SCRIPT_PREFIX.test(name) && (0, utils_js_1.escapeQueryValue)(name) === name;
885
+ }
886
+ function listableNames(updates) {
887
+ const names = new Set();
888
+ let unlistable = 0;
889
+ for (const update of updates) {
890
+ if (isListableName(update.name))
891
+ names.add(update.name);
892
+ else
893
+ unlistable += 1;
894
+ }
895
+ return { listable: [...names].sort(), unlistable };
896
+ }
897
+ function groupsOf(response) {
898
+ return (0, platform_view_upgrades_js_1.rowsOf)(response).map((group) => {
899
+ const fields = new Map();
900
+ for (const entry of Array.isArray(group.groupby_fields) ? group.groupby_fields : []) {
901
+ const record = (0, platform_view_upgrades_js_1.asRecord)(entry);
902
+ const field = (0, platform_view_upgrades_js_1.scalar)(record.field);
903
+ const value = (0, platform_view_upgrades_js_1.scalar)(record.value);
904
+ if (field !== undefined && value !== undefined)
905
+ fields.set(field, value);
906
+ }
907
+ return { fields, count: (0, platform_view_upgrades_js_1.wholeNumber)((0, platform_view_upgrades_js_1.asRecord)(group.stats).count) };
908
+ });
909
+ }
910
+ async function readProblems(reader, access, scope, facts, warnings) {
911
+ const table = "sys_update_preview_problem";
912
+ if ((0, platform_view_upgrades_js_1.firstUnreadable)(access, table, ["sys_id", "remote_update", "status", "remote_update_set"]) !== undefined) {
913
+ warnings.add("problems_unavailable");
914
+ return;
915
+ }
916
+ const fields = (0, platform_view_upgrades_js_1.readableOf)(access, table, PROBLEM_FIELDS);
917
+ try {
918
+ const read = await inScope(reader, () => reader.ops.get(`${platform_view_upgrades_js_1.TABLE_PATH}${table}`, (0, platform_view_upgrades_js_1.listParams)({
919
+ fields,
920
+ query: `remote_update_setIN${scope.sets.map((set) => set.sys_id).join(",")}^ORDERBYsys_id`,
921
+ limit: L.MAX_PROBLEMS + 1,
922
+ })));
923
+ if (read === undefined) {
924
+ warnings.add("problems_unavailable");
925
+ return;
926
+ }
927
+ const rows = (0, platform_view_upgrades_js_1.rowsOf)(read.value).map((row) => (0, platform_view_upgrades_js_1.readableRow)(access, table, row, fields));
928
+ if (rows.length > L.MAX_PROBLEMS) {
929
+ warnings.add("problems_capped");
930
+ facts.unavailable += 1;
931
+ }
932
+ facts.problems = rows.slice(0, L.MAX_PROBLEMS).map((row) => ({
933
+ sys_id: lowerId(row.sys_id) ?? "",
934
+ remote_update: lowerId(row.remote_update) ?? null,
935
+ // Only a string status can be resolved; anything else blocks.
936
+ status: typeof row.status === "string" ? row.status : null,
937
+ type: textOrNull(row.type),
938
+ }));
939
+ }
940
+ catch (error) {
941
+ if (isCancellation(error, reader.signal))
942
+ throw error;
943
+ warnings.add("problems_unavailable");
944
+ }
945
+ }
946
+ /** Local BP004: each name's rows in other open sets. A name not checked is counted. */
947
+ async function readCollisions(reader, access, scope, updates, facts, warnings) {
948
+ const readable = (0, platform_view_upgrades_js_1.firstUnreadable)(access, "sys_update_xml", ["name", "update_set"]) === undefined &&
949
+ access.canRead("sys_update_set", "state");
950
+ const { listable, unlistable } = listableNames(updates);
951
+ if (!readable) {
952
+ warnings.add("collisions_unavailable");
953
+ return; // the engine counts the missing fact
954
+ }
955
+ const checked = listable.slice(0, L.MAX_COLLISION_NAMES);
956
+ const notChecked = listable.length - checked.length + unlistable;
957
+ if (unlistable > 0)
958
+ warnings.add("names_unlistable");
959
+ const collisions = new Map();
960
+ const exclude = scope.sets.map((set) => set.sys_id).join(",");
961
+ try {
962
+ const read = await inScope(reader, () => mapLimited(chunks(checked, L.NAME_CHUNK), L.CONCURRENCY, (chunk) => reader.ops.get(`${platform_view_upgrades_js_1.STATS_PATH}sys_update_xml`, {
963
+ sysparm_query: `nameIN${chunk.join(",")}^update_set.state=in progress^update_setNOT IN${exclude}`,
964
+ sysparm_group_by: "name",
965
+ sysparm_count: "true",
966
+ })));
967
+ if (read === undefined) {
968
+ warnings.add("collisions_unavailable");
969
+ return;
970
+ }
971
+ for (const response of read.value) {
972
+ for (const group of groupsOf(response)) {
973
+ const name = group.fields.get("name");
974
+ // A group with no readable count still says the name is held elsewhere.
975
+ if (name !== undefined && checked.includes(name))
976
+ collisions.set(name, group.count ?? 1);
977
+ }
978
+ }
979
+ }
980
+ catch (error) {
981
+ if (isCancellation(error, reader.signal))
982
+ throw error;
983
+ warnings.add("collisions_unavailable");
984
+ return;
985
+ }
986
+ facts.collisions = collisions;
987
+ if (notChecked > 0) {
988
+ facts.unavailable += notChecked;
989
+ warnings.add("collisions_unavailable");
990
+ }
991
+ }
992
+ /** BP005: which names have a version from a source other than the customer's own sets. */
993
+ /** BP005, run inside the context's scope (see {@link readContext}). */
994
+ async function readBaseline(reader, access, updates, facts, warnings) {
995
+ if ((0, platform_view_upgrades_js_1.firstUnreadable)(access, "sys_update_version", ["name", "source_table"]) !== undefined) {
996
+ warnings.add("baseline_unavailable");
997
+ return;
998
+ }
999
+ const { listable, unlistable } = listableNames(updates);
1000
+ const checked = listable.slice(0, L.MAX_BASELINE_NAMES);
1001
+ try {
1002
+ const responses = await mapLimited(chunks(checked, L.NAME_CHUNK), L.CONCURRENCY, (chunk) => reader.ops.get(`${platform_view_upgrades_js_1.STATS_PATH}sys_update_version`, {
1003
+ sysparm_query: `nameIN${chunk.join(",")}`,
1004
+ sysparm_group_by: "name,source_table",
1005
+ sysparm_count: "true",
1006
+ }));
1007
+ // A checked name with no version is a new record: the customer's own. A
1008
+ // version with no source says nothing, so a name with only such versions
1009
+ // (and none from a baseline) is left out: the engine counts it unchecked.
1010
+ const baseline = new Map(checked.map((name) => [name, "customer"]));
1011
+ const unsourced = new Set();
1012
+ for (const response of responses) {
1013
+ for (const group of groupsOf(response)) {
1014
+ const name = group.fields.get("name");
1015
+ const source = group.fields.get("source_table")?.trim().toLowerCase() ?? "";
1016
+ if (name === undefined || !baseline.has(name))
1017
+ continue;
1018
+ if (source === "")
1019
+ unsourced.add(name);
1020
+ else if (!CUSTOMER_VERSION_SOURCES.has(source))
1021
+ baseline.set(name, "baseline");
1022
+ }
1023
+ }
1024
+ for (const name of unsourced)
1025
+ if (baseline.get(name) !== "baseline")
1026
+ baseline.delete(name);
1027
+ if (unsourced.size > 0)
1028
+ warnings.add("baseline_unavailable");
1029
+ facts.baseline = baseline;
1030
+ }
1031
+ catch (error) {
1032
+ if (isCancellation(error, reader.signal))
1033
+ throw error;
1034
+ warnings.add("baseline_unavailable");
1035
+ return;
1036
+ }
1037
+ // Names left out are missing from the map; the engine counts each one.
1038
+ if (listable.length > checked.length)
1039
+ warnings.add("baseline_unavailable");
1040
+ if (unlistable > 0)
1041
+ warnings.add("names_unlistable");
1042
+ }
1043
+ // ---------------------------------------------------------------------------
1044
+ // Output
1045
+ // ---------------------------------------------------------------------------
1046
+ function findingRow(finding) {
1047
+ return {
1048
+ rule_id: finding.rule_id,
1049
+ group: finding.group,
1050
+ severity: finding.severity,
1051
+ confidence: finding.confidence,
1052
+ message: finding.message,
1053
+ ...(finding.update === undefined
1054
+ ? {}
1055
+ : {
1056
+ update: {
1057
+ sys_id: finding.update.sys_id,
1058
+ name: (0, platform_view_upgrades_js_1.cleanText)(finding.update.name, MAX_NAME_CHARS) ?? "",
1059
+ type: (0, platform_view_upgrades_js_1.cleanText)(finding.update.type, MAX_NAME_CHARS) ?? null,
1060
+ target_name: (0, platform_view_upgrades_js_1.cleanText)(finding.update.target_name, MAX_NAME_CHARS) ?? null,
1061
+ update_set: finding.update.update_set,
1062
+ },
1063
+ }),
1064
+ ...(finding.update_set === undefined
1065
+ ? {}
1066
+ : { update_set: { sys_id: finding.update_set.sys_id, name: (0, platform_view_upgrades_js_1.cleanText)(finding.update_set.name, MAX_NAME_CHARS) ?? "" } }),
1067
+ ...(finding.table === undefined || !TABLE_NAME.test(finding.table) ? {} : { table: finding.table }),
1068
+ ...(finding.field === undefined ? {} : { field: finding.field }),
1069
+ ...(finding.line === undefined ? {} : { line: finding.line }),
1070
+ };
1071
+ }
1072
+ // ---------------------------------------------------------------------------
1073
+ // Handler
1074
+ // ---------------------------------------------------------------------------
1075
+ /**
1076
+ * Build the `view: "evaluate"` handler. `handleEvaluate` is the one the module
1077
+ * registers; a test builds its own with a fixed field access, engine limits,
1078
+ * a fake clock or a smaller scope budget.
1079
+ */
1080
+ function createEvaluateHandler(defaults = {}) {
1081
+ const maxScopes = Math.min(L.MAX_SCOPES, Math.max(1, Math.floor(defaults.maxScopes ?? L.MAX_SCOPES)));
1082
+ const limits = { ...engine_js_1.ENGINE_LIMITS, ...defaults.limits };
1083
+ return async (args, services, fieldAccess) => {
1084
+ const selector = selectorOf(args);
1085
+ const access = (0, platform_view_upgrades_js_1.memoizedFieldAccess)(fieldAccess ?? defaults.fieldAccess ?? platform_view_upgrades_js_1.liveFieldAccess);
1086
+ const reader = {
1087
+ ops: (0, metadata_cache_js_1.uncachedOperations)(services.serviceNow),
1088
+ meta: services.serviceNow,
1089
+ signal: services.context?.signal,
1090
+ scopes: new flow_view_module_js_1.FlowViewScopeBudget(maxScopes),
1091
+ hooks: defaults.hooks ?? {},
1092
+ };
1093
+ const warnings = new Set();
1094
+ const groups = args.groups === undefined || args.groups.length === 0 ? undefined : args.groups;
1095
+ const factsWanted = groups === undefined || groups.includes("bp");
1096
+ try {
1097
+ // 1. The scope.
1098
+ let resolution;
1099
+ try {
1100
+ resolution = await resolveScope(reader, access, selector, warnings);
1101
+ }
1102
+ catch (error) {
1103
+ if ((0, platform_view_upgrades_js_1.errorCategory)(error) === "authorization")
1104
+ throw new ViewStop("denied", exports.EVALUATE_DENIED_HINT);
1105
+ if ((0, platform_view_upgrades_js_1.isMissingTable)(error))
1106
+ throw new ViewStop("unavailable", exports.EVALUATE_UNAVAILABLE_HINT);
1107
+ throw error;
1108
+ }
1109
+ if (resolution.kind === "not_found") {
1110
+ return (0, platform_view_upgrades_js_1.viewResult)(args, { view: "evaluate", status: "ok", summary: { scope: null, note: exports.EVALUATE_NOTE }, results: [], hint: exports.EVALUATE_NOT_FOUND_HINT });
1111
+ }
1112
+ if (resolution.kind === "ambiguous") {
1113
+ return (0, platform_view_upgrades_js_1.viewResult)(args, {
1114
+ view: "evaluate",
1115
+ status: "ok",
1116
+ summary: { scope: null, candidates: resolution.candidates, note: exports.EVALUATE_NOTE },
1117
+ results: [],
1118
+ hint: exports.EVALUATE_AMBIGUOUS_HINT,
1119
+ });
1120
+ }
1121
+ const scope = resolution.scope;
1122
+ // 2. Rows, leaving the scopes the context and the facts need.
1123
+ const payloadAccess = access.canRead("sys_update_xml", "payload") ? "granted" : "denied";
1124
+ // One scope for the context (with the update-version counts), and one
1125
+ // for the problems or collisions when the facts are read.
1126
+ const reserved = 1 + (factsWanted ? 1 : 0);
1127
+ let rows;
1128
+ try {
1129
+ rows = await readRows(reader, access, scope, {
1130
+ maxUpdates: args.max_updates ?? L.DEFAULT_MAX_UPDATES,
1131
+ reserved,
1132
+ payload: payloadAccess === "granted",
1133
+ }, warnings);
1134
+ }
1135
+ catch (error) {
1136
+ if ((0, platform_view_upgrades_js_1.errorCategory)(error) === "authorization")
1137
+ throw new ViewStop("denied", exports.EVALUATE_DENIED_HINT);
1138
+ throw error;
1139
+ }
1140
+ // 3 and 4. Context and facts, together: none depends on another.
1141
+ const facts = { unavailable: 0 };
1142
+ // A set whose description could not be checked is a check not made.
1143
+ if (factsWanted && !scope.descriptionsKnown)
1144
+ facts.unavailable += 1;
1145
+ const baseline = factsWanted && rows.updates.length > 0
1146
+ ? {
1147
+ run: () => readBaseline(reader, access, rows.updates, facts, warnings),
1148
+ noScope: () => warnings.add("baseline_unavailable"),
1149
+ }
1150
+ : undefined;
1151
+ const steps = [readContext(reader, access, rows.updates, warnings, baseline)];
1152
+ if (factsWanted && rows.updates.length > 0) {
1153
+ if (scope.source === "remote")
1154
+ steps.push(readProblems(reader, access, scope, facts, warnings));
1155
+ else
1156
+ steps.push(readCollisions(reader, access, scope, rows.updates, facts, warnings));
1157
+ }
1158
+ else if (factsWanted && scope.source === "remote") {
1159
+ // An empty remote scope still needs its problems: a problem with no row blocks too.
1160
+ steps.push(readProblems(reader, access, scope, facts, warnings));
1161
+ }
1162
+ const [context] = (await Promise.all(steps));
1163
+ if (context.collectionBudgetHit)
1164
+ facts.unavailable += 1;
1165
+ const input = {
1166
+ source: scope.source,
1167
+ sets: scope.sets,
1168
+ batch_root: selector.children ? scope.root : null,
1169
+ updates: rows.updates,
1170
+ updates_total: Number.isFinite(scope.total) ? scope.total : Number.NaN,
1171
+ payload_access: payloadAccess,
1172
+ ...(facts.problems === undefined ? {} : { problems: facts.problems }),
1173
+ ...(facts.collisions === undefined ? {} : { open_set_collisions: facts.collisions }),
1174
+ ...(facts.baseline === undefined ? {} : { baseline_versions: facts.baseline }),
1175
+ context: context.context,
1176
+ };
1177
+ let result;
1178
+ try {
1179
+ result = await (0, engine_js_1.evaluateUpdateSets)(input, { ...(groups === undefined ? {} : { groups }), ...(args.min_severity === undefined ? {} : { min_severity: args.min_severity }) }, limits, defaults.hooks);
1180
+ }
1181
+ catch {
1182
+ // Nothing the engine or a check threw reaches the caller.
1183
+ throw (0, tool_error_js_1.createToolError)("internal", "do_not_retry");
1184
+ }
1185
+ const adapterPartial = scope.setsCapped || rows.scopeBudgetHit || facts.unavailable > 0;
1186
+ const coverage = {
1187
+ ...result.coverage,
1188
+ checks_unavailable: result.coverage.checks_unavailable + facts.unavailable,
1189
+ partial: result.coverage.partial || adapterPartial,
1190
+ rows_read: rows.updates.length,
1191
+ sets_capped: scope.setsCapped,
1192
+ scope_budget_hit: rows.scopeBudgetHit,
1193
+ upstream_scopes: reader.scopes.opened,
1194
+ };
1195
+ const findings = result.findings.map(findingRow);
1196
+ const page = findings.slice(args.offset, args.offset + args.limit);
1197
+ const hasMore = args.offset + page.length < findings.length;
1198
+ const shownSets = scope.sets.slice(0, L.SHOWN_SETS).map((set) => ({
1199
+ sys_id: set.sys_id,
1200
+ name: set.name,
1201
+ state: set.state ?? null,
1202
+ update_count: Number.isFinite(set.update_count) ? set.update_count : null,
1203
+ }));
1204
+ const warningList = [
1205
+ ...(payloadAccess === "denied" ? [exports.EVALUATE_METADATA_ONLY] : []),
1206
+ ...[...warnings].map((key) => exports.EVALUATE_WARNINGS[key]),
1207
+ ];
1208
+ return (0, platform_view_upgrades_js_1.viewResult)(args, {
1209
+ view: "evaluate",
1210
+ status: "ok",
1211
+ summary: {
1212
+ scope: {
1213
+ source: scope.source,
1214
+ root: scope.root,
1215
+ sets: shownSets,
1216
+ sets_total: scope.sets.length,
1217
+ updates_total: Number.isFinite(scope.total) ? scope.total : null,
1218
+ },
1219
+ rules_version: result.rules_version,
1220
+ by_group: result.summary.by_group,
1221
+ by_severity: result.summary.by_severity,
1222
+ findings_returned: findings.length,
1223
+ findings_truncated: result.findings_truncated,
1224
+ coverage,
1225
+ facts: {
1226
+ field_types: context.fieldTypes,
1227
+ hierarchy: context.hierarchyComplete ? "complete" : "partial",
1228
+ },
1229
+ note: exports.EVALUATE_NOTE,
1230
+ },
1231
+ results: page,
1232
+ record_count: page.length,
1233
+ has_more: hasMore,
1234
+ ...(hasMore ? { next_offset: args.offset + page.length } : {}),
1235
+ ...(warningList.length > 0 ? { warnings: warningList.slice(0, 20) } : {}),
1236
+ });
1237
+ }
1238
+ catch (error) {
1239
+ if (error instanceof ViewStop) {
1240
+ return (0, platform_view_upgrades_js_1.viewResult)(args, { view: "evaluate", status: error.status, hint: error.hint });
1241
+ }
1242
+ throw error;
1243
+ }
1244
+ };
1245
+ }
1246
+ /** The handler the dispatcher registers. */
1247
+ exports.handleEvaluate = createEvaluateHandler();
1248
+ // ---------------------------------------------------------------------------
1249
+ // Text
1250
+ // ---------------------------------------------------------------------------
1251
+ function shown(value) {
1252
+ return (0, platform_view_upgrades_js_1.scalar)(value) ?? "-";
1253
+ }
1254
+ /** One line of instance text: control characters gone, bounded. */
1255
+ function line(value) {
1256
+ return (0, platform_view_upgrades_js_1.cleanText)(value, MAX_NAME_CHARS) ?? "-";
1257
+ }
1258
+ const SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"];
1259
+ /**
1260
+ * The readable text of an `evaluate` result. Counts, rule ids, severities and
1261
+ * the engine's fixed messages are this server's own text. Every name (set,
1262
+ * update, target, type, table) is instance text and appears only inside an
1263
+ * `untrustedBlock`. A result with no findings never says only that: it says
1264
+ * what was examined, and that it is not an approval.
1265
+ */
1266
+ function renderEvaluateText(data) {
1267
+ const record = (0, platform_view_upgrades_js_1.asRecord)(data);
1268
+ if (record.view !== "evaluate")
1269
+ return undefined;
1270
+ const status = (0, platform_view_upgrades_js_1.scalar)(record.status);
1271
+ if (status !== "ok") {
1272
+ return (0, markdown_js_1.renderMarkdown)((0, markdown_js_1.headline)("Update set evaluation", { status: "fail", detail: (0, platform_view_upgrades_js_1.scalar)(record.hint) ?? "not available" }));
1273
+ }
1274
+ const summary = (0, platform_view_upgrades_js_1.asRecord)(record.summary);
1275
+ const scope = (0, platform_view_upgrades_js_1.asRecord)(summary.scope);
1276
+ if (summary.scope === null || Object.keys(scope).length === 0) {
1277
+ const candidates = Array.isArray(summary.candidates) ? summary.candidates : [];
1278
+ return (0, markdown_js_1.renderMarkdown)((0, markdown_js_1.headline)("Update set evaluation", { status: "warn", detail: "no scope" }), (0, markdown_js_1.text)((0, platform_view_upgrades_js_1.scalar)(record.hint) ?? exports.EVALUATE_NOT_FOUND_HINT), candidates.length === 0
1279
+ ? undefined
1280
+ : (0, markdown_js_1.untrustedBlock)("Candidates (sys_id | state)", candidates.map((entry) => `${line((0, platform_view_upgrades_js_1.asRecord)(entry).sys_id)} | ${line((0, platform_view_upgrades_js_1.asRecord)(entry).state)}`).join("\n")));
1281
+ }
1282
+ const coverage = (0, platform_view_upgrades_js_1.asRecord)(summary.coverage);
1283
+ const bySeverity = (0, platform_view_upgrades_js_1.asRecord)(summary.by_severity);
1284
+ const total = SEVERITY_ORDER.reduce((sum, severity) => sum + ((0, platform_view_upgrades_js_1.wholeNumber)(bySeverity[severity]) ?? 0), 0);
1285
+ const partial = coverage.partial === true;
1286
+ const blocks = [
1287
+ (0, markdown_js_1.headline)("Update set evaluation", {
1288
+ status: total > 0 || partial ? "warn" : "pass",
1289
+ detail: `${(0, platform_view_upgrades_js_1.scalar)(scope.source) === "remote" ? "remote" : "local"} scope, ${total} finding(s)${partial ? ", partial" : ""}`,
1290
+ }),
1291
+ (0, markdown_js_1.table)(["Severity", "Findings"], SEVERITY_ORDER.map((severity) => [severity, String((0, platform_view_upgrades_js_1.wholeNumber)(bySeverity[severity]) ?? 0)])),
1292
+ (0, markdown_js_1.table)(["Coverage", "Rows"], [
1293
+ ["in scope", shown(coverage.updates_total)],
1294
+ ["read", shown(coverage.rows_read)],
1295
+ ["scanned", shown(coverage.scanned)],
1296
+ ["metadata only (unreadable payload)", shown(coverage.skipped_unreadable)],
1297
+ ["credential rows (not scanned)", shown(coverage.credential_rows)],
1298
+ ["not evaluated", shown(coverage.not_evaluated)],
1299
+ ["checks unavailable", shown(coverage.checks_unavailable)],
1300
+ ]),
1301
+ ];
1302
+ const states = [];
1303
+ if (coverage.metadata_only === true)
1304
+ states.push(exports.EVALUATE_METADATA_ONLY);
1305
+ if (coverage.cpu_budget_hit === true)
1306
+ states.push("The CPU budget ran out; the result is partial.");
1307
+ if (coverage.bytes_cap_hit === true)
1308
+ states.push("The payload byte cap was reached; the result is partial.");
1309
+ if (summary.findings_truncated === true)
1310
+ states.push("More than 500 findings; the highest-severity 500 are kept.");
1311
+ if (total === 0)
1312
+ states.push("No rule matched in what was examined.");
1313
+ states.push(exports.EVALUATE_NOTE);
1314
+ blocks.push((0, markdown_js_1.bulletList)(states));
1315
+ const sets = Array.isArray(scope.sets) ? scope.sets : [];
1316
+ blocks.push((0, markdown_js_1.untrustedBlock)("Sets (sys_id | state | rows | name)", sets
1317
+ .map((entry) => {
1318
+ const set = (0, platform_view_upgrades_js_1.asRecord)(entry);
1319
+ return `${line(set.sys_id)} | ${line(set.state)} | ${shown(set.update_count)} | ${line(set.name)}`;
1320
+ })
1321
+ .join("\n"), 8_000));
1322
+ const rows = Array.isArray(record.results) ? record.results : [];
1323
+ if (rows.length > 0) {
1324
+ const lines = rows.map((entry) => {
1325
+ const finding = (0, platform_view_upgrades_js_1.asRecord)(entry);
1326
+ const update = (0, platform_view_upgrades_js_1.asRecord)(finding.update);
1327
+ const set = (0, platform_view_upgrades_js_1.asRecord)(finding.update_set);
1328
+ const where = Object.keys(update).length > 0
1329
+ ? `${line(update.name)} | ${line(update.type)} | ${line(update.target_name)} | set ${line(update.update_set)}`
1330
+ : `set ${line(set.sys_id)} ${line(set.name)}`;
1331
+ const extra = [
1332
+ finding.table === undefined ? "" : ` | table ${line(finding.table)}`,
1333
+ finding.field === undefined ? "" : ` | ${line(finding.field)}${finding.line === undefined ? "" : `:${shown(finding.line)}`}`,
1334
+ ].join("");
1335
+ return `${shown(finding.severity)} | ${shown(finding.rule_id)} | ${shown(finding.message)} | ${where}${extra}`;
1336
+ });
1337
+ blocks.push((0, markdown_js_1.untrustedBlock)("Findings (severity | rule | message | update | type | target | set)", lines.join("\n"), 16_000));
1338
+ }
1339
+ if (record.has_more === true)
1340
+ blocks.push((0, markdown_js_1.text)(`More findings: next_offset ${shown(record.next_offset)}.`));
1341
+ const warnings = Array.isArray(record.warnings) ? record.warnings : [];
1342
+ if (warnings.length > 0)
1343
+ blocks.push((0, markdown_js_1.bulletList)(warnings.map((warning) => String((0, platform_view_upgrades_js_1.scalar)(warning) ?? ""))));
1344
+ return (0, markdown_js_1.renderMarkdown)(...blocks);
1345
+ }
19
1346
  //# sourceMappingURL=platform-view-evaluate.js.map