@openclaw/feishu 2026.10.1-beta.2 → 2026.10.5-beta.1

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 (151) hide show
  1. package/dist/.setup/{app-registration-BB6TubaW.mjs → app-registration-DQOq5urV.mjs} +13 -32
  2. package/dist/.setup/{channel-CX62T71S.mjs → channel-CjGGyrdx.mjs} +87 -174
  3. package/dist/.setup/{channel.runtime-COiaq-Rv.mjs → channel.runtime-SaC_uTPM.mjs} +57 -74
  4. package/dist/.setup/{chat-BdyvImsY.mjs → chat-fC3dvxFs.mjs} +16 -28
  5. package/dist/.setup/{client-BsBVWJzN.mjs → client-wwr8PGPH.mjs} +24 -30
  6. package/dist/.setup/{conversation-id-C1ofUfU8.mjs → conversation-id-D00i9uy5.mjs} +5 -10
  7. package/dist/.setup/{doctor-contract-B1B9ogdd.mjs → doctor-contract-oIpUWtNO.mjs} +23 -20
  8. package/dist/.setup/{monitor-7DvwUs4Y.mjs → monitor-Yt__BUki.mjs} +33 -54
  9. package/dist/.setup/{monitor.account-7xVu7XWY.mjs → monitor.account-CVz16781.mjs} +377 -664
  10. package/dist/.setup/{probe-B9o7iey6.mjs → probe-DXnFxq5j.mjs} +14 -17
  11. package/dist/.setup/{reply-delivery-result-Bt-BWBEA.mjs → reply-delivery-result-iCCrdxE1.mjs} +153 -181
  12. package/dist/.setup/{session-conversation-C53IEUWt.mjs → session-conversation-BSBNK5Mq.mjs} +1 -1
  13. package/dist/.setup/{setup-api-DmzX9S01.mjs → setup-api-B_LFQQ-Q.mjs} +1 -1
  14. package/dist/.setup/{subagent-hooks-CUXg0pC-.mjs → subagent-hooks-9Pc1-k37.mjs} +7 -17
  15. package/dist/.setup/{thread-bindings-jW2x5VuN.mjs → thread-bindings-DdNLxoL3.mjs} +21 -44
  16. package/dist/api.js +218 -326
  17. package/dist/channel-plugin-api.js +1 -1
  18. package/dist/contract-api.js +1 -1
  19. package/dist/doctor-contract-api.js +2 -2
  20. package/dist/session-binding-contract-api.js +1 -1
  21. package/dist/session-key-api.js +1 -1
  22. package/dist/setup-api.js +1 -1
  23. package/dist/setup-entry.js +1 -1
  24. package/dist/subagent-hooks-api.js +1 -1
  25. package/node_modules/@openclaw/fs-safe/CHANGELOG.md +91 -0
  26. package/node_modules/@openclaw/fs-safe/README.md +1 -1
  27. package/node_modules/@openclaw/fs-safe/dist/advanced.d.ts +1 -0
  28. package/node_modules/@openclaw/fs-safe/dist/advanced.js +1 -0
  29. package/node_modules/@openclaw/fs-safe/dist/archive-durability.js +1 -1
  30. package/node_modules/@openclaw/fs-safe/dist/archive-entry.js +7 -3
  31. package/node_modules/@openclaw/fs-safe/dist/archive-merge.js +4 -4
  32. package/node_modules/@openclaw/fs-safe/dist/archive-parser.wasm +0 -0
  33. package/node_modules/@openclaw/fs-safe/dist/archive-read.js +5 -4
  34. package/node_modules/@openclaw/fs-safe/dist/archive-staging.d.ts +1 -1
  35. package/node_modules/@openclaw/fs-safe/dist/archive-staging.js +22 -38
  36. package/node_modules/@openclaw/fs-safe/dist/copy-path-admission.d.ts +17 -0
  37. package/node_modules/@openclaw/fs-safe/dist/copy-path-admission.js +117 -0
  38. package/node_modules/@openclaw/fs-safe/dist/copy-root-file-sync.d.ts +38 -0
  39. package/node_modules/@openclaw/fs-safe/dist/copy-root-file-sync.js +195 -0
  40. package/node_modules/@openclaw/fs-safe/dist/create.d.ts +1 -0
  41. package/node_modules/@openclaw/fs-safe/dist/create.js +4 -1
  42. package/node_modules/@openclaw/fs-safe/dist/entry-publication.js +3 -1
  43. package/node_modules/@openclaw/fs-safe/dist/errors.d.ts +2 -0
  44. package/node_modules/@openclaw/fs-safe/dist/errors.js +5 -0
  45. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-acquire.d.ts +3 -0
  46. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-acquire.js +57 -11
  47. package/node_modules/@openclaw/fs-safe/dist/guarded-mutation.js +5 -5
  48. package/node_modules/@openclaw/fs-safe/dist/guest-native-python.js +52 -5
  49. package/node_modules/@openclaw/fs-safe/dist/guest.js +1 -1
  50. package/node_modules/@openclaw/fs-safe/dist/index.d.ts +1 -1
  51. package/node_modules/@openclaw/fs-safe/dist/index.js +1 -1
  52. package/node_modules/@openclaw/fs-safe/dist/native-binding.d.ts +4 -0
  53. package/node_modules/@openclaw/fs-safe/dist/native-move-fallback.d.ts +3 -0
  54. package/node_modules/@openclaw/fs-safe/dist/native-move-fallback.js +54 -0
  55. package/node_modules/@openclaw/fs-safe/dist/native-noreplace.d.ts +8 -0
  56. package/node_modules/@openclaw/fs-safe/dist/native-noreplace.js +55 -0
  57. package/node_modules/@openclaw/fs-safe/dist/native-operations.d.ts +0 -1
  58. package/node_modules/@openclaw/fs-safe/dist/native-operations.js +22 -26
  59. package/node_modules/@openclaw/fs-safe/dist/native-pinned-write-windows.js +5 -1
  60. package/node_modules/@openclaw/fs-safe/dist/native-pinned-write.d.ts +1 -1
  61. package/node_modules/@openclaw/fs-safe/dist/native-pinned-write.js +12 -2
  62. package/node_modules/@openclaw/fs-safe/dist/native-rename-outcome.js +3 -1
  63. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.d.ts +1 -1
  64. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.js +52 -6
  65. package/node_modules/@openclaw/fs-safe/dist/permission-exec.js +2 -1
  66. package/node_modules/@openclaw/fs-safe/dist/pinned-write-input.d.ts +2 -0
  67. package/node_modules/@openclaw/fs-safe/dist/pinned-write-input.js +17 -0
  68. package/node_modules/@openclaw/fs-safe/dist/pinned-write-types.d.ts +6 -1
  69. package/node_modules/@openclaw/fs-safe/dist/pinned-write.js +1 -1
  70. package/node_modules/@openclaw/fs-safe/dist/private-temp-workspace.js +2 -2
  71. package/node_modules/@openclaw/fs-safe/dist/publish-file-failure.d.ts +5 -0
  72. package/node_modules/@openclaw/fs-safe/dist/publish-file-failure.js +1 -0
  73. package/node_modules/@openclaw/fs-safe/dist/publish-file.d.ts +2 -0
  74. package/node_modules/@openclaw/fs-safe/dist/publish-file.js +35 -2
  75. package/node_modules/@openclaw/fs-safe/dist/replace-directory.js +6 -5
  76. package/node_modules/@openclaw/fs-safe/dist/replace-file-copy-fallback.js +1 -4
  77. package/node_modules/@openclaw/fs-safe/dist/replace-file-descriptor.js +6 -0
  78. package/node_modules/@openclaw/fs-safe/dist/root-create-input.d.ts +15 -1
  79. package/node_modules/@openclaw/fs-safe/dist/root-create-input.js +4 -0
  80. package/node_modules/@openclaw/fs-safe/dist/root-directory-entry.js +1 -1
  81. package/node_modules/@openclaw/fs-safe/dist/root-directory-list.d.ts +0 -1
  82. package/node_modules/@openclaw/fs-safe/dist/root-directory-list.js +6 -12
  83. package/node_modules/@openclaw/fs-safe/dist/root-errors.js +25 -4
  84. package/node_modules/@openclaw/fs-safe/dist/root-impl.js +18 -18
  85. package/node_modules/@openclaw/fs-safe/dist/root-move-noreplace.d.ts +4 -2
  86. package/node_modules/@openclaw/fs-safe/dist/root-move-noreplace.js +13 -17
  87. package/node_modules/@openclaw/fs-safe/dist/root-paths.js +1 -1
  88. package/node_modules/@openclaw/fs-safe/dist/root-walk.js +4 -4
  89. package/node_modules/@openclaw/fs-safe/dist/root-write-verification.d.ts +10 -1
  90. package/node_modules/@openclaw/fs-safe/dist/root-write-verification.js +20 -0
  91. package/node_modules/@openclaw/fs-safe/dist/secure-temp-dir.js +19 -7
  92. package/node_modules/@openclaw/fs-safe/dist/sibling-staged-file.js +18 -3
  93. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-acquire.js +25 -3
  94. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-admission.d.ts +2 -0
  95. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-retained.d.ts +14 -0
  96. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-retained.js +187 -0
  97. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock.js +15 -1
  98. package/node_modules/@openclaw/fs-safe/dist/staged-file-settlement.js +4 -1
  99. package/node_modules/@openclaw/fs-safe/dist/temp-directory-diagnostics.d.ts +10 -0
  100. package/node_modules/@openclaw/fs-safe/dist/temp-directory-diagnostics.js +29 -0
  101. package/node_modules/@openclaw/fs-safe/dist/temp-target.js +1 -1
  102. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-admission.js +6 -6
  103. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-child-admission.d.ts +4 -4
  104. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-child-admission.js +17 -16
  105. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-descriptor.js +20 -28
  106. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-owner.d.ts +1 -0
  107. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-owner.js +27 -4
  108. package/node_modules/@openclaw/fs-safe/dist/walk.js +2 -13
  109. package/node_modules/@openclaw/fs-safe/dist/watch-native.d.ts +2 -2
  110. package/node_modules/@openclaw/fs-safe/dist/watch-native.js +3 -1
  111. package/node_modules/@openclaw/fs-safe/dist/watch-rescan.js +3 -9
  112. package/node_modules/@openclaw/fs-safe/dist/watch.js +2 -3
  113. package/node_modules/@openclaw/fs-safe/docs/advanced.md +1 -0
  114. package/node_modules/@openclaw/fs-safe/docs/archive.md +5 -1
  115. package/node_modules/@openclaw/fs-safe/docs/atomic.md +11 -3
  116. package/node_modules/@openclaw/fs-safe/docs/contributing.md +1 -1
  117. package/node_modules/@openclaw/fs-safe/docs/copy.md +109 -1
  118. package/node_modules/@openclaw/fs-safe/docs/durability.md +50 -5
  119. package/node_modules/@openclaw/fs-safe/docs/errors.md +37 -0
  120. package/node_modules/@openclaw/fs-safe/docs/guest.md +21 -4
  121. package/node_modules/@openclaw/fs-safe/docs/native-helper.md +5 -3
  122. package/node_modules/@openclaw/fs-safe/docs/native.md +39 -6
  123. package/node_modules/@openclaw/fs-safe/docs/path-scope.md +4 -0
  124. package/node_modules/@openclaw/fs-safe/docs/public-api.md +3 -1
  125. package/node_modules/@openclaw/fs-safe/docs/sidecar-lock.md +46 -8
  126. package/node_modules/@openclaw/fs-safe/docs/staged-file.md +10 -3
  127. package/node_modules/@openclaw/fs-safe/docs/temp.md +12 -0
  128. package/node_modules/@openclaw/fs-safe/docs/watch.md +6 -3
  129. package/node_modules/@openclaw/fs-safe/docs/writing.md +40 -11
  130. package/node_modules/@openclaw/fs-safe/package.json +16 -16
  131. package/node_modules/@openclaw/fs-safe-darwin-arm64/fs-safe-native.node +0 -0
  132. package/node_modules/@openclaw/fs-safe-darwin-arm64/package.json +1 -1
  133. package/node_modules/@openclaw/fs-safe-darwin-x64/fs-safe-native.node +0 -0
  134. package/node_modules/@openclaw/fs-safe-darwin-x64/package.json +1 -1
  135. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/fs-safe-native.node +0 -0
  136. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/package.json +1 -1
  137. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/fs-safe-native.node +0 -0
  138. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/package.json +1 -1
  139. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/fs-safe-native.node +0 -0
  140. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/package.json +1 -1
  141. package/node_modules/@openclaw/fs-safe-linux-x64-musl/fs-safe-native.node +0 -0
  142. package/node_modules/@openclaw/fs-safe-linux-x64-musl/package.json +1 -1
  143. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/fs-safe-native.node +0 -0
  144. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/package.json +1 -1
  145. package/node_modules/follow-redirects/index.js +10 -1
  146. package/node_modules/follow-redirects/package.json +1 -1
  147. package/package.json +5 -5
  148. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-arbitration.d.ts +0 -17
  149. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-arbitration.js +0 -66
  150. package/node_modules/@openclaw/fs-safe/dist/root-move-preflight.d.ts +0 -7
  151. package/node_modules/@openclaw/fs-safe/dist/root-move-preflight.js +0 -16
