@openclaw/matrix 2026.11.6 → 2026.11.8

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 (168) hide show
  1. package/dist/.setup/{approval-handler.runtime-CshxBDs7.mjs → approval-handler.runtime-CKiMSdnX.mjs} +3 -3
  2. package/dist/.setup/{channel-OLndtGNE.mjs → channel-CZJeLUuu.mjs} +8 -8
  3. package/dist/.setup/{channel.runtime-CFSou_MS.mjs → channel.runtime-hpiGNile.mjs} +5 -5
  4. package/dist/.setup/{channel.setup-CqcEb6JR.mjs → channel.setup-Dc4G7kdF.mjs} +6 -2
  5. package/dist/.setup/{cli-CkMedN4Y.mjs → cli-DnLr6VVE.mjs} +8 -8
  6. package/dist/.setup/{cli-doctor-BVstkgJE.mjs → cli-doctor-DRM-8rZg.mjs} +1 -1
  7. package/dist/.setup/{cli-metadata-DN1E7yCf.mjs → cli-metadata-C9wZ_TOY.mjs} +1 -1
  8. package/dist/.setup/{client-Bk_tBqNp.mjs → client-CnPiPhTg.mjs} +4 -4
  9. package/dist/.setup/{client-Rlwtz1hG.mjs → client-CsgjDjyA.mjs} +2 -2
  10. package/dist/.setup/{client-bootstrap-Bhhri97J.mjs → client-bootstrap-CRN75TtW.mjs} +1 -1
  11. package/dist/.setup/{create-client-CzUtZgYF.mjs → create-client-C5bd0RUQ.mjs} +4 -4
  12. package/dist/.setup/{credentials-kT20jk_u.mjs → credentials-Byq2Kcqg.mjs} +1 -1
  13. package/dist/.setup/{crypto-runtime-BI9Pc344.mjs → crypto-runtime-EdW32JgS.mjs} +2 -2
  14. package/dist/.setup/{crypto-state-store-BZLlwkv_.mjs → crypto-state-store-m13QToc7.mjs} +2 -1
  15. package/dist/.setup/{crypto-store-ownership-CiQ1l_O7.mjs → crypto-store-ownership-CVeppnSH.mjs} +1 -1
  16. package/dist/.setup/{crypto-unsafe-state-doctor-CmF1X1dZ.mjs → crypto-unsafe-state-doctor-C_vhqxOm.mjs} +3 -3
  17. package/dist/.setup/{directory-live-DmkH9hcp.mjs → directory-live-Brv_PC6z.mjs} +1 -1
  18. package/dist/.setup/{draft-stream-DbTsJkoL.mjs → draft-stream-BAf9CYmE.mjs} +1 -1
  19. package/dist/.setup/{exec-approvals-CiGrN-cV.mjs → exec-approvals-ClD4sAHY.mjs} +2 -2
  20. package/dist/.setup/{file-sync-store-BpS12yaK.mjs → file-sync-store-Dilb8bVT.mjs} +2 -2
  21. package/dist/.setup/{idb-persistence-BTOsltD9.mjs → idb-persistence-COLTtrm_.mjs} +2 -2
  22. package/dist/.setup/{messages-DJDczJnC.mjs → messages-zsGFORuZ.mjs} +2 -2
  23. package/dist/.setup/{monitor-ZDbuZRVB.mjs → monitor-CdT6CsWk.mjs} +32 -18
  24. package/dist/.setup/{onboarding-DwhMV1fp.mjs → onboarding-FJiJ-X6s.mjs} +3 -3
  25. package/dist/.setup/{outbound-7iSmOloX.mjs → outbound-yjH1XHCr.mjs} +2 -2
  26. package/dist/.setup/{profile-update-Fu4u-aSC.mjs → profile-update-uRiRQTtX.mjs} +9 -4
  27. package/dist/.setup/{reaction-events-CBltCP52.mjs → reaction-events-DYJrx8eq.mjs} +3 -3
  28. package/dist/.setup/{resolve-targets-CWW9zTYp.mjs → resolve-targets-DwRQnBpN.mjs} +1 -1
  29. package/dist/.setup/{retired-state-JGUEBE72.mjs → retired-state-DohpBmxW.mjs} +1 -37
  30. package/dist/.setup/{room-info-DFDDmkBC.mjs → room-info-B6-Yo6I5.mjs} +3 -3
  31. package/dist/.setup/{sdk-ByFgA6Il.mjs → sdk-CPgBCtd2.mjs} +5 -5
  32. package/dist/.setup/{send-DiS4anyi.mjs → send-CCT72yQb.mjs} +7 -7
  33. package/dist/.setup/{setup-bootstrap-OfuocnF0.mjs → setup-bootstrap-CB0idLzk.mjs} +2 -2
  34. package/dist/.setup/{setup-core-CEQJRnym.mjs → setup-core-5sswwYZt.mjs} +1 -1
  35. package/dist/.setup/setup-plugin-api-BU7RNSl9.mjs +2 -0
  36. package/dist/.setup/sqlite-state-7WEloajv.mjs +37 -0
  37. package/dist/.setup/{startup-verification-UkaoSldm.mjs → startup-verification-zrBugJBv.mjs} +3 -2
  38. package/dist/.setup/{storage-C3N6YZIn.mjs → storage-BjNHtYwT.mjs} +4 -3
  39. package/dist/.setup/{sync-cache-state-BKVaKRzQ.mjs → sync-cache-state-CovS1oSw.mjs} +2 -1
  40. package/dist/.setup/{thread-bindings-BvoisBZE.mjs → thread-bindings-DZvpe83d.mjs} +4 -3
  41. package/dist/.setup/{tool-actions-TYBYDIkj.mjs → tool-actions-Dd8WTKXA.mjs} +10 -10
  42. package/dist/.setup/{verification-BhFA9xF6.mjs → verification-BKVxSiIq.mjs} +1 -1
  43. package/dist/.source-module-urls/1cd4d4ff8d44e1c8b830932b44d7cf8a7f3350e09e169910e1d7a85e131b7bea.json +1 -1
  44. package/dist/api.js +4 -4
  45. package/dist/channel-plugin-api.js +1 -1
  46. package/dist/cli-metadata.js +1 -1
  47. package/dist/contract-api.js +2 -2
  48. package/dist/doctor-contract-api.js +6 -5
  49. package/dist/index.js +1 -1
  50. package/dist/plugin-entry.handlers.runtime.js +2 -2
  51. package/dist/session-binding-contract-api.js +1 -1
  52. package/dist/setup-entry.js +1 -1
  53. package/dist/setup-plugin-api.js +1 -1
  54. package/node_modules/@openclaw/fs-safe/CHANGELOG.md +45 -1
  55. package/node_modules/@openclaw/fs-safe/README.md +4 -0
  56. package/node_modules/@openclaw/fs-safe/dist/absolute-path.js +2 -2
  57. package/node_modules/@openclaw/fs-safe/dist/advanced.d.ts +2 -2
  58. package/node_modules/@openclaw/fs-safe/dist/advanced.js +2 -2
  59. package/node_modules/@openclaw/fs-safe/dist/archive-parser.wasm +0 -0
  60. package/node_modules/@openclaw/fs-safe/dist/atomic-io.d.ts +1 -0
  61. package/node_modules/@openclaw/fs-safe/dist/atomic-io.js +6 -0
  62. package/node_modules/@openclaw/fs-safe/dist/atomic.d.ts +1 -0
  63. package/node_modules/@openclaw/fs-safe/dist/directory-mode-node.d.ts +5 -0
  64. package/node_modules/@openclaw/fs-safe/dist/directory-mode-node.js +13 -0
  65. package/node_modules/@openclaw/fs-safe/dist/directory-mode-options.d.ts +3 -0
  66. package/node_modules/@openclaw/fs-safe/dist/directory-mode-options.js +6 -0
  67. package/node_modules/@openclaw/fs-safe/dist/errors.d.ts +1 -1
  68. package/node_modules/@openclaw/fs-safe/dist/errors.js +1 -0
  69. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-admission.d.ts +0 -1
  70. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-admission.js +1 -11
  71. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-root-acquire.js +3 -3
  72. package/node_modules/@openclaw/fs-safe/dist/file-lock-sync-stale-admission.js +2 -3
  73. package/node_modules/@openclaw/fs-safe/dist/file-store-boundary.d.ts +3 -3
  74. package/node_modules/@openclaw/fs-safe/dist/file-store-boundary.js +30 -4
  75. package/node_modules/@openclaw/fs-safe/dist/file-store-prune.d.ts +1 -1
  76. package/node_modules/@openclaw/fs-safe/dist/file-store-prune.js +7 -1
  77. package/node_modules/@openclaw/fs-safe/dist/file-store-sync-directory.d.ts +1 -1
  78. package/node_modules/@openclaw/fs-safe/dist/file-store-sync-directory.js +30 -4
  79. package/node_modules/@openclaw/fs-safe/dist/file-store-sync-write.d.ts +1 -1
  80. package/node_modules/@openclaw/fs-safe/dist/file-store-sync-write.js +2 -0
  81. package/node_modules/@openclaw/fs-safe/dist/file-store.d.ts +2 -1
  82. package/node_modules/@openclaw/fs-safe/dist/file-store.js +5 -0
  83. package/node_modules/@openclaw/fs-safe/dist/guarded-mkdir.d.ts +2 -0
  84. package/node_modules/@openclaw/fs-safe/dist/guarded-mkdir.js +9 -0
  85. package/node_modules/@openclaw/fs-safe/dist/json-store.d.ts +2 -1
  86. package/node_modules/@openclaw/fs-safe/dist/native-binding.d.ts +4 -1
  87. package/node_modules/@openclaw/fs-safe/dist/native-pinned-write.js +1 -1
  88. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.d.ts +1 -1
  89. package/node_modules/@openclaw/fs-safe/dist/native-staged-file.js +19 -13
  90. package/node_modules/@openclaw/fs-safe/dist/overwrite-file-handle.d.ts +2 -0
  91. package/node_modules/@openclaw/fs-safe/dist/overwrite-file-handle.js +27 -5
  92. package/node_modules/@openclaw/fs-safe/dist/path-prefix.d.ts +1 -0
  93. package/node_modules/@openclaw/fs-safe/dist/path-prefix.js +84 -7
  94. package/node_modules/@openclaw/fs-safe/dist/pinned-write-input.js +0 -11
  95. package/node_modules/@openclaw/fs-safe/dist/prepare-directory-mode.d.ts +9 -0
  96. package/node_modules/@openclaw/fs-safe/dist/prepare-directory-mode.js +61 -0
  97. package/node_modules/@openclaw/fs-safe/dist/private-temp-workspace.js +2 -1
  98. package/node_modules/@openclaw/fs-safe/dist/realpath.d.ts +2 -0
  99. package/node_modules/@openclaw/fs-safe/dist/realpath.js +16 -0
  100. package/node_modules/@openclaw/fs-safe/dist/replace-file-descriptor.d.ts +2 -1
  101. package/node_modules/@openclaw/fs-safe/dist/replace-file-descriptor.js +8 -6
  102. package/node_modules/@openclaw/fs-safe/dist/replace-file-types.d.ts +2 -1
  103. package/node_modules/@openclaw/fs-safe/dist/replace-file.js +20 -13
  104. package/node_modules/@openclaw/fs-safe/dist/root-context.js +4 -1
  105. package/node_modules/@openclaw/fs-safe/dist/root-create-native.d.ts +1 -1
  106. package/node_modules/@openclaw/fs-safe/dist/root-create-native.js +18 -9
  107. package/node_modules/@openclaw/fs-safe/dist/root-errors.d.ts +2 -0
  108. package/node_modules/@openclaw/fs-safe/dist/root-errors.js +9 -0
  109. package/node_modules/@openclaw/fs-safe/dist/root-impl.js +4 -1
  110. package/node_modules/@openclaw/fs-safe/dist/root-mkdir-native.d.ts +1 -1
  111. package/node_modules/@openclaw/fs-safe/dist/root-mkdir-native.js +35 -16
  112. package/node_modules/@openclaw/fs-safe/dist/root-path-existing.d.ts +6 -2
  113. package/node_modules/@openclaw/fs-safe/dist/root-path-existing.js +32 -20
  114. package/node_modules/@openclaw/fs-safe/dist/root-path.js +32 -26
  115. package/node_modules/@openclaw/fs-safe/dist/root-write-admission.js +4 -1
  116. package/node_modules/@openclaw/fs-safe/dist/secret-file.d.ts +2 -1
  117. package/node_modules/@openclaw/fs-safe/dist/secret-file.js +2 -0
  118. package/node_modules/@openclaw/fs-safe/dist/sibling-temp.d.ts +2 -1
  119. package/node_modules/@openclaw/fs-safe/dist/sibling-temp.js +5 -4
  120. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-policy.d.ts +3 -2
  121. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-policy.js +8 -9
  122. package/node_modules/@openclaw/fs-safe/dist/sidecar-lock-stale-admission.js +3 -1
  123. package/node_modules/@openclaw/fs-safe/dist/temp-workspace-types.d.ts +2 -1
  124. package/node_modules/@openclaw/fs-safe/dist/text-atomic.d.ts +2 -1
  125. package/node_modules/@openclaw/fs-safe/dist/types.d.ts +1 -0
  126. package/node_modules/@openclaw/fs-safe/dist/watch-hints.js +12 -3
  127. package/node_modules/@openclaw/fs-safe/dist/windows-security-helper.exe +0 -0
  128. package/node_modules/@openclaw/fs-safe/dist/write-file-handle.d.ts +0 -1
  129. package/node_modules/@openclaw/fs-safe/dist/write-file-handle.js +10 -12
  130. package/node_modules/@openclaw/fs-safe/docs/advanced.md +3 -3
  131. package/node_modules/@openclaw/fs-safe/docs/atomic.md +16 -3
  132. package/node_modules/@openclaw/fs-safe/docs/compiler-qualification.md +1 -1
  133. package/node_modules/@openclaw/fs-safe/docs/contributing.md +27 -18
  134. package/node_modules/@openclaw/fs-safe/docs/errors.md +3 -1
  135. package/node_modules/@openclaw/fs-safe/docs/file-store.md +14 -2
  136. package/node_modules/@openclaw/fs-safe/docs/in-place-write.md +31 -0
  137. package/node_modules/@openclaw/fs-safe/docs/install.md +1 -1
  138. package/node_modules/@openclaw/fs-safe/docs/json-store.md +6 -1
  139. package/node_modules/@openclaw/fs-safe/docs/json.md +5 -1
  140. package/node_modules/@openclaw/fs-safe/docs/path-prefix.md +14 -4
  141. package/node_modules/@openclaw/fs-safe/docs/public-api.md +4 -2
  142. package/node_modules/@openclaw/fs-safe/docs/secret-file.md +5 -1
  143. package/node_modules/@openclaw/fs-safe/docs/sidecar-lock.md +4 -0
  144. package/node_modules/@openclaw/fs-safe/docs/temp.md +9 -1
  145. package/node_modules/@openclaw/fs-safe/docs/types.md +5 -1
  146. package/node_modules/@openclaw/fs-safe/package.json +12 -12
  147. package/node_modules/@openclaw/fs-safe-darwin-arm64/fs-safe-native.node +0 -0
  148. package/node_modules/@openclaw/fs-safe-darwin-arm64/package.json +1 -1
  149. package/node_modules/@openclaw/fs-safe-darwin-x64/fs-safe-native.node +0 -0
  150. package/node_modules/@openclaw/fs-safe-darwin-x64/package.json +1 -1
  151. package/node_modules/@openclaw/fs-safe-freebsd-arm64/fs-safe-native.node +0 -0
  152. package/node_modules/@openclaw/fs-safe-freebsd-arm64/package.json +1 -1
  153. package/node_modules/@openclaw/fs-safe-freebsd-x64/fs-safe-native.node +0 -0
  154. package/node_modules/@openclaw/fs-safe-freebsd-x64/package.json +1 -1
  155. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/fs-safe-native.node +0 -0
  156. package/node_modules/@openclaw/fs-safe-linux-arm64-gnu/package.json +1 -1
  157. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/fs-safe-native.node +0 -0
  158. package/node_modules/@openclaw/fs-safe-linux-arm64-musl/package.json +1 -1
  159. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/fs-safe-native.node +0 -0
  160. package/node_modules/@openclaw/fs-safe-linux-x64-gnu/package.json +1 -1
  161. package/node_modules/@openclaw/fs-safe-linux-x64-musl/fs-safe-native.node +0 -0
  162. package/node_modules/@openclaw/fs-safe-linux-x64-musl/package.json +1 -1
  163. package/node_modules/@openclaw/fs-safe-win32-arm64-msvc/fs-safe-native.node +0 -0
  164. package/node_modules/@openclaw/fs-safe-win32-arm64-msvc/package.json +1 -1
  165. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/fs-safe-native.node +0 -0
  166. package/node_modules/@openclaw/fs-safe-win32-x64-msvc/package.json +1 -1
  167. package/package.json +5 -5
  168. package/dist/.setup/setup-plugin-api-4hHy1k4x.mjs +0 -2
