@tenonhq/dovetail-core 0.0.132 → 0.0.134

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.
@@ -0,0 +1,386 @@
1
+ "use strict";
2
+ // Layout elements: mirror what a layout shows, not only that it exists.
3
+ //
4
+ // A list layout (sys_ui_list), a form section (sys_ui_section) and a form
5
+ // (sys_ui_form) are application files, but their content lives in child rows that
6
+ // are not: sys_ui_list_element (the columns), sys_ui_element (the fields) and
7
+ // sys_ui_form_section (the section order). Those rows carry no sys_scope, so the
8
+ // instance cannot list them per application. This module reads them through the
9
+ // Table API, which every instance already serves, and writes them as one text
10
+ // file in the parent layout's folder:
11
+ //
12
+ // sys_ui_list/<layout>/columns.txt one column per line, in list order
13
+ // sys_ui_section/<section>/fields.txt one form element per line, in form order
14
+ // sys_ui_form/<form>/sections.txt one section caption per line, in tab order
15
+ //
16
+ // Configured per table in dove.config.js, off by default:
17
+ //
18
+ // tableOptions: { sys_ui_list: { layoutElements: true } }
19
+ //
20
+ // Applied in snClient to the two reads every writer uses: getManifest lists the
21
+ // file on each record, and getMissingFiles (bulkDownload) fills its content. The
22
+ // file name is never sent to the instance as a field. Push refuses these files
23
+ // (FileUtils.getFileContextWithSkipReason) and a reconcile create leaves them
24
+ // out, so a layout is never written back from them.
25
+ //
26
+ // Client-side only: `layoutElements` is stripped from tableOptions before they
27
+ // are sent to the instance.
28
+ var __importDefault = (this && this.__importDefault) || function (mod) {
29
+ return (mod && mod.__esModule) ? mod : { "default": mod };
30
+ };
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.recordIdsByTable = exports.fillLayoutElementContent = exports.readLayoutElements = exports.splitLayoutElementRequests = exports.addLayoutElementFiles = exports.formatLayoutElements = exports.isLayoutElementsFilePath = exports.isLayoutElementsFile = exports.layoutElementTablesFor = exports.LAYOUT_ELEMENT_TABLES = exports.LAYOUT_ELEMENTS_FILE_TYPE = void 0;
33
+ const path_1 = __importDefault(require("path"));
34
+ exports.LAYOUT_ELEMENTS_FILE_TYPE = "txt";
35
+ const SYS_ID_RE = /^[0-9a-f]{32}$/;
36
+ const isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
37
+ // A Table API value is a plain string, or { value, link } for a reference when
38
+ // the link is not excluded. Anything else reads as "".
39
+ const valueOf = (row, key) => {
40
+ const v = row[key];
41
+ if (typeof v === "string")
42
+ return v;
43
+ if (typeof v === "number" || typeof v === "boolean")
44
+ return String(v);
45
+ if (isPlainObject(v) && typeof v.value === "string")
46
+ return v.value;
47
+ return "";
48
+ };
49
+ const isTrue = (v) => v === "true" || v === "1";
50
+ const AGGREGATES = [
51
+ ["sum", "sum"],
52
+ ["average_value", "average"],
53
+ ["min_value", "min"],
54
+ ["max_value", "max"],
55
+ ];
56
+ const columnLine = (row) => {
57
+ const element = valueOf(row, "element") || "(no element)";
58
+ const flags = [];
59
+ for (let i = 0; i < AGGREGATES.length; i++) {
60
+ if (isTrue(valueOf(row, AGGREGATES[i][0])))
61
+ flags.push(AGGREGATES[i][1]);
62
+ }
63
+ return flags.length ? element + " [" + flags.join(", ") + "]" : element;
64
+ };
65
+ // A split or other marker row repeats its type as the element (".split"), so
66
+ // the type is only written when it adds something ("activity.xml [formatter]").
67
+ const fieldLine = (row) => {
68
+ const element = valueOf(row, "element") || "(no element)";
69
+ const type = valueOf(row, "type");
70
+ return type && type !== element ? element + " [" + type + "]" : element;
71
+ };
72
+ // A form lists its sections by reference. The main section has no caption; a
73
+ // reference to a section that cannot be read keeps its id, so it stays visible.
74
+ const sectionLine = (row) => {
75
+ const sectionId = valueOf(row, "sys_ui_section");
76
+ if (valueOf(row, "sys_ui_section.sys_id") === "") {
77
+ return "(missing section " + (sectionId || "with no id") + ")";
78
+ }
79
+ const caption = valueOf(row, "sys_ui_section.caption");
80
+ return caption !== "" ? caption : "(no caption)";
81
+ };
82
+ const SPECS = {
83
+ sys_ui_list: {
84
+ file: "columns",
85
+ childTable: "sys_ui_list_element",
86
+ parentField: "list_id",
87
+ fields: ["sys_id", "list_id", "element", "position", "sum", "average_value", "min_value", "max_value"],
88
+ line: columnLine,
89
+ },
90
+ sys_ui_section: {
91
+ file: "fields",
92
+ childTable: "sys_ui_element",
93
+ parentField: "sys_ui_section",
94
+ fields: ["sys_id", "sys_ui_section", "element", "type", "position"],
95
+ line: fieldLine,
96
+ },
97
+ sys_ui_form: {
98
+ file: "sections",
99
+ childTable: "sys_ui_form_section",
100
+ parentField: "sys_ui_form",
101
+ fields: ["sys_id", "sys_ui_form", "sys_ui_section", "position", "sys_ui_section.sys_id", "sys_ui_section.caption"],
102
+ line: sectionLine,
103
+ },
104
+ };
105
+ const specFor = (table) => Object.prototype.hasOwnProperty.call(SPECS, table) ? SPECS[table] : undefined;
106
+ /** The tables that can carry layout elements. */
107
+ exports.LAYOUT_ELEMENT_TABLES = Object.keys(SPECS);
108
+ /**
109
+ * The layout tables whose table options set `layoutElements: true`. Any other
110
+ * value, or the option on a table that has no layout elements, is ignored and
111
+ * reported through `warn`, so a typo mirrors nothing instead of guessing.
112
+ */
113
+ const layoutElementTablesFor = (tableOptions, warn) => {
114
+ if (!isPlainObject(tableOptions))
115
+ return [];
116
+ const out = [];
117
+ const tables = Object.keys(tableOptions).sort();
118
+ for (let i = 0; i < tables.length; i++) {
119
+ const opts = tableOptions[tables[i]];
120
+ if (!isPlainObject(opts) || !("layoutElements" in opts))
121
+ continue;
122
+ const value = opts.layoutElements;
123
+ if (!specFor(tables[i])) {
124
+ if (warn)
125
+ warn("tableOptions." + tables[i] + ".layoutElements is ignored: only " + exports.LAYOUT_ELEMENT_TABLES.join(", ") + " have layout elements");
126
+ continue;
127
+ }
128
+ if (value !== true) {
129
+ if (value !== false && warn)
130
+ warn("tableOptions." + tables[i] + ".layoutElements is ignored: it must be true or false");
131
+ continue;
132
+ }
133
+ out.push(tables[i]);
134
+ }
135
+ return out;
136
+ };
137
+ exports.layoutElementTablesFor = layoutElementTablesFor;
138
+ /** True for a layout elements file: one of the three derived files of its table. */
139
+ const isLayoutElementsFile = (table, name, type) => {
140
+ const spec = specFor(table);
141
+ if (!spec || name !== spec.file)
142
+ return false;
143
+ return type === undefined || type === exports.LAYOUT_ELEMENTS_FILE_TYPE;
144
+ };
145
+ exports.isLayoutElementsFile = isLayoutElementsFile;
146
+ /** True for the on-disk path of a layout elements file: <table>/<record>/<file>.txt */
147
+ const isLayoutElementsFilePath = (filePath) => {
148
+ if (typeof filePath !== "string" || filePath === "")
149
+ return false;
150
+ const ext = "." + exports.LAYOUT_ELEMENTS_FILE_TYPE;
151
+ const base = path_1.default.basename(filePath);
152
+ if (base.slice(-ext.length) !== ext)
153
+ return false;
154
+ const table = path_1.default.basename(path_1.default.dirname(path_1.default.dirname(filePath)));
155
+ return (0, exports.isLayoutElementsFile)(table, base.slice(0, -ext.length), exports.LAYOUT_ELEMENTS_FILE_TYPE);
156
+ };
157
+ exports.isLayoutElementsFilePath = isLayoutElementsFilePath;
158
+ const positionOf = (row) => {
159
+ const n = parseInt(valueOf(row, "position"), 10);
160
+ return isNaN(n) ? Number.MAX_SAFE_INTEGER : n;
161
+ };
162
+ /**
163
+ * The file content for one parent's child rows: one line per row, ordered by
164
+ * position, then by the line, then by the row's id, so the file is the same on
165
+ * every pull. No rows is an empty file.
166
+ */
167
+ const formatLayoutElements = (table, rows) => {
168
+ const spec = specFor(table);
169
+ if (!spec)
170
+ throw new Error("Table " + table + " has no layout elements");
171
+ const items = [];
172
+ for (let i = 0; i < rows.length; i++) {
173
+ const row = rows[i];
174
+ if (!isPlainObject(row))
175
+ continue;
176
+ items.push({ pos: positionOf(row), line: spec.line(row), id: valueOf(row, "sys_id") });
177
+ }
178
+ items.sort(function (a, b) {
179
+ if (a.pos !== b.pos)
180
+ return a.pos - b.pos;
181
+ if (a.line !== b.line)
182
+ return a.line < b.line ? -1 : 1;
183
+ if (a.id !== b.id)
184
+ return a.id < b.id ? -1 : 1;
185
+ return 0;
186
+ });
187
+ if (items.length === 0)
188
+ return "";
189
+ return items.map(function (it) { return it.line; }).join("\n") + "\n";
190
+ };
191
+ exports.formatLayoutElements = formatLayoutElements;
192
+ /**
193
+ * Add the layout elements file to every record of an enabled table in a
194
+ * getManifest table map, in place. Idempotent; a no-op for any other table.
195
+ */
196
+ const addLayoutElementFiles = (tables, enabledTables) => {
197
+ if (!isPlainObject(tables))
198
+ return tables;
199
+ for (let t = 0; t < enabledTables.length; t++) {
200
+ const spec = specFor(enabledTables[t]);
201
+ const table = tables[enabledTables[t]];
202
+ if (!spec || !isPlainObject(table) || !isPlainObject(table.records))
203
+ continue;
204
+ const names = Object.keys(table.records);
205
+ for (let r = 0; r < names.length; r++) {
206
+ const record = table.records[names[r]];
207
+ if (!isPlainObject(record))
208
+ continue;
209
+ if (!Array.isArray(record.files))
210
+ record.files = [];
211
+ const has = record.files.some(function (f) { return isPlainObject(f) && f.name === spec.file; });
212
+ if (!has)
213
+ record.files.push({ name: spec.file, type: exports.LAYOUT_ELEMENTS_FILE_TYPE });
214
+ }
215
+ }
216
+ return tables;
217
+ };
218
+ exports.addLayoutElementFiles = addLayoutElementFiles;
219
+ /**
220
+ * Take the layout elements files out of a bulkDownload request (they are not
221
+ * fields, so the instance cannot serve them) and remember which records asked
222
+ * for them. The caller's map is not mutated.
223
+ */
224
+ const splitLayoutElementRequests = (missingFiles) => {
225
+ const request = {};
226
+ const wanted = {};
227
+ if (!isPlainObject(missingFiles))
228
+ return { request: request, wanted: wanted };
229
+ const tables = Object.keys(missingFiles);
230
+ for (let t = 0; t < tables.length; t++) {
231
+ const tableName = tables[t];
232
+ const records = missingFiles[tableName];
233
+ const spec = specFor(tableName);
234
+ if (!spec || !isPlainObject(records)) {
235
+ request[tableName] = records;
236
+ continue;
237
+ }
238
+ const out = {};
239
+ const ids = Object.keys(records);
240
+ for (let r = 0; r < ids.length; r++) {
241
+ const files = Array.isArray(records[ids[r]]) ? records[ids[r]] : [];
242
+ const kept = [];
243
+ let asked = false;
244
+ for (let f = 0; f < files.length; f++) {
245
+ if ((0, exports.isLayoutElementsFile)(tableName, files[f].name, files[f].type))
246
+ asked = true;
247
+ else
248
+ kept.push(files[f]);
249
+ }
250
+ out[ids[r]] = kept;
251
+ if (asked) {
252
+ if (!wanted[tableName])
253
+ wanted[tableName] = [];
254
+ wanted[tableName].push(ids[r]);
255
+ }
256
+ }
257
+ request[tableName] = out;
258
+ }
259
+ return { request: request, wanted: wanted };
260
+ };
261
+ exports.splitLayoutElementRequests = splitLayoutElementRequests;
262
+ const DEFAULT_READ = { pageSize: 1000, chunkSize: 100 };
263
+ const MAX_PAGES_PER_CHUNK = 1000;
264
+ /**
265
+ * Read the child rows of each parent layout and format them. Every parent gets
266
+ * an entry: "" when it has no child rows. A parent id that is not a record id is
267
+ * refused before any query runs, and a failed read throws, so a missing read can
268
+ * never be written as an empty layout.
269
+ */
270
+ const readLayoutElements = async (read, table, parentIds, options) => {
271
+ const spec = specFor(table);
272
+ if (!spec)
273
+ throw new Error("Table " + table + " has no layout elements");
274
+ const opts = Object.assign({}, DEFAULT_READ, options || {});
275
+ if (!(opts.pageSize >= 1) || !(opts.chunkSize >= 1))
276
+ throw new Error("Invalid layout elements read options");
277
+ const ids = [];
278
+ for (let i = 0; i < parentIds.length; i++) {
279
+ const pid = parentIds[i];
280
+ if (typeof pid !== "string" || !SYS_ID_RE.test(pid)) {
281
+ throw new Error("Refusing to read " + spec.childTable + " for '" + String(pid) + "': not a record id");
282
+ }
283
+ if (ids.indexOf(pid) === -1)
284
+ ids.push(pid);
285
+ }
286
+ const rowsByParent = {};
287
+ for (let i = 0; i < ids.length; i++)
288
+ rowsByParent[ids[i]] = [];
289
+ for (let c = 0; c < ids.length; c += opts.chunkSize) {
290
+ const chunk = ids.slice(c, c + opts.chunkSize);
291
+ const query = spec.parentField + "IN" + chunk.join(",") + "^ORDERBYsys_id";
292
+ let offset = 0;
293
+ for (let page = 0;; page++) {
294
+ if (page >= MAX_PAGES_PER_CHUNK) {
295
+ throw new Error("Too many pages reading " + spec.childTable + "; refusing to continue");
296
+ }
297
+ const rows = await read(spec.childTable, query, spec.fields, opts.pageSize, offset);
298
+ if (!Array.isArray(rows))
299
+ throw new Error("Unexpected response reading " + spec.childTable);
300
+ for (let r = 0; r < rows.length; r++) {
301
+ const row = rows[r];
302
+ if (!isPlainObject(row))
303
+ continue;
304
+ const parent = valueOf(row, spec.parentField);
305
+ // A row for a parent that was not asked for is ignored, never attached.
306
+ if (Object.prototype.hasOwnProperty.call(rowsByParent, parent) && chunk.indexOf(parent) !== -1) {
307
+ rowsByParent[parent].push(row);
308
+ }
309
+ }
310
+ if (rows.length < opts.pageSize)
311
+ break;
312
+ offset += opts.pageSize;
313
+ }
314
+ }
315
+ const out = {};
316
+ for (let i = 0; i < ids.length; i++)
317
+ out[ids[i]] = (0, exports.formatLayoutElements)(table, rowsByParent[ids[i]]);
318
+ return out;
319
+ };
320
+ exports.readLayoutElements = readLayoutElements;
321
+ /**
322
+ * Fill the layout elements file of each wanted record in a table map (a
323
+ * bulkDownload result, or a getManifest map read with contents), in place.
324
+ * Records are matched by sys_id, never by name. A wanted record the map does
325
+ * not hold is left alone.
326
+ */
327
+ const fillLayoutElementContent = async (tables, wanted, read, options) => {
328
+ if (!isPlainObject(tables) || !isPlainObject(wanted))
329
+ return tables;
330
+ const tableNames = Object.keys(wanted).sort();
331
+ for (let t = 0; t < tableNames.length; t++) {
332
+ const tableName = tableNames[t];
333
+ const spec = specFor(tableName);
334
+ const ids = wanted[tableName];
335
+ if (!spec || !Array.isArray(ids) || ids.length === 0)
336
+ continue;
337
+ const content = await (0, exports.readLayoutElements)(read, tableName, ids, options);
338
+ const table = tables[tableName];
339
+ if (!isPlainObject(table) || !isPlainObject(table.records))
340
+ continue;
341
+ const names = Object.keys(table.records);
342
+ for (let r = 0; r < names.length; r++) {
343
+ const record = table.records[names[r]];
344
+ if (!isPlainObject(record) || typeof record.sys_id !== "string")
345
+ continue;
346
+ if (!Object.prototype.hasOwnProperty.call(content, record.sys_id))
347
+ continue;
348
+ if (!Array.isArray(record.files))
349
+ record.files = [];
350
+ const file = { name: spec.file, type: exports.LAYOUT_ELEMENTS_FILE_TYPE, content: content[record.sys_id] };
351
+ let replaced = false;
352
+ for (let f = 0; f < record.files.length; f++) {
353
+ if (isPlainObject(record.files[f]) && record.files[f].name === spec.file) {
354
+ record.files[f] = file;
355
+ replaced = true;
356
+ }
357
+ }
358
+ if (!replaced)
359
+ record.files.push(file);
360
+ }
361
+ }
362
+ return tables;
363
+ };
364
+ exports.fillLayoutElementContent = fillLayoutElementContent;
365
+ /** Record ids of every record of the enabled tables in a table map. */
366
+ const recordIdsByTable = (tables, enabledTables) => {
367
+ const out = {};
368
+ if (!isPlainObject(tables))
369
+ return out;
370
+ for (let t = 0; t < enabledTables.length; t++) {
371
+ const table = tables[enabledTables[t]];
372
+ if (!isPlainObject(table) || !isPlainObject(table.records))
373
+ continue;
374
+ const ids = [];
375
+ const names = Object.keys(table.records);
376
+ for (let r = 0; r < names.length; r++) {
377
+ const record = table.records[names[r]];
378
+ if (isPlainObject(record) && typeof record.sys_id === "string")
379
+ ids.push(record.sys_id);
380
+ }
381
+ if (ids.length)
382
+ out[enabledTables[t]] = ids;
383
+ }
384
+ return out;
385
+ };
386
+ exports.recordIdsByTable = recordIdsByTable;
@@ -73,6 +73,7 @@ const recordSource_1 = require("./reconcile/recordSource");
73
73
  const recordDiff_1 = require("./reconcile/recordDiff");