@@ -0,0 +1,195 @@
1
+ import fs, {} from "node:fs";
2
+ import path from "node:path";
3
+ import { normalizeMaxBytes } from "./byte-budget.js";
4
+ import { createCopyPathAdmissionCache } from "./copy-path-admission.js";
5
+ import { resolveCopyCloneMode } from "./copy-policy.js";
6
+ import { createFileWithAdmissionSync } from "./create.js";
7
+ import { ownFileDescriptorSync } from "./create-owned-file.js";
8
+ import { creationAdmissionFromParent, removeRecordedCreationFileSync } from "./creation-boundary.js";
9
+ import { FsSafeError } from "./errors.js";
10
+ import { assertExclusiveCreateLeaf } from "./exclusive-create.js";
11
+ import { copyFileDescriptorSync } from "./file-handle-transfer.js";
12
+ import { captureNativeFdClose } from "./native-binding.js";
13
+ import { getNativeBinding } from "./native.js";
14
+ import { openRootFileSync } from "./root-file.js";
15
+ import { inspectOpenedPathIdentitySync } from "./root-read-admission.js";
16
+ import { openStagedDirectory } from "./staged-directory.js";
17
+ import { inspectFileIdentitySync } from "./strict-file-identity.js";
18
+ function copyError(error) {
19
+ if (error instanceof FsSafeError)
20
+ return error;
21
+ const code = error?.code;
22
+ return new FsSafeError(code === "EEXIST" ? "already-exists" : code === "ENOENT" ? "not-found" :
23
+ code === "too-large" ? "too-large" :
24
+ ["ENOTSUP", "EOPNOTSUPP", "ENOSYS", "EXDEV", "EINVAL"].includes(code ?? "")
25
+ ? "unsupported-platform" : "helper-failed", "guarded synchronous file copy failed", { cause: error });
26
+ }
27
+ /** Exclusively copies an admitted source and transfers the owned destination fd. */
28
+ export function copyRootFileSync(options) {
29
+ return copyRootFileWithAdmissionSync(options, createCopyPathAdmissionCache());
30
+ }
31
+ /** Reuses directory admissions while retaining fresh checks for every copy. */
32
+ export function createRootFileCopyBatchSync() {
33
+ const cache = createCopyPathAdmissionCache();
34
+ let closed = false;
35
+ const close = () => { closed = true; cache.clear(); };
36
+ return Object.freeze({
37
+ copyFile(options) {
38
+ if (closed)
39
+ throw new FsSafeError("invalid-path", "copy batch is closed");
40
+ return copyRootFileWithAdmissionSync(options, cache);
41
+ },
42
+ close,
43
+ [Symbol.dispose]: close,
44
+ });
45
+ }
46
+ function copyRootFileWithAdmissionSync(options, cache) {
47
+ // Snapshot caller options before the first filesystem observation.
48
+ const sourceInput = options.source;
49
+ const sourcePath = { rootPath: sourceInput.rootPath, absolutePath: sourceInput.absolutePath };
50
+ const targetInput = options.destination;
51
+ const targetPath = { rootPath: targetInput.rootPath, absolutePath: targetInput.absolutePath };
52
+ const expectedInput = options.expectedSourceIdentity;
53
+ const expectedSourceIdentity = expectedInput === undefined ? undefined : { dev: expectedInput.dev, ino: expectedInput.ino };
54
+ const clone = resolveCopyCloneMode(options.clone, "never");
55
+ const maxBytes = normalizeMaxBytes(options.maxBytes);
56
+ const mode = options.mode;
57
+ const preserveSourceMode = options.preserveSourceMode;
58
+ const sourceHardlinks = options.sourceHardlinks ?? "reject";
59
+ if (mode !== undefined && (!Number.isInteger(mode) || mode < 0 || mode > 0o777)) {
60
+ throw new FsSafeError("invalid-path", "copy mode must be an integer from 0 to 0o777");
61
+ }
62
+ if (sourceHardlinks !== "allow" && sourceHardlinks !== "reject") {
63
+ throw new FsSafeError("invalid-path", "invalid copy source hardlink policy");
64
+ }
65
+ let sourceOwner;
66
+ let targetOwner;
67
+ let parentOwner;
68
+ let parentOpen = false;
69
+ let target;
70
+ let identity;
71
+ const native = getNativeBinding();
72
+ const nativeCopy = process.platform !== "win32" && native?.copyFileExclusiveSync && native.removeStagedFile
73
+ ? native.copyFileExclusiveSync.bind(native) : undefined;
74
+ try {
75
+ const source = cache.admit(sourcePath);
76
+ target = cache.admit(targetPath, true);
77
+ // Preserve exclusive-create collision semantics for dangling Windows leaves.
78
+ assertExclusiveCreateLeaf(targetPath.absolutePath);
79
+ if (fs.lstatSync(target.path, { throwIfNoEntry: false })) {
80
+ throw new FsSafeError("already-exists", "copy destination already exists");
81
+ }
82
+ const opened = openRootFileSync({
83
+ ...sourcePath, rootRealPath: source.rootCanonicalPath, boundaryLabel: "copy source", maxBytes,
84
+ rejectHardlinks: sourceHardlinks !== "allow",
85
+ });
86
+ if (!opened.ok)
87
+ throw opened.error ?? new FsSafeError("helper-failed", "copy source admission failed");
88
+ sourceOwner = ownFileDescriptorSync(opened.fd);
89
+ const sourceIdentity = inspectFileIdentitySync(() => fs.fstatSync(opened.fd, { bigint: true }), expectedSourceIdentity);
90
+ const verifySource = () => {
91
+ source.assertCurrent();
92
+ for (const inspect of [
93
+ () => fs.fstatSync(opened.fd, { bigint: true }),
94
+ () => inspectOpenedPathIdentitySync(source.path, undefined),
95
+ ]) {
96
+ const current = inspectFileIdentitySync(inspect, sourceIdentity);
97
+ if (!current.isFile())
98
+ throw new FsSafeError("not-file", "copy source must be a regular file");
99
+ if (sourceHardlinks !== "allow" && current.nlink > 1n) {
100
+ throw new FsSafeError("hardlink", "copy source must not be hardlinked");
101
+ }
102
+ }
103
+ };
104
+ const selectedMode = mode ?? (preserveSourceMode ? Number(sourceIdentity.mode & 511n) : 0o600 & ~process.umask());
105
+ let copied;
106
+ verifySource();
107
+ target.assertCurrent();
108
+ if (nativeCopy) {
109
+ const closeNative = captureNativeFdClose(native);
110
+ const parent = openStagedDirectory(target.parent.realPath);
111
+ parentOwner = ownFileDescriptorSync(parent.fd);
112
+ parentOpen = true;
113
+ inspectFileIdentitySync(() => fs.fstatSync(parent.fd, { bigint: true }), { dev: BigInt(target.parent.stat.dev), ino: BigInt(target.parent.stat.ino) });
114
+ target.assertCurrent();
115
+ copied = nativeCopy(opened.fd, parent.fd, path.basename(target.path), clone, maxBytes !== undefined && Number.isFinite(maxBytes) ? maxBytes : undefined);
116
+ targetOwner = ownFileDescriptorSync(copied.fd, closeNative);
117
+ }
118
+ else {
119
+ if (clone === "always")
120
+ throw new FsSafeError("unsupported-platform", "synchronous native file cloning is unavailable");
121
+ targetOwner = createFileWithAdmissionSync(target.path, { mode: 0o600, assertBeforeMutation: target.assertCurrent }, creationAdmissionFromParent(target.parent));
122
+ }
123
+ identity = inspectFileIdentitySync(() => fs.fstatSync(targetOwner.fd, { bigint: true }));
124
+ const verifyTarget = () => {
125
+ target.assertCurrent();
126
+ const current = inspectFileIdentitySync(() => fs.fstatSync(targetOwner.fd, { bigint: true }), identity);
127
+ const named = inspectFileIdentitySync(() => inspectOpenedPathIdentitySync(target.path, undefined), identity);
128
+ if (!current.isFile() || current.nlink !== 1n || !named.isFile() || named.nlink !== 1n) {
129
+ throw new FsSafeError("path-mismatch", "copy destination changed");
130
+ }
131
+ return current;
132
+ };
133
+ verifyTarget();
134
+ if (copied?.errorCode) {
135
+ throw copyError(Object.assign(new Error(copied.errorMessage), { code: copied.errorCode }));
136
+ }
137
+ const method = copied ? copied.method : "copy";
138
+ if (method !== "clone" && method !== "copy-file-range" && method !== "copy") {
139
+ throw new FsSafeError("helper-failed", "native copy returned an unknown method");
140
+ }
141
+ if (!copied) {
142
+ copyFileDescriptorSync(opened.fd, targetOwner.fd, { maxBytes });
143
+ }
144
+ verifySource();
145
+ const completed = verifyTarget();
146
+ if (maxBytes !== undefined && Number.isFinite(maxBytes) && completed.size > BigInt(maxBytes)) {
147
+ throw new FsSafeError("too-large", "copy exceeds maxBytes");
148
+ }
149
+ fs.fchmodSync(targetOwner.fd, selectedMode);
150
+ verifySource();
151
+ verifyTarget();
152
+ sourceOwner.close();
153
+ parentOpen = false;
154
+ parentOwner?.close();
155
+ return Object.freeze({
156
+ ...targetOwner, path: target.path, bytes: Number(completed.size), method,
157
+ identity: Object.freeze({ dev: identity.dev, ino: identity.ino }),
158
+ sourceIdentity: Object.freeze({ dev: sourceIdentity.dev, ino: sourceIdentity.ino }),
159
+ });
160
+ }
161
+ catch (error) {
162
+ const primary = copyError(error);
163
+ const cleanup = [];
164
+ if (targetOwner && target) {
165
+ try {
166
+ if (parentOpen) {
167
+ const removed = native.removeStagedFile(parentOwner.fd, path.basename(target.path), targetOwner.fd);
168
+ if (removed === "preserved")
169
+ throw new FsSafeError("path-mismatch", "copy cleanup preserved a replacement");
170
+ }
171
+ else if (identity) {
172
+ removeRecordedCreationFileSync(target.path, identity, target.assertCurrent);
173
+ }
174
+ }
175
+ catch (failure) {
176
+ cleanup.push(failure);
177
+ }
178
+ }
179
+ for (const owner of [targetOwner, sourceOwner, parentOwner]) {
180
+ try {
181
+ owner?.close();
182
+ }
183
+ catch (failure) {
184
+ cleanup.push(failure);
185
+ }
186
+ }
187
+ if (cleanup.length) {
188
+ throw new FsSafeError(primary.code, primary.message, {
189
+ cause: new AggregateError([primary, ...cleanup], "copy and cleanup failed"),
190
+ details: { path: target?.path, cleanup: "failed" },
191
+ });
192
+ }
193
+ throw primary;
194
+ }
195
+ }
@@ -4,6 +4,7 @@ import { type CreationPermissions, type CreationParentIdentity } from "./creatio
4
4
  export type { OwnedFileDescriptorSync } from "./create-owned-file.js";
