@indigoai-us/hq-cloud 6.18.107 → 6.18.109

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/bin/sync-runner-company.d.ts +1 -0
  2. package/dist/bin/sync-runner-company.d.ts.map +1 -1
  3. package/dist/bin/sync-runner-company.js +29 -8
  4. package/dist/bin/sync-runner-company.js.map +1 -1
  5. package/dist/bin/sync-runner-manifest.d.ts +27 -0
  6. package/dist/bin/sync-runner-manifest.d.ts.map +1 -1
  7. package/dist/bin/sync-runner-manifest.js +104 -0
  8. package/dist/bin/sync-runner-manifest.js.map +1 -1
  9. package/dist/bin/sync-runner-planning.d.ts +48 -0
  10. package/dist/bin/sync-runner-planning.d.ts.map +1 -1
  11. package/dist/bin/sync-runner-planning.js +140 -0
  12. package/dist/bin/sync-runner-planning.js.map +1 -1
  13. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
  14. package/dist/bin/sync-runner-watch-loop.js +8 -2
  15. package/dist/bin/sync-runner-watch-loop.js.map +1 -1
  16. package/dist/bin/sync-runner.d.ts +1 -0
  17. package/dist/bin/sync-runner.d.ts.map +1 -1
  18. package/dist/bin/sync-runner.js +24 -1
  19. package/dist/bin/sync-runner.js.map +1 -1
  20. package/dist/cli/rescue-core.d.ts +64 -1
  21. package/dist/cli/rescue-core.d.ts.map +1 -1
  22. package/dist/cli/rescue-core.js +272 -125
  23. package/dist/cli/rescue-core.js.map +1 -1
  24. package/dist/cli/rescue-git.d.ts +47 -0
  25. package/dist/cli/rescue-git.d.ts.map +1 -0
  26. package/dist/cli/rescue-git.js +126 -0
  27. package/dist/cli/rescue-git.js.map +1 -0
  28. package/dist/cli/rescue-native-copy.d.ts +88 -0
  29. package/dist/cli/rescue-native-copy.d.ts.map +1 -0
  30. package/dist/cli/rescue-native-copy.js +823 -0
  31. package/dist/cli/rescue-native-copy.js.map +1 -0
  32. package/dist/cli/rescue-snapshot.d.ts +22 -0
  33. package/dist/cli/rescue-snapshot.d.ts.map +1 -1
  34. package/dist/cli/rescue-snapshot.js +27 -0
  35. package/dist/cli/rescue-snapshot.js.map +1 -1
  36. package/dist/cli/rescue.d.ts +21 -1
  37. package/dist/cli/rescue.d.ts.map +1 -1
  38. package/dist/cli/rescue.js +68 -2
  39. package/dist/cli/rescue.js.map +1 -1
  40. package/dist/cli/share.d.ts +14 -0
  41. package/dist/cli/share.d.ts.map +1 -1
  42. package/dist/cli/share.js +19 -8
  43. package/dist/cli/share.js.map +1 -1
  44. package/dist/cli/sync.d.ts +8 -0
  45. package/dist/cli/sync.d.ts.map +1 -1
  46. package/dist/cli/sync.js +5 -5
  47. package/dist/cli/sync.js.map +1 -1
  48. package/dist/cognito-auth.d.ts +57 -0
  49. package/dist/cognito-auth.d.ts.map +1 -1
  50. package/dist/cognito-auth.js +182 -3
  51. package/dist/cognito-auth.js.map +1 -1
  52. package/dist/ignore.d.ts +5 -1
  53. package/dist/ignore.d.ts.map +1 -1
  54. package/dist/ignore.js +32 -2
  55. package/dist/ignore.js.map +1 -1
  56. package/dist/index.d.ts +3 -2
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +6 -1
  59. package/dist/index.js.map +1 -1
  60. package/dist/manifest/leg-skip-store.d.ts +59 -0
  61. package/dist/manifest/leg-skip-store.d.ts.map +1 -0
  62. package/dist/manifest/leg-skip-store.js +140 -0
  63. package/dist/manifest/leg-skip-store.js.map +1 -0
  64. package/dist/manifest/upload-manifest.d.ts +11 -0
  65. package/dist/manifest/upload-manifest.d.ts.map +1 -1
  66. package/dist/manifest/upload-manifest.js +30 -1
  67. package/dist/manifest/upload-manifest.js.map +1 -1
  68. package/dist/manifest-folder-alias.d.ts +70 -0
  69. package/dist/manifest-folder-alias.d.ts.map +1 -0
  70. package/dist/manifest-folder-alias.js +139 -0
  71. package/dist/manifest-folder-alias.js.map +1 -0
  72. package/dist/manifest-reconcile.d.ts +5 -0
  73. package/dist/manifest-reconcile.d.ts.map +1 -1
  74. package/dist/manifest-reconcile.js +14 -2
  75. package/dist/manifest-reconcile.js.map +1 -1
  76. package/dist/outposts/billing.d.ts +0 -2
  77. package/dist/outposts/billing.d.ts.map +1 -1
  78. package/dist/outposts/billing.js +0 -2
  79. package/dist/outposts/billing.js.map +1 -1
  80. package/dist/outposts/cli-billing.d.ts +8 -2
  81. package/dist/outposts/cli-billing.d.ts.map +1 -1
  82. package/dist/outposts/cli-billing.js +13 -8
  83. package/dist/outposts/cli-billing.js.map +1 -1
  84. package/dist/outposts/client.d.ts +6 -3
  85. package/dist/outposts/client.d.ts.map +1 -1
  86. package/dist/outposts/client.js +12 -8
  87. package/dist/outposts/client.js.map +1 -1
  88. package/dist/outposts/command.d.ts +30 -0
  89. package/dist/outposts/command.d.ts.map +1 -1
  90. package/dist/outposts/command.js +79 -13
  91. package/dist/outposts/command.js.map +1 -1
  92. package/dist/outposts/company-outposts.d.ts +2 -2
  93. package/dist/outposts/company-outposts.d.ts.map +1 -1
  94. package/dist/outposts/company-outposts.js +5 -4
  95. package/dist/outposts/company-outposts.js.map +1 -1
  96. package/dist/outposts/hq-pro-routes.d.ts +15 -0
  97. package/dist/outposts/hq-pro-routes.d.ts.map +1 -0
  98. package/dist/outposts/hq-pro-routes.js +21 -0
  99. package/dist/outposts/hq-pro-routes.js.map +1 -0
  100. package/dist/outposts/index.d.ts +3 -1
  101. package/dist/outposts/index.d.ts.map +1 -1
  102. package/dist/outposts/index.js +2 -1
  103. package/dist/outposts/index.js.map +1 -1
  104. package/dist/outposts/sizes.d.ts +56 -0
  105. package/dist/outposts/sizes.d.ts.map +1 -0
  106. package/dist/outposts/sizes.js +120 -0
  107. package/dist/outposts/sizes.js.map +1 -0
  108. package/dist/outposts/types.d.ts +3 -0
  109. package/dist/outposts/types.d.ts.map +1 -1
  110. package/dist/outposts/types.js +0 -11
  111. package/dist/outposts/types.js.map +1 -1
  112. package/dist/sync/pull-scope.d.ts +1 -1
  113. package/dist/sync/pull-scope.d.ts.map +1 -1
  114. package/dist/sync/pull-scope.js +8 -3
  115. package/dist/sync/pull-scope.js.map +1 -1
  116. package/dist/types.d.ts +7 -0
  117. package/dist/types.d.ts.map +1 -1
  118. package/package.json +1 -1