74
74
  const fields_1 = require("./reconcile/fields");
75
75
  const fingerprint_1 = require("./fingerprint");
76
+ const layoutElements_1 = require("./layoutElements");
76
77
  const baseline_1 = require("./reconcile/baseline");
77
78
  const report_1 = require("./reconcile/report");
78
79
  const applyPlan_1 = require("./reconcile/applyPlan");
@@ -333,6 +334,11 @@ async function buildCreateFields(scope, change) {
333
334
  if (!(0, fields_1.isComparableField)({ name, type })) {
334
335
  continue;
335
336
  }
337
+ // A layout elements file is read from the layout's child rows
338
+ // (layoutElements.ts), not a field of the record: never send it.
339
+ if ((0, layoutElements_1.isLayoutElementsFile)(change.table, name, type)) {
340
+ continue;
341
+ }
336
342
  try {
337
343
  const stat = await fs_1.promises.stat(path_1.default.join(recordDir, entry));
338
344
  if (stat.isFile()) {
package/dist/snClient.js CHANGED
@@ -18,6 +18,7 @@ const genericUtils_1 = require("./genericUtils");
18
18
  const Logger_1 = require("./Logger");
19
19
  const FileLogger_1 = require("./FileLogger");
20
20
  const fingerprint_1 = require("./fingerprint");
21
+ const layoutElements_1 = require("./layoutElements");
21
22
  const authFailure_1 = require("./authFailure");
22
23
  // Benchmark sink. Null when --benchmark is off; zero overhead in that case.
23
24
  let _benchmarkSink = null;
@@ -606,20 +607,52 @@ const snClient = (baseURL, username, password, apiKey) => {
606
607
  user: userSysId,
607
608
  });
608
609
  };
610
+ // Rows of one table through the Table API, raw values, reference links left
611
+ // out. Used for the child rows of layouts (layoutElements.ts); the table, the
612
+ // fields and the query are built there from constants and checked record ids.
613
+ const readTableRows = async (table, query, fields, limit, offset) => {
614
+ const endpoint = "api/now/table/" + encodeURIComponent(table);
615
+ const resp = await client.get(endpoint, {
616
+ params: {
617
+ sysparm_query: query,
618
+ sysparm_fields: fields.join(","),
619
+ sysparm_limit: String(limit),
620
+ sysparm_offset: String(offset),
621
+ sysparm_exclude_reference_link: "true",
622
+ sysparm_display_value: "false",
623
+ // With a long IN list the instance cannot build its pagination Link
624
+ // header and answers HTTP 400 "Pagination not supported". Paging is
625
+ // done here by limit and offset, so the header is not needed.
626
+ sysparm_suppress_pagination_header: "true",
627
+ },
628
+ });
629
+ const rows = resp && resp.data ? resp.data.result : undefined;
630
+ if (!Array.isArray(rows)) {
631
+ throw new Error("Unexpected response reading " + table + " (no result array)");
632
+ }
633
+ return rows;
634
+ };
635
+ const warnLayoutOption = (message) => {
636
+ Logger_1.logger.warn(message);
637
+ };
609
638
  const getMissingFiles = (missingFiles, tableOptions) => {
610
639
  const endpoint = `api/cadso/dovetail_sync/bulkDownload`;
611
640
  const tableCount = Object.keys(missingFiles).length;
612
641
  FileLogger_1.fileLogger.debug("Bulk downloading files for " + tableCount + " tables");
613
- // `fingerprint` is client-only: stripped from the request, applied to the
614
- // response (see fingerprint.ts).
642
+ // A layout elements file is not a field: ask the instance for the real
643
+ // fields only, then read the child rows through the Table API.
644
+ const layoutRequests = (0, layoutElements_1.splitLayoutElementRequests)(missingFiles);
645
+ // `fingerprint` and `layoutElements` are client-only: stripped from the
646
+ // request, applied to the response (see fingerprint.ts, layoutElements.ts).
615
647
  return client
616
648
  .post(endpoint, {
617
- missingFiles,
649
+ missingFiles: layoutRequests.request,
618
650
  tableOptions: (0, fingerprint_1.stripClientOnlyTableOptions)(tableOptions),
619
651
  })
620
- .then(function (resp) {
652
+ .then(async function (resp) {
621
653
  if (resp && resp.data && resp.data.result) {
622
654
  (0, fingerprint_1.applyFingerprints)(resp.data.result, tableOptions);
655
+ await (0, layoutElements_1.fillLayoutElementContent)(resp.data.result, layoutRequests.wanted, readTableRows);
623
656
  }
624
657
  return resp;
625
658
  });
@@ -639,12 +672,22 @@ const snClient = (baseURL, username, password, apiKey) => {
639
672
  withFiles,
640
673
  getContents: withFiles, // ServiceNow expects getContents, not withFiles
641
674
  })
642
- .then(function (resp) {
675
+ .then(async function (resp) {
643
676
  // Fingerprinted fields come back as `<field>.sha256` entries (and with
644
677
  // hashed content when withFiles is set), so the manifest, the
645
678
  // missing-file check and every writer agree on the on-disk name.
646
679
  if (resp && resp.data && resp.data.result && resp.data.result.tables) {
647
- (0, fingerprint_1.applyFingerprints)(resp.data.result.tables, tableOptions);
680
+ const tables = resp.data.result.tables;
681
+ (0, fingerprint_1.applyFingerprints)(tables, tableOptions);
682
+ // Layout elements: list the file on every record of an enabled layout
683
+ // table, and read its content now when contents were asked for.
684
+ const layoutTables = (0, layoutElements_1.layoutElementTablesFor)(tableOptions, warnLayoutOption);
685
+ if (layoutTables.length > 0) {
686
+ (0, layoutElements_1.addLayoutElementFiles)(tables, layoutTables);
687
+ if (withFiles) {
688
+ await (0, layoutElements_1.fillLayoutElementContent)(tables, (0, layoutElements_1.recordIdsByTable)(tables, layoutTables), readTableRows);
689
+ }
690
+ }
648
691
  }
649
692
  return resp;
650
693
  });
@@ -230,3 +230,143 @@ describe("DovetailUtilsMS.processMissingFiles — duplicate display names", () =
230
230
  expect(out.warnings).toHaveLength(0);
231
231
  });
232
232
  });
233
+ /**
234
+ * NAME TWINS. Records created in one transaction (the access controls of a new
235
+ * table) get sys_ids that differ only in the last few characters, so two that
236
+ * share a display name also share `Name (first 8)`. That key collapsed exactly
237
+ * like the bare name used to: one record left the manifest, silently.
238
+ */
239
+ const TWIN_A = "15f0e0ea33dfc7107b18bc534d5c7bc4";
240
+ const TWIN_B = "15f0e0ea33dfc7107b18bc534d5c7bf5";
241
+ const TRIPLET = [
242
+ "6d462a3bc3744714d4ddf1db05013163",
243
+ "6d462a3bc3744714d4ddf1db0501317b",
244
+ "6d462a3bc3744714d4ddf1db05013193",
245
+ ];
246
+ describe("DovetailUtilsMS.buildTableMap — same name and same first 8 id characters", () => {
247
+ it("keeps BOTH twins (regression: the 8-character key collapsed and one was dropped)", () => {
248
+ const out = buildMap([
249
+ { sys_id: TWIN_A, name: "x_cadso_journey_fire_log" },
250
+ { sys_id: TWIN_B, name: "x_cadso_journey_fire_log" },
251
+ ]);
252
+ const keys = Object.keys(out.records);
253
+ expect(keys).toHaveLength(2);
254
+ expect(keys.map((k) => out.records[k].sys_id).sort()).toEqual([TWIN_A, TWIN_B]);
255
+ });
256
+ it("lengthens the suffix to the full id for both, so neither holds the ambiguous key", () => {
257
+ const out = buildMap([
258
+ { sys_id: TWIN_A, name: "x_cadso_journey_fire_log" },
259
+ { sys_id: TWIN_B, name: "x_cadso_journey_fire_log" },
260
+ ]);
261
+ expect(Object.keys(out.records).sort()).toEqual([
262
+ "x_cadso_journey_fire_log (" + TWIN_A + ")",
263
+ "x_cadso_journey_fire_log (" + TWIN_B + ")",
264
+ ]);
265
+ expect(out.records["x_cadso_journey_fire_log (15f0e0ea)"]).toBeUndefined();
266
+ Object.keys(out.records).forEach((key) => {
267
+ expect(out.records[key].name).toBe(key);
268
+ });
269
+ });
270
+ it("keeps all three of a three-way twin group", () => {
271
+ const out = buildMap(TRIPLET.map((id) => ({ sys_id: id, name: "x_cadso_core_announcement" })));
272
+ expect(Object.keys(out.records).sort()).toEqual(TRIPLET.map((id) => "x_cadso_core_announcement (" + id + ")"));
273
+ });
274
+ it("lengthens only the records that collide; a namesake with another prefix keeps 8 characters", () => {
275
+ const out = buildMap([
276
+ { sys_id: TWIN_A, name: "x_cadso_journey_fire_log" },
277
+ { sys_id: TWIN_B, name: "x_cadso_journey_fire_log" },
278
+ { sys_id: "aa11bb22cc33dd44ee55ff6600112233", name: "x_cadso_journey_fire_log" },
279
+ ]);
280
+ expect(Object.keys(out.records).sort()).toEqual([
281
+ "x_cadso_journey_fire_log (" + TWIN_A + ")",
282
+ "x_cadso_journey_fire_log (" + TWIN_B + ")",
283
+ "x_cadso_journey_fire_log (aa11bb22)",
284
+ ]);
285
+ });
286
+ it("never returns fewer records than the table holds", () => {
287
+ const rows = [];
288
+ for (let i = 0; i < 25; i++) {
289
+ rows.push({
290
+ sys_id: "c7fdaa3d470ef510b0361ae8036d43" + (i < 16 ? "0" : "") + i.toString(16),
291
+ name: "x_cadso_work_goal",
292
+ });
293
+ }
294
+ expect(Object.keys(buildMap(rows).records)).toHaveLength(25);
295
+ });
296
+ });
297
+ /**
298
+ * LETTER-CASE TWINS. "Search default" and "Search Default" are two keys in a
299
+ * map and one folder on macOS and Windows. Counting names without regard to
300
+ * letter case gives both the id suffix, so the tree is the same on every disk.
301
+ */
302
+ describe("DovetailUtilsMS.buildTableMap — names that differ only in letter case", () => {
303
+ it("suffixes both, so they are two folders on a case-insensitive disk", () => {
304
+ const out = buildMap([
305
+ { sys_id: "7daaf59947d56910fc4c1ae8036d43c0", name: "Search default" },
306
+ { sys_id: "fb55e60db195a5101b815df7b6dd8425", name: "Search Default" },
307
+ ]);
308
+ expect(Object.keys(out.records).sort()).toEqual([
309
+ "Search Default (fb55e60d)",
310
+ "Search default (7daaf599)",
311
+ ]);
312
+ });
313
+ it("counts a differently-cased name against its exact namesakes", () => {
314
+ const out = buildMap([
315
+ { sys_id: "497eb251c3591610d4ddf1db05013100", name: "Skip" },
316
+ { sys_id: "74d107d5c3591610d4ddf1db05013101", name: "Skip" },
317
+ { sys_id: "0a0b0c0dc3591610d4ddf1db05013102", name: "skip" },
318
+ ]);
319
+ expect(Object.keys(out.records).sort()).toEqual([
320
+ "Skip (497eb251)",
321
+ "Skip (74d107d5)",
322
+ "skip (0a0b0c0d)",
323
+ ]);
324
+ });
325
+ it("lengthens case twins that also share the first 8 id characters", () => {
326
+ const out = buildMap([
327
+ { sys_id: "abcdef0011111111111111111111111a", name: "Report" },
328
+ { sys_id: "abcdef0011111111111111111111111b", name: "REPORT" },
329
+ ]);
330
+ expect(Object.keys(out.records).sort()).toEqual([
331
+ "REPORT (abcdef0011111111111111111111111b)",
332
+ "Report (abcdef0011111111111111111111111a)",
333
+ ]);
334
+ });
335
+ it("leaves names that are unique ignoring case untouched", () => {
336
+ const out = buildMap([
337
+ { sys_id: "11111111c3591610d4ddf1db05013100", name: "Nav Header API Success" },
338
+ { sys_id: "22222222c3591610d4ddf1db05013100", name: "Nav Header API Failure" },
339
+ ]);
340
+ expect(Object.keys(out.records).sort()).toEqual([
341
+ "Nav Header API Failure",
342
+ "Nav Header API Success",
343
+ ]);
344
+ expect(out.warnings).toHaveLength(0);
345
+ });
346
+ });
347
+ describe("DovetailUtilsMS.processMissingFiles — twins keep their own content", () => {
348
+ it("returns both name twins, each with its own payload", () => {
349
+ const out = processMissing([
350
+ { sys_id: TWIN_A, name: "x_cadso_journey_fire_log", script: "// read" },
351
+ { sys_id: TWIN_B, name: "x_cadso_journey_fire_log", script: "// write" },
352
+ ]);
353
+ expect(Object.keys(out.records).sort()).toEqual([
354
+ "x_cadso_journey_fire_log (" + TWIN_A + ")",
355
+ "x_cadso_journey_fire_log (" + TWIN_B + ")",
356
+ ]);
357
+ expect(out.records["x_cadso_journey_fire_log (" + TWIN_A + ")"].files[0].content).toBe("// read");
358
+ expect(out.records["x_cadso_journey_fire_log (" + TWIN_B + ")"].files[0].content).toBe("// write");
359
+ });
360
+ it("returns both letter-case twins, each with its own payload", () => {
361
+ const out = processMissing([
362
+ { sys_id: "a77c5d71c3af025085b196c4e40131a4", name: "Attachment", script: "// upper" },
363
+ { sys_id: "67ac6651c34b421085b196c4e40131ea", name: "attachment", script: "// lower" },
364
+ ]);
365
+ expect(Object.keys(out.records).sort()).toEqual([
366
+ "Attachment (a77c5d71)",
367
+ "attachment (67ac6651)",
368
+ ]);
369
+ expect(out.records["Attachment (a77c5d71)"].files[0].content).toBe("// upper");
370
+ expect(out.records["attachment (67ac6651)"].files[0].content).toBe("// lower");
371
+ });
372
+ });