5
5
  export type CreateFileOptions = CreateDirectoryOptions;
6
6
  export declare function createFileSync(targetPath: string, options?: CreateFileOptions): OwnedFileDescriptorSync;
7
+ export declare function createFileWithAdmissionSync(targetPath: string, options?: CreateFileOptions, admission?: CreationAdmission): OwnedFileDescriptorSync;
7
8
  /** Internal async writer; Windows preparation uses the nonblocking stage owner. */
8
9
  export declare function createFileHandle(targetPath: string, options?: CreateFileOptions, admission?: CreationAdmission): Promise<FileHandle>;
9
10
  export type CreateDirectoryOptions = CreationPermissions & {
@@ -108,9 +108,12 @@ function createPrivateWindowsFile(selected, options, mode) {
108
108
  }
109
109
  }
110
110
  export function createFileSync(targetPath, options = {}) {
111
+ return createFileWithAdmissionSync(targetPath, options);
112
+ }
113
+ export function createFileWithAdmissionSync(targetPath, options = {}, admission = {}) {
111
114
  const permissions = resolveCreationPermissions(options, false);
112
115
  const assertion = options.assertBeforeMutation;
113
- const selected = prepareCreationPath(targetPath);
116
+ const selected = prepareCreationPath(targetPath, admission.expectedParentIdentity);
114
117
  if (permissions.private && process.platform === "win32") {
115
118
  assertPrivateFileCreationAvailable();
116
119
  return createPrivateWindowsFile(selected, { ...permissions, assertBeforeMutation: assertion }, permissions.mode);
@@ -2,6 +2,7 @@ import fs, {} from "node:fs";
2
2
  import path from "node:path";
3
3
  import { assertDirectoryIdentitySync } from "./directory-guard.js";
4
4
  import { FsSafeError } from "./errors.js";
5
+ import { noReplaceUnavailable } from "./native-noreplace.js";
5
6
  import { assertSynchronousCallbackResult } from "./mutation-authority.js";
6
7
  import { captureNativeFdClose } from "./native-binding.js";
7
8
  import { requireNativeBinding } from "./native.js";
@@ -120,7 +121,8 @@ class Publication {
120
121
  }
121
122
  transition = native.outcome; // Capture BEFORE diagnostics, observations or close.
122
123
  if (native.errorCode || transition !== "committed") {
123
- throw Object.assign(new Error(native.errorMessage ?? "entry publication did not commit"), { code: native.errorCode ?? "helper-failed" });
124
+ const error = Object.assign(new Error(native.errorMessage ?? "entry publication did not commit"), { code: native.errorCode ?? "helper-failed" });
125
+ throw noReplaceUnavailable(error, "retained entry publication") ?? error;
124
126
  }
125
127
  phase = "postcheck";
126
128
  verification = "failed";
@@ -12,4 +12,6 @@ export declare class FsSafeError extends Error {
12
12
  details?: FsSafeErrorDetails;
13
13
  });
14
14
  }
