@tenonhq/dovetail-core 0.0.130 → 0.0.132

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/README.md CHANGED
@@ -49,6 +49,44 @@ See [`UPDATE_SET_COMMANDS.md`](UPDATE_SET_COMMANDS.md) for the full update-set C
49
49
  - An in-progress set with the same name already in that scope is refused (exit 1) rather than duplicated.
50
50
  - The set is created, not activated — the success line prints its sys_id; use `npx dove switchUpdateSet --sysId <sys_id> -s <scope>` (or `npx dove createUpdateSet`, which creates and activates in one step).
51
51
 
52
+ ### Exit codes
53
+
54
+ | Code | Meaning |
55
+ | ---- | ------- |
56
+ | `0` | The command finished. |
57
+ | `1` | The command failed (any reason not listed below). |
58
+ | `77` | ServiceNow rejected the credentials or refused the request. A write got HTTP 401 or 403, or a failing command got HTTP 401 on a read. |
59
+
60
+ A write is any request that changes the instance, whichever command sends it: `push`,
61
+ `reconcile --apply` (create and delete), `create`, `delete`, `createUpdateSet`, the
62
+ update-set and scope switches that save a user preference, and so on. The check runs
63
+ on every request `dove` makes, so a new command is covered without extra wiring.
64
+
65
+ On a 401, or a 403 on a write, `dove` names the instance host, the request, and the
66
+ env file the credentials were loaded from. That message prints once per run, not once
67
+ per record. It never prints a credential. The next step depends on the status:
68
+
69
+ - **401**: the credentials were rejected. `dove` prints the command that
70
+ re-authenticates: `dove login`, or `dove login --env <name>` when the command ran
71
+ with `--env`.
72
+ - **403 on a write**: the sign-in worked and the instance refused the write for this
73
+ user. `dove` names the table when it can and says to check the role or ACL for it.
74
+ It does not suggest `dove login`, because signing in again as the same user changes
75
+ nothing.
76
+
77
+ Exit codes:
78
+
79
+ - A write that was turned away exits `77` even when the command itself reports
80
+ per-record results and would otherwise exit `0` (`push`) or `1` (`reconcile --apply`).
81
+ - A 401 on a read changes the exit code only when the command then fails: `1` becomes
82
+ `77`. A command that tolerated it and succeeded still exits `0`.
83
+ - A 403 on a read does not change the exit code, because it is usually one table's
84
+ ACL. The manifest and file downloads behind `refresh` count as reads.
85
+ - Every other exit code is unchanged.
86
+
87
+ Exit code `77` and the credential-failure message are in `@tenonhq/dovetail-core` 0.0.131
88
+ and later.
89
+
52
90
  ## Plugins
53
91
 
54
92
  Dovetail's build pipeline is plugin-driven. Each plugin is an npm package implementing `run(context, content, options) => Promise<PluginResults>`. Shipped plugins live in sibling packages (`@tenonhq/dovetail-typescript-plugin`, `-babel-plugin`, `-webpack-plugin`, `-sass-plugin`, `-eslint-plugin`, `-prettier-plugin`, `-babel-preset-servicenow`, `-babel-plugin-remove-modules`).
package/dist/FileUtils.js CHANGED
@@ -44,6 +44,7 @@ const fs_1 = __importStar(require("fs"));
44
44
  const path_1 = __importDefault(require("path"));
45
45
  const ConfigManager = __importStar(require("./config"));
46
46
  const FileLogger_1 = require("./FileLogger");
