@tenonhq/dovetail-core 0.0.131 → 0.0.133

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.
@@ -545,13 +545,25 @@ async function createRecordCommand(args) {
545
545
  if (syncResult && syncResult.failedScopes && syncResult.failedScopes.length > 0) {
546
546
  throw new Error(syncResult.failedScopes[0].error);
547
547
  }
548
- // Resolve the scope's own source directory — syncManifest writes into
549
- // getSourcePathForScope(scope), which a scope config can override. Using
550
- // the top-level getSourcePath() here would print a wrong path in
551
- // multi-scope setups even though the files landed correctly.
552
- var sourcePath = ConfigManager.getSourcePathForScope(scope);
553
- var localPath = path_1.default.join(sourcePath, table, recordName);
554
- Logger_1.logger.success(chalk_1.default.green("Local files created at: ") + localPath);
548
+ // A record the refresh reached but could not put into the repository
549
+ // (a folder git ignores, a path that could not be written) is not a
550
+ // failed sync, and not a success either: say which and why.
551
+ var unwritten = (syncResult && Array.isArray(syncResult.notWritten)) ? syncResult.notWritten : [];
552
+ if (unwritten.length > 0) {
553
+ for (var u = 0; u < unwritten.length; u++) {
554
+ Logger_1.logger.warn("Record created on instance, but not written to the repository: " +
555
+ unwritten[u].path + ": " + unwritten[u].reason);
556
+ }
557
+ }
558
+ else {
559
+ // Resolve the scope's own source directory — syncManifest writes into
560
+ // getSourcePathForScope(scope), which a scope config can override. Using
561
+ // the top-level getSourcePath() here would print a wrong path in
562
+ // multi-scope setups even though the files landed correctly.
563
+ 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);
566
+ }
555
567
  }