15
+ /** A rejected no-replace rename capability, not a generic missing native helper. */
16
+ export declare function isNoReplaceUnsupported(error: unknown): error is FsSafeError;
15
17
  export {};
@@ -25,3 +25,8 @@ export class FsSafeError extends Error {
25
25
  this.details = options.details;
26
26
  }
27
27
  }
28
+ /** A rejected no-replace rename capability, not a generic missing native helper. */
29
+ export function isNoReplaceUnsupported(error) {
30
+ return error instanceof FsSafeError && error.code === "helper-unavailable" &&
31
+ error.details?.capability === "rename-noreplace";
32
+ }
@@ -1,3 +1,6 @@
1
1
  import type { FileLockSyncAcquireOptions, FileLockSyncHandle } from "./file-lock-sync.js";
2
2
  import type { Root } from "./root-impl.js";
3
+ import { type FileLockSyncRootPath } from "./file-lock-sync-root.js";
4
+ import { type FileLockSyncRootFileReceipt } from "./file-lock-sync-root-io.js";
5
+ export declare function cleanupCreatedRootSyncLock(lockRootPath: FileLockSyncRootPath, fd: number, receipt: FileLockSyncRootFileReceipt, timer?: NodeJS.Timeout): void;
3
6
  export declare function acquireFileLockSyncWithRoot<TPayload extends Record<string, unknown>>(targetPath: string, inputOptions: FileLockSyncAcquireOptions<TPayload>, lockRoot: Root): FileLockSyncHandle;