@@ -0,0 +1,823 @@
1
+ /**
2
+ * Built-in file copy for the `hq rescue` overlay, used when rsync is not on
3
+ * PATH (a stock Windows install, for example).
4
+ *
5
+ * The rescue builds one rsync argument vector per overlay call and either
6
+ * hands it to rsync or to {@link runNativeOverlay}. This module reads the same
7
+ * vector: `--include=`, `--exclude=` and the NUL-separated `--exclude-from=`
8
+ * protect list written by `appendLiteralRsyncExclude`, applied in rsync's
9
+ * first-match order, so both engines leave the same paths alone. An option it
10
+ * does not model is refused instead of ignored.
11
+ *
12
+ * What it does, matching `rsync -a` without `--delete`:
13
+ * - Never deletes anything the source does not replace.
14
+ * - Never follows a destination symlink: a link where the source has a
15
+ * directory is replaced by a real directory, and a file is renamed over
16
+ * the link itself.
17
+ * - Skips a file when size and whole-second mtime match (or, with
18
+ * `--checksum`, when the bytes match). Otherwise it writes a temp file in
19
+ * the same directory (`.hq-rescue-tmp-<8 hex>`, short enough for any
20
+ * name), sets mode and times, and renames it into place. On Windows a
21
+ * rename that a scanner or editor briefly blocks is retried with backoff,
22
+ * and a read-only destination file has the attribute cleared first, as
23
+ * Cygwin rsync does (and restored when the replace still fails). Temp
24
+ * files a killed run left behind are removed the next time the copy
25
+ * writes into that folder, unless the filters or the protect list
26
+ * exclude that name.
27
+ * - A dry run also checks that each file it would write is readable and
28
+ * that each folder it would write into is writable (outside Windows).
29
+ * - Recreates symlinks. On Windows, when the account cannot create one, it
30
+ * writes the git-style text stub (the link text), which
31
+ * `normalizeWindowsGitSymlinks` turns into a native link or junction.
32
+ * - Refuses to replace a non-empty directory, reports it, carries on, and
33
+ * returns status 23 like rsync's partial transfer, so the existing
34
+ * `rsync-partial` failure kind and restore path apply.
35
+ * - `--dry-run --itemize-changes` prints rsync-style itemized lines, so
36
+ * `rsyncOutputHasOnlyDirectoryChanges` reads both engines' output.
37
+ *
38
+ * Prior art: indigoai-us/hq-cloud#735 (`runNativeOverlay`).
39
+ */
40
+ import * as fs from "fs";
41
+ import * as path from "path";
42
+ import { randomBytes } from "crypto";
43
+ const POSIX_CHARACTER_CLASSES = {
44
+ alnum: "A-Za-z0-9",
45
+ alpha: "A-Za-z",
46
+ blank: " \\t",
47
+ cntrl: "\\x00-\\x1f\\x7f",
48
+ digit: "0-9",
49
+ graph: "\\x21-\\x7e",
50
+ lower: "a-z",
51
+ print: "\\x20-\\x7e",
52
+ punct: "!-\\/:-@\\[-`{-~",
53
+ space: " \\t\\n\\r\\f\\v",
54
+ upper: "A-Z",
55
+ xdigit: "0-9A-Fa-f",
56
+ };
57
+ function regexLiteral(text) {
58
+ return text.replace(/[\\^$.*+?()[\]{}|/-]/g, "\\$&");
59
+ }
60
+ /**
61
+ * Translate an rsync wildcard pattern (rsync's wildmatch) to a RegExp body.
62
+ * `*` stops at `/`, two or more stars cross it, `?` is one non-slash
63
+ * character, `[...]` is a class (`!` or `^` negates, `[:alpha:]` names a
64
+ * POSIX class, a leading `]` is literal) that never matches `/`, and a
65
+ * backslash makes the next character literal. Returns null for a pattern
66
+ * wildmatch can never match (an unclosed class or a trailing backslash).
67
+ */
68
+ function wildmatchRegexBody(pattern) {
69
+ let body = "";
70
+ for (let i = 0; i < pattern.length; i++) {
71
+ const ch = pattern[i];
72
+ if (ch === "\\") {
73
+ if (i + 1 >= pattern.length)
74
+ return null;
75
+ body += regexLiteral(pattern[++i]);
76
+ }
77
+ else if (ch === "*") {
78
+ let stars = 1;
79
+ while (pattern[i + stars] === "*")
80
+ stars++;
81
+ body += stars >= 2 ? ".*" : "[^/]*";
82
+ i += stars - 1;
83
+ }
84
+ else if (ch === "?") {
85
+ body += "[^/]";
86
+ }
87
+ else if (ch === "[") {
88
+ let j = i + 1;
89
+ let negate = false;
90
+ if (pattern[j] === "!" || pattern[j] === "^") {
91
+ negate = true;
92
+ j++;
93
+ }
94
+ let members = "";
95
+ let first = true;
96
+ let closed = false;
97
+ for (; j < pattern.length; j++) {
98
+ let c = pattern[j];
99
+ if (c === "]" && !first) {
100
+ closed = true;
101
+ break;
102
+ }
103
+ first = false;
104
+ if (c === "[" && pattern[j + 1] === ":") {
105
+ const end = pattern.indexOf(":]", j + 2);
106
+ const name = end < 0 ? "" : pattern.slice(j + 2, end);
107
+ const cls = POSIX_CHARACTER_CLASSES[name];
108
+ if (cls !== undefined) {
109
+ members += cls;
110
+ j = end + 1;
111
+ continue;
112
+ }
113
+ }
114
+ if (c === "\\") {
115
+ if (j + 1 >= pattern.length)
116
+ return null;
117
+ c = pattern[++j];
118
+ }
119
+ if (pattern[j + 1] === "-" && j + 2 < pattern.length && pattern[j + 2] !== "]") {
120
+ let hi = pattern[j + 2];
121
+ let next = j + 2;
122
+ if (hi === "\\") {
123
+ if (next + 1 >= pattern.length)
124
+ return null;
125
+ hi = pattern[++next];
126
+ }
127
+ members += `${regexLiteral(c)}-${regexLiteral(hi)}`;
128
+ j = next;
129
+ continue;
130
+ }
131
+ members += regexLiteral(c);
132
+ }
133
+ if (!closed)
134
+ return null;
135
+ body += negate ? `[^/${members}]` : `(?=[^/])[${members}]`;
136
+ i = j;
137
+ }
138
+ else {
139
+ body += regexLiteral(ch);
140
+ }
141
+ }
142
+ return body;
143
+ }
144
+ function anchoredLiteral(rawPattern) {
145
+ let pattern = rawPattern;
146
+ let dirOnly = false;
147
+ if (pattern.length > 1 && pattern.endsWith("/")) {
148
+ dirOnly = true;
149
+ pattern = pattern.slice(0, -1);
150
+ }
151
+ if (!pattern.startsWith("/") || pattern.length < 2 || /[*?[]/.test(pattern))
152
+ return null;
153
+ return { path: pattern.slice(1), dirOnly };
154
+ }
155
+ /**
156
+ * Compile one rsync `--include=`/`--exclude=` pattern, following rsync's
157
+ * `rule_matches`:
158
+ * - a trailing `/` matches directories only;
159
+ * - a leading `/` anchors the pattern at the transfer root;
160
+ * - a pattern with no `/` and no `**` matches the last path element;
161
+ * - any other unanchored pattern matches at a path-element boundary;
162
+ * - a pattern that starts with `**` and a slash also matches at the
163
+ * start of the path (rsync puts a slash in front of the name), so
164
+ * `**` + `/cache/` + `**` matches `cache/x`;
165
+ * - `dir/***` matches the directory `dir` itself and everything below it;
166
+ * - backslash escapes apply only when the pattern holds a wildcard
167
+ * (`*`, `?` or `[`); without one the pattern is compared literally.
168
+ */
169
+ export function compileRsyncPattern(rawPattern) {
170
+ let pattern = rawPattern;
171
+ let dirOnly = false;
172
+ if (pattern.length > 1 && pattern.endsWith("/")) {
173
+ dirOnly = true;
174
+ pattern = pattern.slice(0, -1);
175
+ }
176
+ if (pattern.length === 0)
177
+ return () => false;
178
+ const wild = /[*?[]/.test(pattern);
179
+ const wild2 = wild && pattern.includes("**");
180
+ const wild2Prefix = wild2 && pattern.startsWith("**");
181
+ const wild3Suffix = wild2 && pattern.endsWith("***");
182
+ const slashCount = (pattern.match(/\//g) ?? []).length;
183
+ const anchored = pattern.startsWith("/");
184
+ const body = anchored ? pattern.slice(1) : pattern;
185
+ const lastElementOnly = slashCount === 0 && !wild2;
186
+ const anyBoundary = !anchored && (slashCount > 0 || (wild2 && !wild2Prefix));
187
+ let test;
188
+ if (!wild) {
189
+ test = (subject) => subject === body || (anyBoundary && subject.endsWith(`/${body}`));
190
+ }
191
+ else {
192
+ const regexBody = wildmatchRegexBody(body);
193
+ if (regexBody === null)
194
+ return () => false;
195
+ const regex = new RegExp(`^${anyBoundary ? "(?:.*/)?" : ""}${regexBody}$`);
196
+ test = (subject) => regex.test(subject);
197
+ }
198
+ return (rel, isDir) => {
199
+ if (dirOnly && !isDir)
200
+ return false;
201
+ let subject = rel.replace(/^\/+/, "");
202
+ if (subject.length === 0)
203
+ return false;
204
+ if (lastElementOnly)
205
+ subject = subject.slice(subject.lastIndexOf("/") + 1);
206
+ if (wild2Prefix)
207
+ subject = `/${subject}`;
208
+ // rsync appends "/" to a directory's name for a trailing `/***`, so the
209
+ // pattern matches the directory as well as its contents.
210
+ if (wild3Suffix && isDir)
211
+ subject += "/";
212
+ return test(subject);
213
+ };
214
+ }
215
+ /** Whether one rsync filter pattern matches `rel`. See {@link compileRsyncPattern}. */
216
+ export function rsyncFilterRuleMatches(rawPattern, rel, isDir) {
217
+ return compileRsyncPattern(rawPattern)(rel, isDir);
218
+ }
219
+ /**
220
+ * Compile a filter list once for a whole walk. A run of plain anchored
221
+ * paths with the same action (the protect list holds one per unchanged
222
+ * file) becomes one set lookup; first-match order is unchanged because
223
+ * every rule in the run has the same action.
224
+ */
225
+ export function compileOverlayRules(rules) {
226
+ const compiled = [];
227
+ let run = null;
228
+ const flush = () => {
229
+ if (!run)
230
+ return;
231
+ const { any, dirs } = run;
232
+ compiled.push({
233
+ include: run.include,
234
+ matches: (rel, isDir) => any.has(rel) || (isDir && dirs.has(rel)),
235
+ });
236
+ run = null;
237
+ };
238
+ for (const rule of rules) {
239
+ const literal = anchoredLiteral(rule.pattern);
240
+ if (!literal) {
241
+ flush();
242
+ compiled.push({ include: rule.include, matches: compileRsyncPattern(rule.pattern) });
243
+ continue;
244
+ }
245
+ if (run && run.include !== rule.include)
246
+ flush();
247
+ run ??= { include: rule.include, any: new Set(), dirs: new Set() };
248
+ (literal.dirOnly ? run.dirs : run.any).add(literal.path);
249
+ }
250
+ flush();
251
+ return compiled;
252
+ }
253
+ /** Whether rsync's filter list admits this one entry (its parents admitted). */
254
+ export function overlayRulesAdmitEntry(rules, rel, isDir) {
255
+ for (const rule of rules) {
256
+ if (rule.matches(rel, isDir))
257
+ return rule.include;
258
+ }
259
+ return true;
260
+ }
261
+ /**
262
+ * Read the overlay options from an rsync argument vector, without the two
263
+ * trailing source/destination paths. Throws on an option the built-in copy
264
+ * does not implement, so a new rsync flag cannot be silently dropped.
265
+ */
266
+ export function nativeOverlayOptionsFromRsyncArgs(args, readFile = (file) => fs.readFileSync(file)) {
267
+ const from0 = args.includes("--from0");
268
+ const options = {
269
+ rules: [],
270
+ dryRun: false,
271
+ checksum: false,
272
+ times: false,
273
+ perms: false,
274
+ itemize: false,
275
+ };
276
+ let noTimes = false;
277
+ let noPerms = false;
278
+ for (const arg of args) {
279
+ if (arg === "-a" || arg === "--archive") {
280
+ options.times = true;
281
+ options.perms = true;
282
+ }
283
+ else if (arg === "--dry-run" || arg === "-n") {
284
+ options.dryRun = true;
285
+ }
286
+ else if (arg === "--checksum" || arg === "-c") {
287
+ options.checksum = true;
288
+ }
289
+ else if (arg === "--itemize-changes" || arg === "-i") {
290
+ options.itemize = true;
291
+ }
292
+ else if (arg === "--no-times") {
293
+ noTimes = true;
294
+ }
295
+ else if (arg === "--no-perms") {
296
+ noPerms = true;
297
+ }
298
+ else if (arg === "--from0" ||
299
+ arg === "--no-owner" ||
300
+ arg === "--no-group" ||
301
+ arg.startsWith("--chmod=")) {
302
+ // --from0 is read above. Owner, group and --chmod apply to the Windows
303
+ // receiver, where the built-in copy never sets POSIX modes.
304
+ }
305
+ else if (arg.startsWith("--include=")) {
306
+ options.rules.push({ include: true, pattern: arg.slice("--include=".length) });
307
+ }
308
+ else if (arg.startsWith("--exclude=")) {
309
+ options.rules.push({ include: false, pattern: arg.slice("--exclude=".length) });
310
+ }
311
+ else if (arg.startsWith("--exclude-from=")) {
312
+ const text = readFile(arg.slice("--exclude-from=".length)).toString("utf8");
313
+ const entries = from0 ? text.split("\0") : text.split(/\r?\n/);
314
+ for (const entry of entries) {
315
+ if (entry.length === 0)
316
+ continue;
317
+ if (!from0 && (entry.startsWith("#") || entry.startsWith(";")))
318
+ continue;
319
+ if (entry.startsWith("+ ")) {
320
+ options.rules.push({ include: true, pattern: entry.slice(2) });
321
+ }
322
+ else if (entry.startsWith("- ")) {
323
+ options.rules.push({ include: false, pattern: entry.slice(2) });
324
+ }
325
+ else {
326
+ options.rules.push({ include: false, pattern: entry });
327
+ }
328
+ }
329
+ }
330
+ else {
331
+ throw new Error(`the built-in file copy does not support rsync argument ${arg}`);
332
+ }
333
+ }
334
+ if (noTimes)
335
+ options.times = false;
336
+ if (noPerms)
337
+ options.perms = false;
338
+ return options;
339
+ }
340
+ /**
341
+ * Temp files are `<prefix><8 hex>` in the destination folder. The name is
342
+ * short so a long release file name cannot push it past the file system's
343
+ * name limit. Nothing else uses this prefix, so a file with exactly this
344
+ * shape is a leftover from a killed copy and is removed, never kept as a
345
+ * user file.
346
+ */
347
+ export const NATIVE_COPY_TEMP_PREFIX = ".hq-rescue-tmp-";
348
+ const NATIVE_COPY_TEMP_NAME = /^\.hq-rescue-tmp-[0-9a-f]{8}$/;
349
+ /**
350
+ * Waits between rename attempts on Windows, where Defender, the search
351
+ * indexer, OneDrive or an editor can hold a just-written file or its target
352
+ * for a moment (EPERM, EBUSY, EACCES). About 1.6 s in total.
353
+ */
354
+ export const WINDOWS_RENAME_RETRY_DELAYS_MS = [10, 25, 50, 100, 200, 400, 800];
355
+ const WINDOWS_TRANSIENT_RENAME_CODES = new Set(["EPERM", "EBUSY", "EACCES"]);
356
+ function sleepSync(ms) {
357
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
358
+ }
359
+ const defaultOps = {
360
+ symlink(target, destination, type) {
361
+ fs.symlinkSync(target, destination, type);
362
+ },
363
+ };
364
+ function lstatOrNull(p) {
365
+ try {
366
+ return fs.lstatSync(p);
367
+ }
368
+ catch (error) {
369
+ if (error.code === "ENOENT")
370
+ return null;
371
+ throw error;
372
+ }
373
+ }
374
+ /** Remove a file or a symlink (a Windows directory link or junction included). */
375
+ function removeNonDirectory(p) {
376
+ try {
377
+ fs.unlinkSync(p);
378
+ }
379
+ catch (error) {
380
+ const code = error.code;
381
+ if (code === "ENOENT")
382
+ return;
383
+ // A Windows directory symlink or junction is removed with RemoveDirectory,
384
+ // which never removes a real directory that still has entries.
385
+ if (code === "EPERM" || code === "EISDIR" || code === "EACCES") {
386
+ fs.rmdirSync(p);
387
+ return;
388
+ }
389
+ throw error;
390
+ }
391
+ }
392
+ function sameFileBytes(left, right) {
393
+ const chunk = 64 * 1024;
394
+ const a = Buffer.alloc(chunk);
395
+ const b = Buffer.alloc(chunk);
396
+ const fa = fs.openSync(left, "r");
397
+ try {
398
+ const fb = fs.openSync(right, "r");
399
+ try {
400
+ for (;;) {
401
+ const na = fs.readSync(fa, a, 0, chunk, null);
402
+ const nb = fs.readSync(fb, b, 0, chunk, null);
403
+ if (na !== nb)
404
+ return false;
405
+ if (na === 0)
406
+ return true;
407
+ if (!a.subarray(0, na).equals(b.subarray(0, nb)))
408
+ return false;
409
+ }
410
+ }
411
+ finally {
412
+ fs.closeSync(fb);
413
+ }
414
+ }
415
+ finally {
416
+ fs.closeSync(fa);
417
+ }
418
+ }
419
+ function errorMessage(error) {
420
+ return error instanceof Error ? error.message : String(error);
421
+ }
422
+ /** Item flags in rsync's `%i` layout: type, then c s t p o g u a x. */
423
+ function itemFlags(kind, created, set = []) {
424
+ if (created)
425
+ return `${kind}+++++++++`;
426
+ const flags = [..."cstpoguax"].map((flag) => (set.includes(flag) ? flag : "."));
427
+ return `${kind}${flags.join("")}`;
428
+ }
429
+ class NativeOverlay {
430
+ sourceRoot;
431
+ destinationRoot;
432
+ options;
433
+ platform;
434
+ ops;
435
+ stdout = "";
436
+ stderr = "";
437
+ partial = false;
438
+ rules;
439
+ writableChecked = new Set();
440
+ constructor(sourceRoot, destinationRoot, options, platform, ops) {
441
+ this.sourceRoot = sourceRoot;
442
+ this.destinationRoot = destinationRoot;
443
+ this.options = options;
444
+ this.platform = platform;
445
+ this.ops = ops;
446
+ this.rules = compileOverlayRules(options.rules);
447
+ }
448
+ run() {
449
+ const sourceStat = fs.statSync(this.sourceRoot);
450
+ if (!sourceStat.isDirectory()) {
451
+ return { status: 1, stdout: "", stderr: `built-in copy: source ${this.sourceRoot} is not a directory\n` };
452
+ }
453
+ let destinationStat = lstatOrNull(this.destinationRoot);
454
+ if (destinationStat && !destinationStat.isDirectory()) {
455
+ destinationStat = fs.statSync(this.destinationRoot);
456
+ }
457
+ if (destinationStat && !destinationStat.isDirectory()) {
458
+ return {
459
+ status: 1,
460
+ stdout: "",
461
+ stderr: `built-in copy: destination ${this.destinationRoot} is not a directory\n`,
462
+ };
463
+ }
464
+ if (!destinationStat && !this.options.dryRun)
465
+ fs.mkdirSync(this.destinationRoot);
466
+ this.copyDirectoryContents("", !destinationStat && this.options.dryRun);
467
+ if (!this.options.dryRun)
468
+ this.applyDirectoryMetadata(this.destinationRoot, sourceStat);
469
+ return { status: this.partial ? 23 : 0, stdout: this.stdout, stderr: this.stderr };
470
+ }
471
+ fail(message) {
472
+ this.partial = true;
473
+ this.stderr += `built-in copy: ${message}\n`;
474
+ }
475
+ itemize(flags, rel, suffix = "") {
476
+ if (this.options.itemize)
477
+ this.stdout += `${flags} ${rel}${suffix}\n`;
478
+ }
479
+ sourcePath(rel) {
480
+ return rel ? path.join(this.sourceRoot, ...rel.split("/")) : this.sourceRoot;
481
+ }
482
+ destinationPath(rel) {
483
+ return rel ? path.join(this.destinationRoot, ...rel.split("/")) : this.destinationRoot;
484
+ }
485
+ /**
486
+ * Copy one source directory's admitted children. `destinationMissing` is
487
+ * true in a dry run when the destination directory does not exist yet as a
488
+ * real directory, so nothing below it is read through a link.
489
+ */
490
+ copyDirectoryContents(relDir, destinationMissing) {
491
+ if (!this.options.dryRun)
492
+ this.removeStaleTemps(relDir);
493
+ let names;
494
+ try {
495
+ names = fs.readdirSync(this.sourcePath(relDir)).sort();
496
+ }
497
+ catch (error) {
498
+ this.fail(`cannot read source directory ${relDir || "."}: ${errorMessage(error)}`);
499
+ return;
500
+ }
501
+ for (const name of names) {
502
+ const rel = relDir ? `${relDir}/${name}` : name;
503
+ let sourceStat;
504
+ try {
505
+ sourceStat = fs.lstatSync(this.sourcePath(rel));
506
+ }
507
+ catch (error) {
508
+ this.fail(`cannot read ${rel}: ${errorMessage(error)}`);
509
+ continue;
510
+ }
511
+ const isDir = sourceStat.isDirectory();
512
+ if (!overlayRulesAdmitEntry(this.rules, rel, isDir))
513
+ continue;
514
+ try {
515
+ if (sourceStat.isSymbolicLink()) {
516
+ this.copySymlink(rel, destinationMissing);
517
+ }
518
+ else if (isDir) {
519
+ this.copyDirectory(rel, sourceStat, destinationMissing);
520
+ }
521
+ else if (sourceStat.isFile()) {
522
+ this.copyFile(rel, sourceStat, destinationMissing);
523
+ }
524
+ else {
525
+ this.stderr += `built-in copy: skipping non-regular file ${rel}\n`;
526
+ }
527
+ }
528
+ catch (error) {
529
+ this.fail(`cannot copy ${rel}: ${errorMessage(error)}`);
530
+ }
531
+ }
532
+ }
533
+ /**
534
+ * Remove temp files a killed copy left in this destination folder. Only a
535
+ * name the copy itself could have written here is removed: an entry the
536
+ * filters or the protect list exclude is left alone, like every other
537
+ * excluded path.
538
+ */
539
+ removeStaleTemps(relDir) {
540
+ const directory = this.destinationPath(relDir);
541
+ let names;
542
+ try {
543
+ names = fs.readdirSync(directory);
544
+ }
545
+ catch {
546
+ return;
547
+ }
548
+ for (const name of names) {
549
+ if (!NATIVE_COPY_TEMP_NAME.test(name))
550
+ continue;
551
+ const rel = relDir ? `${relDir}/${name}` : name;
552
+ if (!overlayRulesAdmitEntry(this.rules, rel, false))
553
+ continue;
554
+ const leftover = path.join(directory, name);
555
+ try {
556
+ if (lstatOrNull(leftover)?.isFile())
557
+ fs.unlinkSync(leftover);
558
+ }
559
+ catch (error) {
560
+ this.stderr += `built-in copy: cannot remove leftover temp file ${leftover}: ${errorMessage(error)}\n`;
561
+ }
562
+ }
563
+ }
564
+ /**
565
+ * In a dry run, report what the real copy could not do: read a source file,
566
+ * or create an entry in a folder this account cannot write. Windows folder
567
+ * permissions do not map to these checks, so only the read check runs there.
568
+ */
569
+ dryRunCheck(rel, source, parentMissing) {
570
+ if (!this.options.dryRun)
571
+ return;
572
+ if (source !== null) {
573
+ try {
574
+ fs.accessSync(source, fs.constants.R_OK);
575
+ }
576
+ catch (error) {
577
+ this.fail(`cannot read ${rel}: ${errorMessage(error)}`);
578
+ }
579
+ }
580
+ if (parentMissing || this.platform === "win32")
581
+ return;
582
+ const parentRel = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "";
583
+ if (this.writableChecked.has(parentRel))
584
+ return;
585
+ this.writableChecked.add(parentRel);
586
+ try {
587
+ fs.accessSync(this.destinationPath(parentRel), fs.constants.W_OK);
588
+ }
589
+ catch (error) {
590
+ this.fail(`cannot write in ${parentRel || "."}: ${errorMessage(error)}`);
591
+ }
592
+ }
593
+ /**
594
+ * A real directory stands where the source has a file or link. rsync -a
595
+ * without --force removes it only when it is empty; otherwise the entry
596
+ * fails and the transfer ends with status 23.
597
+ */
598
+ makeRoomInDirectory(rel, destination, existing, what) {
599
+ if (!existing.isDirectory() || existing.isSymbolicLink())
600
+ return true;
601
+ if (fs.readdirSync(destination).length > 0) {
602
+ this.fail(`cannot delete non-empty directory: ${rel}`);
603
+ this.fail(`could not make way for new ${what}: ${rel}`);
604
+ return false;
605
+ }
606
+ if (!this.options.dryRun)
607
+ fs.rmdirSync(destination);
608
+ return true;
609
+ }
610
+ copyDirectory(rel, sourceStat, parentMissing) {
611
+ const destination = this.destinationPath(rel);
612
+ const existing = parentMissing ? null : lstatOrNull(destination);
613
+ const realDirectory = existing !== null && existing.isDirectory() && !existing.isSymbolicLink();
614
+ if (!realDirectory) {
615
+ this.itemize(`c${itemFlags("d", true)}`, rel, "/");
616
+ this.dryRunCheck(rel, null, parentMissing);
617
+ if (!this.options.dryRun) {
618
+ // rsync -a without --keep-dirlinks replaces a link (or a file) with a
619
+ // real directory, so nothing is ever written through a link.
620
+ if (existing)
621
+ removeNonDirectory(destination);
622
+ fs.mkdirSync(destination);
623
+ }
624
+ }
625
+ this.copyDirectoryContents(rel, this.options.dryRun && !realDirectory);
626
+ if (!this.options.dryRun)
627
+ this.applyDirectoryMetadata(destination, sourceStat);
628
+ }
629
+ applyDirectoryMetadata(destination, sourceStat) {
630
+ try {
631
+ if (this.options.perms && this.platform !== "win32") {
632
+ fs.chmodSync(destination, sourceStat.mode & 0o7777);
633
+ }
634
+ if (this.options.times)
635
+ fs.utimesSync(destination, sourceStat.atime, sourceStat.mtime);
636
+ }
637
+ catch (error) {
638
+ this.fail(`cannot set attributes on ${destination}: ${errorMessage(error)}`);
639
+ }
640
+ }
641
+ copyFile(rel, sourceStat, parentMissing) {
642
+ const source = this.sourcePath(rel);
643
+ const destination = this.destinationPath(rel);
644
+ const existing = parentMissing ? null : lstatOrNull(destination);
645
+ const setPerms = this.options.perms && this.platform !== "win32";
646
+ const sourceMode = sourceStat.mode & 0o7777;
647
+ if (existing?.isFile()) {
648
+ const sameSize = existing.size === sourceStat.size;
649
+ const unchanged = this.options.checksum
650
+ ? sameSize && sameFileBytes(source, destination)
651
+ : sameSize &&
652
+ Math.floor(existing.mtimeMs / 1000) === Math.floor(sourceStat.mtimeMs / 1000);
653
+ if (unchanged) {
654
+ const permsDiffer = setPerms && (existing.mode & 0o7777) !== sourceMode;
655
+ if (permsDiffer) {
656
+ this.itemize(`.${itemFlags("f", false, ["p"])}`, rel);
657
+ if (!this.options.dryRun)
658
+ fs.chmodSync(destination, sourceMode);
659
+ }
660
+ return;
661
+ }
662
+ const changed = ["c"];
663
+ if (!sameSize)
664
+ changed.push("s");
665
+ if (this.options.times && existing.mtimeMs !== sourceStat.mtimeMs)
666
+ changed.push("t");
667
+ if (setPerms && (existing.mode & 0o7777) !== sourceMode)
668
+ changed.push("p");
669
+ this.itemize(`>${itemFlags("f", false, changed)}`, rel);
670
+ }
671
+ else {
672
+ if (existing && !this.makeRoomInDirectory(rel, destination, existing, "regular file"))
673
+ return;
674
+ this.itemize(`>${itemFlags("f", true)}`, rel);
675
+ }
676
+ this.dryRunCheck(rel, source, parentMissing);
677
+ if (this.options.dryRun)
678
+ return;
679
+ const temp = path.join(path.dirname(destination), `${NATIVE_COPY_TEMP_PREFIX}${randomBytes(4).toString("hex")}`);
680
+ try {
681
+ fs.copyFileSync(source, temp, fs.constants.COPYFILE_EXCL);
682
+ if (setPerms)
683
+ fs.chmodSync(temp, sourceMode);
684
+ if (this.options.times)
685
+ fs.utimesSync(temp, sourceStat.atime, sourceStat.mtime);
686
+ this.renameIntoPlace(temp, destination);
687
+ }
688
+ catch (error) {
689
+ try {
690
+ fs.unlinkSync(temp);
691
+ }
692
+ catch {
693
+ /* temp was renamed or never created */
694
+ }
695
+ throw error;
696
+ }
697
+ }
698
+ /**
699
+ * Rename the temp file over the destination entry (never through it).
700
+ * - Windows will not rename over a directory link or junction: remove the
701
+ * link, then rename.
702
+ * - Windows will not replace a read-only file: clear the attribute once,
703
+ * and set it again if the replace still fails.
704
+ * - Windows EPERM, EBUSY or EACCES from a scanner or editor holding the
705
+ * file: wait and retry, then give up (the entry fails, status 23).
706
+ */
707
+ renameIntoPlace(temp, destination) {
708
+ const rename = this.ops.rename ?? ((from, to) => fs.renameSync(from, to));
709
+ const sleep = this.ops.sleep ?? sleepSync;
710
+ let removedLink = false;
711
+ let readOnlyMode = null;
712
+ let retries = 0;
713
+ for (;;) {
714
+ try {
715
+ rename(temp, destination);
716
+ return;
717
+ }
718
+ catch (error) {
719
+ const code = error.code ?? "";
720
+ const current = lstatOrNull(destination);
721
+ let retry = false;
722
+ if (!removedLink && current?.isSymbolicLink()) {
723
+ removeNonDirectory(destination);
724
+ removedLink = true;
725
+ retry = true;
726
+ }
727
+ else if (this.platform === "win32" && WINDOWS_TRANSIENT_RENAME_CODES.has(code)) {
728
+ if (readOnlyMode === null && current?.isFile() && (current.mode & 0o200) === 0) {
729
+ readOnlyMode = current.mode & 0o7777;
730
+ fs.chmodSync(destination, 0o666);
731
+ retry = true;
732
+ }
733
+ else if (retries < WINDOWS_RENAME_RETRY_DELAYS_MS.length) {
734
+ sleep(WINDOWS_RENAME_RETRY_DELAYS_MS[retries]);
735
+ retries += 1;
736
+ retry = true;
737
+ }
738
+ }
739
+ if (retry)
740
+ continue;
741
+ if (readOnlyMode !== null) {
742
+ // The old file stays; give it back its read-only attribute.
743
+ try {
744
+ if (lstatOrNull(destination)?.isFile())
745
+ fs.chmodSync(destination, readOnlyMode);
746
+ }
747
+ catch {
748
+ /* best effort: the entry already fails with status 23 */
749
+ }
750
+ }
751
+ throw error;
752
+ }
753
+ }
754
+ }
755
+ copySymlink(rel, parentMissing) {
756
+ const source = this.sourcePath(rel);
757
+ const destination = this.destinationPath(rel);
758
+ const linkText = fs.readlinkSync(source);
759
+ const existing = parentMissing ? null : lstatOrNull(destination);
760
+ if (existing?.isSymbolicLink()) {
761
+ let current = null;
762
+ try {
763
+ current = fs.readlinkSync(destination);
764
+ }
765
+ catch {
766
+ current = null;
767
+ }
768
+ if (current === linkText)
769
+ return;
770
+ this.itemize(`c${itemFlags("L", false, ["c"])}`, rel, ` -> ${linkText}`);
771
+ }
772
+ else {
773
+ if (existing && !this.makeRoomInDirectory(rel, destination, existing, "symlink"))
774
+ return;
775
+ this.itemize(`c${itemFlags("L", true)}`, rel, ` -> ${linkText}`);
776
+ }
777
+ this.dryRunCheck(rel, null, parentMissing);
778
+ if (this.options.dryRun)
779
+ return;
780
+ if (existing && (existing.isSymbolicLink() || !existing.isDirectory())) {
781
+ removeNonDirectory(destination);
782
+ }
783
+ let targetIsDir = false;
784
+ try {
785
+ targetIsDir = fs.statSync(source).isDirectory();
786
+ }
787
+ catch {
788
+ targetIsDir = false;
789
+ }
790
+ try {
791
+ this.ops.symlink(linkText, destination, targetIsDir ? "dir" : "file");
792
+ }
793
+ catch (error) {
794
+ if (this.platform !== "win32")
795
+ throw error;
796
+ // No symlink privilege: write what Git for Windows writes for a link
797
+ // with core.symlinks=false. normalizeWindowsGitSymlinks repairs it.
798
+ fs.writeFileSync(destination, linkText.replace(/\\/g, "/"));
799
+ }
800
+ }
801
+ }
802
+ /**
803
+ * Copy `sourceRoot` onto `destinationRoot` as `rsync -a <args> src/ dst/`
804
+ * would. `args` is the rsync argument vector without the two paths. Returns
805
+ * rsync-style status: 0, 23 when some entries could not be copied (the rest
806
+ * were), or 1 when the copy could not start.
807
+ */
808
+ export function runNativeOverlay(sourceRoot, destinationRoot, args, platform = process.platform, ops = defaultOps) {
809
+ let options;
810
+ try {
811
+ options = nativeOverlayOptionsFromRsyncArgs(args);
812
+ }
813
+ catch (error) {
814
+ return { status: 1, stdout: "", stderr: `built-in copy: ${errorMessage(error)}\n` };
815
+ }
816
+ try {
817
+ return new NativeOverlay(sourceRoot, destinationRoot, options, platform, ops).run();
818
+ }
819
+ catch (error) {
820
+ return { status: 1, stdout: "", stderr: `built-in copy: ${errorMessage(error)}\n` };
821
+ }
822
+ }
823
+ //# sourceMappingURL=rescue-native-copy.js.map