556
568
  catch (syncErr) {
557
569
  Logger_1.logger.warn("Record created on instance but local sync failed.");
@@ -226,8 +226,11 @@ async function deleteRecordCommand(args) {
226
226
  if (!typedArgs.keepLocal) {
227
227
  Logger_1.logger.info("Cleaning up local files...");
228
228
  try {
229
- // Remove local record directory
230
- var sourcePath = ConfigManager.getSourcePath();
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);
231
234
  var recordDir = path_1.default.join(sourcePath, table, name || recordName);
232
235
  if (fs_1.default.existsSync(recordDir)) {
233
236
  fs_1.default.rmSync(recordDir, { recursive: true, force: true });
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ // Fingerprint mode: mirror a field as a SHA-256 digest instead of its content.
3
+ //
4
+ // Built for compiled UI component bundles (sys_ux_lib_source_script.script):
5
+ // minified JS, often several MB, that no reviewer reads line by line. What a
6
+ // mirror needs from it is "is the bundle on this instance the same as on that
7
+ // one", and a digest answers that without MB-sized diffs.
8
+ //
9
+ // Configured per table in dove.config.js:
10
+ //
11
+ // tableOptions: { sys_ux_lib_source_script: { fingerprint: ["script"] } }
12
+ //
13
+ // Applied to every getManifest and bulkDownload response in snClient, so each
14
+ // writer (download, refresh, missing-file fill, single-record pull) and every
15
+ // manifest consumer sees the same thing without knowing about it:
16
+ // - the manifest lists the field as `<field>.sha256`, so the missing-file
17
+ // check finds it on disk and the next refresh does not re-download it;
18
+ // - the field file's content becomes "sha256:<hex>\nbytes:<n>\n";
19
+ // - the field's value in metaData.json becomes "sha256:<hex>".
20
+ // Push refuses a `.sha256` file (FileUtils.getFileContextWithSkipReason), so a
21
+ // digest can never be written back over a bundle.
22
+ //
23
+ // Client-side only: `fingerprint` is stripped from tableOptions before they are
24
+ // sent to the instance. The server echoes the requested file type back, so a
25
+ // bulkDownload asked for `script` as type "sha256" still returns the raw
26
+ // content, which is hashed here.
27
+ var __importDefault = (this && this.__importDefault) || function (mod) {
28
+ return (mod && mod.__esModule) ? mod : { "default": mod };
29
+ };
30
+ 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
+ const crypto_1 = __importDefault(require("crypto"));
33
+ exports.FINGERPRINT_FILE_TYPE = "sha256";
34
+ const DIGEST_PREFIX = "sha256:";
35
+ const FINGERPRINT_CONTENT_RE = /^sha256:[0-9a-f]{64}\nbytes:\d+\n$/;
36
+ const METADATA_DIGEST_RE = /^sha256:[0-9a-f]{64}$/;
37
+ const isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
38
+ const digestOf = (content) => DIGEST_PREFIX + crypto_1.default.createHash("sha256").update(content, "utf8").digest("hex");
39
+ // The on-disk content of a fingerprint file. The byte length rides along so a
40
+ // diff between two instances reads as "bundle grew by N bytes", not just "changed".
41
+ const formatFingerprint = (content) => digestOf(content) + "\nbytes:" + Buffer.byteLength(content, "utf8") + "\n";
42
+ exports.formatFingerprint = formatFingerprint;
43
+ const isFingerprintContent = (content) => typeof content === "string" && FINGERPRINT_CONTENT_RE.test(content);
44
+ exports.isFingerprintContent = isFingerprintContent;
45
+ // Fields configured for fingerprinting on one table. Anything malformed in the
46
+ // config (not an array, non-string or empty entries) is dropped rather than
47
+ // trusted, so a typo fingerprints nothing instead of throwing mid-refresh.
48
+ const fingerprintFieldsFor = (tableOptions, tableName) => {
49
+ if (!isPlainObject(tableOptions))
50
+ return [];
51
+ const opts = tableOptions[tableName];
52
+ if (!isPlainObject(opts))
53
+ return [];
54
+ const raw = opts.fingerprint;
55
+ if (!Array.isArray(raw))
56
+ return [];
57
+ const fields = [];
58
+ for (let i = 0; i < raw.length; i++) {
59
+ const f = raw[i];
60
+ if (typeof f === "string" && f.trim() !== "" && fields.indexOf(f) === -1) {
61
+ fields.push(f);
62
+ }
63
+ }
64
+ return fields;
65
+ };
66
+ 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.
70
+ const stripClientOnlyTableOptions = (tableOptions) => {
71
+ const out = {};
72
+ if (!isPlainObject(tableOptions))
73
+ return out;
74
+ const tables = Object.keys(tableOptions);
75
+ for (let i = 0; i < tables.length; i++) {
76
+ const opts = tableOptions[tables[i]];
77
+ // A non-object entry is not a valid table option; never forward it.
78
+ if (!isPlainObject(opts))
79
+ continue;
80
+ const copy = Object.assign({}, opts);
81
+ delete copy.fingerprint;
82
+ out[tables[i]] = copy;
83
+ }
84
+ return out;
85
+ };
86
+ exports.stripClientOnlyTableOptions = stripClientOnlyTableOptions;
87
+ // Replace each fingerprinted field's value in a metaData.json body with its
88
+ // digest. Leaves the content untouched when it is not a JSON object, or when a
89
+ // field is absent or not a { value: string } pair.
90
+ const fingerprintMetadataContent = (content, fields) => {
91
+ let metadata;
92
+ try {
93
+ metadata = JSON.parse(content);
94
+ }
95
+ catch (e) {
96
+ return content;
97
+ }
98
+ if (!isPlainObject(metadata))
99
+ return content;
100
+ let changed = false;
101
+ for (let i = 0; i < fields.length; i++) {
102
+ const pair = metadata[fields[i]];
103
+ if (!isPlainObject(pair))
104
+ continue;
105
+ const value = pair.value;
106
+ if (typeof value === "string" && !METADATA_DIGEST_RE.test(value)) {
107
+ pair.value = digestOf(value);
108
+ changed = true;
109
+ }
110
+ if ("display_value" in pair) {
111
+ // display_value repeats the content (or a rendering of it); keeping it
112
+ // would put the bundle straight back into the mirror.
113
+ delete pair.display_value;
114
+ changed = true;
115
+ }
116
+ }
117
+ return changed ? JSON.stringify(metadata, null, 2) : content;
118
+ };
119
+ const fingerprintFile = (file, fields) => {
120
+ if (!isPlainObject(file) || typeof file.name !== "string")
121
+ return;
122
+ if (file.name === "metaData" && file.type === "json") {
123
+ if (typeof file.content === "string" && file.content !== "") {
124
+ file.content = fingerprintMetadataContent(file.content, fields);
125
+ }
126
+ return;
127
+ }
128
+ if (fields.indexOf(file.name) === -1)
129
+ return;
130
+ file.type = exports.FINGERPRINT_FILE_TYPE;
131
+ // Absent content = a structure-only manifest entry; only the type changes.
132
+ // Already-fingerprinted content is left alone so applying twice is a no-op.
133
+ if (typeof file.content === "string" && !(0, exports.isFingerprintContent)(file.content)) {
134
+ file.content = (0, exports.formatFingerprint)(file.content);
135
+ }
136
+ };
137
+ // Apply fingerprinting in place to a table map from getManifest (`.tables`) or
138
+ // bulkDownload (the whole result). Returns the same object for chaining.
139
+ // Idempotent, and a no-op for any table without fingerprint config.
140
+ const applyFingerprints = (tables, tableOptions) => {
141
+ if (!isPlainObject(tables))
142
+ return tables;
143
+ const tableNames = Object.keys(tables);
144
+ for (let t = 0; t < tableNames.length; t++) {
145
+ const fields = (0, exports.fingerprintFieldsFor)(tableOptions, tableNames[t]);
146
+ if (fields.length === 0)
147
+ continue;
148
+ const table = tables[tableNames[t]];
149
+ if (!isPlainObject(table) || !isPlainObject(table.records))
150
+ continue;
151
+ const records = table.records;
152
+ const recKeys = Object.keys(records);
153
+ for (let r = 0; r < recKeys.length; r++) {
154
+ const rec = records[recKeys[r]];
155
+ if (!isPlainObject(rec) || !Array.isArray(rec.files))
156
+ continue;
157
+ const files = rec.files;
158
+ for (let f = 0; f < files.length; f++) {
159
+ fingerprintFile(files[f], fields);
160
+ }
161
+ }
162
+ }
163
+ return tables;
164
+ };
165
+ exports.applyFingerprints = applyFingerprints;
166
+ // True for a `<field>.sha256` path. Push uses it to refuse a digest outright,
167
+ // before any manifest lookup, so a fingerprint can never overwrite a bundle.
168
+ const isFingerprintFilePath = (filePath) => typeof filePath === "string" && filePath.slice(-(exports.FINGERPRINT_FILE_TYPE.length + 1)) === "." + exports.FINGERPRINT_FILE_TYPE;
169
+ exports.isFingerprintFilePath = isFingerprintFilePath;
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ /**
3
+ * Record folder naming: the one place a record's on-disk folder name is decided.
4
+ *
5
+ * The rule, for the records of ONE table in ONE application:
6
+ *
7
+ * 1. A record is named after its display name.
8
+ * 2. When another record's name is the same ignoring letter case and Unicode
9
+ * normalization form, every record of that group gets
10
+ * ` (first 8 characters of its sys_id)` added.
11
+ * 3. When two records of a group also share those 8 characters, each of them
12
+ * gets ` (its full sys_id)` instead. Only the records that collide are
13
+ * lengthened; their other namesakes keep 8 characters.
14
+ * 4. A name no disk can hold (see isSafeFolderName) falls back to the sys_id.
15
+ *
16
+ * Why case and normalization count: macOS and Windows compare folder names
17
+ * without regard to letter case (macOS also without regard to normalization
18
+ * form), Linux compares bytes. Deciding collisions with the strictest of the
19
+ * three gives the same tree on all of them.
20
+ *
21
+ * Why step 3 jumps straight to the full id rather than growing a few characters
22
+ * at a time: sys_ids generated in one transaction (the access controls of a new
23
+ * table) are identical in all but their last two or three characters, so a
24
+ * stepwise suffix ends at 30+ characters anyway, and its length would depend on
25
+ * which other ids happen to exist. Add a third twin later and the first two
26
+ * would be renamed again. The full id is the only length that is unique by
27
+ * construction, so a record's name depends on one yes-or-no fact (does a
28
+ * namesake share my first 8 characters) and never on how much of the id that
29
+ * namesake happens to share.
30
+ *
31
+ * Why every colliding record is renamed and none keeps the short name: the
32
+ * record that kept `Name (first 8)` would hand that folder to its twin the day
33
+ * it is deleted, and a push from that folder would then write the wrong record.
34
+ *
35
+ * The instance names records by steps 1 to 3 as well (DovetailUtilsMS). This
36
+ * module recomputes the name from the display name instead of trusting what
37
+ * arrived, so the tree is the same whichever version of the instance-side code
38
+ * answered: it strips the id suffix the instance added (baseRecordName) and
39
+ * applies the whole rule again. Naming is therefore idempotent.
40
+ *
41
+ * One exception: a table whose name the project configured to carry the record's
42
+ * own id (tableOptions differentiatorField: "sys_id", or a nameTemplate). There
43
+ * a trailing ` (sys_id)` is the name that was asked for, not a suffix to strip,
44
+ * so those tables are named from the names as they arrive (`configuredNames`).
45
+ * Every record still gets its own folder; only the recomputation is skipped.
46
+ */
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.assignFolderNames = exports.baseRecordName = exports.foldFolderName = exports.isSafeFolderName = exports.ID_SUFFIX_LENGTH = exports.FolderNameCollisionError = void 0;
49
+ /** Two records would share one folder and nothing tells them apart. */
50
+ class FolderNameCollisionError extends Error {
51
+ folder;
52
+ records;
53
+ constructor(folder, records) {
54
+ super("Cannot give these " + records.length + " records their own folder: they all resolve to '" +
55
+ folder + "' and no sys_id tells them apart (" +
56
+ records
57
+ .map(function (r) {
58
+ return "'" + r.name + "' sys_id " + (r.sys_id === "" ? "<none>" : r.sys_id);
59
+ })
60
+ .join(", ") +
61
+ "). Refusing to write one and drop the rest.");
62
+ this.name = "FolderNameCollisionError";
63
+ this.folder = folder;
64
+ this.records = records;
65
+ Object.setPrototypeOf(this, FolderNameCollisionError.prototype);
66
+ }
67
+ }
68
+ exports.FolderNameCollisionError = FolderNameCollisionError;
69
+ /** Characters of the sys_id in the suffix namesakes get. */
70
+ exports.ID_SUFFIX_LENGTH = 8;
71
+ /**
72
+ * Whether every supported disk can hold `name` as a folder. Windows forbids
73
+ * `< > : " | ? * \ /` in a path component, and a trailing space or dot.
74
+ */
75
+ const isSafeFolderName = (name) => {
76
+ return !(/[<>:"|?*\\/]/.test(name) || /[ .]$/.test(name) || name === "");
77
+ };
78
+ exports.isSafeFolderName = isSafeFolderName;
79
+ /**
80
+ * The form of a name under which two names are one folder on some disk: equal
81
+ * results mean a case-insensitive or normalization-insensitive disk cannot hold
82
+ * both. Upper then lower case approximates full Unicode case folding (ß and SS,
83
+ * long s and s); folding too much only adds a suffix, folding too little loses
84
+ * a record, so this errs towards more.
85
+ */
86
+ const foldFolderName = (name) => {
87
+ return String(name).normalize("NFC").toUpperCase().toLowerCase().normalize("NFC");
88
+ };
89
+ exports.foldFolderName = foldFolderName;
90
+ const idSuffix = (sysId, length) => {
91
+ return " (" + sysId.substring(0, length) + ")";
92
+ };
93
+ /**
94
+ * The display name a record's name was built from: `name` without the id
95
+ * suffix naming added. A suffix is a trailing ` (X)` where X is at least
96
+ * ID_SUFFIX_LENGTH characters long and is the start of the record's OWN sys_id,
97
+ * so parentheses in a display name, and another record's id, are left alone.
98
+ */
99
+ const baseRecordName = (name, sysId) => {
100
+ if (typeof name !== "string" || typeof sysId !== "string")
101
+ return typeof name === "string" ? name : "";
102
+ if (sysId === "" || name.charAt(name.length - 1) !== ")")
103
+ return name;
104
+ var open = name.lastIndexOf(" (");
105
+ if (open === -1)
106
+ return name;
107
+ var inner = name.substring(open + 2, name.length - 1);
108
+ if (inner.length < exports.ID_SUFFIX_LENGTH || sysId.indexOf(inner) !== 0)
109
+ return name;
110
+ return name.substring(0, open);
111
+ };
112
+ exports.baseRecordName = baseRecordName;
113
+ const groupBy = (items, keyOf) => {
114
+ var groups = new Map();
115
+ for (var i = 0; i < items.length; i++) {
116
+ var key = keyOf(items[i]);
117
+ var group = groups.get(key);
118
+ if (group)
119
+ group.push(items[i]);
120
+ else
121
+ groups.set(key, [items[i]]);
122
+ }
123
+ return groups;
124
+ };
125
+ const distinctIdentities = (group) => {
126
+ // A Set, not a plain object: an id is data and may be named "constructor".
127
+ var seen = new Set();
128
+ for (var i = 0; i < group.length; i++) {
129
+ seen.add(group[i].identity);
130
+ }
131
+ return seen.size;
132
+ };
133
+ const safeOrId = (folder, sysId) => {
134
+ // A record with no sys_id has no fallback; its name stands and the final
135
+ // check below refuses it if that leaves two records in one folder.
136
+ return (0, exports.isSafeFolderName)(folder) || sysId === "" ? folder : sysId;
137
+ };
138
+ /**
139
+ * Folder names for the records of one table, in input order.
140
+ *
141
+ * The answer depends only on the set of records, never on their order. One
142
+ * sys_id listed twice is one record and gets one name. No two different
143
+ * records ever get the same folder, compared the way the strictest disk
144
+ * compares: if that cannot be achieved (records without a sys_id that share a
145
+ * name), this throws FolderNameCollisionError rather than return a name that
146
+ * would drop a record.
147
+ */
148
+ const assignFolderNames = (records, options = {}) => {
149
+ if (!Array.isArray(records)) {
150
+ throw new TypeError("assignFolderNames expects an array of records");
151
+ }
152
+ var configuredNames = !!(options && options.configuredNames);
153
+ var candidates = [];
154
+ for (var i = 0; i < records.length; i++) {
155
+ var record = records[i];
156
+ var isRecord = record !== null && typeof record === "object";
157
+ var sysId = isRecord && typeof record.sys_id === "string" ? record.sys_id : "";
158
+ var name = isRecord && typeof record.name === "string" ? record.name : "";
159
+ candidates.push({
160
+ index: i,
161
+ identity: sysId === "" ? "#" + i : sysId,
162
+ sysId: sysId,
163
+ name: name,
164
+ base: configuredNames ? name : (0, exports.baseRecordName)(name, sysId),
165
+ folder: "",
166
+ });
167
+ }
168
+ // Steps 1 and 2: the display name, plus 8 id characters for namesakes.
169
+ groupBy(candidates, function (c) { return (0, exports.foldFolderName)(c.base); }).forEach(function (group) {
170
+ var shared = distinctIdentities(group) > 1;
171
+ for (var g = 0; g < group.length; g++) {
172
+ var c = group[g];
173
+ c.folder = safeOrId(shared ? c.base + idSuffix(c.sysId, exports.ID_SUFFIX_LENGTH) : c.base, c.sysId);
174
+ }
175
+ });
176
+ // Step 3: records still in one folder get their full id.
177
+ groupBy(candidates, function (c) { return (0, exports.foldFolderName)(c.folder); }).forEach(function (group) {
178
+ if (distinctIdentities(group) < 2)
179
+ return;
180
+ for (var g = 0; g < group.length; g++) {
181
+ var c = group[g];
182
+ c.folder = safeOrId(c.base + idSuffix(c.sysId, c.sysId.length), c.sysId);
183
+ }
184
+ });
185
+ // Nothing may be dropped: every folder belongs to exactly one record.
186
+ groupBy(candidates, function (c) { return (0, exports.foldFolderName)(c.folder); }).forEach(function (group, folded) {
187
+ if (distinctIdentities(group) < 2)
188
+ return;
189
+ throw new FolderNameCollisionError(group[0].folder === "" ? folded : group[0].folder, group.map(function (c) { return { name: c.name, sys_id: c.sysId }; }));
190
+ });
191
+ return candidates.map(function (c) { return c.folder; });
192
+ };
193
+ exports.assignFolderNames = assignFolderNames;
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ /**
3
+ * Which of the files a refresh wrote will git refuse to see?
4
+ *
5
+ * A record folder whose name matches an ignore rule (a client script named
6
+ * `console.log` under a `*.log` rule) is written to disk and then never staged:
7
+ * the record is missing from the repository and nothing said so. This asks git
8
+ * itself, so every source of ignore rules counts (nested .gitignore files,
9
+ * .git/info/exclude, the user's global excludes file) and a file git already
10
+ * tracks is never reported, because an ignore rule does not hide it.
11
+ *
12
+ * It lives in core, next to the writer: the refresh is the only code that knows
13
+ * every path it just wrote, and core already runs git for `--diff`. A repository
14
+ * hook could not report it, since an ignored path never reaches a commit.
15
+ *
16
+ * git is run without a shell and the paths go in on stdin, NUL-separated, so no
17
+ * record name is ever interpolated into a command line.
18
+ */
19
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ var desc = Object.getOwnPropertyDescriptor(m, k);
22
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
23
+ desc = { enumerable: true, get: function() { return m[k]; } };
24
+ }
25
+ Object.defineProperty(o, k2, desc);
26
+ }) : (function(o, m, k, k2) {
27
+ if (k2 === undefined) k2 = k;
28
+ o[k2] = m[k];
29
+ }));
30
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
31
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
32
+ }) : function(o, v) {
33
+ o["default"] = v;
34
+ });
35
+ var __importStar = (this && this.__importStar) || (function () {
36
+ var ownKeys = function(o) {
37
+ ownKeys = Object.getOwnPropertyNames || function (o) {
38
+ var ar = [];
39
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
40
+ return ar;
41
+ };
42
+ return ownKeys(o);
43
+ };
44
+ return function (mod) {
45
+ if (mod && mod.__esModule) return mod;
46
+ var result = {};
47
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
48
+ __setModuleDefault(result, mod);
49
+ return result;
50
+ };
51
+ })();
52
+ var __importDefault = (this && this.__importDefault) || function (mod) {
53
+ return (mod && mod.__esModule) ? mod : { "default": mod };
54
+ };
55
+ Object.defineProperty(exports, "__esModule", { value: true });
56
+ exports.findGitIgnoredPaths = void 0;
57
+ const cp = __importStar(require("child_process"));
58
+ const path_1 = __importDefault(require("path"));
59
+ const runGit = (args, cwd, input) => {
60
+ return new Promise(function (resolve) {
61
+ var stdout = [];
62
+ var stderr = [];
63
+ var settled = false;
64
+ var finish = function (run) {
65
+ if (settled)
66
+ return;
67
+ settled = true;
68
+ resolve(run);
69
+ };
70
+ var child;
71
+ try {
72
+ // check-ignore reads each path literally (`[`, `*` and `:` in a folder
73
+ // name are not pattern syntax to it), so no pathspec switch is needed; it
74
+ // rejects GIT_LITERAL_PATHSPECS outright.
75
+ child = cp.spawn("git", args, { cwd: cwd, windowsHide: true });
76
+ }
77
+ catch (e) {
78
+ finish({ code: null, stdout: "", stderr: "", spawnError: e });
79
+ return;
80
+ }
81
+ child.stdout.on("data", function (chunk) { stdout.push(chunk); });
82
+ child.stderr.on("data", function (chunk) { stderr.push(chunk); });
83
+ child.on("error", function (err) {
84
+ finish({ code: null, stdout: "", stderr: "", spawnError: err });
85
+ });
86
+ child.on("close", function (code) {
87
+ finish({
88
+ code: code,
89
+ stdout: Buffer.concat(stdout).toString("utf8"),
90
+ stderr: Buffer.concat(stderr).toString("utf8"),
91
+ });
92
+ });
93
+ // git may exit before it has read everything (not a repository): a write
94
+ // to its closed stdin must not take the refresh down.
95
+ child.stdin.on("error", function () { });
96
+ child.stdin.end(input);
97
+ });
98
+ };
99
+ /**
100
+ * Asks git which of `filePaths` it ignores. `baseDir` is the directory the
101
+ * paths live under (the application's source folder); paths outside it are not
102
+ * asked about.
103
+ *
104
+ * Never throws: a refresh must not fail because git could not be asked.
105
+ */
106
+ const findGitIgnoredPaths = async (filePaths, baseDir) => {
107
+ if (!Array.isArray(filePaths) || typeof baseDir !== "string" || baseDir === "") {
108
+ return { ignored: [], checked: false };
109
+ }
110
+ // Relative to where git runs, with forward slashes: git then never has to
111
+ // reconcile a symlinked absolute prefix with its own idea of the work tree.
112
+ var relativeToAbsolute = new Map();
113
+ var relatives = [];
114
+ for (var i = 0; i < filePaths.length; i++) {
115
+ var absolute = filePaths[i];
116
+ if (typeof absolute !== "string" || absolute === "" || absolute.indexOf("\0") !== -1)
117
+ continue;
118
+ var relative = path_1.default.relative(baseDir, absolute);
119
+ if (relative === "" || relative.split(path_1.default.sep)[0] === ".." || path_1.default.isAbsolute(relative))
120
+ continue;
121
+ var forGit = relative.split(path_1.default.sep).join("/");
122
+ if (!relativeToAbsolute.has(forGit)) {
123
+ relativeToAbsolute.set(forGit, absolute);
124
+ relatives.push(forGit);
125
+ }
126
+ }
127
+ if (relatives.length === 0)
128
+ return { ignored: [], checked: true };
129
+ var run = await runGit(["check-ignore", "--verbose", "-z", "--stdin"], baseDir, relatives.join("\0") + "\0");
130
+ if (run.spawnError) {
131
+ // ENOENT: no git installed, or the source folder does not exist yet.
132
+ return { ignored: [], checked: false };
133
+ }
134
+ // 0: at least one path is ignored. 1: none is. Anything else is a failure.
135
+ if (run.code !== 0 && run.code !== 1) {
136
+ if (/not a git repository/i.test(run.stderr)) {
137
+ return { ignored: [], checked: false };
138
+ }
139
+ return {
140
+ ignored: [],
141
+ checked: false,
142
+ warning: "could not check git ignore rules under " + baseDir + ": " +
143
+ (run.stderr.trim().split(/\r?\n/)[0] || "git exited with code " + String(run.code)),
144
+ };
145
+ }
146
+ // --verbose -z prints <source> NUL <line> NUL <pattern> NUL <path> NUL per match.
147
+ var fields = run.stdout.split("\0");
148
+ var ignored = [];
149
+ for (var f = 0; f + 3 < fields.length; f += 4) {
150
+ var source = fields[f];
151
+ var line = fields[f + 1];
152
+ var pattern = fields[f + 2];
153
+ var reported = fields[f + 3];
154
+ // A match on a negated rule means the path is explicitly NOT ignored.
155
+ if (pattern === "" || pattern.charAt(0) === "!")
156
+ continue;
157
+ var asked = relativeToAbsolute.get(reported);
158
+ ignored.push({
159
+ path: asked !== undefined ? asked : path_1.default.join(baseDir, reported),
160
+ source: source,
161
+ line: line,
162
+ pattern: pattern,
163
+ });
164
+ }
165
+ return { ignored: ignored, checked: true };
166
+ };
167
+ exports.findGitIgnoredPaths = findGitIgnoredPaths;
@@ -72,6 +72,7 @@ const projectFiles_1 = require("./projectFiles");
72
72
  const recordSource_1 = require("./reconcile/recordSource");