@@ -16,6 +16,8 @@ export declare function mkdirPathComponentsWithGuards(params: {
16
16
  createMissing?: boolean;
17
17
  synchronousMkdir?: boolean;
18
18
  mode?: number;
19
+ /** Correct only directories this walk exclusively creates; never change existing entries. */
20
+ finalizeCreatedMode?: boolean;
19
21
  private?: boolean;
20
22
  rejectSymlinks?: boolean;
21
23
  revalidateParentAfterBeforeComponent?: boolean;
@@ -2,6 +2,8 @@ import fsSync, {} from "node:fs";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { createDirectoryWithAdmission } from "./create.js";
5
+ import { AtomicIo, runAsync } from "./atomic-io.js";
6
+ import { applyDirectoryMode } from "./replace-file-descriptor.js";
5
7
  import { assertDirectoryGuard, captureDirectoryGuard, inspectDirectoryIdentitySync, } from "./directory-guard.js";
6
8
  import { FsSafeError } from "./errors.js";
7
9
  import { hasNodeErrorCode, isNotFoundPathError, isPathRelativeEscape } from "./path.js";
@@ -270,6 +272,13 @@ export async function mkdirPathComponentsWithGuards(params) {
270
272
  if (!createdAuthorization || !createdEvidence) {
271
273
  assertDirectoryGuard(parentGuard, "native");
272
274
  }
275
+ if (created && params.finalizeCreatedMode && params.mode !== undefined) {
276
+ await runAsync(applyDirectoryMode(AtomicIo.async(fs), {
277
+ dirPath: currentGuard.dir, mode: params.mode, expectedIdentity: currentGuard.stat,
278
+ }));
279
+ assertDirectoryGuard(parentGuard, "native");
280
+ assertDirectoryGuard(currentGuard, "native");
281
+ }
273
282
  current = admittedNextPath;
274
283
  }
275
284
  return current;
@@ -1,7 +1,8 @@
1
+ import type { DirectoryMode } from "./directory-mode-options.js";
1
2
  import { type JsonFileStoreOptions, type JsonStore, type JsonStoreLockOptions } from "./json-document-store.js";
2
3
  export type JsonStoreOptions<T> = JsonFileStoreOptions & {
3
4
  filePath: string;
4
- dirMode?: number;
5
+ dirMode?: DirectoryMode;
5
6
  mode?: number;
6
7
  };
7
8
  export type { JsonFileStoreOptions, JsonStore, JsonStoreLockOptions };
@@ -247,7 +247,10 @@ export interface NativeBinding {
247
247
  stagedSymlinkMatches?(parentFd: number, basename: string, linkFd: number): boolean;
248
248
  publishStagedSymlink?(parentFd: number, basename: string, linkFd: number, destination: string): void;
249
249
  removeStagedSymlink?(parentFd: number, basename: string, linkFd: number): "removed" | "name-absent" | "preserved";
250
- createStagedFile?(parentFd: number, basename: string): number;
250
+ createStagedFile?(parentFd: number, basename: string): Promise<number>;
251
+ /** POSIX staging: caller retains both parents until the worker settles. */
252
+ renameReplaceAsync?(sourceFd: number, source: string, targetFd: number, target: string): Promise<void>;
253
+ renameNoReplaceAsync?(sourceFd: number, source: string, targetFd: number, target: string): Promise<void>;
251
254
  stagedFileMetadata?(parentFd: number, basename: string, fd: number): {
252
255
  mode: bigint;
253
256
  nlink: bigint;
@@ -62,7 +62,7 @@ import { cachedNoReplaceUnavailable } from "./native-noreplace.js";
62
62
  import { isFsSafeNativeRequired } from "./native-config.js";
63
63
  import { copyLinkAtParent } from "./copy-link.js";
64
64
  const writeCapabilities = ["openBeneath", "mkdirBeneath", "renameNoReplace", "renameReplace"];
65
- const posixWriteCapabilities = [...writeCapabilities, "createStagedFile", "stagedFileMatches", "removeStagedFile"];
65
+ const posixWriteCapabilities = [...writeCapabilities, "createStagedFile", "stagedFileMatches", "removeStagedFile", "renameReplaceAsync", "renameNoReplaceAsync"];
66
66
  function pinnedWriteCapabilities(params) {
67
67
  const windows = process.platform === "win32";
68
68
  const capabilities = windows ? [...writeCapabilities, "fstatIdentity"] : posixWriteCapabilities;
@@ -5,7 +5,7 @@ import type { FileIdentityStat } from "./file-identity.js";
5
5
  import { type NativeBinding } from "./native-binding.js";
6
6
  import type { PinnedWriteInput, PinnedWriteParams } from "./pinned-write-types.js";
7
7
  import type { PublishedFileReceipt, StagedFile, StagedFileCleanupReceipt, StagedFileReceipt } from "./staged-file-types.js";
8
- export type NativeStagingBinding = NativeBinding & Required<Pick<NativeBinding, "createStagedFile" | "stagedFileMatches" | "removeStagedFile" | "renameReplace" | "renameNoReplace">>;
8
+ export type NativeStagingBinding = NativeBinding & Required<Pick<NativeBinding, "createStagedFile" | "stagedFileMatches" | "removeStagedFile" | "renameReplaceAsync" | "renameNoReplaceAsync">>;
9
9
  export declare function assertNativeStaging(binding: NativeBinding): asserts binding is NativeStagingBinding;
10
10
  type StagedPermissionPolicy = "private-creation" | "mode-only";
11
11
  type NativeStageOwner = Readonly<{
@@ -76,8 +76,8 @@ export function assertNativeStaging(binding) {
76
76
  binding.createStagedFile,
77
77
  binding.stagedFileMatches,
78
78
  binding.removeStagedFile,
79
- binding.renameReplace,
80
- binding.renameNoReplace,
79
+ binding.renameReplaceAsync,
80
+ binding.renameNoReplaceAsync,
81
81
  ].some((fn) => typeof fn !== "function")) {
82
82
  throw new FsSafeError("helper-unavailable", "native retained-directory staging is unavailable");
83
83
  }
@@ -97,7 +97,7 @@ class NativeStagedFile {
97
97
  #verifyMode;
98
98
  #state = { status: "open", publication: NOT_PUBLISHED };
99
99
  #receipt;
100
- #publicationFlush;
100
+ #publicationTask;
101
101
  #rejectFinalSymlink = false;
102
102
  #unsupportedNoReplace;
103
103
  #fallbackCleanup;
@@ -288,7 +288,7 @@ class NativeStagedFile {
288
288
  if (this.#private)
289
289
  assertDarwinCreationAcl(this.#owner.parentFd, "file");
290
290
  try {
291
- state.fileFd = this.#owner.binding.createStagedFile(this.#owner.parentFd, this.#owner.name);
291
+ state.fileFd = await this.#owner.binding.createStagedFile(this.#owner.parentFd, this.#owner.name);
292
292
  }
293
293
  catch (error) {
294
294
  annotateReadOnlyOpenError(error, path.join(this.#owner.directory.realPath, this.#owner.name));
@@ -337,7 +337,14 @@ class NativeStagedFile {
337
337
  async assertCurrent() {
338
338
  this.#assertCurrent();
339
339
  }
340
- async publish(basename, options, onPublished) {
340
+ publish(basename, options, onPublished) {
341
+ if (this.#publicationTask)
342
+ return Promise.reject(stagedFailure("file", new FsSafeError("helper-failed", "staged file publication is pending"), { phase: "publish", publication: this.#state.status === "closed" ? this.#state.receipt.publication : this.#state.publication }));
343
+ // Claim the operation before yielding so cleanup cannot recycle a worker's fds.
344
+ return this.#publicationTask = Promise.resolve().then(() => this.#publish(basename, options, onPublished))
345
+ .finally(() => { this.#publicationTask = undefined; });
346
+ }
347
+ async #publish(basename, options, onPublished) {
341
348
  const overwrite = options?.overwrite;
342
349
  try {
343
350
  const state = this.#open();
@@ -354,10 +361,10 @@ class NativeStagedFile {
354
361
  }
355
362
  try {
356
363
  if (overwrite) {
357
- this.#owner.binding.renameReplace(this.#owner.parentFd, this.#owner.name, this.#owner.parentFd, basename);
364
+ await this.#owner.binding.renameReplaceAsync(this.#owner.parentFd, this.#owner.name, this.#owner.parentFd, basename);
358
365
  }
359
366
  else {
360
- this.#owner.binding.renameNoReplace(this.#owner.parentFd, this.#owner.name, this.#owner.parentFd, basename);
367
+ await this.#owner.binding.renameNoReplaceAsync(this.#owner.parentFd, this.#owner.name, this.#owner.parentFd, basename);
361
368
  }
362
369
  }
363
370
  catch (error) {
@@ -412,14 +419,13 @@ class NativeStagedFile {
412
419
  };
413
420
  if (this.#owner.sync === false)
414
421
  return verify();
415
- this.#publicationFlush = Promise.resolve().then(async () => {
422
+ return Promise.resolve().then(async () => {
416
423
  if ((this.#owner.mode & 0o600) !== 0o600 || (stagedMode & ~this.#owner.mode) !== 0) {
417
424
  await (this.#owner.strictFileSync ? syncFile(fd) : syncFileBestEffort(fd));
418
425
  }
419
426
  await syncFileBestEffort(this.#owner.parentFd);
420
427
  return verify();
421
- }).finally(() => { this.#publicationFlush = undefined; });
422
- return this.#publicationFlush;
428
+ });
423
429
  }
424
430
  #finalize() {
425
431
  if (this.#state.status === "closed") {
@@ -474,9 +480,9 @@ class NativeStagedFile {
474
480
  return this.#state;
475
481
  }
476
482
  async cleanup() {
477
- // Native descriptors cannot close or be recycled while libuv is synchronizing them.
478
- if (this.#publicationFlush)
479
- await this.#publicationFlush.catch(() => { });
483
+ // Native descriptors stay owned through the rename and all durability fences.
484
+ if (this.#publicationTask)
485
+ await this.#publicationTask.catch(() => { });
480
486
  const closed = this.#finalize();
481
487
  if (closed.error) {
482
488
  throw closed.error;
@@ -5,3 +5,5 @@ export type OverwriteFileHandleOptions = {
5
5
  };
6
6
  /** Overwrite a borrowed, non-append read/write handle with best-effort failure rollback. */
7
7
  export declare function overwriteFileHandle(handle: FileHandle, data: Uint8Array, options?: OverwriteFileHandleOptions): Promise<void>;
8
+ /** Await authority preparation, then synchronously admit the whole borrowed-handle write. */
9
+ export declare function overwriteFileHandleWithAuthority(handle: FileHandle, data: Uint8Array, prepareAuthority: () => Promise<() => void>): Promise<void>;
@@ -9,11 +9,21 @@ export async function overwriteFileHandle(handle, data, options = {}) {
9
9
  // former method-call receiver while preventing a later getter mutation from
10
10
  // replacing authority after rollback preparation.
11
11
  const beforeWrite = options.beforeWrite;
12
+ return overwrite(handle, data, options, beforeWrite);
13
+ }
14
+ /** Await authority preparation, then synchronously admit the whole borrowed-handle write. */
15
+ export async function overwriteFileHandleWithAuthority(handle, data, prepareAuthority) {
16
+ if (typeof prepareAuthority !== "function") {
17
+ throw new TypeError("prepareAuthority must be a function");
18
+ }
19
+ return overwrite(handle, data, undefined, undefined, prepareAuthority);
20
+ }
21
+ async function overwrite(handle, data, receiver, beforeWrite, prepareAuthority) {
12
22
  const payload = data.subarray(0, data.byteLength);
13
23
  const payloadBytes = payload.byteLength;
14
24
  const fd = handle.fd;
15
- // Keep FileHandle's closed-handle error while avoiding a metadata I/O hop.
16
- const stat = fd < 0 ? await handle.stat() : fs.fstatSync(fd);
25
+ // The awaited API keeps metadata I/O off-thread; preserve the legacy fast path.
26
+ const stat = prepareAuthority || fd < 0 ? await handle.stat() : fs.fstatSync(fd);
17
27
  if (!stat.isFile()) {
18
28
  throw new FsSafeError("not-file", "overwrite handle must be a regular file");
19
29
  }
@@ -26,15 +36,27 @@ export async function overwriteFileHandle(handle, data, options = {}) {
26
36
  if (await readFileWindowFully(handle, originalPrefix, 0) !== prefixBytes) {
27
37
  throw new FsSafeError("read-failed", "file ended before overwrite rollback preparation completed");
28
38
  }
29
- assertSynchronousCallbackResult(beforeWrite === undefined ? undefined : Reflect.apply(beforeWrite, options, []), "beforeWrite");
39
+ if (prepareAuthority) {
40
+ const assertCurrent = await prepareAuthority();
41
+ if (typeof assertCurrent !== "function") {
42
+ throw new TypeError("prepareAuthority must return a synchronous assertion");
43
+ }
44
+ assertSynchronousCallbackResult(assertCurrent(), "prepared authority assertion");
45
+ }
46
+ else {
47
+ assertSynchronousCallbackResult(beforeWrite === undefined ? undefined : Reflect.apply(beforeWrite, receiver, []), "beforeWrite");
48
+ }
30
49
  let prefixStarted = false;
31
50
  try {
32
51
  // Leave existing bytes intact until any additional storage has been written.
33
52
  if (payloadBytes > originalSize) {
34
53
  await writeAllToFile(handle, payload.subarray(originalSize), { position: originalSize });
35
54
  }
36
- prefixStarted = true;
37
- await writeAllToFile(handle, payload.subarray(0, prefixBytes), { position: 0 });
55
+ // An empty prepared write must dispatch truncation before yielding after admission.
56
+ if (prefixBytes > 0 || !prepareAuthority) {
57
+ prefixStarted = true;
58
+ await writeAllToFile(handle, payload.subarray(0, prefixBytes), { position: 0 });
59
+ }
38
60
  if (payloadBytes < originalSize) {
39
61
  await handle.truncate(payloadBytes);
40
62
  }
@@ -4,3 +4,4 @@ export type ResolvedPathPrefix = {
4
4
  readonly unresolvedSegments: readonly string[];
5
5
  };
6
6
  export declare function resolvePathPrefixSync(input: string): ResolvedPathPrefix;
7
+ export declare function resolvePathPrefix(input: string): Promise<ResolvedPathPrefix>;
@@ -1,8 +1,9 @@
1
1
  import fs from "node:fs";
2
+ import asyncFs from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { formatErrorDetail } from "./error-detail.js";
4
5
  import { assertNoNulPathInput, hasNodeErrorCode } from "./path.js";
5
- import { realpathSync } from "./realpath.js";
6
+ import { realpathNative, realpathSync } from "./realpath.js";
6
7
  import { absolutePathWithRawSegments } from "./root-path-existing.js";
7
8
  import { pathForWindowsFilesystem } from "./windows-path-alias.js";
8
9
  function rawRoot(absolutePath) {
@@ -23,7 +24,12 @@ function resolutionError(code, absolutePath) {
23
24
  // path. At 32 components, repeated front removal can reindex at most 496 array
24
25
  // positions per constructed queue; longer queues use a forward cursor instead.
25
26
  const SHIFT_QUEUE_COMPONENT_LIMIT = 32;
26
- export function resolvePathPrefixSync(input) {
27
+ function* read(operation) {
28
+ let value;
29
+ yield async () => { value = await operation(); };
30
+ return value;
31
+ }
32
+ function* resolvePrefix(input, synchronous = false) {
27
33
  assertNoNulPathInput(input);
28
34
  const absolutePath = absolutePathWithRawSegments(input);
29
35
  let resolved = rawRoot(absolutePath);
@@ -43,7 +49,11 @@ export function resolvePathPrefixSync(input) {
43
49
  const lookup = segment === ".." && atRoot ? "." : segment;
44
50
  // lstat(dir) does not test search permission, and realpath may erase dots.
45
51
  const operationBase = pathForWindowsFilesystem(resolved);
46
- fs.lstatSync(`${operationBase}${operationBase.endsWith(path.sep) ? "" : path.sep}${lookup}`, { bigint: true });
52
+ const lookupPath = `${operationBase}${operationBase.endsWith(path.sep) ? "" : path.sep}${lookup}`;
53
+ if (synchronous)
54
+ fs.lstatSync(lookupPath, { bigint: true });
55
+ else
56
+ yield* read(() => asyncFs.lstat(lookupPath, { bigint: true }));
47
57
  if (segment === ".." && !atRoot)
48
58
  resolved = path.dirname(resolved);
49
59
  continue;
@@ -51,14 +61,16 @@ export function resolvePathPrefixSync(input) {
51
61
  const candidate = path.join(resolved, segment);
52
62
  let stat;
53
63
  try {
54
- stat = fs.lstatSync(candidate, { bigint: true });
64
+ stat = synchronous ? fs.lstatSync(candidate, { bigint: true })
65
+ : yield* read(() => asyncFs.lstat(candidate, { bigint: true }));
55
66
  }
56
67
  catch (error) {
57
68
  if (!hasNodeErrorCode(error, "ENOENT"))
58
69
  throw error;
59
70
  return {
60
71
  absolutePath,
61
- existingPath: realpathSync.native(pathForWindowsFilesystem(resolved)),
72
+ existingPath: synchronous ? realpathSync.native(pathForWindowsFilesystem(resolved))
73
+ : yield* read(() => realpathNative(pathForWindowsFilesystem(resolved))),
62
74
  unresolvedSegments: shiftQueue ? [segment, ...remaining] : remaining.slice(nextSegment - 1),
63
75
  };
64
76
  }
@@ -74,7 +86,7 @@ export function resolvePathPrefixSync(input) {
74
86
  throw resolutionError("ELOOP", absolutePath);
75
87
  visitedStates.add(state);
76
88
  symlinkHops++;
77
- const target = fs.readlinkSync(candidate);
89
+ const target = synchronous ? fs.readlinkSync(candidate) : yield* read(() => asyncFs.readlink(candidate));
78
90
  const rawTarget = path.sep === "\\" ? target.replaceAll("/", "\\") : target;
79
91
  let targetSegments;
80
92
  if (path.isAbsolute(rawTarget)) {
@@ -100,5 +112,70 @@ export function resolvePathPrefixSync(input) {
100
112
  shiftQueue = remainingCount <= SHIFT_QUEUE_COMPONENT_LIMIT;
101
113
  nextSegment = 0;
102
114
  }
103
- return { absolutePath, existingPath: realpathSync.native(pathForWindowsFilesystem(resolved)), unresolvedSegments: [] };
115
+ return { absolutePath, existingPath: synchronous ? realpathSync.native(pathForWindowsFilesystem(resolved))
116
+ : yield* read(() => realpathNative(pathForWindowsFilesystem(resolved))), unresolvedSegments: [] };
117
+ }
118
+ export function resolvePathPrefixSync(input) {
119
+ const result = resolvePrefix(input, true).next();
120
+ if (!result.done)
121
+ throw new Error("Synchronous path prefix resolution yielded asynchronous IO");
122
+ return result.value;
123
+ }
124
+ export async function resolvePathPrefix(input) {
125
+ if (process.platform !== "win32" && !process.versions.bun) {
126
+ assertNoNulPathInput(input);
127
+ const absolutePath = absolutePathWithRawSegments(input);
128
+ let entry;
129
+ try {
130
+ entry = await asyncFs.lstat(absolutePath);
131
+ }
132
+ catch (error) {
133
+ if (hasNodeErrorCode(error, "ENOENT") && absolutePath === path.resolve(absolutePath)) {
134
+ // The leaf is absent, so only its nearest existing directory is needed.
135
+ // Stop at aliases: dangling targets still require physical expansion.
136
+ for (let parent = path.dirname(absolutePath);; parent = path.dirname(parent)) {
137
+ let stat;
138
+ try {
139
+ stat = await asyncFs.lstat(parent);
140
+ }
141
+ catch (error) {
142
+ if (hasNodeErrorCode(error, "ENOENT") && path.dirname(parent) !== parent)
143
+ continue;
144
+ break;
145
+ }
146
+ if (!stat.isDirectory())
147
+ break;
148
+ return {
149
+ absolutePath,
150
+ existingPath: await realpathNative(parent),
151
+ unresolvedSegments: absolutePath.slice(parent.length + (parent.endsWith(path.sep) ? 0 : 1)).split(path.sep),
152
+ };
153
+ }
154
+ }
155
+ }
156
+ if (entry) {
157
+ try {
158
+ // lstat checked raw parent traversal; a final link also needs its target's search permissions.
159
+ if (entry.isSymbolicLink())
160
+ await asyncFs.access(absolutePath);
161
+ return { absolutePath, existingPath: await realpathNative(absolutePath), unresolvedSegments: [] };
162
+ }
163
+ catch {
164
+ // Raw suffixes, dangling links and uncertain failures retain the walker.
165
+ }
166
+ }
167
+ }
168
+ const reads = resolvePrefix(input);
169
+ let step = reads.next();
170
+ while (!step.done) {
171
+ try {
172
+ await step.value();
173
+ }
174
+ catch (error) {
175
+ step = reads.throw(error);
176
+ continue;
177
+ }
178
+ step = reads.next();
179
+ }
180
+ return step.value;
104
181
  }
@@ -21,7 +21,6 @@ export function replayPinnedInput(fd, input) {
21
21
  })() };
22
22
  }
23
23
  const isUint8Array = types.isUint8Array;
24
- const SMALL_BUFFER_BYTES = 64 * 1024;
25
24
  function streamChunkBytes(chunk) {
26
25
  if (Buffer.isBuffer(chunk))
27
26
  return chunk;
@@ -36,16 +35,6 @@ export async function writePinnedInput(target, input, maxBytes, assertBeforeMuta
36
35
  await writeCopyFileToFd(typeof target === "number" ? target : target.fd, input, maxBytes, assertBeforeMutation);
37
36
  return;
38
37
  }
39
- if (typeof target === "number" && input.kind === "buffer" &&
40
- input.stageBeforePublish !== false && !assertBeforeMutation) {
41
- const data = typeof input.data === "string" ? Buffer.from(input.data, input.encoding ?? "utf8") : input.data;
42
- if (data.byteLength <= SMALL_BUFFER_BYTES) {
43
- if (maxBytes !== undefined && data.byteLength > maxBytes) {
44
- throw new FsSafeError("too-large", `file exceeds limit of ${maxBytes} bytes (got at least ${data.byteLength})`);
45
- }
46
- return writeAllToFile(target, data, { synchronous: true });
47
- }
48
- }
49
38
  let bytes = 0;
50
39
  const write = async (data) => {
51
40
  bytes += data.byteLength;
@@ -0,0 +1,9 @@
1
+ import { type AtomicIo, type Procedure } from "./atomic-io.js";
2
+ import type { AtomicMutation } from "./replace-file-mutation.js";
3
+ /** Retain numeric compatibility; preservation distinguishes exclusive creation from EEXIST. */
4
+ export declare function prepareDirectoryMode(io: AtomicIo, params: {
5
+ dirPath: string;
6
+ mode: number | "preserve";
7
+ mutation?: AtomicMutation;
8
+ ignoreChmodError?: boolean;
9
+ }): Procedure<void>;
@@ -0,0 +1,61 @@
1
+ import path from "node:path";
2
+ import { inspectAtomicIdentity } from "./atomic-io.js";
3
+ import { FsSafeError } from "./errors.js";
4
+ import { hasErrorCode } from "./file-cleanup.js";
5
+ import { applyDirectoryMode } from "./replace-file-descriptor.js";
6
+ /** Retain numeric compatibility; preservation distinguishes exclusive creation from EEXIST. */
7
+ export function* prepareDirectoryMode(io, params) {
8
+ if (params.mode !== "preserve") {
9
+ params.mutation?.assert();
10
+ yield* io.mkdir(params.dirPath, params.mode);
11
+ yield* applyDirectoryMode(io, params);
12
+ return;
13
+ }
14
+ const inspect = function* (expected) {
15
+ const observed = inspectAtomicIdentity(io, () => io.lstatExact(params.dirPath), expected, false, stat => {
16
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
17
+ throw new FsSafeError("not-file", `Atomic replace parent must be a real directory: ${params.dirPath}`);
18
+ }
19
+ });
20
+ return (io.asynchronous ? yield observed : observed);
21
+ };
22
+ let expectedIdentity;
23
+ let created = false;
24
+ try {
25
+ expectedIdentity = yield* inspect();
26
+ }
27
+ catch (error) {
28
+ if (!hasErrorCode(error, "ENOENT"))
29
+ throw error;
30
+ if (!io.asynchronous && !io.fchmodSync && process.platform !== "win32") {
31
+ throw new TypeError("fileSystem.fchmodSync is required to finalize a created directory with dirMode: preserve");
32
+ }
33
+ const parent = path.dirname(params.dirPath);
34
+ if (parent === params.dirPath)
35
+ throw error;
36
+ yield* prepareDirectoryMode(io, { ...params, dirPath: parent });
37
+ params.mutation?.assert();
38
+ try {
39
+ yield* io.mkdirExclusive(params.dirPath, 0o700);
40
+ created = true;
41
+ }
42
+ catch (mkdirError) {
43
+ if (!hasErrorCode(mkdirError, "EEXIST"))
44
+ throw mkdirError;
45
+ }
46
+ expectedIdentity = yield* inspect();
47
+ }
48
+ yield* applyDirectoryMode(io, {
49
+ ...params,
50
+ mode: created ? 0o700 : "preserve",
51
+ expectedIdentity,
52
+ // A successfully created directory must finish at 0700 even for best-effort callers.
53
+ ignoreChmodError: created ? false : params.ignoreChmodError,
54
+ });
55
+ if (created && process.platform !== "win32") {
56
+ const finalized = yield* inspect(expectedIdentity);
57
+ if ((finalized.mode & 4095n) !== 448n) {
58
+ throw new FsSafeError("path-mismatch", "created directory mode could not be finalized");
59
+ }
60
+ }
61
+ }
@@ -130,7 +130,8 @@ function throwTempWorkspaceOpenFailure(failure) {
130
130
  function tempWorkspaceSettings(options) {
131
131
  const rootDir = options.rootDir;
132
132
  assertNoWindowsPathAlias(rootDir, "filesystem", "temp workspace root uses a Windows filesystem namespace alias");
133
- const dirMode = options.dirMode ?? 0o700;
133
+ const requestedDirMode = options.dirMode;
134
+ const dirMode = requestedDirMode === "preserve" ? 0o700 : requestedDirMode ?? 0o700;
134
135
  validateTempWorkspaceDirMode(dirMode);
135
136
  const mode = options.mode ?? 0o600;
136
137
  const cleanupSafety = resolveTempWorkspaceCleanupSafety(options.cleanupSafety);
@@ -1,3 +1,5 @@
1
1
  export declare const realpathSync: ((input: string) => string) & {
2
2
  native: (input: string) => string;
3
3
  };
4
+ /** Async on Node; retain runtime-specific native canonicalization guarantees. */
5
+ export declare function realpathNative(input: string): Promise<string>;
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import asyncFs from "node:fs/promises";
2
3
  import { platform } from "node:os";
3
4
  import { getSystemErrorName } from "node:util";
4
5
  import { FsSafeError } from "./errors.js";
@@ -73,3 +74,18 @@ function resolve(input, native) {
73
74
  export const realpathSync = Object.assign((input) => resolve(input, false), {
74
75
  native: (input) => resolve(input, true),
75
76
  });
77
+ /** Async on Node; retain runtime-specific native canonicalization guarantees. */
78
+ export async function realpathNative(input) {
79
+ if (bunPosix)
80
+ return realpathSync.native(input);
81
+ try {
82
+ return await asyncFs.realpath(input);
83
+ }
84
+ catch (error) {
85
+ if (process.platform !== "win32" || error.code !== "EPERM" ||
86
+ error.syscall !== "realpath")
87
+ throw error;
88
+ // AppContainer DOS-name translation still belongs to the native sync owner.
89
+ return realpathSync.native(input);
90
+ }
91
+ }
@@ -4,7 +4,8 @@ import { type AtomicFile, type AtomicIo, type Procedure } from "./atomic-io.js";
4
4
  export declare function syncDirectoryBestEffort(io: AtomicIo, dirPath: string): Procedure<void>;
5
5
  export declare function applyDirectoryMode(io: AtomicIo, params: {
6
6
  dirPath: string;
7
- mode: number;
7
+ mode: number | "preserve";
8
+ expectedIdentity?: BigIntStats;
8
9
  ignoreChmodError?: boolean;
9
10
  mutation?: AtomicMutation;
10
11
  }): Procedure<void>;
@@ -46,9 +46,9 @@ async function pinDirectoryForMode(params) {
46
46
  if (process.platform === "win32") {
47
47
  return;
48
48
  }
49
- const expected = params.fsModule === fs
49
+ const expected = params.expectedIdentity ?? (params.fsModule === fs
50
50
  ? inspectFileIdentitySync(() => assertDirectory(syncFs.lstatSync(params.dirPath, { bigint: true }), params.dirPath))
51
- : await inspectFileIdentity(async () => assertDirectory(await params.fsModule.lstat(params.dirPath, { bigint: true }), params.dirPath));
51
+ : await inspectFileIdentity(async () => assertDirectory(await params.fsModule.lstat(params.dirPath, { bigint: true }), params.dirPath)));
52
52
  const handle = await params.fsModule.open(params.dirPath, directoryOpenFlags());
53
53
  try {
54
54
  const owner = ownDirectoryMode({
@@ -86,7 +86,7 @@ export function* applyDirectoryMode(io, params) {
86
86
  }));
87
87
  let primary;
88
88
  try {
89
- if (owner)
89
+ if (owner && params.mode !== "preserve")
90
90
  yield* wait(owner.apply(params.mode));
91
91
  }
92
92
  catch (error) {
@@ -107,13 +107,15 @@ export function* applyDirectoryMode(io, params) {
107
107
  if (process.platform === "win32")
108
108
  return;
109
109
  const admit = (stat) => assertDirectory(stat, params.dirPath);
110
- const expected = inspectAtomicIdentity(io, () => io.lstatExact(params.dirPath), undefined, false, admit);
110
+ const expected = params.expectedIdentity ?? inspectAtomicIdentity(io, () => io.lstatExact(params.dirPath), undefined, false, admit);
111
111
  const file = yield* io.open(params.dirPath, directoryOpenFlags());
112
112
  let primary;
113
113
  try {
114
114
  inspectAtomicIdentity(io, () => file.statExact(), expected, false, admit);
115
- params.mutation?.assert();
116
- file.chmod(params.mode & 0o7777);
115
+ if (params.mode !== "preserve") {
116
+ params.mutation?.assert();
117
+ file.chmod(params.mode & 0o7777);
118
+ }
117
119
  }
118
120
  catch (error) {
119
121
  primary = { error };
@@ -1,4 +1,5 @@
1
1
  import type syncFs from "node:fs";
2
+ import type { DirectoryMode } from "./directory-mode-options.js";
2
3
  import type fs from "node:fs/promises";
3
4
  import type { RenameIdentityPolicy } from "./pinned-write-types.js";
4
5
  import type { AtomicMutationOptions } from "./replace-file-mutation.js";
@@ -12,7 +13,7 @@ export type ReplaceFileAtomicSyncFileSystem = Pick<typeof syncFs, "mkdirSync" |
12
13
  export type ReplaceFileAtomicBaseOptions = AtomicMutationOptions & {
13
14
  filePath: string;
14
15
  content: string | Uint8Array;
15
- dirMode?: number;
16
+ dirMode?: DirectoryMode;
16
17
  mode?: number;
17
18
  /** Inherit only rwx bits from an existing non-symlink regular file. */
18
19
  preserveExistingMode?: boolean;
@@ -4,7 +4,8 @@ import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { recursiveMkdirPath } from "./recursive-mkdir-path.js";
6
6
  import { assertDestinationHardlinkPolicy, copyFallbackReplace } from "./replace-file-copy-fallback.js";
7
- import { applyDirectoryMode, syncDirectoryBestEffort, writeTempFile } from "./replace-file-descriptor.js";
7
+ import { syncDirectoryBestEffort, writeTempFile } from "./replace-file-descriptor.js";
8
+ import { prepareDirectoryMode } from "./prepare-directory-mode.js";
8
9
  import { inheritedRegularFileMode } from "./replace-file-mode.js";
9
10
  import { atomicExpectedContentHash, validateRenameIdentity, withAtomicRenameIdentityLock, withAtomicRenameIdentityLockSync, } from "./replace-file-rename-policy.js";
10
11
  import { AtomicTempOwner } from "./replace-file-temp-owner.js";
@@ -109,10 +110,14 @@ export async function replaceFileAtomicWithDirectorySync(options, syncParent) {
109
110
  const fsModule = options.fileSystem?.promises ?? fs;
110
111
  const dir = path.dirname(filePath);
111
112
  mutation.assert();
112
- await fsModule.mkdir(fsModule === fs ? recursiveMkdirPath(dir) : dir, {
113
- recursive: true,
114
- mode: options.dirMode ?? 0o700,
115
- });
113
+ const dirMode = options.dirMode ?? 0o700;
114
+ if (dirMode === "preserve") {
115
+ await runAsync(prepareDirectoryMode(AtomicIo.async(fsModule), { dirPath: dir, mode: "preserve", mutation }));
116
+ }
117
+ else
118
+ await fsModule.mkdir(fsModule === fs ? recursiveMkdirPath(dir) : dir, {
119
+ recursive: true, mode: dirMode,
120
+ });
116
121
  mutation.assert();
117
122
  return await withAtomicRenameIdentityLock(filePath, () => replaceAsync(options, filePath, renameIdentity, mutation, syncParent));
118
123
  });
@@ -132,10 +137,14 @@ export function replaceFileAtomicSync(options) {
132
137
  const fsModule = options.fileSystem ?? syncFs;
133
138
  const dir = path.dirname(filePath);
134
139
  mutation.assert();
135
- fsModule.mkdirSync(fsModule === syncFs ? recursiveMkdirPath(dir) : dir, {
136
- recursive: true,
137
- mode: options.dirMode ?? 0o700,
138
- });
140
+ const dirMode = options.dirMode ?? 0o700;
141
+ if (dirMode === "preserve") {
142
+ runSync(prepareDirectoryMode(AtomicIo.sync(fsModule, fsModule.fchmodSync), { dirPath: dir, mode: "preserve", mutation }));
143
+ }
144
+ else
145
+ fsModule.mkdirSync(fsModule === syncFs ? recursiveMkdirPath(dir) : dir, {
146
+ recursive: true, mode: dirMode,
147
+ });
139
148
  mutation.assert();
140
149
  return withAtomicRenameIdentityLockSync(filePath, () => replaceSync(options, filePath, renameIdentity, mutation));
141
150
  }
@@ -151,7 +160,7 @@ function* replace(io, options, filePath, renameIdentity, mutation, syncParent) {
151
160
  const syncOptions = options;
152
161
  io.fchmodSync = syncOptions.fileSystem?.fchmodSync ?? (syncOptions.fileSystem === undefined ? syncFs.fchmodSync : undefined);
153
162
  if (!io.fchmodSync && (options.mode !== undefined || options.preserveExistingMode === true ||
154
- (process.platform !== "win32" && options.dirMode !== undefined))) {
163
+ (process.platform !== "win32" && typeof options.dirMode === "number"))) {
155
164
  throw new TypeError("fileSystem.fchmodSync is required when mode, dirMode, or preserveExistingMode is specified");
156
165
  }
157
166
  }
@@ -159,9 +168,7 @@ function* replace(io, options, filePath, renameIdentity, mutation, syncParent) {
159
168
  const tempOwner = new AtomicTempOwner(tempPath, io);
160
169
  let originalFailure;
161
170
  try {
162
- mutation.assert();
163
- yield* io.mkdir(dir, dirMode);
164
- yield* applyDirectoryMode(io, { dirPath: dir, mode: dirMode, mutation });
171
+ yield* prepareDirectoryMode(io, { dirPath: dir, mode: dirMode, mutation });
165
172
  tempOwner.start();
166
173
  tempOwner.adopt(yield* writeTempFile(io, {
167
174
  tempPath,