@@ -10,10 +10,40 @@ import { SyncLockAcquisition } from "./file-lock-sync-acquisition.js";
10
10
  import { assertSynchronousCallbackResult } from "./mutation-authority.js";
11
11
  import { assertNoWindowsPathAlias } from "./windows-path-alias.js";
12
12
  import { admitFileLockSyncRootPath, assertFileLockSyncRootPathsCurrent, captureFileLockSyncRootAuthority, normalizeFileLockSyncTargetWithRoot, } from "./file-lock-sync-root.js";
13
- import { cleanupCreatedRootSyncLock, FileLockSyncRootArbitrationCollision, tryReuseCurrentRootSyncHeldLock, } from "./file-lock-sync-root-arbitration.js";
14
13
  import { fileLockSyncRootSnapshotStillCurrent, } from "./file-lock-sync-root-io.js";
15
14
  import { createFileLockSyncRootDirectory, createFileLockSyncRootFile, fileLockSyncRootGuardExists, fileLockSyncRootDirectoryReceiptStillCurrent, refreshFileLockSyncRootFileReceipt, removeFileLockSyncRootDirectory, removeFileLockSyncRootFile, } from "./file-lock-sync-root-mutation.js";
16
- import { createRootSyncHeldLockHandle, ensureRootSyncExitCleanupRegistered, getRootSyncHeldLocks, readRootSidecarSnapshotSync, } from "./file-lock-sync-root-held.js";
15
+ import { createRootSyncHeldLockHandle, ensureRootSyncExitCleanupRegistered, getRootSyncHeldLocks, readRootSidecarSnapshotSync, verifyRootSyncHeldLock, } from "./file-lock-sync-root-held.js";
16
+ class FileLockSyncRootArbitrationCollision extends FsSafeError {
17
+ constructor() {
18
+ super("path-mismatch", "file lock arbitration changed during local creation");
19
+ }
20
+ }
21
+ export function cleanupCreatedRootSyncLock(lockRootPath, fd, receipt, timer) {
22
+ let timerCleanupFailed = false;
23
+ let timerCleanupError;
24
+ try {
25
+ if (timer)
26
+ clearInterval(timer);
27
+ }
28
+ catch (error) {
29
+ timerCleanupFailed = true;
30
+ timerCleanupError = error;
31
+ }
32
+ try {
33
+ fs.closeSync(fd);
34
+ if (!removeFileLockSyncRootFile(lockRootPath, receipt)) {
35
+ throw new FsSafeError("path-mismatch", "created sidecar lock changed before cleanup");
36
+ }
37
+ }
38
+ catch (fileCleanupError) {
39
+ if (timerCleanupFailed) {
40
+ throw createSuppressedError(timerCleanupError, fileCleanupError, "unpublished lock timer and file cleanup both failed");
41
+ }
42
+ throw fileCleanupError;
43
+ }
44
+ if (timerCleanupFailed)
45
+ throw timerCleanupError;
46
+ }
17
47
  export function acquireFileLockSyncWithRoot(targetPath, inputOptions, lockRoot) {
18
48
  // The public dispatcher already read lockRoot exactly once. Validate and
19
49
  // snapshot that genuine Root before any remaining option or retry getter can
@@ -37,23 +67,39 @@ export function acquireFileLockSyncWithRoot(targetPath, inputOptions, lockRoot)
37
67
  const heldLocks = getRootSyncHeldLocks();
38
68
  const currentTargetHolder = () => heldLocks.get(normalizedTargetPath) ??
39
69
  foreignSyncHeldLock("root", normalizedTargetPath);
40
- const arbitration = Object.freeze({
41
- authority,
42
- heldLocks,
43
- lockRootPath,
44
- normalizedTargetPath,
45
- reentrantOwner: options.reentrantOwner,
46
- });
70
+ const tryReuseCurrentHeld = () => {
71
+ const held = heldLocks.get(normalizedTargetPath);
72
+ const reusable = held && !foreignSyncHeldLock("root", normalizedTargetPath) &&
73
+ options.reentrantOwner !== undefined && held.reentrantOwner !== undefined &&
74
+ options.reentrantOwner === held.reentrantOwner &&
75
+ authority.adapter === held.rootAuthority.adapter &&
76
+ lockRootPath.relativePath === held.rootPath.relativePath &&
77
+ path.relative(lockRootPath.path, held.rootPath.path) === "" &&
78
+ held.releaseState !== "released";
79
+ if (!reusable)
80
+ return undefined;
81
+ if (!verifyRootSyncHeldLock(held)) {
82
+ throw new FsSafeError("path-mismatch", "held sidecar lock changed before reentrant reuse");
83
+ }
84
+ // The parser can reenter acquisition; recheck the exact held entry before reuse.
85
+ if (heldLocks.get(normalizedTargetPath) !== held || held.releaseState === "released" ||
86
+ foreignSyncHeldLock("root", normalizedTargetPath)) {
87
+ throw new FsSafeError("path-mismatch", "held sidecar lock changed during reentrant reuse");
88
+ }
89
+ held.refCount += 1;
90
+ held.revision += 1;
91
+ return createRootSyncHeldLockHandle(held);
92
+ };
47
93
  if (heldLocks.has(normalizedTargetPath) && !foreignSyncHeldLock("root", normalizedTargetPath)) {
48
94
  assertFileLockSyncRootPathsCurrent(guardedPaths);
49
- const initiallyReusable = tryReuseCurrentRootSyncHeldLock(arbitration);
95
+ const initiallyReusable = tryReuseCurrentHeld();
50
96
  if (initiallyReusable)
51
97
  return initiallyReusable;
52
98
  }
53
99
  const acquisition = new SyncLockAcquisition(lockPath, normalizedTargetPath, options.retry, options.timeoutMs);
54
100
  let ownedReclaimGuard;
55
101
  let reclaimCleanupAttempted = false;
56
- const reuseCurrentHeld = () => ownedReclaimGuard ? undefined : tryReuseCurrentRootSyncHeldLock(arbitration);
102
+ const reuseCurrentHeld = () => ownedReclaimGuard ? undefined : tryReuseCurrentHeld();
57
103
  const releaseReclaimGuard = () => {
58
104
  const receipt = ownedReclaimGuard;
59
105
  if (!receipt)
@@ -1,16 +1,16 @@
1
1
  import fsSync, {} from "node:fs";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { assertAsyncDirectoryGuard, assertSyncDirectoryGuard, createAsyncDirectoryGuard, createSyncDirectoryGuard, } from "./directory-guard.js";
4
+ import { assertDirectoryGuard, assertSyncDirectoryGuard, createAsyncDirectoryGuard, createSyncDirectoryGuard, } from "./directory-guard.js";
5
5
  export async function withAsyncDirectoryGuards(guards, mutate, options = {}) {
6
6
  for (const guard of guards) {
7
- await assertAsyncDirectoryGuard(guard);
7
+ assertDirectoryGuard(guard, "native");
8
8
  }
9
9
  const result = await mutate();
10
10
  if (options.verifyAfter !== false) {
11
11
  try {
12
12
  for (const guard of guards) {
13
- await assertAsyncDirectoryGuard(guard);
13
+ assertDirectoryGuard(guard, "native");
14
14
  }
15
15
  }
16
16
  catch (error) {
@@ -46,11 +46,11 @@ export async function guardedRename(params) {
46
46
  const sourceGuard = await createAsyncDirectoryGuard(path.dirname(params.from));
47
47
  const targetGuard = await createAsyncDirectoryGuard(path.dirname(params.to));
48
48
  await withAsyncDirectoryGuards([sourceGuard, targetGuard], async () => {
49
+ // Authority must survive all awaited guards; do not yield before rename dispatch.
50
+ params.assertBeforeRename?.();
49
51
  if (params.onSourceInspected) {
50
52
  params.onSourceInspected(fsSync.lstatSync(params.from, { bigint: true }));
51
53
  }
52
- // Authority must survive all awaited guards; do not yield before rename dispatch.
53
- params.assertBeforeRename?.();
54
54
  await fs.rename(params.from, params.to);
55
55
  params.onRenamed?.();
56
56
  });
@@ -32,6 +32,16 @@ export const GUEST_FILESYSTEM_CREATE_STAGING_PYTHON = [
32
32
  ].join("\n");
33
33
  export const GUEST_FILESYSTEM_RENAME_NO_REPLACE_PYTHON = [
34
34
  "def rename_no_replace(src_parent_fd, src_basename, dst_parent_fd, dst_basename):",
35
+ " import stat",
36
+ " source = os.lstat(src_basename, dir_fd=src_parent_fd)",
37
+ " kind = stat.S_IFMT(source.st_mode)",
38
+ " expected = (source.st_dev, source.st_ino, kind)",
39
+ " def verify(parent_fd, basename, links):",
40
+ " current = os.lstat(basename, dir_fd=parent_fd)",
41
+ " if (current.st_dev, current.st_ino, stat.S_IFMT(current.st_mode)) != expected:",
42
+ " raise OSError(errno.ESTALE, 'no-replace publication identity changed', basename)",
43
+ " if kind == stat.S_IFREG and current.st_nlink != links:",
44
+ " raise OSError(errno.ESTALE, 'no-replace publication link count changed', basename)",
35
45
  " libc = ctypes.CDLL(None, use_errno=True)",
36
46
  " is_linux = sys.platform.startswith('linux')",
37
47
  " if is_linux:",
@@ -62,6 +72,31 @@ export const GUEST_FILESYSTEM_RENAME_NO_REPLACE_PYTHON = [
62
72
  " raise OSError(error_code, os.strerror(error_code), dst_basename)",
63
73
  " elif not is_linux:",
64
74
  " raise OSError(errno.ENOSYS, 'atomic no-replace rename is unavailable')",
75
+ " # Only a definitive rejection of the fixed flags reaches this fallback.",
76
+ " if kind not in (stat.S_IFDIR, stat.S_IFREG):",
77
+ " raise OSError(errno.EINVAL, 'no-replace fallback requires a file or directory', src_basename)",
78
+ " verify(src_parent_fd, src_basename, 1)",
79
+ " try:",
80
+ " os.lstat(dst_basename, dir_fd=dst_parent_fd)",
81
+ " except FileNotFoundError:",
82
+ " pass",
83
+ " else:",
84
+ " raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), dst_basename)",
85
+ " if kind == stat.S_IFDIR:",
86
+ " verify(src_parent_fd, src_basename, 1)",
87
+ " # A directory rename can replace only an EMPTY directory raced into",
88
+ " # the absent target. Non-empty directories and files are refused.",
89
+ " # The slash enforces source directory type at the syscall, even if",
90
+ " # a peer substitutes a file/symlink after verification. Identity",
91
+ " # checks are not compare-and-swap; verify publication afterward.",
92
+ " try:",
93
+ " os.rename(src_basename + '/', dst_basename, src_dir_fd=src_parent_fd, dst_dir_fd=dst_parent_fd)",
94
+ " except OSError as error:",
95
+ " if error.errno in (errno.ENOTEMPTY, errno.ENOTDIR, errno.EEXIST):",
96
+ " raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), dst_basename) from error",
97
+ " raise",
98
+ " verify(dst_parent_fd, dst_basename, 1)",
99
+ " return",
65
100
  " os.link(",
66
101
  " src_basename,",
67
102
  " dst_basename,",
@@ -69,12 +104,19 @@ export const GUEST_FILESYSTEM_RENAME_NO_REPLACE_PYTHON = [
69
104
  " dst_dir_fd=dst_parent_fd,",
70
105
  " follow_symlinks=False,",
71
106
  " )",
107
+ " # Only this exact two-name interval permits nlink=2. Never roll back the",
108
+ " # target on failure: it may be the only remaining link to the source.",
109
+ " verify(dst_parent_fd, dst_basename, 2)",
110
+ " verify(src_parent_fd, src_basename, 2)",
111
+ " os.unlink(src_basename, dir_fd=src_parent_fd)",
112
+ " verify(dst_parent_fd, dst_basename, 1)",
72
113
  ].join("\n");
73
114
  export const GUEST_FILESYSTEM_CREATE_EXCLUSIVE_PYTHON = [
74
115
  "def create_exclusive(parent_fd, basename, stdin_buffer):",
75
116
  " staging_fd = None",
76
117
  " staging_name = None",
77
118
  " temp_fd = None",
119
+ " temp_inode = None",
78
120
  " temp_name = 'payload'",
79
121
  " try:",
80
122
  " try:",
@@ -85,6 +127,7 @@ export const GUEST_FILESYSTEM_CREATE_EXCLUSIVE_PYTHON = [
85
127
  " raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), basename)",
86
128
  " staging_name, staging_fd = create_staging_dir(parent_fd)",
87
129
  " temp_fd = os.open(temp_name, WRITE_FLAGS, 0o600, dir_fd=staging_fd)",
130
+ " temp_inode = inode_identity(os.fstat(temp_fd))",
88
131
  " while True:",
89
132
  " chunk = stdin_buffer.read(65536)",
90
133
  " if not chunk:",
@@ -92,8 +135,7 @@ export const GUEST_FILESYSTEM_CREATE_EXCLUSIVE_PYTHON = [
92
135
  " write_all(temp_fd, chunk)",
93
136
  " # exclusive create payload is durable before publication",
94
137
  " os.fsync(temp_fd)",
95
- " temp_inode = inode_identity(os.fstat(temp_fd))",
96
- " # Publish with a native atomic no-replace rename.",
138
+ " # Publish with no-replace rename or the checked file fallback.",
97
139
  " rename_no_replace(staging_fd, temp_name, parent_fd, basename)",
98
140
  " target_stat = os.lstat(basename, dir_fd=parent_fd)",
99
141
  " if temp_inode != inode_identity(target_stat):",
@@ -105,14 +147,19 @@ export const GUEST_FILESYSTEM_CREATE_EXCLUSIVE_PYTHON = [
105
147
  " if staging_fd is not None:",
106
148
  " # Cleanup stays relative to the private pinned directory, so a",
107
149
  " # parent-path substitution cannot redirect payload deletion.",
150
+ " payload_removed = False",
108
151
  " try:",
109
- " os.unlink(temp_name, dir_fd=staging_fd)",
152
+ " current_payload = os.lstat(temp_name, dir_fd=staging_fd)",
153
+ " # Preserve ambiguous or partially published link pairs.",
154
+ " if temp_inode == inode_identity(current_payload) and current_payload.st_nlink == 1:",
155
+ " os.unlink(temp_name, dir_fd=staging_fd)",
156
+ " payload_removed = True",
110
157
  " except FileNotFoundError:",
111
- " pass",
158
+ " payload_removed = True",
112
159
  " staging_identity = entry_identity(os.fstat(staging_fd))",
113
160
  " os.close(staging_fd)",
114
161
  " staging_removed = False",
115
- " if staging_name is not None:",
162
+ " if staging_name is not None and payload_removed:",
116
163
  " try:",
117
164
  " current_staging = os.lstat(staging_name, dir_fd=parent_fd)",
118
165
  " if same_identity(staging_identity, current_staging):",
@@ -395,7 +395,7 @@ export const GUEST_FILESYSTEM_PYTHON = [
395
395
  " break",
396
396
  " write_all(temp_fd, chunk)",
397
397
  " try:",
398
- " os.fchmod(temp_fd, stat.S_IMODE(src_stat.st_mode))",
398
+ " os.fchmod(temp_fd, stat.S_IMODE(src_file_stat.st_mode))",
399
399
  " except AttributeError:",
400
400
  " pass",
401
401
  " os.fsync(temp_fd)",
@@ -1,4 +1,4 @@
1
- export { FsSafeError, categorizeFsSafeError, } from "./errors.js";
1
+ export { FsSafeError, categorizeFsSafeError, isNoReplaceUnsupported, } from "./errors.js";
2
2
  export type * from "./errors.js";
3
3
  export { DEFAULT_ROOT_MAX_BYTES, root, type Root, } from "./root.js";
4
4
  export type * from "./root-public-types.js";
@@ -1,4 +1,4 @@
1
- export { FsSafeError, categorizeFsSafeError, } from "./errors.js";
1
+ export { FsSafeError, categorizeFsSafeError, isNoReplaceUnsupported, } from "./errors.js";
2
2
  export { DEFAULT_ROOT_MAX_BYTES, root, } from "./root.js";
3
3
  export { configureFsSafeNative, getFsSafeNativeConfig, } from "./native-config.js";
4
4
  export { writeExternalFileWithinRoot, } from "./output.js";
@@ -139,6 +139,7 @@ export interface NativeBinding {
139
139
  renameReplaceWithIdentity?(sourceParent: number, source: string, targetParent: number, target: string, dev: bigint, ino: bigint): void;
140
140
  /** Windows-only, private handle custody; no borrowed/runtime descriptors. */
141
141
  retainWindowsFile?(directory: string, basename: string, parentDev: bigint, parentIno: bigint, dev: bigint, ino: bigint, size: bigint, mtimeNs: bigint, ctimeNs: bigint, sha256: string, maxBytes: number): NativeRetainedFile;
142
+ retainWindowsSidecar?(parentFd: number, directory: string, basename: string, parentDev: bigint, parentIno: bigint, dev: bigint, ino: bigint, size: bigint, sha256: string, maxBytes: number): NativeRetainedFile;
142
143
  watchRegister?(root: string, limit: number, callback: (batch: import("./watch-native.js").NativeWatchWireBatch) => void, persistent: boolean): number;
143
144
  watchConfigure?(id: number, anchors: string[], exclusions: string[]): void;
144
145
  watchEntries?(id: number, entries: import("./watch-native.js").NativeWatchEntry[]): {
@@ -203,6 +204,7 @@ export interface NativeBinding {
203
204
  stagedFileMatches?(parentFd: number, basename: string, fileFd: number): boolean;
204
205
  removeStagedFile?(parentFd: number, basename: string, fileFd: number): "removed" | "name-absent" | "preserved";
205
206
  copyFileExclusive?(sourceFd: number, parentFd: number, basename: string, clone: CopyCloneMode, maxBytes: number | undefined, signal: AbortSignal | undefined): Promise<NativeFileCopyResult>;
207
+ copyFileExclusiveSync?(sourceFd: number, parentFd: number, basename: string, clone: CopyCloneMode, maxBytes: number | undefined): NativeFileCopyResult;
206
208
  cloneFileExclusive(sourceFd: number, targetRootFd: number, targetRelPath: string): number;
207
209
  copyFileRangeExclusive(sourceFd: number, targetRootFd: number, targetRelPath: string): Promise<NativeCopyResult>;
208
210
  createPrivateDirectory(path: string): void;
@@ -235,6 +237,8 @@ export interface NativeBinding {
235
237
  entryPublicationFilesystem?(parentFd: number): string;
236
238
  publishRetainedEntryNoReplace?(sourceParentFd: number, sourceBasename: string, sourceFd: number, targetParentFd: number, targetBasename: string): NativePublicationTransition;
237
239
  renameNoReplace(...args: NativeTwoPathArgs): void;
240
+ /** Linux auto-mode fallback through already-admitted direct-child parents. */
241
+ moveNoReplaceFallback?(...args: [...paths: NativeTwoPathArgs, expectedSourceDev: bigint, expectedSourceIno: bigint]): void;
238
242
  /** Identity-fenced retained-directory rename capability. */
239
243
  renameNoReplaceWithIdentity?(...args: [...paths: NativeTwoPathArgs, expectedSourceDev: bigint, expectedSourceIno: bigint]): void;
240
244
  renameReplace(...args: NativeTwoPathArgs): void;
@@ -0,0 +1,3 @@
1
+ import type { BigIntStats } from "node:fs";
2
+ import type { NativeBinding } from "./native-binding.js";
3
+ export declare function nativeMoveNoReplace(binding: NativeBinding, paths: Parameters<NativeBinding["renameNoReplace"]>, expected: BigIntStats | undefined, allowFallback: boolean, operation?: string): "link-unlink" | undefined;
@@ -0,0 +1,54 @@
1
+ import { FsSafeError } from "./errors.js";
2
+ import { cachedNoReplaceUnavailable, noReplaceUnavailable, rememberNoReplaceUnavailable, } from "./native-noreplace.js";
3
+ function fallbackError(error, operation) {
4
+ const code = error?.code;
5
+ const message = error instanceof Error ? error.message : "native no-replace move fallback failed";
6
+ if (code === "EEXIST") {
7
+ return new FsSafeError("already-exists", "no-replace fallback destination exists", { cause: error });
8
+ }
9
+ if (code === "FS_SAFE_INTERNAL_MOVE_LINK_UNSUPPORTED") {
10
+ return new FsSafeError("helper-unavailable", message, { cause: error,
11
+ details: { capability: "rename-noreplace", fallback: "link-unlink", fallbackCapability: "linkat" } });
12
+ }
13
+ const sourceRemoval = new Map([
14
+ ["FS_SAFE_INTERNAL_MOVE_LINK_CHANGED", "not-attempted"],
15
+ ["FS_SAFE_INTERNAL_MOVE_SOURCE_LINKED", "still-linked"],
16
+ ["FS_SAFE_INTERNAL_MOVE_UNLINK_UNVERIFIED", "unverified"],
17
+ ["FS_SAFE_INTERNAL_MOVE_PUBLISHED", "removed"],
18
+ ]).get(code ?? "");
19
+ if (sourceRemoval) {
20
+ return new FsSafeError(code === "FS_SAFE_INTERNAL_MOVE_LINK_CHANGED" ? "path-mismatch" : "helper-failed", message, { cause: error, details: { operation, fallback: "link-unlink",
21
+ publication: "published", sourceRemoval } });
22
+ }
23
+ // Keep identity errors available to the caller's normalizer.
24
+ return error;
25
+ }
26
+ export function nativeMoveNoReplace(binding, paths, expected, allowFallback, operation = "move") {
27
+ const [sourceFd, source, targetFd, target] = paths;
28
+ let unavailable = cachedNoReplaceUnavailable(binding, sourceFd, operation);
29
+ if (!unavailable) {
30
+ try {
31
+ binding.renameNoReplace(...paths);
32
+ return;
33
+ }
34
+ catch (error) {
35
+ unavailable = noReplaceUnavailable(error, operation, true);
36
+ if (!unavailable)
37
+ throw error;
38
+ // As in sibling publication/quarantine, distinct sibling names cannot
39
+ // have a directory-ancestry EINVAL. Cross-parent moves must not cache it.
40
+ if (sourceFd === targetFd && source !== target) {
41
+ rememberNoReplaceUnavailable(binding, sourceFd, unavailable);
42
+ }
43
+ }
44
+ }
45
+ if (!allowFallback || process.platform !== "linux" || !binding.moveNoReplaceFallback || !expected)
46
+ throw unavailable;
47
+ try {
48
+ binding.moveNoReplaceFallback(...paths, expected.dev, expected.ino);
49
+ return expected.isFile() ? "link-unlink" : undefined;
50
+ }
51
+ catch (error) {
52
+ throw fallbackError(error, operation);
53
+ }
54
+ }
@@ -0,0 +1,8 @@
1
+ import { FsSafeError } from "./errors.js";
2
+ import type { NativeBinding } from "./native-binding.js";
3
+ export declare const NATIVE_NOREPLACE_UNSUPPORTED = "FS_SAFE_INTERNAL_RENAME_NOREPLACE_UNSUPPORTED";
4
+ export declare function isNoReplaceUnavailable(error: unknown): error is FsSafeError;
5
+ export declare function noReplaceUnavailable(error: unknown, operation: string, syscallOnly?: boolean): FsSafeError | undefined;
6
+ export declare function rememberNoReplaceUnavailable(binding: NativeBinding, parentFd: number, error: FsSafeError): void;
7
+ export declare function cachedNoReplaceUnavailable(binding: NativeBinding, parentFd: number, operation?: string): FsSafeError | undefined;
8
+ export declare function cachedNoReplaceDevice(binding: NativeBinding, device: bigint, operation: string): FsSafeError | undefined;