73
73
  const recordDiff_1 = require("./reconcile/recordDiff");
74
74
  const fields_1 = require("./reconcile/fields");
75
+ const fingerprint_1 = require("./fingerprint");
75
76
  const baseline_1 = require("./reconcile/baseline");
76
77
  const report_1 = require("./reconcile/report");
77
78
  const applyPlan_1 = require("./reconcile/applyPlan");
@@ -321,6 +322,14 @@ async function buildCreateFields(scope, change) {
321
322
  }
322
323
  const name = entry.slice(0, dot);
323
324
  const type = entry.slice(dot + 1);
325
+ // A fingerprinted field lives in git as a digest only (fingerprint.ts), and
326
+ // its metaData value is the digest too, so the record cannot be rebuilt
327
+ // from the branch. Refuse the create rather than send a digest as content;
328
+ // such records ship from their own source (e.g. a UI component deploy).
329
+ if (type === fingerprint_1.FINGERPRINT_FILE_TYPE) {
330
+ throw new Error(change.table + "/" + change.name + ": field '" + name +
331
+ "' is mirrored as a fingerprint only, so the record cannot be created from the branch");
332
+ }
324
333
  if (!(0, fields_1.isComparableField)({ name, type })) {
325
334
  continue;
326
335
  }
package/dist/snClient.js CHANGED
@@ -17,6 +17,7 @@ const tough_cookie_1 = require("tough-cookie");
17
17
  const genericUtils_1 = require("./genericUtils");
