@tenonhq/dovetail-core 0.0.133 → 0.0.135

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/FileUtils.js CHANGED
@@ -45,6 +45,7 @@ const path_1 = __importDefault(require("path"));
45
45
  const ConfigManager = __importStar(require("./config"));
46
46
  const FileLogger_1 = require("./FileLogger");
47
47
  const fingerprint_1 = require("./fingerprint");
48
+ const layoutElements_1 = require("./layoutElements");
48
49
  const SNFileExists = (parentDirPath) => async (file) => {
49
50
  try {
50
51
  const files = await fs_1.promises.readdir(parentDirPath);
@@ -211,6 +212,12 @@ const getFileContextWithSkipReason = (filePath) => {
211
212
  if ((0, fingerprint_1.isFingerprintFilePath)(filePath)) {
212
213
  return { skipReason: "fingerprint only, read-only" };
213
214
  }
215
+ // A layout elements file (columns.txt, fields.txt, sections.txt) is read from
216
+ // a layout's child rows (layoutElements.ts); it is not a field of the layout,
217
+ // so it is never pushed, whatever the manifest says.
218
+ if ((0, layoutElements_1.isLayoutElementsFilePath)(filePath)) {
219
+ return { skipReason: "layout elements, read-only" };
220
+ }
214
221
  const ext = getFileExtension(filePath);
215
222
  const [tableName, recordName] = path_1.default
216
223
  .dirname(filePath)
@@ -247,6 +254,13 @@ const getFileContextWithSkipReason = (filePath) => {
247
254
  if (!field) {
248
255
  return { skipReason: "not in manifest" };
249
256
  }
257
+ // The field is mirrored as a fingerprint, so no file on disk holds its
258
+ // content: a `script.js` beside a fingerprinted `script` is stale (left
259
+ // from before `fingerprint` was set; refresh never deletes) and pushing
260
+ // it would write an old bundle over the live one.
261
+ if (field.type === fingerprint_1.FINGERPRINT_FILE_TYPE) {
262
+ return { skipReason: "fingerprinted field, read-only" };
263
+ }
250
264
  return {
251
265
  context: {
252
266
  filePath,
@@ -50,6 +50,7 @@ const commands_1 = require("./commands");
50
50
  const ConfigManager = __importStar(require("./config"));
51
51
  const AppUtils = __importStar(require("./appUtils"));
52
52
  const projectFiles_1 = require("./projectFiles");
53
+ const recordFolder_1 = require("./recordFolder");
53
54
  /**
54
55
  * Table whose rows must NOT go through the generic record insert. A plain
55
56
  * insert lets ServiceNow default `application` to the API session's current
@@ -560,9 +561,24 @@ async function createRecordCommand(args) {
560
561
  // getSourcePathForScope(scope), which a scope config can override. Using
561
562
  // the top-level getSourcePath() here would print a wrong path in
562
563
  // multi-scope setups even though the files landed correctly.
564
+ //
565
+ // The folder is the record's key in the manifest the sync just wrote,
566
+ // found by sys_id, not its display name: a namesake or letter-case
567
+ // twin gets a suffixed folder (folderNaming.ts), and the bare name
568
+ // would point at the other record's folder.
563
569
  var sourcePath = ConfigManager.getSourcePathForScope(scope);
564
- var localPath = path_1.default.join(sourcePath, table, recordName);
565
- Logger_1.logger.success(chalk_1.default.green("Local files created at: ") + localPath);
570
+ var syncedManifest = await ConfigManager.loadScopeManifest(scope);
571
+ var folders = (0, recordFolder_1.recordFoldersBySysId)(syncedManifest, table, newSysId);
572
+ var localPath = folders.length === 1 ? (0, recordFolder_1.recordDirFor)(sourcePath, table, folders[0]) : undefined;
573
+ if (localPath !== undefined) {
574
+ Logger_1.logger.success(chalk_1.default.green("Local files created at: ") + localPath);
575
+ }
576
+ else {
577
+ // syncManifest has already warned when the record is not in the
578
+ // refreshed manifest; never print a path the files may not be at.
579
+ FileLogger_1.fileLogger.debug("Created record " + newSysId + " has " + folders.length +
580
+ " folder(s) in the " + scope + " manifest for " + table + "; no local path printed");
581
+ }
566
582
  }
567
583
  }
568
584
  catch (syncErr) {
@@ -47,6 +47,7 @@ const FileLogger_1 = require("./FileLogger");
47
47
  const commands_1 = require("./commands");
48
48
  const ConfigManager = __importStar(require("./config"));
49
49
  const FileUtils = __importStar(require("./FileUtils"));
50
+ const recordFolder_1 = require("./recordFolder");
50
51
  /**
51
52
  * Resolves the target scope from args, manifest, or user prompt.
52
53
  */
@@ -226,28 +227,52 @@ async function deleteRecordCommand(args) {
226
227
  if (!typedArgs.keepLocal) {
227
228
  Logger_1.logger.info("Cleaning up local files...");
228
229
  try {
229
- // Remove local record directory. The scope's own folder, not the
230
- // top-level sourceDirectory: records live at <scope dir>/<table>/<name>
231
- // (src/Core/..., src/UIComponents/<scope>/...), so joining the top-level
232
- // path never found them and the cleanup was a silent no-op.
233
- var sourcePath = ConfigManager.getSourcePathForScope(scope);
234
- var recordDir = path_1.default.join(sourcePath, table, name || recordName);
235
- if (fs_1.default.existsSync(recordDir)) {
236
- fs_1.default.rmSync(recordDir, { recursive: true, force: true });
237
- Logger_1.logger.success(chalk_1.default.green("Removed: ") + recordDir);
230
+ // The record's folder is its manifest key, found by sys_id: the
231
+ // manifest is the naming authority (folderNaming.ts). A folder built
232
+ // from the instance's display name is wrong for every record the
233
+ // naming rule renamed, and is ANOTHER record's folder when a local
234
+ // namesake exists and this one was never refreshed.
235
+ var manifest = await ConfigManager.loadScopeManifest(scope);
236
+ var folderSource = manifest;
237
+ if (!folderSource) {
238
+ // A project without per-scope manifests keeps one dove.manifest.json.
239
+ var loadedManifest = ConfigManager.getManifest(true);
240
+ folderSource = loadedManifest
241
+ ? ConfigManager.resolveManifestForScope(loadedManifest, scope)
242
+ : undefined;
238
243
  }
239
- else {
240
- FileLogger_1.fileLogger.debug("Local directory not found: " + recordDir);
244
+ var folders = (0, recordFolder_1.recordFoldersBySysId)(folderSource, table, sysId);
245
+ if (folders.length === 0) {
246
+ Logger_1.logger.warn("Record " + sysId + " is not in the " + scope + " manifest for " + table +
247
+ ", so no local folder was removed. Remove its folder by hand if it has one.");
241
248
  }
242
- // Update manifest
243
- var manifest = await ConfigManager.loadScopeManifest(scope);
244
- if (manifest &&
245
- manifest.tables &&
246
- manifest.tables[table] &&
247
- manifest.tables[table].records) {
248
- var recordKey = name || recordName;
249
- if (manifest.tables[table].records[recordKey]) {
250
- delete manifest.tables[table].records[recordKey];
249
+ else if (folders.length > 1) {
250
+ Logger_1.logger.warn("Record " + sysId + " is listed more than once in the " + scope + " manifest for " + table +
251
+ " (" + folders.join(", ") + "), so no local folder was removed. Run 'npx dove refresh' and check the folders by hand.");
252
+ }
253
+ else {
254
+ var folder = folders[0];
255
+ // Records live at <scope dir>/<table>/<folder> (src/Core/...,
256
+ // src/UIComponents/<scope>/...), not under the top-level
257
+ // sourceDirectory. recordDirFor refuses anything that is not a direct
258
+ // child of <scope dir>/<table>, so a folder or table such as ".."
259
+ // can never point the recursive delete at the scope folder.
260
+ var sourcePath = ConfigManager.getSourcePathForScope(scope);
261
+ var recordDir = (0, recordFolder_1.recordDirFor)(sourcePath, table, folder);
262
+ if (recordDir === undefined) {
263
+ Logger_1.logger.warn("Not removing '" + folder + "': it is not a record folder under " +
264
+ path_1.default.join(sourcePath, table) + ".");
265
+ }
266
+ else if (fs_1.default.existsSync(recordDir)) {
267
+ fs_1.default.rmSync(recordDir, { recursive: true, force: true });
268
+ Logger_1.logger.success(chalk_1.default.green("Removed: ") + recordDir);
269
+ }
270
+ else {
271
+ FileLogger_1.fileLogger.debug("Local directory not found: " + recordDir);
272
+ }
273
+ // Update the scope manifest: drop the entry this sys_id owns, and no other.
274
+ if (manifest && manifest.tables && manifest.tables[table] && manifest.tables[table].records) {
275
+ delete manifest.tables[table].records[folder];
251
276
  // Remove table entry if no records remain
252
277
  if (Object.keys(manifest.tables[table].records).length === 0) {
253
278
  delete manifest.tables[table];
@@ -18,7 +18,8 @@
18
18
  // - the field file's content becomes "sha256:<hex>\nbytes:<n>\n";
19
19
  // - the field's value in metaData.json becomes "sha256:<hex>".
20
20
  // Push refuses a `.sha256` file (FileUtils.getFileContextWithSkipReason), so a
21
- // digest can never be written back over a bundle.
21
+ // digest can never be written back over a bundle, and any other file of a
22
+ // fingerprinted field (a stale `script.js` from before the option was set).
22
23
  //
23
24
  // Client-side only: `fingerprint` is stripped from tableOptions before they are
24
25
  // sent to the instance. The server echoes the requested file type back, so a
@@ -28,7 +29,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
28
29
  return (mod && mod.__esModule) ? mod : { "default": mod };
29
30
  };
30
31
  Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.isFingerprintFilePath = exports.applyFingerprints = exports.stripClientOnlyTableOptions = exports.fingerprintFieldsFor = exports.isFingerprintContent = exports.formatFingerprint = exports.FINGERPRINT_FILE_TYPE = void 0;
32
+ exports.isFingerprintFilePath = exports.applyFingerprints = exports.stripClientOnlyTableOptions = exports.checkFingerprintOptions = exports.fingerprintFieldsFor = exports.isFingerprintContent = exports.formatFingerprint = exports.FINGERPRINT_FILE_TYPE = void 0;
32
33
  const crypto_1 = __importDefault(require("crypto"));
33
34
  exports.FINGERPRINT_FILE_TYPE = "sha256";
34
35
  const DIGEST_PREFIX = "sha256:";
@@ -45,6 +46,7 @@ exports.isFingerprintContent = isFingerprintContent;
45
46
  // Fields configured for fingerprinting on one table. Anything malformed in the
46
47
  // config (not an array, non-string or empty entries) is dropped rather than
47
48
  // trusted, so a typo fingerprints nothing instead of throwing mid-refresh.
49
+ // checkFingerprintOptions reports what was dropped.
48
50
  const fingerprintFieldsFor = (tableOptions, tableName) => {
49
51
  if (!isPlainObject(tableOptions))
50
52
  return [];
@@ -64,9 +66,45 @@ const fingerprintFieldsFor = (tableOptions, tableName) => {
64
66
  return fields;
65
67
  };
66
68
  exports.fingerprintFieldsFor = fingerprintFieldsFor;
67
- // A copy of tableOptions without the client-only `fingerprint` key, for the
68
- // request body. The input is never mutated: the caller keeps using it to apply
69
- // the fingerprints to the response.
69
+ // An entry fingerprintFieldsFor would use as is. One with surrounding spaces is
70
+ // kept there but can never equal a field name, so it is reported here too.
71
+ const isFieldName = (f) => typeof f === "string" && f.trim() !== "" && f.trim() === f;
72
+ /**
73
+ * Reports through `warn` every `fingerprint` option that does not fingerprint
74
+ * what it names: a value that is not an array (`fingerprint: "script"`), or
75
+ * entries that are not field names. Without this the option is dropped
76
+ * silently and the next refresh writes, and a commit carries, the full bundle:
77
+ * the outcome the option exists to prevent. Matches layoutElementTablesFor's
78
+ * warning. An empty array, like an absent option, means off and is not reported.
79
+ */
80
+ const checkFingerprintOptions = (tableOptions, warn) => {
81
+ if (!isPlainObject(tableOptions))
82
+ return;
83
+ const tables = Object.keys(tableOptions).sort();
84
+ for (let i = 0; i < tables.length; i++) {
85
+ const opts = tableOptions[tables[i]];
86
+ if (!isPlainObject(opts) || !("fingerprint" in opts) || opts.fingerprint === undefined)
87
+ continue;
88
+ const raw = opts.fingerprint;
89
+ if (!Array.isArray(raw)) {
90
+ warn("tableOptions." + tables[i] + ".fingerprint is ignored: it must be an array of field names, e.g. [\"script\"]");
91
+ continue;
92
+ }
93
+ const bad = [];
94
+ for (let j = 0; j < raw.length; j++) {
95
+ if (!isFieldName(raw[j]))
96
+ bad.push(String(JSON.stringify(raw[j])));
97
+ }
98
+ if (bad.length > 0) {
99
+ warn("tableOptions." + tables[i] + ".fingerprint ignores " + bad.join(", ") +
100
+ ": each entry must be a field name, e.g. \"script\"");
101
+ }
102
+ }
103
+ };
104
+ exports.checkFingerprintOptions = checkFingerprintOptions;
105
+ // A copy of tableOptions without the client-only keys (`fingerprint`, and
106
+ // `layoutElements` from layoutElements.ts), for the request body. The input is
107
+ // never mutated: the caller keeps using it to apply them to the response.
70
108
  const stripClientOnlyTableOptions = (tableOptions) => {
71
109
  const out = {};
72
110
  if (!isPlainObject(tableOptions))
@@ -79,6 +117,7 @@ const stripClientOnlyTableOptions = (tableOptions) => {
79
117
  continue;
80
118
  const copy = Object.assign({}, opts);
81
119
  delete copy.fingerprint;
120
+ delete copy.layoutElements;
82
121
  out[tables[i]] = copy;
83
122
  }
84
123
  return out;
@@ -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()) {