47
+ const fingerprint_1 = require("./fingerprint");
47
48
  const SNFileExists = (parentDirPath) => async (file) => {
48
49
  try {
49
50
  const files = await fs_1.promises.readdir(parentDirPath);
@@ -204,6 +205,12 @@ const getTargetFieldFromPath = (filePath, table, ext) => {
204
205
  : path_1.default.basename(filePath, ext);
205
206
  };
206
207
  const getFileContextWithSkipReason = (filePath) => {
208
+ // A `.sha256` file holds a digest, not the field's content (fingerprint.ts).
209
+ // Refuse it before any manifest lookup, so push and build can never send a
210
+ // digest over the real value.
211
+ if ((0, fingerprint_1.isFingerprintFilePath)(filePath)) {
212
+ return { skipReason: "fingerprint only, read-only" };
213
+ }
207
214
  const ext = getFileExtension(filePath);
208
215
  const [tableName, recordName] = path_1.default
209
216
  .dirname(filePath)
@@ -458,7 +458,7 @@ class MultiScopeWatcherManager {
458
458
  // Ensure an update set exists for this scope
459
459
  await this.ensureUpdateSetForScope(scopeWatcher.scope);
460
460
  // Load the manifest for this specific scope
461
- await this.loadScopeManifest(scopeWatcher.scope, scopeWatcher.sourceDirectory);
461
+ await this.loadScopeManifest(scopeWatcher.scope);
462
462
  // Process the files — track skip reasons for summary
463
463
  const fileContexts = [];
464
464
  const skippedFiles = [];
@@ -509,11 +509,13 @@ class MultiScopeWatcherManager {
509
509
  Logger_1.logger.error(`[${scopeWatcher.scope}] Error processing queue: ${error}`);
510
510
  }
511
511
  }
512
- async loadScopeManifest(scopeName, sourceDirectory) {
512
+ async loadScopeManifest(scopeName) {
513
513
  try {
514
- // The sourceDirectory is like /path/to/ServiceNow/src/x_cadso_core
515
- // We need to go up two levels to get to the ServiceNow directory where manifests are stored
516
- const projectRoot = path.dirname(path.dirname(sourceDirectory)); // Go up from src/scope to project root
514
+ // Manifests live at the project root (next to dove.config.js). Derive it
515
+ // from the config, not from sourceDirectory: going "up two levels" only
516
+ // holds for src/<scope> and lands in src/ for a nested folder such as
517
+ // src/UIComponents/<scope>.
518
+ const projectRoot = ConfigManager.getRootDir();
517
519
  const fs = await Promise.resolve().then(() => __importStar(require("fs")));
518
520
  // First try to load scope-specific manifest file (prefer dove.*, fall back to sinc.*).
519
521
  const doveScopeManifestPath = path.join(projectRoot, `dove.manifest.${scopeName}.json`);
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ /**
3
+ * What `dove` says and how it exits when ServiceNow rejects its credentials (#185).
4
+ *
5
+ * A 401 or 403 used to surface as a generic "verify your credentials" line and the
6
+ * same exit code as every other failure, so a script could not tell "the instance
7
+ * turned us away" from "a record failed to build". This module owns the two halves
8
+ * of the fix:
9
+ *
10
+ * 1. The MESSAGE — which instance, which env file the credentials came from, and
11
+ * the next step. For a 401: the exact command that re-authenticates
12
+ * (`dove login`, with `--env <name>` when one was used). For a 403 on a write:
13
+ * check the role or ACL for the table, since signing in again changes nothing.
14
+ * 2. The EXIT CODE — AUTH_EXIT_CODE, distinct from the generic 1.
15
+ *
16
+ * NEVER A CREDENTIAL. The message is built only from the instance host, the env
17
+ * file's PATH and the `--env` selector the user typed. Nothing is read out of the
18
+ * env file, and the host is reduced to a bare hostname first, so a value that
19
+ * carries userinfo (`user:pass@host`) cannot leak through it.
20
+ *
21
+ * No imports from the rest of core: snClient.ts must be able to use this without
22
+ * a circular dependency on config.ts. bootstrap.ts pushes the context in.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.AUTH_EXIT_CODE = void 0;
26
+ exports.setAuthContext = setAuthContext;
27
+ exports.resetAuthFailureState = resetAuthFailureState;
28
+ exports.isAuthStatus = isAuthStatus;
29
+ exports.requestPath = requestPath;
30
+ exports.classifyAuthRejection = classifyAuthRejection;
31
+ exports.firstRejectionOfKind = firstRejectionOfKind;
32
+ exports.instanceHost = instanceHost;
33
+ exports.reauthCommand = reauthCommand;
34
+ exports.buildAuthFailureMessage = buildAuthFailureMessage;
35
+ exports.recordAuthFailure = recordAuthFailure;
36
+ exports.resolveExitCode = resolveExitCode;
37
+ exports.installAuthExitCode = installAuthExitCode;
38
+ /**
39
+ * Exit code for "ServiceNow rejected the credentials" (HTTP 401 or 403).
40
+ * 77 is EX_NOPERM in sysexits.h — "permission denied". Every other failure keeps
41
+ * the exit code it had (1).
42
+ */
43
+ exports.AUTH_EXIT_CODE = 77;
44
+ var context = { envPath: "", envArg: "" };
45
+ /** A failed WRITE was rejected (forces the auth exit code, even over a clean exit). */
46
+ var writeRejected = false;
47
+ /** Any request was rejected (re-maps a generic failure exit to the auth exit code). */
48
+ var anyRejected = false;
49
+ /** Called once by bootstrap, after the env file is resolved. Values are paths/names only. */
50
+ function setAuthContext(next) {
51
+ var n = next || {};
52
+ context = {
53
+ envPath: typeof n.envPath === "string" ? n.envPath : "",
54
+ envArg: typeof n.envArg === "string" ? n.envArg : "",
55
+ };
56
+ }
57
+ /** Which rejection kinds already had their full message printed (see classifyAuthRejection). */
58
+ var announced = {};
59
+ /** Test seam: forget the context and every recorded failure. */
60
+ function resetAuthFailureState() {
61
+ context = { envPath: "", envArg: "" };
62
+ writeRejected = false;
63
+ anyRejected = false;
64
+ announced = {};
65
+ }
66
+ function isAuthStatus(status) {
67
+ return status === 401 || status === 403;
68
+ }
69
+ /**
70
+ * POST endpoints that only READ. Everything else that is not a GET changes the
71
+ * instance. A 403 on one of these is treated like a 403 on a GET.
72
+ */
73
+ var READ_ONLY_POST_ENDPOINTS = [
74
+ "api/cadso/dovetail_sync/getManifest",
75
+ "api/cadso/dovetail_sync/bulkDownload",
76
+ ];
77
+ /**
78
+ * The request path, safe to echo: no scheme, host, userinfo, query or fragment,
79
+ * and only ordinary path characters. Returns "" for anything else.
80
+ */
81
+ function requestPath(rawUrl) {
82
+ if (typeof rawUrl !== "string")
83
+ return "";
84
+ var path = rawUrl.trim().replace(/^[a-z][a-z0-9+.-]*:\/\/[^\/?#]*/i, "");
85
+ var cut = path.search(/[?#]/);
86
+ if (cut !== -1)
87
+ path = path.slice(0, cut);
88
+ path = path.replace(/^\/+/, "");
89
+ if (path.length === 0 || path.length > 200)
90
+ return "";
91
+ if (!/^[A-Za-z0-9._\/-]+$/.test(path))
92
+ return "";
93
+ return path;
94
+ }
95
+ function isReadOnlyPost(method, path) {
96
+ if (method !== "POST")
97
+ return false;
98
+ for (var i = 0; i < READ_ONLY_POST_ENDPOINTS.length; i += 1) {
99
+ var endpoint = READ_ONLY_POST_ENDPOINTS[i];
100
+ if (path === endpoint || path.indexOf(endpoint + "/") === 0)
101
+ return true;
102
+ }
103
+ return false;
104
+ }
105
+ /**
106
+ * Decide what a rejected HTTP request means for the exit code. Pure.
107
+ *
108
+ * - 401 on any request: the credentials were rejected
109
+ * - 403 on a write (any method but GET, bar the read-only POSTs above): the
110
+ * instance refused the change
111
+ * - 403 on a read: null. It is usually one table's ACL, and callers probe and
112
+ * fall back, so it changes nothing
113
+ * - any other status: null
114
+ *
115
+ * An unknown method counts as a read, so a malformed error can never force the
116
+ * auth exit code on its own.
117
+ */
118
+ function classifyAuthRejection(input) {
119
+ var i = input || { status: undefined, method: undefined };
120
+ if (!isAuthStatus(i.status))
121
+ return null;
122
+ var method = typeof i.method === "string" ? i.method.toUpperCase() : "";
123
+ var write = method !== "" && method !== "GET" && !isReadOnlyPost(method, requestPath(i.url));
124
+ if (i.status === 403 && !write)
125
+ return null;
126
+ return { status: i.status, write: write };
127
+ }
128
+ /**
129
+ * True the first time a rejection of this kind is seen in the process, so the full
130
+ * message prints once instead of once per record on a large push.
131
+ */
132
+ function firstRejectionOfKind(rejection) {
133
+ var kind = rejection.status + (rejection.write ? ":write" : ":read");
134
+ if (announced[kind] === true)
135
+ return false;
136
+ announced[kind] = true;
137
+ return true;
138
+ }
139
+ /**
140
+ * Reduce an SN_INSTANCE value to a bare hostname: no scheme, no userinfo, no path,
141
+ * no query. Returns "" for anything that is not a plain host, so the caller falls
142
+ * back to a neutral phrase instead of echoing an unexpected value.
143
+ */
144
+ function instanceHost(raw) {
145
+ if (typeof raw !== "string")
146
+ return "";
147
+ var host = raw.trim().replace(/^[a-z][a-z0-9+.-]*:\/\//i, "");
148
+ var at = host.lastIndexOf("@");
149
+ if (at !== -1)
150
+ host = host.slice(at + 1);
151
+ var cut = host.search(/[\/?#]/);
152
+ if (cut !== -1)
153
+ host = host.slice(0, cut);
154
+ if (!/^[A-Za-z0-9.-]+(:[0-9]{1,5})?$/.test(host))
155
+ return "";
156
+ return host;
157
+ }
158
+ /**
159
+ * The `--env` selector, when it is safe to echo into a suggested command: a bare
160
+ * name or a path made of ordinary filename characters. Anything else (spaces, shell
161
+ * metacharacters) yields "" and the suggestion uses a placeholder instead.
162
+ */
163
+ function echoableEnvArg(envArg) {
164
+ return /^[A-Za-z0-9._\/~-]+$/.test(envArg) ? envArg : "";
165
+ }
166
+ /** The command that re-authenticates this invocation's instance. */
167
+ function reauthCommand(envArg) {
168
+ var arg = typeof envArg === "string" ? envArg : context.envArg;
169
+ if (!arg)
170
+ return "dove login";
171
+ var safe = echoableEnvArg(arg);
172
+ return "dove login --env " + (safe ? safe : "<name>");
173
+ }
174
+ /** A table name safe to echo, or "". */
175
+ function echoableTable(table) {
176
+ return typeof table === "string" && /^[A-Za-z0-9_]{1,80}$/.test(table) ? table : "";
177
+ }
178
+ /**
179
+ * The actionable message for a 401/403. Pure: reads the module context and its
180
+ * arguments, nothing else. Contains no credential.
181
+ *
182
+ * The two statuses need different remedies. A 401 means the credentials were
183
+ * rejected, so the fix is to sign in again. A 403 means the sign-in worked and the
184
+ * instance refused the write for this user: signing in again as the same user
185
+ * changes nothing, so the message points at the role or ACL instead.
186
+ */
187
+ function buildAuthFailureMessage(input) {
188
+ var host = instanceHost(input.instance);
189
+ var where = host ? host : "the ServiceNow instance";
190
+ if (input.status === 401) {
191
+ var source = context.envPath
192
+ ? "the credentials loaded from " + context.envPath
193
+ : "the credentials in the loaded env file";
194
+ return ("Unauthorized (401) " + input.action + ". " +
195
+ where + " rejected " + source + " — the user, password or API key is wrong or expired." +
196
+ " Re-authenticate with: " + reauthCommand() +
197
+ " — then re-run. (dove exits " + exports.AUTH_EXIT_CODE + " for a credential failure.)");
198
+ }
199
+ var table = echoableTable(input.table);
200
+ return ("Forbidden (403) " + input.action + ". " +
201
+ where + " accepted the sign-in but refused the write for this user." +
202
+ " Check the role or ACL for " + (table ? "table " + table : "the table") +
203
+ " for the user in " + (context.envPath ? context.envPath : "the loaded env file") +
204
+ ", then re-run. (dove exits " + exports.AUTH_EXIT_CODE + " for a refused write.)");
205
+ }
206
+ /**
207
+ * Record that the instance rejected a request. `write: true` is a rejected WRITE —
208
+ * the command did not do what it was asked, so it must not exit clean.
209
+ */
210
+ function recordAuthFailure(opts) {
211
+ anyRejected = true;
212
+ if (opts && opts.write === true)
213
+ writeRejected = true;
214
+ }
215
+ /**
216
+ * The exit code the process should finish with, given the code it was about to use.
217
+ *
218
+ * - a rejected WRITE: 0 or 1 becomes AUTH_EXIT_CODE (a push that was turned away
219
+ * is not a success, even though the push command itself exits 0 after reporting)
220
+ * - any other rejection: only a generic failure (1) becomes AUTH_EXIT_CODE — a
221
+ * command that tolerated the rejection and succeeded still exits 0
222
+ * - every other code is left exactly as it was
223
+ */
224
+ function resolveExitCode(code) {
225
+ var current = typeof code === "number" && !isNaN(code) ? code : 0;
226
+ if (writeRejected && (current === 0 || current === 1))
227
+ return exports.AUTH_EXIT_CODE;
228
+ if (anyRejected && current === 1)
229
+ return exports.AUTH_EXIT_CODE;
230
+ return current;
231
+ }
232
+ /**
233
+ * Install the process `exit` hook that applies resolveExitCode. Called only from the
234
+ * CLI entry point — importing dovetail-core as a library never touches exit codes.
235
+ */
236
+ function installAuthExitCode(proc) {
237
+ proc.on("exit", function (code) {
238
+ var next = resolveExitCode(code);
239
+ if (next !== code) {
240
+ proc.exitCode = next;
241
+ }
242
+ });
243
+ }
package/dist/bootstrap.js CHANGED
@@ -41,6 +41,7 @@ const dotenv_1 = __importDefault(require("dotenv"));
41
41
  const ConfigManager = __importStar(require("./config"));
42
42
  const Logger_1 = require("./Logger");
43
43
  const envArg_1 = require("./envArg");
44
+ const authFailure_1 = require("./authFailure");
44
45
  async function init() {
45
46
  // Honor a per-command `--env <path>` override before config/env load so
46
47
  // dotenv reads the requested file. Resolved here (not in loadConfigs) because
@@ -71,6 +72,9 @@ async function init() {
71
72
  try {
72
73
  let path = ConfigManager.getEnvPath();
73
74
  dotenv_1.default.config({ path });
75
+ // Only the file's PATH and the selector the user typed — never its contents.
76
+ // Lets a 401/403 name the env file and the exact re-auth command (#185).
77
+ (0, authFailure_1.setAuthContext)({ envPath: path, envArg: envArg || "" });
74
78
  }
75
79
  catch (e) {
76
80
  Logger_1.logger.error("Failed to load environment: " + String(e));
package/dist/config.js CHANGED
@@ -496,18 +496,31 @@ function resolveManifestForScope(man, scope) {
496
496
  }
497
497
  return undefined;
498
498
  }
499
+ // A path sits under a scope's folder only at a separator boundary. A plain
500
+ // string prefix lets "src/UIComponents/x_cadso_ui_form" claim a file in a
501
+ // sibling "src/UIComponents/x_cadso_ui_form_x/". When folders nest
502
+ // ("src/UIComponents" as a scope and "src/UIComponents/x_..." as another), the
503
+ // deepest match wins, whatever order the scopes are declared in.
499
504
  function resolveScopeFromPath(filePath) {
505
+ if (typeof filePath !== "string" || filePath === "")
506
+ return undefined;
500
507
  var cfg = getConfig();
501
508
  if (!cfg.scopes)
502
509
  return undefined;
510
+ var resolvedFile = path_1.default.resolve(filePath);
503
511
  var scopeNames = Object.keys(cfg.scopes);
512
+ var best = undefined;
513
+ var bestLength = -1;
504
514
  for (var i = 0; i < scopeNames.length; i++) {
505
- var scopeSourcePath = getSourcePathForScope(scopeNames[i]);
506
- if (filePath.indexOf(scopeSourcePath) === 0) {
507
- return scopeNames[i];
515
+ var scopeSourcePath = path_1.default.resolve(getSourcePathForScope(scopeNames[i]));
516
+ var isUnder = resolvedFile === scopeSourcePath ||
517
+ resolvedFile.indexOf(scopeSourcePath + path_1.default.sep) === 0;
518
+ if (isUnder && scopeSourcePath.length > bestLength) {
519
+ best = scopeNames[i];
520
+ bestLength = scopeSourcePath.length;
508
521
  }
509
522
  }
510
- return undefined;
523
+ return best;
511
524
  }
512
525
  // Exported for tests only.
513
526
  async function loadConfigPath(pth) {
@@ -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;
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ exports.encodeV2Values = exports.decodeV2Values = void 0;
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const bootstrap_1 = require("./bootstrap");
10
10
  const FileLogger_1 = require("./FileLogger");
11
+ const authFailure_1 = require("./authFailure");
11
12
  // Library exports — consumers can `import { decodeV2Values } from "@tenonhq/dovetail-core"`.
12
13
  // Keep exports above the CLI entry so bundlers/TS can tree-shake and require() consumers
13
14
  // never accidentally invoke main().
@@ -28,6 +29,9 @@ async function main() {
28
29
  // Only run the CLI when this file is executed directly (e.g. `npx dove`, `node dist/index.js`).
29
30
  // When imported as a library, require.main !== module and main() is skipped.
30
31
  if (require.main === module) {
32
+ // A run the instance turned away (HTTP 401/403) exits AUTH_EXIT_CODE (77), not the
33
+ // generic 1 — see authFailure.ts. Every other exit code is left as it was.
34
+ (0, authFailure_1.installAuthExitCode)(process);
31
35
  main().catch(function (e) {
32
36
  FileLogger_1.fileLogger.error("Fatal error: " + String(e));
33
37
  process.exit(1);
@@ -53,6 +53,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
53
53
  return (mod && mod.__esModule) ? mod : { "default": mod };
54
54
  };
55
55
  Object.defineProperty(exports, "__esModule", { value: true });
56
+ exports.applyDeletes = applyDeletes;
56
57
  exports.applyCreates = applyCreates;
57
58
  exports.reconcileCommand = reconcileCommand;
58
59
  const path_1 = __importDefault(require("path"));
@@ -71,6 +72,7 @@ const projectFiles_1 = require("./projectFiles");
71
72
  const recordSource_1 = require("./reconcile/recordSource");
72
73
  const recordDiff_1 = require("./reconcile/recordDiff");
73
74
  const fields_1 = require("./reconcile/fields");
75
+ const fingerprint_1 = require("./fingerprint");
74
76
  const baseline_1 = require("./reconcile/baseline");
75
77
  const report_1 = require("./reconcile/report");
76
78
  const applyPlan_1 = require("./reconcile/applyPlan");
@@ -320,6 +322,14 @@ async function buildCreateFields(scope, change) {
320
322
  }
321
323
  const name = entry.slice(0, dot);
322
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
+ }
323
333
  if (!(0, fields_1.isComparableField)({ name, type })) {
324
334
  continue;
325
335
  }