18
18
  const Logger_1 = require("./Logger");
19
19
  const FileLogger_1 = require("./FileLogger");
20
+ const fingerprint_1 = require("./fingerprint");
20
21
  const authFailure_1 = require("./authFailure");
21
22
  // Benchmark sink. Null when --benchmark is off; zero overhead in that case.
22
23
  let _benchmarkSink = null;
@@ -609,7 +610,19 @@ const snClient = (baseURL, username, password, apiKey) => {
609
610
  const endpoint = `api/cadso/dovetail_sync/bulkDownload`;
610
611
  const tableCount = Object.keys(missingFiles).length;
611
612
  FileLogger_1.fileLogger.debug("Bulk downloading files for " + tableCount + " tables");
612
- return client.post(endpoint, { missingFiles, tableOptions });
613
+ // `fingerprint` is client-only: stripped from the request, applied to the
614
+ // response (see fingerprint.ts).
615
+ return client
616
+ .post(endpoint, {
617
+ missingFiles,
618
+ tableOptions: (0, fingerprint_1.stripClientOnlyTableOptions)(tableOptions),
619
+ })
620
+ .then(function (resp) {
621
+ if (resp && resp.data && resp.data.result) {
622
+ (0, fingerprint_1.applyFingerprints)(resp.data.result, tableOptions);
623
+ }
624
+ return resp;
625
+ });
613
626
  };
614
627
  const getManifest = (scope, config, withFiles = false) => {
615
628
  const endpoint = `api/cadso/dovetail_sync/getManifest/${scope}`;
@@ -618,12 +631,22 @@ const snClient = (baseURL, username, password, apiKey) => {
618
631
  var cleanIncludes = _stripUnderscoreKeys(includes);
619
632
  var cleanExcludes = _stripUnderscoreKeys(excludes);
620
633
  FileLogger_1.fileLogger.debug("Fetching manifest for scope " + scope + (withFiles ? " (with file contents)" : " (structure only)"));
621
- return client.post(endpoint, {
634
+ return client
635
+ .post(endpoint, {
622
636
  includes: cleanIncludes,
623
637
  excludes: cleanExcludes,
624
- tableOptions,
638
+ tableOptions: (0, fingerprint_1.stripClientOnlyTableOptions)(tableOptions),
625
639
  withFiles,
626
640
  getContents: withFiles, // ServiceNow expects getContents, not withFiles
641
+ })
642
+ .then(function (resp) {
643
+ // Fingerprinted fields come back as `<field>.sha256` entries (and with
644
+ // hashed content when withFiles is set), so the manifest, the
645
+ // missing-file check and every writer agree on the on-disk name.
646
+ if (resp && resp.data && resp.data.result && resp.data.result.tables) {
647
+ (0, fingerprint_1.applyFingerprints)(resp.data.result.tables, tableOptions);
648
+ }
649
+ return resp;
627
650
  });
628
651
  };
629
652
  const changeUpdateSet = (params) => {