@cortexkit/opencode-antigravity-auth 3.0.40 → 3.0.42

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 (231) hide show
  1. package/dist/cli.js +1277 -1073
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +122 -112
  4. package/dist/index.js +7472 -4214
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +1494 -509
  7. package/dist/server.js +5990 -2678
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/commands/builtins.d.ts +20 -1
  11. package/dist/src/common-auth-embedded/commands/builtins.js +28 -12
  12. package/dist/src/common-auth-embedded/commands/index.d.ts +1 -1
  13. package/dist/src/common-auth-embedded/commands/menu.d.ts +6 -1
  14. package/dist/src/common-auth-embedded/commands/menu.js +1 -0
  15. package/dist/src/common-auth-embedded/fs/file-read-cache.js +9 -5
  16. package/dist/src/common-auth-embedded/fs/refresh-file-lock.d.ts +11 -0
  17. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +159 -11
  18. package/dist/src/common-auth-embedded/fs/with-lock.d.ts +2 -0
  19. package/dist/src/common-auth-embedded/fs/with-lock.js +1 -1
  20. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +33 -5
  21. package/dist/src/common-auth-embedded/routing-accessor/index.js +49 -7
  22. package/dist/src/common-auth-embedded/settings/define.d.ts +35 -0
  23. package/dist/src/common-auth-embedded/settings/define.js +52 -0
  24. package/dist/src/common-auth-embedded/settings/descriptors.d.ts +97 -0
  25. package/dist/src/common-auth-embedded/settings/descriptors.js +81 -0
  26. package/dist/src/common-auth-embedded/settings/edit.d.ts +24 -0
  27. package/dist/src/common-auth-embedded/settings/edit.js +229 -0
  28. package/dist/src/common-auth-embedded/settings/fs.js +19 -0
  29. package/dist/src/common-auth-embedded/settings/handle.d.ts +30 -0
  30. package/dist/src/common-auth-embedded/settings/handle.js +228 -0
  31. package/dist/src/common-auth-embedded/settings/index.d.ts +10 -0
  32. package/dist/src/common-auth-embedded/settings/index.js +7 -0
  33. package/dist/src/common-auth-embedded/settings/lock-errors.js +15 -0
  34. package/dist/src/common-auth-embedded/settings/move.d.ts +76 -0
  35. package/dist/src/common-auth-embedded/settings/move.js +351 -0
  36. package/dist/src/common-auth-embedded/settings/parse.d.ts +24 -0
  37. package/dist/src/common-auth-embedded/settings/parse.js +65 -0
  38. package/dist/src/common-auth-embedded/settings/paths.d.ts +12 -0
  39. package/dist/src/common-auth-embedded/settings/paths.js +48 -0
  40. package/dist/src/common-auth-embedded/settings/refusal.d.ts +7 -0
  41. package/dist/src/common-auth-embedded/settings/refusal.js +15 -0
  42. package/dist/src/common-auth-embedded/settings/resolve.d.ts +15 -0
  43. package/dist/src/common-auth-embedded/settings/resolve.js +51 -0
  44. package/dist/src/common-auth-embedded/settings/schema.d.ts +29 -0
  45. package/dist/src/common-auth-embedded/settings/schema.js +81 -0
  46. package/dist/src/common-auth-embedded/settings/snapshot.d.ts +24 -0
  47. package/dist/src/common-auth-embedded/settings/snapshot.js +150 -0
  48. package/dist/src/common-auth-embedded/settings/update.js +139 -0
  49. package/dist/src/common-auth-embedded/settings/write.js +88 -0
  50. package/dist/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  51. package/dist/src/common-auth-embedded/setup/command-error.js +3 -2
  52. package/dist/src/common-auth-embedded/setup/command.js +5 -1
  53. package/dist/src/common-auth-embedded/setup/enroll.js +3 -3
  54. package/dist/src/common-auth-embedded/setup/enrollment-access.js +13 -4
  55. package/dist/src/common-auth-embedded/setup/types.d.ts +4 -0
  56. package/dist/src/common-auth-embedded/source-output.json +297 -61
  57. package/dist/src/common-auth-embedded/tui-prefs/watcher.js +196 -0
  58. package/dist/src/ga/tui/host-ga.js +1 -1
  59. package/dist/src/ga/tui/host-ga.js.map +1 -1
  60. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  61. package/dist/src/plugin/command-apply.d.ts +43 -3
  62. package/dist/src/plugin/command-apply.d.ts.map +1 -1
  63. package/dist/src/plugin/command-apply.js +92 -12
  64. package/dist/src/plugin/command-apply.js.map +1 -1
  65. package/dist/src/plugin/commands.d.ts +5 -1
  66. package/dist/src/plugin/commands.d.ts.map +1 -1
  67. package/dist/src/plugin/commands.js +4 -3
  68. package/dist/src/plugin/commands.js.map +1 -1
  69. package/dist/src/plugin/config/writer.d.ts +10 -3
  70. package/dist/src/plugin/config/writer.d.ts.map +1 -1
  71. package/dist/src/plugin/config/writer.js +30 -22
  72. package/dist/src/plugin/config/writer.js.map +1 -1
  73. package/dist/src/plugin/fetch-interceptor.d.ts +8 -3
  74. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  75. package/dist/src/plugin/fetch-interceptor.js +1 -0
  76. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  77. package/dist/src/plugin/ga-location-services.d.ts +3 -1
  78. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  79. package/dist/src/plugin/ga-location-services.js +35 -5
  80. package/dist/src/plugin/ga-location-services.js.map +1 -1
  81. package/dist/src/plugin/index.d.ts.map +1 -1
  82. package/dist/src/plugin/index.js +65 -15
  83. package/dist/src/plugin/index.js.map +1 -1
  84. package/dist/src/plugin/killswitch.d.ts +20 -0
  85. package/dist/src/plugin/killswitch.d.ts.map +1 -1
  86. package/dist/src/plugin/killswitch.js +14 -4
  87. package/dist/src/plugin/killswitch.js.map +1 -1
  88. package/dist/src/plugin/operator-settings.d.ts +6 -0
  89. package/dist/src/plugin/operator-settings.d.ts.map +1 -1
  90. package/dist/src/plugin/operator-settings.js.map +1 -1
  91. package/dist/src/plugin/request-helpers.d.ts +15 -0
  92. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  93. package/dist/src/plugin/request-helpers.js +17 -2
  94. package/dist/src/plugin/request-helpers.js.map +1 -1
  95. package/dist/src/plugin/shared/request-services.d.ts +18 -2
  96. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  97. package/dist/src/plugin/shared/request-services.js +130 -13
  98. package/dist/src/plugin/shared/request-services.js.map +1 -1
  99. package/dist/src/plugin/shared/runtime.d.ts +15 -0
  100. package/dist/src/plugin/shared/runtime.d.ts.map +1 -1
  101. package/dist/src/plugin/shared/runtime.js +43 -11
  102. package/dist/src/plugin/shared/runtime.js.map +1 -1
  103. package/dist/src/plugin/shared/vault-menu.d.ts +11 -1
  104. package/dist/src/plugin/shared/vault-menu.d.ts.map +1 -1
  105. package/dist/src/plugin/shared/vault-menu.js +33 -7
  106. package/dist/src/plugin/shared/vault-menu.js.map +1 -1
  107. package/dist/src/settings/core-settings.d.ts +7 -0
  108. package/dist/src/settings/core-settings.d.ts.map +1 -0
  109. package/dist/src/settings/core-settings.js +7 -0
  110. package/dist/src/settings/core-settings.js.map +1 -0
  111. package/dist/src/settings/legacy.d.ts +89 -0
  112. package/dist/src/settings/legacy.d.ts.map +1 -0
  113. package/dist/src/settings/legacy.js +184 -0
  114. package/dist/src/settings/legacy.js.map +1 -0
  115. package/dist/src/settings/location.d.ts +22 -0
  116. package/dist/src/settings/location.d.ts.map +1 -0
  117. package/dist/src/settings/location.js +49 -0
  118. package/dist/src/settings/location.js.map +1 -0
  119. package/dist/src/settings/move.d.ts +38 -0
  120. package/dist/src/settings/move.d.ts.map +1 -0
  121. package/dist/src/settings/move.js +83 -0
  122. package/dist/src/settings/move.js.map +1 -0
  123. package/dist/src/settings/protection.d.ts +11 -0
  124. package/dist/src/settings/protection.d.ts.map +1 -0
  125. package/dist/src/settings/protection.js +17 -0
  126. package/dist/src/settings/protection.js.map +1 -0
  127. package/dist/src/settings/report.d.ts +33 -0
  128. package/dist/src/settings/report.d.ts.map +1 -0
  129. package/dist/src/settings/report.js +103 -0
  130. package/dist/src/settings/report.js.map +1 -0
  131. package/dist/src/settings/runtime.d.ts +145 -0
  132. package/dist/src/settings/runtime.d.ts.map +1 -0
  133. package/dist/src/settings/runtime.js +697 -0
  134. package/dist/src/settings/runtime.js.map +1 -0
  135. package/dist/tui-build-map.json +1 -1
  136. package/dist/tui-ga-build-map.json +5 -5
  137. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +20 -1
  138. package/dist/types/src/common-auth-embedded/commands/index.d.ts +1 -1
  139. package/dist/types/src/common-auth-embedded/commands/menu.d.ts +6 -1
  140. package/dist/types/src/common-auth-embedded/fs/refresh-file-lock.d.ts +11 -0
  141. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +33 -5
  142. package/dist/types/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  143. package/dist/types/src/common-auth-embedded/setup/types.d.ts +4 -0
  144. package/dist/types/src/plugin/command-apply.d.ts +43 -3
  145. package/dist/types/src/plugin/command-apply.d.ts.map +1 -1
  146. package/dist/types/src/plugin/commands.d.ts +5 -1
  147. package/dist/types/src/plugin/commands.d.ts.map +1 -1
  148. package/dist/types/src/plugin/config/writer.d.ts +10 -3
  149. package/dist/types/src/plugin/config/writer.d.ts.map +1 -1
  150. package/dist/types/src/plugin/fetch-interceptor.d.ts +8 -3
  151. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  152. package/dist/types/src/plugin/ga-location-services.d.ts +3 -1
  153. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  154. package/dist/types/src/plugin/index.d.ts.map +1 -1
  155. package/dist/types/src/plugin/killswitch.d.ts +20 -0
  156. package/dist/types/src/plugin/killswitch.d.ts.map +1 -1
  157. package/dist/types/src/plugin/operator-settings.d.ts +6 -0
  158. package/dist/types/src/plugin/operator-settings.d.ts.map +1 -1
  159. package/dist/types/src/plugin/request-helpers.d.ts +15 -0
  160. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  161. package/dist/types/src/plugin/shared/request-services.d.ts +18 -2
  162. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  163. package/dist/types/src/plugin/shared/runtime.d.ts +15 -0
  164. package/dist/types/src/plugin/shared/runtime.d.ts.map +1 -1
  165. package/dist/types/src/plugin/shared/vault-menu.d.ts +11 -1
  166. package/dist/types/src/plugin/shared/vault-menu.d.ts.map +1 -1
  167. package/dist/types/src/settings/core-settings.d.ts +7 -0
  168. package/dist/types/src/settings/core-settings.d.ts.map +1 -0
  169. package/dist/types/src/settings/legacy.d.ts +89 -0
  170. package/dist/types/src/settings/legacy.d.ts.map +1 -0
  171. package/dist/types/src/settings/location.d.ts +22 -0
  172. package/dist/types/src/settings/location.d.ts.map +1 -0
  173. package/dist/types/src/settings/move.d.ts +38 -0
  174. package/dist/types/src/settings/move.d.ts.map +1 -0
  175. package/dist/types/src/settings/protection.d.ts +11 -0
  176. package/dist/types/src/settings/protection.d.ts.map +1 -0
  177. package/dist/types/src/settings/report.d.ts +33 -0
  178. package/dist/types/src/settings/report.d.ts.map +1 -0
  179. package/dist/types/src/settings/runtime.d.ts +145 -0
  180. package/dist/types/src/settings/runtime.d.ts.map +1 -0
  181. package/package.json +3 -2
  182. package/src/common-auth-embedded/commands/builtins.d.ts +20 -1
  183. package/src/common-auth-embedded/commands/builtins.js +28 -12
  184. package/src/common-auth-embedded/commands/index.d.ts +1 -1
  185. package/src/common-auth-embedded/commands/menu.d.ts +6 -1
  186. package/src/common-auth-embedded/commands/menu.js +1 -0
  187. package/src/common-auth-embedded/fs/file-read-cache.js +9 -5
  188. package/src/common-auth-embedded/fs/refresh-file-lock.d.ts +11 -0
  189. package/src/common-auth-embedded/fs/refresh-file-lock.js +159 -11
  190. package/src/common-auth-embedded/fs/with-lock.d.ts +2 -0
  191. package/src/common-auth-embedded/fs/with-lock.js +1 -1
  192. package/src/common-auth-embedded/routing-accessor/index.d.ts +33 -5
  193. package/src/common-auth-embedded/routing-accessor/index.js +49 -7
  194. package/src/common-auth-embedded/settings/define.d.ts +35 -0
  195. package/src/common-auth-embedded/settings/define.js +52 -0
  196. package/src/common-auth-embedded/settings/descriptors.d.ts +97 -0
  197. package/src/common-auth-embedded/settings/descriptors.js +81 -0
  198. package/src/common-auth-embedded/settings/edit.d.ts +24 -0
  199. package/src/common-auth-embedded/settings/edit.js +229 -0
  200. package/src/common-auth-embedded/settings/fs.js +19 -0
  201. package/src/common-auth-embedded/settings/handle.d.ts +30 -0
  202. package/src/common-auth-embedded/settings/handle.js +228 -0
  203. package/src/common-auth-embedded/settings/index.d.ts +10 -0
  204. package/src/common-auth-embedded/settings/index.js +7 -0
  205. package/src/common-auth-embedded/settings/lock-errors.js +15 -0
  206. package/src/common-auth-embedded/settings/move.d.ts +76 -0
  207. package/src/common-auth-embedded/settings/move.js +351 -0
  208. package/src/common-auth-embedded/settings/parse.d.ts +24 -0
  209. package/src/common-auth-embedded/settings/parse.js +65 -0
  210. package/src/common-auth-embedded/settings/paths.d.ts +12 -0
  211. package/src/common-auth-embedded/settings/paths.js +48 -0
  212. package/src/common-auth-embedded/settings/refusal.d.ts +7 -0
  213. package/src/common-auth-embedded/settings/refusal.js +15 -0
  214. package/src/common-auth-embedded/settings/resolve.d.ts +15 -0
  215. package/src/common-auth-embedded/settings/resolve.js +51 -0
  216. package/src/common-auth-embedded/settings/schema.d.ts +29 -0
  217. package/src/common-auth-embedded/settings/schema.js +81 -0
  218. package/src/common-auth-embedded/settings/snapshot.d.ts +24 -0
  219. package/src/common-auth-embedded/settings/snapshot.js +150 -0
  220. package/src/common-auth-embedded/settings/update.js +139 -0
  221. package/src/common-auth-embedded/settings/write.js +88 -0
  222. package/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  223. package/src/common-auth-embedded/setup/command-error.js +3 -2
  224. package/src/common-auth-embedded/setup/command.js +5 -1
  225. package/src/common-auth-embedded/setup/enroll.js +3 -3
  226. package/src/common-auth-embedded/setup/enrollment-access.js +13 -4
  227. package/src/common-auth-embedded/setup/types.d.ts +4 -0
  228. package/src/common-auth-embedded/source-output.json +297 -61
  229. package/src/common-auth-embedded/tui-prefs/watcher.js +196 -0
  230. package/src/tui-ga-compiled/host-ga.js +1 -1
  231. package/src/tui-ga-raw/host-ga.tsx +1 -1
package/dist/cli.js CHANGED
@@ -8770,501 +8770,1001 @@ var init_lock_record = __esm({
8770
8770
  }
8771
8771
  });
8772
8772
 
8773
- // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
8774
- import { randomUUID as randomUUID7 } from "node:crypto";
8775
- import { link as link2, lstat as lstat3, mkdir as mkdir7, open as open4, readFile as readFile5, rename as rename6, rm as rm4, stat as stat3 } from "node:fs/promises";
8776
- import { dirname as dirname7, join as join5 } from "node:path";
8777
- async function createExclusiveText(path2, text2) {
8778
- const tempPath = `${path2}.${randomUUID7()}.tmp`;
8779
- let handle;
8780
- try {
8781
- handle = await open4(tempPath, "wx", 384);
8782
- try {
8783
- if (leaseCreationTestHooks?.beforeWrite)
8784
- await leaseCreationTestHooks.beforeWrite(tempPath);
8785
- await handle.writeFile(text2, "utf8");
8786
- } finally {
8787
- await handle.close();
8773
+ // ../core/dist/common-auth-embedded/logger/capture-sink.js
8774
+ function createCaptureSink() {
8775
+ const records = [];
8776
+ const sink = (record3) => {
8777
+ records.push(record3);
8778
+ };
8779
+ return {
8780
+ records,
8781
+ sink,
8782
+ clear: () => {
8783
+ records.length = 0;
8784
+ }
8785
+ };
8786
+ }
8787
+ var init_capture_sink = __esm({
8788
+ "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
8789
+ "use strict";
8790
+ }
8791
+ });
8792
+
8793
+ // ../core/dist/common-auth-embedded/logger/redact.js
8794
+ function isError(value) {
8795
+ return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
8796
+ }
8797
+ function createRedactor(options = {}) {
8798
+ const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
8799
+ function isSecretKey(key) {
8800
+ const normalized = key.toLowerCase().replace(/[-_]/g, "");
8801
+ return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
8802
+ }
8803
+ function errorEntries(error) {
8804
+ const fields2 = error;
8805
+ const entries = [
8806
+ ["name", error.name],
8807
+ ["message", error.message],
8808
+ ["stack", error.stack]
8809
+ ];
8810
+ for (const key of ["code", "status", "cause"])
8811
+ if (fields2[key] !== void 0)
8812
+ entries.push([key, fields2[key]]);
8813
+ const listed = new Set(entries.map(([key]) => key));
8814
+ for (const entry of Object.entries(error))
8815
+ if (!listed.has(entry[0]))
8816
+ entries.push(entry);
8817
+ return entries;
8818
+ }
8819
+ function walk(value, keys, seen, errorDepth = 0) {
8820
+ if (typeof value === "string") {
8821
+ return patterns.reduce((text2, pattern) => text2.replace(pattern, MASK), value);
8788
8822
  }
8823
+ if (!value || typeof value !== "object")
8824
+ return value;
8825
+ if (seen.has(value))
8826
+ return "[Circular]";
8827
+ seen.add(value);
8789
8828
  try {
8790
- if (leaseCreationTestHooks?.beforeLink)
8791
- await leaseCreationTestHooks.beforeLink(tempPath, path2);
8792
- await link2(tempPath, path2);
8793
- } catch (error) {
8794
- const code2 = error.code;
8795
- if (code2 !== "EPERM" && code2 !== "ENOTSUP" && code2 !== "EOPNOTSUPP" && code2 !== "EXDEV")
8796
- throw error;
8797
- await writeExclusiveText(path2, text2);
8829
+ if (Array.isArray(value))
8830
+ return value.map((item) => walk(item, keys, seen, errorDepth));
8831
+ const error = isError(value);
8832
+ if (error && errorDepth >= MAX_ERROR_DEPTH)
8833
+ return "[Truncated]";
8834
+ const childDepth = error ? errorDepth + 1 : errorDepth;
8835
+ return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
8836
+ key,
8837
+ keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
8838
+ ]));
8839
+ } finally {
8840
+ seen.delete(value);
8798
8841
  }
8799
- } finally {
8800
- if (handle)
8801
- await rm4(tempPath, { force: true }).catch(() => {
8802
- });
8803
8842
  }
8843
+ return {
8844
+ redact: (value) => walk(value, true, /* @__PURE__ */ new WeakSet()),
8845
+ // Schema keys describe arguments, not credentials; only their string values are scrubbed.
8846
+ redactStrings: (value) => walk(value, false, /* @__PURE__ */ new WeakSet())
8847
+ };
8804
8848
  }
8805
- async function writeExclusiveText(path2, text2) {
8806
- const handle = await open4(path2, "wx", 384);
8807
- let createdStat;
8849
+ var SECRET_KEY_EXACT, TOKEN_VALUE, MASK, MAX_ERROR_DEPTH, defaultRedactor, redact, redactStrings;
8850
+ var init_redact = __esm({
8851
+ "../core/dist/common-auth-embedded/logger/redact.js"() {
8852
+ "use strict";
8853
+ SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
8854
+ TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
8855
+ MASK = "***REDACTED***";
8856
+ MAX_ERROR_DEPTH = 8;
8857
+ defaultRedactor = createRedactor();
8858
+ redact = defaultRedactor.redact;
8859
+ redactStrings = defaultRedactor.redactStrings;
8860
+ }
8861
+ });
8862
+
8863
+ // ../core/dist/common-auth-embedded/logger/engine.js
8864
+ import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
8865
+ import { open as open4 } from "node:fs/promises";
8866
+ import { dirname as dirname7, resolve as resolve4 } from "node:path";
8867
+ function chmodPrivate(path2) {
8808
8868
  try {
8809
- createdStat = await handle.stat();
8869
+ chmodSync(path2, 384);
8810
8870
  } catch {
8811
- createdStat = void 0;
8812
8871
  }
8872
+ }
8873
+ function rotateIfNeeded(f) {
8813
8874
  try {
8814
- if (leaseCreationTestHooks?.beforeWrite)
8815
- await leaseCreationTestHooks.beforeWrite(path2);
8816
- await handle.writeFile(text2, "utf8");
8817
- } catch (error) {
8818
- try {
8819
- const current = await lstat3(path2).catch(() => void 0);
8820
- if (createdStat && current && current.dev === createdStat.dev && current.ino === createdStat.ino) {
8821
- await rm4(path2, { force: true }).catch(() => {
8822
- });
8875
+ if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
8876
+ return;
8877
+ for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
8878
+ if (existsSync(`${f}.${i}`)) {
8879
+ const rotated2 = `${f}.${i + 1}`;
8880
+ renameSync(`${f}.${i}`, rotated2);
8881
+ chmodPrivate(rotated2);
8823
8882
  }
8824
- } catch {
8825
8883
  }
8826
- throw error;
8827
- } finally {
8828
- await handle.close();
8884
+ const rotated = `${f}.1`;
8885
+ renameSync(f, rotated);
8886
+ chmodPrivate(rotated);
8887
+ } catch {
8829
8888
  }
8830
8889
  }
8831
- function isLostMarkerRaceError(error) {
8832
- const code2 = error?.code;
8833
- return code2 === "ENOENT" || !windowsPrivateFiles && (code2 === "EINVAL" || code2 === "ENOTDIR");
8834
- }
8835
- function sameMarkerDirectory(created, current) {
8836
- if (created.dev !== current.dev || created.ino !== current.ino)
8837
- return false;
8838
- if (created.ino === 0 && created.birthtimeMs !== current.birthtimeMs)
8839
- return false;
8840
- return true;
8841
- }
8842
- function acquireRefreshFileLock(options) {
8843
- return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
8890
+ async function closeWindowsFile(sink) {
8891
+ const { file, handle } = sink;
8892
+ sink.file = void 0;
8893
+ sink.handle = void 0;
8894
+ if (file && handle)
8895
+ await privateOperation(file, "log-close", () => handle.close());
8844
8896
  }
8845
- async function acquireRefreshFileLockWithClock(options) {
8846
- const lockPath = lockPathFor(options.path, options.name);
8847
- const legacyOwnerPath = join5(lockPath, "owner.json");
8848
- const ownerId = randomUUID7();
8849
- const now = options.now ?? Date.now;
8850
- let renewTimer = null;
8851
- let released = false;
8852
- let releaseConfirmed = false;
8853
- let loss;
8854
- let resolveLoss;
8855
- const lostPromise = new Promise((resolve24) => {
8856
- resolveLoss = resolve24;
8857
- });
8858
- function notifyTimerStep(event) {
8897
+ async function openWindowsFile(sink, file) {
8898
+ await ensurePrivateDirectory(dirname7(file));
8899
+ try {
8900
+ await verifyPrivate(file, "file", true);
8901
+ } catch (error) {
8902
+ if (error.code !== "ENOENT")
8903
+ throw error;
8859
8904
  try {
8860
- const result = options.onRenewalTimer?.(event);
8861
- if (result && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function") {
8862
- void Promise.resolve(result).catch(() => {
8863
- });
8864
- }
8865
- } catch {
8905
+ await createPrivateBytes(file, "");
8906
+ } catch (creationError) {
8907
+ if (creationError.code !== "EEXIST")
8908
+ throw creationError;
8909
+ await verifyPrivate(file, "file", true);
8866
8910
  }
8867
8911
  }
8868
- function cancelRenewalTimer() {
8869
- if (!renewTimer)
8870
- return;
8871
- clearRefreshLockRenewalTimeout(renewTimer);
8872
- renewTimer = null;
8873
- notifyTimerStep("cancelled");
8874
- }
8875
- function recordLoss(reason, owner) {
8876
- if (loss || released)
8877
- return;
8878
- loss = Object.freeze({
8879
- reason,
8880
- expectedOwnerId: ownerId,
8881
- ...typeof owner?.ownerId === "string" ? { observedOwnerId: owner.ownerId } : {},
8882
- ...typeof owner?.expiresAt === "number" ? { observedExpiresAt: owner.expiresAt } : {}
8912
+ sink.handle = await privateOperation(file, "log-open", () => open4(file, "a"));
8913
+ sink.file = file;
8914
+ return sink.handle;
8915
+ }
8916
+ async function flushWindowsFile(sink, file, text2) {
8917
+ file = resolve4(file);
8918
+ try {
8919
+ if (sink.file !== file)
8920
+ await closeWindowsFile(sink);
8921
+ let handle = sink.handle ?? await openWindowsFile(sink, file);
8922
+ const info = await privateOperation(file, "log-stat", () => handle.stat());
8923
+ if (info.size >= MAX_BYTES) {
8924
+ await closeWindowsFile(sink);
8925
+ for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
8926
+ const source = i === 0 ? file : `${file}.${i}`;
8927
+ const target = `${file}.${i + 1}`;
8928
+ try {
8929
+ await verifyPrivate(source, "file", true);
8930
+ } catch (error) {
8931
+ if (error.code === "ENOENT")
8932
+ continue;
8933
+ throw error;
8934
+ }
8935
+ try {
8936
+ await verifyPrivate(target, "file", true);
8937
+ } catch (error) {
8938
+ if (error.code !== "ENOENT")
8939
+ throw error;
8940
+ }
8941
+ await replaceWindowsFile(source, target);
8942
+ await verifyPrivate(target, "file");
8943
+ }
8944
+ handle = await openWindowsFile(sink, file);
8945
+ }
8946
+ await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
8947
+ } catch (error) {
8948
+ await closeWindowsFile(sink).catch(() => {
8883
8949
  });
8884
- cancelRenewalTimer();
8885
- resolveLoss(loss);
8886
- }
8887
- let terminalIOError;
8888
- let renewalInFlight = null;
8889
- const evictPath = `${lockPath}.evicting`;
8890
- const evictOwnerPath = join5(evictPath, "owner.json");
8891
- const evictOwnerId = randomUUID7();
8892
- const EVICT_TTL = 5e3;
8893
- const MAX_STEAL_ATTEMPTS = 8;
8894
- function isChangingLockCreate(error) {
8895
- return windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [lockPath], "create") || isWindowsAccessDeniedCreate(error, [evictPath], "directory-create"));
8950
+ throw error;
8896
8951
  }
8897
- async function readOwner() {
8898
- if (windowsPrivateFiles) {
8899
- try {
8900
- return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
8901
- } catch (error) {
8902
- if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
8903
- throw error;
8904
- await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
8905
- return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
8906
- }
8952
+ }
8953
+ function safeSerialize(data) {
8954
+ try {
8955
+ return ` ${JSON.stringify(data)}`;
8956
+ } catch {
8957
+ return " [unserializable]";
8958
+ }
8959
+ }
8960
+ function createEngine(options) {
8961
+ let logFileSource;
8962
+ let initLevelSource;
8963
+ let runtimeLevel;
8964
+ let redactor = createRedactor();
8965
+ let captureSink;
8966
+ let buffer = [];
8967
+ let timer;
8968
+ let orderedSink = Promise.resolve();
8969
+ let sinkError;
8970
+ const windowsFile = {};
8971
+ function queueWindows(operation) {
8972
+ const next = orderedSink.then(operation);
8973
+ orderedSink = next.catch((error) => {
8974
+ sinkError = error;
8975
+ });
8976
+ return next;
8977
+ }
8978
+ function configure(next) {
8979
+ if (windowsPrivateFiles && next.file !== logFileSource)
8980
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
8981
+ });
8982
+ logFileSource = next.file;
8983
+ initLevelSource = next.level;
8984
+ redactor = createRedactor(next);
8985
+ captureSink = next.captureSink;
8986
+ }
8987
+ function setLogLevel3(l) {
8988
+ if (l === void 0 || l in ORDER)
8989
+ runtimeLevel = l;
8990
+ }
8991
+ function logFilePath() {
8992
+ if (logFileSource === void 0)
8993
+ return void 0;
8994
+ const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
8995
+ return resolved || void 0;
8996
+ }
8997
+ function configuredLevel() {
8998
+ if (runtimeLevel)
8999
+ return runtimeLevel;
9000
+ const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
9001
+ if (floor && floor in ORDER)
9002
+ return floor;
9003
+ return "info";
9004
+ }
9005
+ function flushLogs3(close = true) {
9006
+ if (timer) {
9007
+ clearTimeout(timer);
9008
+ timer = void 0;
9009
+ }
9010
+ if (!buffer.length) {
9011
+ if (windowsPrivateFiles)
9012
+ return queueWindows(async () => {
9013
+ if (close)
9014
+ await closeWindowsFile(windowsFile);
9015
+ if (sinkError)
9016
+ throw sinkError;
9017
+ });
9018
+ return;
8907
9019
  }
9020
+ let file;
8908
9021
  try {
8909
- return JSON.parse(await readFile5(lockPath, "utf8"));
8910
- } catch (error) {
8911
- const code2 = error.code;
8912
- if (code2 !== "EISDIR")
8913
- throw error;
8914
- return JSON.parse(await readFile5(legacyOwnerPath, "utf8"));
9022
+ file = logFilePath();
9023
+ } catch {
9024
+ buffer = [];
9025
+ if (windowsPrivateFiles && close)
9026
+ return queueWindows(() => closeWindowsFile(windowsFile));
9027
+ return;
9028
+ }
9029
+ const text2 = buffer.join("");
9030
+ buffer = [];
9031
+ if (!file) {
9032
+ if (windowsPrivateFiles && close)
9033
+ return queueWindows(() => closeWindowsFile(windowsFile));
9034
+ return;
8915
9035
  }
8916
- }
8917
- async function writeOwner() {
8918
9036
  if (windowsPrivateFiles) {
8919
- const owner = await readOwner();
8920
- const remaining = Number(owner?.expiresAt) - now();
8921
- await writePrivateAtomic(lockPath, `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
8922
- `, {
8923
- deadline: performance.now() + Math.max(0, remaining),
8924
- beforeRename: async () => {
8925
- const current = await readOwner();
8926
- if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
8927
- throw new LockOwnershipError({
8928
- target: options.path,
8929
- name: options.name
8930
- });
8931
- }
9037
+ return queueWindows(async () => {
9038
+ try {
9039
+ await flushWindowsFile(windowsFile, file, text2);
9040
+ } finally {
9041
+ if (close)
9042
+ await closeWindowsFile(windowsFile);
8932
9043
  }
8933
9044
  });
8934
- return;
8935
9045
  }
8936
- const tempPath = `${lockPath}.${randomUUID7()}.tmp`;
8937
- let handle;
8938
- let created = false;
8939
9046
  try {
8940
- handle = await open4(tempPath, "wx", 384);
8941
- created = true;
8942
- await handle.writeFile(`${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
8943
- `, "utf8");
8944
- await handle.chmod(384);
8945
- await handle.close();
8946
- handle = void 0;
8947
- const current = await readOwner();
8948
- if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
8949
- throw new LockOwnershipError({
8950
- target: options.path,
8951
- name: options.name
8952
- });
8953
- }
8954
- await rename6(tempPath, lockPath);
8955
- created = false;
8956
- } finally {
8957
- await handle?.close().catch(() => {
8958
- });
8959
- if (created)
8960
- await rm4(tempPath, { force: true }).catch(() => {
8961
- });
9047
+ rotateIfNeeded(file);
9048
+ if (existsSync(file))
9049
+ chmodPrivate(file);
9050
+ appendFileSync(file, text2, { encoding: "utf8", mode: 384 });
9051
+ } catch {
8962
9052
  }
8963
9053
  }
8964
- async function createLease() {
8965
- const bytes = `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
8966
- `;
8967
- if (windowsPrivateFiles)
8968
- await createPrivateBytes(lockPath, bytes);
8969
- else
8970
- await createExclusiveText(lockPath, bytes);
9054
+ function schedule2() {
9055
+ if (!timer)
9056
+ timer = setTimeout(() => {
9057
+ timer = void 0;
9058
+ const flushed = flushLogs3(false);
9059
+ if (flushed instanceof Promise)
9060
+ void flushed.catch(() => {
9061
+ });
9062
+ }, 500);
8971
9063
  }
8972
- async function leaseContention(error) {
8973
- const code2 = error.code;
8974
- if (code2 !== "EEXIST" && code2 !== "EISDIR")
8975
- return false;
8976
- if (windowsPrivateFiles) {
8977
- if (options.onStep)
8978
- await options.onStep("lease-contention-read-ready");
9064
+ function emit(channel3, level, message, data) {
9065
+ if (logFileSource === void 0 && captureSink === void 0)
9066
+ return;
9067
+ try {
9068
+ if (ORDER[level] > ORDER[configuredLevel()])
9069
+ return;
9070
+ const scrubbedMessage = redactor.redactStrings(message);
9071
+ let scrubbedData;
8979
9072
  try {
8980
- if (code2 === "EISDIR") {
8981
- await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
8982
- await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
8983
- } else
8984
- await readOwner();
8985
- } catch (readError) {
8986
- if (readError.code !== "ENOENT")
8987
- throw readError;
9073
+ scrubbedData = redactor.redact(data);
9074
+ } catch {
9075
+ scrubbedData = "[unserializable]";
9076
+ }
9077
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${level.toUpperCase()} [${channel3}] ${scrubbedMessage}` + (data === void 0 ? "" : safeSerialize(scrubbedData)) + "\n";
9078
+ try {
9079
+ captureSink?.({
9080
+ channel: channel3,
9081
+ level,
9082
+ message: scrubbedMessage,
9083
+ data: scrubbedData
9084
+ });
9085
+ } catch {
8988
9086
  }
9087
+ if (logFileSource === void 0)
9088
+ return;
9089
+ buffer.push(line);
9090
+ if (buffer.length >= 50) {
9091
+ const flushed = flushLogs3(false);
9092
+ if (flushed instanceof Promise)
9093
+ void flushed.catch(() => {
9094
+ });
9095
+ } else
9096
+ schedule2();
9097
+ } catch {
8989
9098
  }
8990
- return true;
8991
9099
  }
8992
- async function tryAcquire() {
9100
+ function createLogger5(channel3) {
9101
+ return {
9102
+ error: (m, d) => emit(channel3, "error", m, d),
9103
+ warn: (m, d) => emit(channel3, "warn", m, d),
9104
+ info: (m, d) => emit(channel3, "info", m, d),
9105
+ debug: (m, d) => emit(channel3, "debug", m, d),
9106
+ trace: (m, d) => emit(channel3, "trace", m, d)
9107
+ };
9108
+ }
9109
+ function reset() {
8993
9110
  if (windowsPrivateFiles)
8994
- await ensurePrivateDirectory(dirname7(lockPath));
8995
- try {
8996
- await createLease();
8997
- return true;
8998
- } catch (error) {
8999
- const code2 = error.code;
9000
- if (await leaseContention(error))
9001
- return false;
9002
- if (code2 === "ENOENT") {
9003
- if (windowsPrivateFiles)
9004
- await ensurePrivateDirectory(dirname7(lockPath));
9005
- else
9006
- await mkdir7(dirname7(lockPath), { recursive: true });
9007
- try {
9008
- await createLease();
9009
- return true;
9010
- } catch (retryError) {
9011
- if (await leaseContention(retryError))
9012
- return false;
9013
- throw retryError;
9014
- }
9015
- }
9016
- throw error;
9111
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
9112
+ });
9113
+ sinkError = void 0;
9114
+ buffer = [];
9115
+ if (timer) {
9116
+ clearTimeout(timer);
9117
+ timer = void 0;
9017
9118
  }
9119
+ logFileSource = void 0;
9120
+ initLevelSource = void 0;
9121
+ runtimeLevel = void 0;
9122
+ redactor = createRedactor();
9123
+ captureSink = void 0;
9018
9124
  }
9019
- async function backoff() {
9020
- await new Promise((resolve24) => setTimeout(resolve24, Math.floor(Math.random() * 4)));
9125
+ if (options)
9126
+ configure(options);
9127
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
9128
+ }
9129
+ function createLoggerInstance(options) {
9130
+ const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
9131
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
9132
+ }
9133
+ function initLogger(options) {
9134
+ defaultEngine.configure(options);
9135
+ const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = defaultEngine;
9136
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
9137
+ }
9138
+ function setLogLevel(l) {
9139
+ defaultEngine.setLogLevel(l);
9140
+ }
9141
+ function flushLogs() {
9142
+ return defaultEngine.flushLogs();
9143
+ }
9144
+ function createLogger2(channel3) {
9145
+ return defaultEngine.createLogger(channel3);
9146
+ }
9147
+ async function flushForTest() {
9148
+ return defaultEngine.flushLogs();
9149
+ }
9150
+ function resetLoggerForTest() {
9151
+ defaultEngine.reset();
9152
+ }
9153
+ var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
9154
+ var init_engine = __esm({
9155
+ "../core/dist/common-auth-embedded/logger/engine.js"() {
9156
+ "use strict";
9157
+ init_private_files();
9158
+ init_redact();
9159
+ ORDER = {
9160
+ error: 0,
9161
+ warn: 1,
9162
+ info: 2,
9163
+ debug: 3,
9164
+ trace: 4
9165
+ };
9166
+ MAX_BYTES = 5 * 1024 * 1024;
9167
+ ROTATE_KEEP = 3;
9168
+ defaultEngine = createEngine();
9021
9169
  }
9022
- async function readLockState(notifyReady = true) {
9023
- if (notifyReady && options.onStep)
9024
- await options.onStep("lock-read-ready");
9025
- let owner;
9026
- try {
9027
- owner = await readOwner();
9028
- } catch (error) {
9029
- if (error instanceof DisappearedLockRecordError)
9030
- return { status: "missing" };
9031
- if (windowsPrivateFiles && error.code !== "ENOENT")
9032
- throw error;
9033
- }
9034
- const expiresAt = Number(owner?.expiresAt);
9035
- if (Number.isFinite(expiresAt) && expiresAt > now())
9036
- return { status: "live" };
9037
- if (typeof owner?.ownerId === "string" && Number.isFinite(expiresAt)) {
9038
- return {
9039
- status: "stale",
9040
- identity: { kind: "owner", ownerId: owner.ownerId, expiresAt }
9041
- };
9042
- }
9043
- try {
9044
- const current = await stat3(lockPath);
9045
- const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
9046
- if (legacyExpiry > now())
9047
- return { status: "live" };
9048
- return {
9049
- status: "stale",
9050
- identity: {
9051
- kind: "stat",
9052
- dev: current.dev,
9053
- ino: current.ino,
9054
- mtimeMs: current.mtimeMs,
9055
- expiresAt: legacyExpiry
9056
- }
9057
- };
9058
- } catch (error) {
9059
- if (error.code === "ENOENT") {
9060
- if (options.onStep)
9061
- await options.onStep("lock-missing");
9062
- return { status: "missing" };
9063
- }
9064
- throw error;
9065
- }
9170
+ });
9171
+
9172
+ // ../core/dist/common-auth-embedded/logger/index.js
9173
+ var logger_exports = {};
9174
+ __export(logger_exports, {
9175
+ createCaptureSink: () => createCaptureSink,
9176
+ createLogger: () => createLogger2,
9177
+ createLoggerInstance: () => createLoggerInstance,
9178
+ createRedactor: () => createRedactor,
9179
+ flushForTest: () => flushForTest,
9180
+ flushLogs: () => flushLogs,
9181
+ initLogger: () => initLogger,
9182
+ redact: () => redact,
9183
+ redactStrings: () => redactStrings,
9184
+ resetLoggerForTest: () => resetLoggerForTest,
9185
+ setLogLevel: () => setLogLevel
9186
+ });
9187
+ var init_logger2 = __esm({
9188
+ "../core/dist/common-auth-embedded/logger/index.js"() {
9189
+ "use strict";
9190
+ init_capture_sink();
9191
+ init_engine();
9192
+ init_redact();
9066
9193
  }
9067
- function sameStaleLock(observed, current) {
9068
- if (current.status !== "stale")
9069
- return false;
9070
- const identity3 = current.identity;
9071
- if (observed.kind === "owner" && identity3.kind === "owner") {
9072
- return observed.ownerId === identity3.ownerId && observed.expiresAt === identity3.expiresAt;
9194
+ });
9195
+
9196
+ // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
9197
+ import { randomUUID as randomUUID7 } from "node:crypto";
9198
+ import { link as link2, lstat as lstat3, mkdir as mkdir7, open as open5, readdir, readFile as readFile5, rename as rename6, rm as rm4, stat as stat3, unlink as unlink6 } from "node:fs/promises";
9199
+ import { basename as basename3, dirname as dirname8, join as join5 } from "node:path";
9200
+ async function createExclusiveText(path2, text2) {
9201
+ const tempPath = `${path2}.${randomUUID7()}.tmp`;
9202
+ let handle;
9203
+ try {
9204
+ handle = await open5(tempPath, "wx", 384);
9205
+ try {
9206
+ if (leaseCreationTestHooks?.beforeWrite)
9207
+ await leaseCreationTestHooks.beforeWrite(tempPath);
9208
+ await handle.writeFile(text2, "utf8");
9209
+ } finally {
9210
+ await handle.close();
9073
9211
  }
9074
- return observed.kind === "stat" && identity3.kind === "stat" && observed.dev === identity3.dev && observed.ino === identity3.ino && observed.mtimeMs === identity3.mtimeMs && observed.expiresAt === identity3.expiresAt;
9075
- }
9076
- async function ownsEvictionMarker() {
9077
9212
  try {
9078
- const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
9079
- return owner?.ownerId === evictOwnerId;
9213
+ if (leaseCreationTestHooks?.beforeLink)
9214
+ await leaseCreationTestHooks.beforeLink(tempPath, path2);
9215
+ await link2(tempPath, path2);
9080
9216
  } catch (error) {
9081
- if (windowsPrivateFiles && error.code !== "ENOENT")
9217
+ const code2 = error.code;
9218
+ if (code2 !== "EPERM" && code2 !== "ENOTSUP" && code2 !== "EOPNOTSUPP" && code2 !== "EXDEV")
9082
9219
  throw error;
9083
- return false;
9220
+ await writeExclusiveText(path2, text2);
9084
9221
  }
9085
- }
9086
- async function removeLeaseObject(path2) {
9087
- if (windowsPrivateFiles)
9088
- await privateOperation(path2, "remove", () => rm4(path2, { recursive: true, force: true }));
9089
- else
9090
- await rm4(path2, { recursive: true, force: true }).catch(() => {
9222
+ } finally {
9223
+ if (handle)
9224
+ await rm4(tempPath, { force: true }).catch(() => {
9091
9225
  });
9092
9226
  }
9093
- function isRetryableRemoval(error, path2) {
9094
- if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path2)
9095
- return false;
9096
- return isWindowsSharingViolation(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
9227
+ }
9228
+ async function writeExclusiveText(path2, text2) {
9229
+ const handle = await open5(path2, "wx", 384);
9230
+ let createdStat;
9231
+ try {
9232
+ createdStat = await handle.stat();
9233
+ } catch {
9234
+ createdStat = void 0;
9097
9235
  }
9098
- async function removeOwnedLeaseObject(path2, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
9099
- let original;
9100
- let delayMs = 5;
9101
- while (await stillOwned()) {
9102
- try {
9103
- await removeLeaseObject(path2);
9104
- return;
9105
- } catch (error) {
9106
- if (!isRetryableRemoval(error, path2))
9107
- throw error;
9108
- original ??= error;
9236
+ try {
9237
+ if (leaseCreationTestHooks?.beforeWrite)
9238
+ await leaseCreationTestHooks.beforeWrite(path2);
9239
+ await handle.writeFile(text2, "utf8");
9240
+ } catch (error) {
9241
+ try {
9242
+ const current = await lstat3(path2).catch(() => void 0);
9243
+ if (createdStat && current && current.dev === createdStat.dev && current.ino === createdStat.ino) {
9244
+ await rm4(path2, { force: true }).catch(() => {
9245
+ });
9109
9246
  }
9110
- const remainingMs = deadline - performance.now();
9111
- if (remainingMs <= 0)
9112
- throw original;
9113
- await new Promise((resolve24) => setTimeout(resolve24, Math.min(delayMs, remainingMs)));
9114
- if (performance.now() >= deadline)
9115
- throw original;
9116
- delayMs = Math.min(delayMs * 2, 50);
9247
+ } catch {
9117
9248
  }
9249
+ throw error;
9250
+ } finally {
9251
+ await handle.close();
9118
9252
  }
9119
- async function releaseEvictionMarker(deadline) {
9120
- let ownedDirectory;
9121
- await removeOwnedLeaseObject(evictPath, async () => {
9122
- if (!windowsPrivateFiles)
9123
- return ownsEvictionMarker();
9124
- const current = await lstat3(evictPath).catch((error) => {
9125
- if (error.code !== "ENOENT")
9126
- throw error;
9127
- return void 0;
9128
- });
9129
- if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
9130
- return false;
9131
- if (await ownsEvictionMarker()) {
9132
- ownedDirectory = current;
9133
- return true;
9134
- }
9135
- if (!ownedDirectory)
9136
- return false;
9137
- try {
9138
- await stat3(evictOwnerPath);
9139
- return false;
9140
- } catch (error) {
9141
- if (error.code !== "ENOENT")
9142
- throw error;
9143
- return true;
9144
- }
9145
- }, deadline);
9253
+ }
9254
+ function isStagingName(name, lockName) {
9255
+ const prefix = `${lockName}.`;
9256
+ const suffix = ".tmp";
9257
+ if (!name.startsWith(prefix) || !name.endsWith(suffix))
9258
+ return false;
9259
+ return STAGING_UUID.test(name.slice(prefix.length, -suffix.length));
9260
+ }
9261
+ function sameStagingFile(a, b) {
9262
+ return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.birthtimeMs === b.birthtimeMs;
9263
+ }
9264
+ async function readStagedOwner(path2) {
9265
+ const before = await lstat3(path2);
9266
+ if (!before.isFile() || before.isSymbolicLink())
9267
+ return void 0;
9268
+ if (before.size > STAGING_SWEEP_MAX_BYTES)
9269
+ return void 0;
9270
+ const handle = await open5(path2, "r");
9271
+ let text2;
9272
+ try {
9273
+ if (!sameStagingFile(before, await handle.stat()))
9274
+ return void 0;
9275
+ text2 = await handle.readFile("utf8");
9276
+ } finally {
9277
+ await handle.close();
9146
9278
  }
9147
- async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
9148
- if (!created)
9149
- return false;
9150
- let stillOurs = false;
9279
+ let record3;
9280
+ try {
9281
+ record3 = JSON.parse(text2);
9282
+ } catch {
9283
+ return void 0;
9284
+ }
9285
+ if (!record3 || typeof record3 !== "object" || Array.isArray(record3))
9286
+ return void 0;
9287
+ const keys = Object.keys(record3).sort();
9288
+ if (keys.length !== 2 || keys[0] !== "expiresAt" || keys[1] !== "ownerId")
9289
+ return void 0;
9290
+ const { ownerId, expiresAt } = record3;
9291
+ if (typeof ownerId !== "string" || !STAGING_UUID.test(ownerId))
9292
+ return void 0;
9293
+ if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
9294
+ return void 0;
9295
+ return { identity: before, expiresAt };
9296
+ }
9297
+ async function sweepAbandonedStaging(lockPath, ttlMs, now) {
9298
+ const directory = dirname8(lockPath);
9299
+ const lockName = basename3(lockPath);
9300
+ const hooks = stagingSweepTestHooks;
9301
+ const names = await (hooks?.readdir ?? readdir)(directory);
9302
+ const candidates = names.filter((name) => isStagingName(name, lockName)).slice(0, STAGING_SWEEP_MAX_CANDIDATES);
9303
+ const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS);
9304
+ for (const name of candidates) {
9305
+ const path2 = join5(directory, name);
9151
9306
  try {
9152
- await removeOwnedLeaseObject(evictPath, async () => {
9153
- stillOurs = false;
9154
- const st = await lstat3(evictPath).catch(() => void 0);
9155
- if (!st || !sameMarkerDirectory(created, st))
9156
- return false;
9157
- stillOurs = true;
9158
- try {
9159
- await stat3(evictOwnerPath);
9160
- return false;
9161
- } catch (error) {
9162
- return error.code === "ENOENT";
9163
- }
9164
- }, deadline);
9307
+ if (now() - (await lstat3(path2)).mtimeMs < marginMs)
9308
+ continue;
9309
+ const staged = await readStagedOwner(path2);
9310
+ if (!staged || !(staged.expiresAt < now() - marginMs))
9311
+ continue;
9312
+ if (hooks?.beforeUnlink)
9313
+ await hooks.beforeUnlink(path2);
9314
+ const current = await readStagedOwner(path2);
9315
+ if (!current || !sameStagingFile(staged.identity, current.identity) || !(current.expiresAt < now() - marginMs))
9316
+ continue;
9317
+ await (hooks?.unlink ?? unlink6)(path2);
9165
9318
  } catch {
9166
9319
  }
9167
- return stillOurs;
9168
9320
  }
9169
- async function tryAcquireEvictionMarker(deadline) {
9170
- if (windowsPrivateFiles)
9171
- await createPrivateDirectoryExclusive(evictPath);
9172
- else
9173
- await mkdir7(evictPath);
9174
- let created;
9321
+ }
9322
+ function startStagingSweep(lockPath, ttlMs, now) {
9323
+ if (sweptLockPaths.has(lockPath))
9324
+ return;
9325
+ sweptLockPaths.add(lockPath);
9326
+ const sweep = Promise.resolve().then(() => sweepAbandonedStaging(lockPath, ttlMs, now)).catch(() => {
9327
+ });
9328
+ pendingStagingSweeps.add(sweep);
9329
+ void sweep.finally(() => pendingStagingSweeps.delete(sweep));
9330
+ }
9331
+ function isLostMarkerRaceError(error) {
9332
+ const code2 = error?.code;
9333
+ return code2 === "ENOENT" || !windowsPrivateFiles && (code2 === "EINVAL" || code2 === "ENOTDIR");
9334
+ }
9335
+ function sameMarkerDirectory(created, current) {
9336
+ if (created.dev !== current.dev || created.ino !== current.ino)
9337
+ return false;
9338
+ if (created.ino === 0 && created.birthtimeMs !== current.birthtimeMs)
9339
+ return false;
9340
+ return true;
9341
+ }
9342
+ function acquireRefreshFileLock(options) {
9343
+ return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
9344
+ }
9345
+ async function acquireRefreshFileLockWithClock(options) {
9346
+ const lockPath = lockPathFor(options.path, options.name);
9347
+ const legacyOwnerPath = join5(lockPath, "owner.json");
9348
+ const ownerId = randomUUID7();
9349
+ const now = options.now ?? Date.now;
9350
+ let renewTimer = null;
9351
+ let released = false;
9352
+ let releaseConfirmed = false;
9353
+ let loss;
9354
+ let resolveLoss;
9355
+ const lostPromise = new Promise((resolve24) => {
9356
+ resolveLoss = resolve24;
9357
+ });
9358
+ function notifyTimerStep(event) {
9175
9359
  try {
9176
- const st = await lstat3(evictPath);
9177
- created = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
9360
+ const result = options.onRenewalTimer?.(event);
9361
+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function") {
9362
+ void Promise.resolve(result).catch(() => {
9363
+ });
9364
+ }
9178
9365
  } catch {
9179
- created = void 0;
9180
9366
  }
9181
- try {
9182
- await evictionMarkerTestHooks?.beforeOwnerWrite?.(evictPath, evictOwnerPath);
9183
- const injected = await evictionMarkerTestHooks?.failOwnerWrite?.(evictPath, evictOwnerPath);
9184
- if (injected !== void 0)
9185
- throw injected;
9186
- const bytes = `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}
9187
- `;
9188
- if (windowsPrivateFiles)
9189
- await createPrivateBytes(evictOwnerPath, bytes);
9190
- else
9191
- await writeExclusiveText(evictOwnerPath, bytes);
9192
- } catch (error) {
9193
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
9194
- if (isLostMarkerRaceError(error) && !stillOurs)
9195
- return false;
9367
+ }
9368
+ function cancelRenewalTimer() {
9369
+ if (!renewTimer)
9370
+ return;
9371
+ clearRefreshLockRenewalTimeout(renewTimer);
9372
+ renewTimer = null;
9373
+ notifyTimerStep("cancelled");
9374
+ }
9375
+ function recordLoss(reason, owner) {
9376
+ if (loss || released)
9377
+ return;
9378
+ loss = Object.freeze({
9379
+ reason,
9380
+ expectedOwnerId: ownerId,
9381
+ ...typeof owner?.ownerId === "string" ? { observedOwnerId: owner.ownerId } : {},
9382
+ ...typeof owner?.expiresAt === "number" ? { observedExpiresAt: owner.expiresAt } : {}
9383
+ });
9384
+ cancelRenewalTimer();
9385
+ resolveLoss(loss);
9386
+ }
9387
+ let terminalIOError;
9388
+ let renewalInFlight = null;
9389
+ const evictPath = `${lockPath}.evicting`;
9390
+ const evictOwnerPath = join5(evictPath, "owner.json");
9391
+ const evictOwnerId = randomUUID7();
9392
+ const EVICT_TTL = 5e3;
9393
+ const MAX_STEAL_ATTEMPTS = 8;
9394
+ function isChangingLockCreate(error) {
9395
+ return windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [lockPath], "create") || isWindowsAccessDeniedCreate(error, [evictPath], "directory-create"));
9396
+ }
9397
+ async function readOwner() {
9398
+ if (windowsPrivateFiles) {
9196
9399
  try {
9197
- await releaseEvictionMarker(deadline);
9198
- } catch {
9400
+ return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
9401
+ } catch (error) {
9402
+ if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
9403
+ throw error;
9404
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
9405
+ return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
9199
9406
  }
9200
- throw error;
9201
9407
  }
9202
- if (options.onStep)
9203
- await options.onStep("eviction-marker-acquired");
9204
- return true;
9205
- }
9206
- async function recoverStaleEvictionMarker(deadline) {
9207
- let evictStat;
9208
9408
  try {
9209
- evictStat = await stat3(evictPath);
9409
+ return JSON.parse(await readFile5(lockPath, "utf8"));
9210
9410
  } catch (error) {
9211
- if (error.code === "ENOENT")
9212
- return "missing";
9213
- throw error;
9411
+ const code2 = error.code;
9412
+ if (code2 !== "EISDIR")
9413
+ throw error;
9414
+ return JSON.parse(await readFile5(legacyOwnerPath, "utf8"));
9214
9415
  }
9416
+ }
9417
+ async function writeOwner() {
9215
9418
  if (windowsPrivateFiles) {
9216
- try {
9217
- await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9218
- } catch (error) {
9219
- if (error.code === "ENOENT")
9220
- return "missing";
9221
- throw error;
9419
+ const owner = await readOwner();
9420
+ const remaining = Number(owner?.expiresAt) - now();
9421
+ await writePrivateAtomic(lockPath, `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9422
+ `, {
9423
+ deadline: performance.now() + Math.max(0, remaining),
9424
+ beforeRename: async () => {
9425
+ const current = await readOwner();
9426
+ if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
9427
+ throw new LockOwnershipError({
9428
+ target: options.path,
9429
+ name: options.name
9430
+ });
9431
+ }
9432
+ }
9433
+ });
9434
+ return;
9435
+ }
9436
+ const tempPath = `${lockPath}.${randomUUID7()}.tmp`;
9437
+ let handle;
9438
+ let created = false;
9439
+ try {
9440
+ handle = await open5(tempPath, "wx", 384);
9441
+ created = true;
9442
+ await handle.writeFile(`${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9443
+ `, "utf8");
9444
+ await handle.chmod(384);
9445
+ await handle.close();
9446
+ handle = void 0;
9447
+ const current = await readOwner();
9448
+ if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
9449
+ throw new LockOwnershipError({
9450
+ target: options.path,
9451
+ name: options.name
9452
+ });
9222
9453
  }
9454
+ await rename6(tempPath, lockPath);
9455
+ created = false;
9456
+ } finally {
9457
+ await handle?.close().catch(() => {
9458
+ });
9459
+ if (created)
9460
+ await rm4(tempPath, { force: true }).catch(() => {
9461
+ });
9223
9462
  }
9224
- if (evictStat.mtimeMs + EVICT_TTL > now()) {
9225
- let hasOwner = true;
9463
+ }
9464
+ async function createLease() {
9465
+ const bytes = `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
9466
+ `;
9467
+ if (windowsPrivateFiles)
9468
+ await createPrivateBytes(lockPath, bytes);
9469
+ else
9470
+ await createExclusiveText(lockPath, bytes);
9471
+ }
9472
+ async function leaseContention(error) {
9473
+ const code2 = error.code;
9474
+ if (code2 !== "EEXIST" && code2 !== "EISDIR")
9475
+ return false;
9476
+ if (windowsPrivateFiles) {
9477
+ if (options.onStep)
9478
+ await options.onStep("lease-contention-read-ready");
9226
9479
  try {
9227
- await stat3(evictOwnerPath);
9228
- } catch (error) {
9229
- if (error.code === "ENOENT")
9230
- hasOwner = false;
9231
- else
9232
- return "fresh";
9480
+ if (code2 === "EISDIR") {
9481
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
9482
+ await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
9483
+ } else
9484
+ await readOwner();
9485
+ } catch (readError) {
9486
+ if (readError.code !== "ENOENT")
9487
+ throw readError;
9233
9488
  }
9234
- if (hasOwner)
9235
- return "fresh";
9236
- if (evictStat.mtimeMs + OWNERLESS_MARKER_GRACE_MS > now())
9237
- return "fresh";
9238
9489
  }
9239
- if (options.onStep)
9240
- await options.onStep("stale-marker-stat");
9241
- const claimedPath = `${evictPath}.${randomUUID7()}`;
9490
+ return true;
9491
+ }
9492
+ async function tryAcquire() {
9493
+ if (windowsPrivateFiles)
9494
+ await ensurePrivateDirectory(dirname8(lockPath));
9242
9495
  try {
9243
- await rename6(evictPath, claimedPath);
9496
+ await createLease();
9497
+ return true;
9244
9498
  } catch (error) {
9245
- if (error.code === "ENOENT")
9246
- return "missing";
9499
+ const code2 = error.code;
9500
+ if (await leaseContention(error))
9501
+ return false;
9502
+ if (code2 === "ENOENT") {
9503
+ if (windowsPrivateFiles)
9504
+ await ensurePrivateDirectory(dirname8(lockPath));
9505
+ else
9506
+ await mkdir7(dirname8(lockPath), { recursive: true });
9507
+ try {
9508
+ await createLease();
9509
+ return true;
9510
+ } catch (retryError) {
9511
+ if (await leaseContention(retryError))
9512
+ return false;
9513
+ throw retryError;
9514
+ }
9515
+ }
9247
9516
  throw error;
9248
9517
  }
9249
- if (options.onStep)
9250
- await options.onStep("stale-marker-claimed");
9251
- const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : void 0;
9252
- await removeOwnedLeaseObject(claimedPath, async () => {
9253
- if (!claimedIdentity)
9254
- return true;
9255
- const current = await lstat3(claimedPath).catch((error) => {
9256
- if (error.code !== "ENOENT")
9257
- throw error;
9258
- return void 0;
9259
- });
9260
- return !!current && sameMarkerDirectory(claimedIdentity, current);
9261
- }, deadline);
9262
- return "recovered";
9263
9518
  }
9264
- async function withEvictionMarker(action, deadline) {
9265
- try {
9266
- if (!await tryAcquireEvictionMarker(deadline))
9267
- return false;
9519
+ async function backoff() {
9520
+ await new Promise((resolve24) => setTimeout(resolve24, Math.floor(Math.random() * 4)));
9521
+ }
9522
+ async function readLockState(notifyReady = true) {
9523
+ if (notifyReady && options.onStep)
9524
+ await options.onStep("lock-read-ready");
9525
+ let owner;
9526
+ try {
9527
+ owner = await readOwner();
9528
+ } catch (error) {
9529
+ if (error instanceof DisappearedLockRecordError)
9530
+ return { status: "missing" };
9531
+ if (windowsPrivateFiles && error.code !== "ENOENT")
9532
+ throw error;
9533
+ }
9534
+ const expiresAt = Number(owner?.expiresAt);
9535
+ if (Number.isFinite(expiresAt) && expiresAt > now())
9536
+ return { status: "live" };
9537
+ if (typeof owner?.ownerId === "string" && Number.isFinite(expiresAt)) {
9538
+ return {
9539
+ status: "stale",
9540
+ identity: { kind: "owner", ownerId: owner.ownerId, expiresAt }
9541
+ };
9542
+ }
9543
+ try {
9544
+ const current = await stat3(lockPath);
9545
+ const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
9546
+ if (legacyExpiry > now())
9547
+ return { status: "live" };
9548
+ return {
9549
+ status: "stale",
9550
+ identity: {
9551
+ kind: "stat",
9552
+ dev: current.dev,
9553
+ ino: current.ino,
9554
+ mtimeMs: current.mtimeMs,
9555
+ expiresAt: legacyExpiry
9556
+ }
9557
+ };
9558
+ } catch (error) {
9559
+ if (error.code === "ENOENT") {
9560
+ if (options.onStep)
9561
+ await options.onStep("lock-missing");
9562
+ return { status: "missing" };
9563
+ }
9564
+ throw error;
9565
+ }
9566
+ }
9567
+ function sameStaleLock(observed, current) {
9568
+ if (current.status !== "stale")
9569
+ return false;
9570
+ const identity3 = current.identity;
9571
+ if (observed.kind === "owner" && identity3.kind === "owner") {
9572
+ return observed.ownerId === identity3.ownerId && observed.expiresAt === identity3.expiresAt;
9573
+ }
9574
+ return observed.kind === "stat" && identity3.kind === "stat" && observed.dev === identity3.dev && observed.ino === identity3.ino && observed.mtimeMs === identity3.mtimeMs && observed.expiresAt === identity3.expiresAt;
9575
+ }
9576
+ async function ownsEvictionMarker() {
9577
+ try {
9578
+ const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
9579
+ return owner?.ownerId === evictOwnerId;
9580
+ } catch (error) {
9581
+ if (windowsPrivateFiles && error.code !== "ENOENT")
9582
+ throw error;
9583
+ return false;
9584
+ }
9585
+ }
9586
+ async function removeLeaseObject(path2) {
9587
+ if (windowsPrivateFiles)
9588
+ await privateOperation(path2, "remove", () => rm4(path2, { recursive: true, force: true }));
9589
+ else
9590
+ await rm4(path2, { recursive: true, force: true }).catch(() => {
9591
+ });
9592
+ }
9593
+ function isRetryableRemoval(error, path2) {
9594
+ if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path2)
9595
+ return false;
9596
+ return isWindowsSharingViolation(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
9597
+ }
9598
+ async function removeOwnedLeaseObject(path2, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
9599
+ let original;
9600
+ let delayMs = 5;
9601
+ while (await stillOwned()) {
9602
+ try {
9603
+ await removeLeaseObject(path2);
9604
+ return;
9605
+ } catch (error) {
9606
+ if (!isRetryableRemoval(error, path2))
9607
+ throw error;
9608
+ original ??= error;
9609
+ }
9610
+ const remainingMs = deadline - performance.now();
9611
+ if (remainingMs <= 0)
9612
+ throw original;
9613
+ await new Promise((resolve24) => setTimeout(resolve24, Math.min(delayMs, remainingMs)));
9614
+ if (performance.now() >= deadline)
9615
+ throw original;
9616
+ delayMs = Math.min(delayMs * 2, 50);
9617
+ }
9618
+ }
9619
+ async function releaseEvictionMarker(deadline) {
9620
+ let ownedDirectory;
9621
+ await removeOwnedLeaseObject(evictPath, async () => {
9622
+ if (!windowsPrivateFiles)
9623
+ return ownsEvictionMarker();
9624
+ const current = await lstat3(evictPath).catch((error) => {
9625
+ if (error.code !== "ENOENT")
9626
+ throw error;
9627
+ return void 0;
9628
+ });
9629
+ if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
9630
+ return false;
9631
+ if (await ownsEvictionMarker()) {
9632
+ ownedDirectory = current;
9633
+ return true;
9634
+ }
9635
+ if (!ownedDirectory)
9636
+ return false;
9637
+ try {
9638
+ await stat3(evictOwnerPath);
9639
+ return false;
9640
+ } catch (error) {
9641
+ if (error.code !== "ENOENT")
9642
+ throw error;
9643
+ return true;
9644
+ }
9645
+ }, deadline);
9646
+ }
9647
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
9648
+ if (!created)
9649
+ return false;
9650
+ let stillOurs = false;
9651
+ try {
9652
+ await removeOwnedLeaseObject(evictPath, async () => {
9653
+ stillOurs = false;
9654
+ const st = await lstat3(evictPath).catch(() => void 0);
9655
+ if (!st || !sameMarkerDirectory(created, st))
9656
+ return false;
9657
+ stillOurs = true;
9658
+ try {
9659
+ await stat3(evictOwnerPath);
9660
+ return false;
9661
+ } catch (error) {
9662
+ return error.code === "ENOENT";
9663
+ }
9664
+ }, deadline);
9665
+ } catch {
9666
+ }
9667
+ return stillOurs;
9668
+ }
9669
+ async function tryAcquireEvictionMarker(deadline) {
9670
+ if (windowsPrivateFiles)
9671
+ await createPrivateDirectoryExclusive(evictPath);
9672
+ else
9673
+ await mkdir7(evictPath);
9674
+ let created;
9675
+ try {
9676
+ const st = await lstat3(evictPath);
9677
+ created = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
9678
+ } catch {
9679
+ created = void 0;
9680
+ }
9681
+ try {
9682
+ await evictionMarkerTestHooks?.beforeOwnerWrite?.(evictPath, evictOwnerPath);
9683
+ const injected = await evictionMarkerTestHooks?.failOwnerWrite?.(evictPath, evictOwnerPath);
9684
+ if (injected !== void 0)
9685
+ throw injected;
9686
+ const bytes = `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}
9687
+ `;
9688
+ if (windowsPrivateFiles)
9689
+ await createPrivateBytes(evictOwnerPath, bytes);
9690
+ else
9691
+ await writeExclusiveText(evictOwnerPath, bytes);
9692
+ } catch (error) {
9693
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
9694
+ if (isLostMarkerRaceError(error) && !stillOurs)
9695
+ return false;
9696
+ try {
9697
+ await releaseEvictionMarker(deadline);
9698
+ } catch {
9699
+ }
9700
+ throw error;
9701
+ }
9702
+ if (options.onStep)
9703
+ await options.onStep("eviction-marker-acquired");
9704
+ return true;
9705
+ }
9706
+ async function recoverStaleEvictionMarker(deadline) {
9707
+ let evictStat;
9708
+ try {
9709
+ evictStat = await stat3(evictPath);
9710
+ } catch (error) {
9711
+ if (error.code === "ENOENT")
9712
+ return "missing";
9713
+ throw error;
9714
+ }
9715
+ if (windowsPrivateFiles) {
9716
+ try {
9717
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9718
+ } catch (error) {
9719
+ if (error.code === "ENOENT")
9720
+ return "missing";
9721
+ throw error;
9722
+ }
9723
+ }
9724
+ if (evictStat.mtimeMs + EVICT_TTL > now()) {
9725
+ let hasOwner = true;
9726
+ try {
9727
+ await stat3(evictOwnerPath);
9728
+ } catch (error) {
9729
+ if (error.code === "ENOENT")
9730
+ hasOwner = false;
9731
+ else
9732
+ return "fresh";
9733
+ }
9734
+ if (hasOwner)
9735
+ return "fresh";
9736
+ if (evictStat.mtimeMs + OWNERLESS_MARKER_GRACE_MS > now())
9737
+ return "fresh";
9738
+ }
9739
+ if (options.onStep)
9740
+ await options.onStep("stale-marker-stat");
9741
+ const claimedPath = `${evictPath}.${randomUUID7()}`;
9742
+ try {
9743
+ await rename6(evictPath, claimedPath);
9744
+ } catch (error) {
9745
+ if (error.code === "ENOENT")
9746
+ return "missing";
9747
+ throw error;
9748
+ }
9749
+ if (options.onStep)
9750
+ await options.onStep("stale-marker-claimed");
9751
+ const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : void 0;
9752
+ await removeOwnedLeaseObject(claimedPath, async () => {
9753
+ if (!claimedIdentity)
9754
+ return true;
9755
+ const current = await lstat3(claimedPath).catch((error) => {
9756
+ if (error.code !== "ENOENT")
9757
+ throw error;
9758
+ return void 0;
9759
+ });
9760
+ return !!current && sameMarkerDirectory(claimedIdentity, current);
9761
+ }, deadline);
9762
+ return "recovered";
9763
+ }
9764
+ async function withEvictionMarker(action, deadline) {
9765
+ try {
9766
+ if (!await tryAcquireEvictionMarker(deadline))
9767
+ return false;
9268
9768
  } catch (error) {
9269
9769
  if (error.code === "EEXIST") {
9270
9770
  if (windowsPrivateFiles) {
@@ -9520,6 +10020,7 @@ async function acquireRefreshFileLockWithClock(options) {
9520
10020
  return null;
9521
10021
  }
9522
10022
  scheduleRenewal();
10023
+ startStagingSweep(lockPath, options.ttlMs, now);
9523
10024
  return {
9524
10025
  ownerId,
9525
10026
  whenLost: () => lostPromise,
@@ -9583,17 +10084,15 @@ async function acquireRefreshFileLockWithClock(options) {
9583
10084
  removalConfirmed = true;
9584
10085
  }, deadline);
9585
10086
  changingRecordError = void 0;
9586
- if (markerAcquired) {
9587
- if (windowsPrivateFiles && !removalConfirmed)
9588
- throw new PrivateFileError(lockPath, "release-not-confirmed", {
9589
- code: "EIO"
9590
- });
9591
- releaseConfirmed = removalConfirmed;
10087
+ if (markerAcquired && removalConfirmed) {
10088
+ releaseConfirmed = true;
9592
10089
  return;
9593
10090
  }
9594
- if (signal?.aborted)
9595
- return;
9596
- await recoverStaleEvictionMarker(deadline);
10091
+ if (!markerAcquired) {
10092
+ if (signal?.aborted)
10093
+ return;
10094
+ await recoverStaleEvictionMarker(deadline);
10095
+ }
9597
10096
  } catch (error) {
9598
10097
  const changingRecord = windowsPrivateFiles && (isChangingLockCreate(error) || isWindowsAccessDeniedRead(error, [
9599
10098
  lockPath,
@@ -9623,16 +10122,26 @@ async function acquireRefreshFileLockWithClock(options) {
9623
10122
  throw changingRecordError ?? removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
9624
10123
  code: "ETIMEDOUT"
9625
10124
  });
10125
+ createLogger2("fs").warn("File lock release deadline expired", {
10126
+ lockPath
10127
+ });
9626
10128
  }
9627
10129
  };
9628
10130
  }
9629
- var leaseCreationTestHooks, setRefreshLockRenewalTimeout, clearRefreshLockRenewalTimeout, evictionMarkerTestHooks, OWNERLESS_MARKER_GRACE_MS;
10131
+ var leaseCreationTestHooks, STAGING_UUID, STAGING_SWEEP_MIN_AGE_MS, STAGING_SWEEP_MAX_CANDIDATES, STAGING_SWEEP_MAX_BYTES, sweptLockPaths, pendingStagingSweeps, stagingSweepTestHooks, setRefreshLockRenewalTimeout, clearRefreshLockRenewalTimeout, evictionMarkerTestHooks, OWNERLESS_MARKER_GRACE_MS;
9630
10132
  var init_refresh_file_lock = __esm({
9631
10133
  "../core/dist/common-auth-embedded/fs/refresh-file-lock.js"() {
9632
10134
  "use strict";
10135
+ init_logger2();
9633
10136
  init_lock_record();
9634
10137
  init_private_files();
9635
10138
  init_with_lock();
10139
+ STAGING_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
10140
+ STAGING_SWEEP_MIN_AGE_MS = 10 * 6e4;
10141
+ STAGING_SWEEP_MAX_CANDIDATES = 256;
10142
+ STAGING_SWEEP_MAX_BYTES = 4096;
10143
+ sweptLockPaths = /* @__PURE__ */ new Set();
10144
+ pendingStagingSweeps = /* @__PURE__ */ new Set();
9636
10145
  setRefreshLockRenewalTimeout = globalThis.setTimeout.bind(globalThis);
9637
10146
  clearRefreshLockRenewalTimeout = globalThis.clearTimeout.bind(globalThis);
9638
10147
  OWNERLESS_MARKER_GRACE_MS = 1e3;
@@ -9640,12 +10149,12 @@ var init_refresh_file_lock = __esm({
9640
10149
  });
9641
10150
 
9642
10151
  // ../core/dist/common-auth-embedded/fs/with-lock.js
9643
- import { join as join6, resolve as resolve4 } from "node:path";
10152
+ import { join as join6, resolve as resolve5 } from "node:path";
9644
10153
  function lockPathFor(target, name) {
9645
10154
  return `${target}.${name}.lock`;
9646
10155
  }
9647
10156
  function isChangingLockRecord(error, target, name) {
9648
- const path2 = resolve4(lockPathFor(target, name));
10157
+ const path2 = resolve5(lockPathFor(target, name));
9649
10158
  const paths = [path2, join6(path2, "owner.json")];
9650
10159
  return (isWindowsSharingViolation(error) || isWindowsAccessDeniedRead(error, paths)) && (error.stage === "read" || error.stage === "verify") && paths.includes(error.path) || windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [path2], "create") || isWindowsAccessDeniedCreate(error, [`${path2}.evicting`], "directory-create"));
9651
10160
  }
@@ -12439,567 +12948,144 @@ async function publishRoster(rt, plan, options = {}) {
12439
12948
  await tx.commitConfig({ durable: true, publicationDecision: true });
12440
12949
  return { outcome: "published", receipt: await cleanup(tx, receipt2) };
12441
12950
  }, { completeTorn: false });
12442
- if (result)
12443
- return result;
12444
- await locks.releaseAll();
12445
- if (attempt >= 1)
12446
- throw refusal2("publishRoster", plan.operationId, "row-key-changed", "a named row changed lock key twice during publication", true);
12447
- }
12448
- });
12449
- }
12450
- var init_publication = __esm({
12451
- "../core/dist/common-auth-embedded/store/publication.js"() {
12452
- "use strict";
12453
- init_hooks();
12454
- init_mutate();
12455
- init_rows();
12456
- init_runtime();
12457
- init_schema();
12458
- }
12459
- });
12460
-
12461
- // ../core/dist/common-auth-embedded/store/pull.js
12462
- var PullScheduler;
12463
- var init_pull = __esm({
12464
- "../core/dist/common-auth-embedded/store/pull.js"() {
12465
- "use strict";
12466
- init_attribution();
12467
- init_errors();
12468
- init_mutate();
12469
- init_refresh_lock();
12470
- init_runtime();
12471
- PullScheduler = class {
12472
- rt;
12473
- hook;
12474
- onFailure;
12475
- firedAtLoad;
12476
- logger;
12477
- inflight = /* @__PURE__ */ new Set();
12478
- constructor(rt, hook, onFailure, firedAtLoad, logger2) {
12479
- this.rt = rt;
12480
- this.hook = hook;
12481
- this.onFailure = onFailure;
12482
- this.firedAtLoad = firedAtLoad;
12483
- this.logger = logger2;
12484
- }
12485
- fire(id, reason) {
12486
- if (!this.hook)
12487
- return;
12488
- if (reason === "load") {
12489
- if (this.firedAtLoad.has(id))
12490
- return;
12491
- this.firedAtLoad.add(id);
12492
- }
12493
- const run = this.run(id, reason);
12494
- this.inflight.add(run);
12495
- void run.finally(() => this.inflight.delete(run));
12496
- }
12497
- /** Resolves once every pull fired so far has settled. */
12498
- async settled() {
12499
- while (this.inflight.size > 0)
12500
- await Promise.allSettled([...this.inflight]);
12501
- }
12502
- async run(id, reason) {
12503
- const rt = this.rt();
12504
- const { ctx } = rt;
12505
- const locks = new LockStack(ctx.lockDefaults, ctx.lockEnv);
12506
- const progress = { writes: 0 };
12507
- try {
12508
- const request2 = await withTransaction(ctx, locks, progress, { operation: "pull", rowId: id }, async (tx) => {
12509
- if (tx.reservation(id) !== void 0)
12510
- return void 0;
12511
- await tx.completeTorn();
12512
- const row = tx.row(id);
12513
- if (row?.unbound && row.enabled && row.type === "oauth" && row.credential && !row.invalid)
12514
- requireBound("pull", row);
12515
- if (!row?.candidate || row.type !== "oauth")
12516
- return void 0;
12517
- if (!row.hasEntry) {
12518
- tx.setEntry(id, { credentialEpoch: 1, needsFirstReading: true });
12519
- await tx.commitConfig();
12520
- }
12521
- const current = tx.row(id);
12522
- if (!current?.credential || current.credentialEpoch === void 0)
12523
- return void 0;
12524
- return {
12525
- id,
12526
- credential: current.credential,
12527
- credentialEpoch: current.credentialEpoch,
12528
- ...current.identity !== void 0 ? { identity: current.identity } : {},
12529
- reason
12530
- };
12531
- }, { completeTorn: false });
12532
- await locks.releaseAll();
12533
- if (!request2) {
12534
- this.firedAtLoad.delete(id);
12535
- return;
12536
- }
12537
- await ctx.hold?.("pull-before-request", id);
12538
- let observation;
12539
- try {
12540
- observation = await this.hook?.(request2);
12541
- } catch (cause) {
12542
- throw new PoolOperationError({
12543
- operation: "pull",
12544
- rowId: id,
12545
- phase: "pull",
12546
- retryable: true,
12547
- kind: "pull",
12548
- message: "the quota pull rejected",
12549
- cause
12550
- });
12551
- }
12552
- const publish = rt.publishQuota ?? ((rowId2, attribution, value) => recordQuota(rt, rowId2, attribution, value));
12553
- await publish(id, {
12554
- credentialEpoch: request2.credentialEpoch,
12555
- ...request2.identity !== void 0 ? { identity: request2.identity } : {}
12556
- }, observation);
12557
- } catch (error) {
12558
- this.firedAtLoad.delete(id);
12559
- const failure = toFailure(error, "pull", id, progress);
12560
- if (this.onFailure) {
12561
- try {
12562
- await this.onFailure(id, failure);
12563
- } catch (hookError) {
12564
- this.logger?.warn("pull failure hook threw", {
12565
- rowId: id,
12566
- error: hookError instanceof Error ? hookError.message : String(hookError)
12567
- });
12568
- }
12569
- } else {
12570
- this.logger?.warn("quota pull failed", {
12571
- rowId: id,
12572
- kind: failure.kind
12573
- });
12574
- }
12575
- } finally {
12576
- await locks.releaseAll();
12577
- }
12578
- }
12579
- };
12580
- }
12581
- });
12582
-
12583
- // ../core/dist/common-auth-embedded/logger/capture-sink.js
12584
- function createCaptureSink() {
12585
- const records = [];
12586
- const sink = (record3) => {
12587
- records.push(record3);
12588
- };
12589
- return {
12590
- records,
12591
- sink,
12592
- clear: () => {
12593
- records.length = 0;
12594
- }
12595
- };
12596
- }
12597
- var init_capture_sink = __esm({
12598
- "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
12599
- "use strict";
12600
- }
12601
- });
12602
-
12603
- // ../core/dist/common-auth-embedded/logger/redact.js
12604
- function isError(value) {
12605
- return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
12606
- }
12607
- function createRedactor(options = {}) {
12608
- const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
12609
- function isSecretKey(key) {
12610
- const normalized = key.toLowerCase().replace(/[-_]/g, "");
12611
- return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
12612
- }
12613
- function errorEntries(error) {
12614
- const fields2 = error;
12615
- const entries = [
12616
- ["name", error.name],
12617
- ["message", error.message],
12618
- ["stack", error.stack]
12619
- ];
12620
- for (const key of ["code", "status", "cause"])
12621
- if (fields2[key] !== void 0)
12622
- entries.push([key, fields2[key]]);
12623
- const listed = new Set(entries.map(([key]) => key));
12624
- for (const entry of Object.entries(error))
12625
- if (!listed.has(entry[0]))
12626
- entries.push(entry);
12627
- return entries;
12628
- }
12629
- function walk(value, keys, seen, errorDepth = 0) {
12630
- if (typeof value === "string") {
12631
- return patterns.reduce((text2, pattern) => text2.replace(pattern, MASK), value);
12632
- }
12633
- if (!value || typeof value !== "object")
12634
- return value;
12635
- if (seen.has(value))
12636
- return "[Circular]";
12637
- seen.add(value);
12638
- try {
12639
- if (Array.isArray(value))
12640
- return value.map((item) => walk(item, keys, seen, errorDepth));
12641
- const error = isError(value);
12642
- if (error && errorDepth >= MAX_ERROR_DEPTH)
12643
- return "[Truncated]";
12644
- const childDepth = error ? errorDepth + 1 : errorDepth;
12645
- return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
12646
- key,
12647
- keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
12648
- ]));
12649
- } finally {
12650
- seen.delete(value);
12651
- }
12652
- }
12653
- return {
12654
- redact: (value) => walk(value, true, /* @__PURE__ */ new WeakSet()),
12655
- // Schema keys describe arguments, not credentials; only their string values are scrubbed.
12656
- redactStrings: (value) => walk(value, false, /* @__PURE__ */ new WeakSet())
12657
- };
12658
- }
12659
- var SECRET_KEY_EXACT, TOKEN_VALUE, MASK, MAX_ERROR_DEPTH, defaultRedactor, redact, redactStrings;
12660
- var init_redact = __esm({
12661
- "../core/dist/common-auth-embedded/logger/redact.js"() {
12662
- "use strict";
12663
- SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
12664
- TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
12665
- MASK = "***REDACTED***";
12666
- MAX_ERROR_DEPTH = 8;
12667
- defaultRedactor = createRedactor();
12668
- redact = defaultRedactor.redact;
12669
- redactStrings = defaultRedactor.redactStrings;
12670
- }
12671
- });
12672
-
12673
- // ../core/dist/common-auth-embedded/logger/engine.js
12674
- import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
12675
- import { open as open5 } from "node:fs/promises";
12676
- import { dirname as dirname8, resolve as resolve5 } from "node:path";
12677
- function chmodPrivate(path2) {
12678
- try {
12679
- chmodSync(path2, 384);
12680
- } catch {
12681
- }
12682
- }
12683
- function rotateIfNeeded(f) {
12684
- try {
12685
- if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
12686
- return;
12687
- for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
12688
- if (existsSync(`${f}.${i}`)) {
12689
- const rotated2 = `${f}.${i + 1}`;
12690
- renameSync(`${f}.${i}`, rotated2);
12691
- chmodPrivate(rotated2);
12692
- }
12693
- }
12694
- const rotated = `${f}.1`;
12695
- renameSync(f, rotated);
12696
- chmodPrivate(rotated);
12697
- } catch {
12698
- }
12699
- }
12700
- async function closeWindowsFile(sink) {
12701
- const { file, handle } = sink;
12702
- sink.file = void 0;
12703
- sink.handle = void 0;
12704
- if (file && handle)
12705
- await privateOperation(file, "log-close", () => handle.close());
12706
- }
12707
- async function openWindowsFile(sink, file) {
12708
- await ensurePrivateDirectory(dirname8(file));
12709
- try {
12710
- await verifyPrivate(file, "file", true);
12711
- } catch (error) {
12712
- if (error.code !== "ENOENT")
12713
- throw error;
12714
- try {
12715
- await createPrivateBytes(file, "");
12716
- } catch (creationError) {
12717
- if (creationError.code !== "EEXIST")
12718
- throw creationError;
12719
- await verifyPrivate(file, "file", true);
12720
- }
12721
- }
12722
- sink.handle = await privateOperation(file, "log-open", () => open5(file, "a"));
12723
- sink.file = file;
12724
- return sink.handle;
12725
- }
12726
- async function flushWindowsFile(sink, file, text2) {
12727
- file = resolve5(file);
12728
- try {
12729
- if (sink.file !== file)
12730
- await closeWindowsFile(sink);
12731
- let handle = sink.handle ?? await openWindowsFile(sink, file);
12732
- const info = await privateOperation(file, "log-stat", () => handle.stat());
12733
- if (info.size >= MAX_BYTES) {
12734
- await closeWindowsFile(sink);
12735
- for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
12736
- const source = i === 0 ? file : `${file}.${i}`;
12737
- const target = `${file}.${i + 1}`;
12738
- try {
12739
- await verifyPrivate(source, "file", true);
12740
- } catch (error) {
12741
- if (error.code === "ENOENT")
12742
- continue;
12743
- throw error;
12744
- }
12745
- try {
12746
- await verifyPrivate(target, "file", true);
12747
- } catch (error) {
12748
- if (error.code !== "ENOENT")
12749
- throw error;
12750
- }
12751
- await replaceWindowsFile(source, target);
12752
- await verifyPrivate(target, "file");
12753
- }
12754
- handle = await openWindowsFile(sink, file);
12755
- }
12756
- await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
12757
- } catch (error) {
12758
- await closeWindowsFile(sink).catch(() => {
12759
- });
12760
- throw error;
12761
- }
12762
- }
12763
- function safeSerialize(data) {
12764
- try {
12765
- return ` ${JSON.stringify(data)}`;
12766
- } catch {
12767
- return " [unserializable]";
12768
- }
12769
- }
12770
- function createEngine(options) {
12771
- let logFileSource;
12772
- let initLevelSource;
12773
- let runtimeLevel;
12774
- let redactor = createRedactor();
12775
- let captureSink;
12776
- let buffer = [];
12777
- let timer;
12778
- let orderedSink = Promise.resolve();
12779
- let sinkError;
12780
- const windowsFile = {};
12781
- function queueWindows(operation) {
12782
- const next = orderedSink.then(operation);
12783
- orderedSink = next.catch((error) => {
12784
- sinkError = error;
12785
- });
12786
- return next;
12787
- }
12788
- function configure(next) {
12789
- if (windowsPrivateFiles && next.file !== logFileSource)
12790
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
12791
- });
12792
- logFileSource = next.file;
12793
- initLevelSource = next.level;
12794
- redactor = createRedactor(next);
12795
- captureSink = next.captureSink;
12796
- }
12797
- function setLogLevel3(l) {
12798
- if (l === void 0 || l in ORDER)
12799
- runtimeLevel = l;
12800
- }
12801
- function logFilePath() {
12802
- if (logFileSource === void 0)
12803
- return void 0;
12804
- const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
12805
- return resolved || void 0;
12806
- }
12807
- function configuredLevel() {
12808
- if (runtimeLevel)
12809
- return runtimeLevel;
12810
- const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
12811
- if (floor && floor in ORDER)
12812
- return floor;
12813
- return "info";
12814
- }
12815
- function flushLogs3(close = true) {
12816
- if (timer) {
12817
- clearTimeout(timer);
12818
- timer = void 0;
12819
- }
12820
- if (!buffer.length) {
12821
- if (windowsPrivateFiles)
12822
- return queueWindows(async () => {
12823
- if (close)
12824
- await closeWindowsFile(windowsFile);
12825
- if (sinkError)
12826
- throw sinkError;
12827
- });
12828
- return;
12829
- }
12830
- let file;
12831
- try {
12832
- file = logFilePath();
12833
- } catch {
12834
- buffer = [];
12835
- if (windowsPrivateFiles && close)
12836
- return queueWindows(() => closeWindowsFile(windowsFile));
12837
- return;
12838
- }
12839
- const text2 = buffer.join("");
12840
- buffer = [];
12841
- if (!file) {
12842
- if (windowsPrivateFiles && close)
12843
- return queueWindows(() => closeWindowsFile(windowsFile));
12844
- return;
12845
- }
12846
- if (windowsPrivateFiles) {
12847
- return queueWindows(async () => {
12848
- try {
12849
- await flushWindowsFile(windowsFile, file, text2);
12850
- } finally {
12851
- if (close)
12852
- await closeWindowsFile(windowsFile);
12853
- }
12854
- });
12855
- }
12856
- try {
12857
- rotateIfNeeded(file);
12858
- if (existsSync(file))
12859
- chmodPrivate(file);
12860
- appendFileSync(file, text2, { encoding: "utf8", mode: 384 });
12861
- } catch {
12862
- }
12863
- }
12864
- function schedule2() {
12865
- if (!timer)
12866
- timer = setTimeout(() => {
12867
- timer = void 0;
12868
- const flushed = flushLogs3(false);
12869
- if (flushed instanceof Promise)
12870
- void flushed.catch(() => {
12871
- });
12872
- }, 500);
12873
- }
12874
- function emit(channel3, level, message, data) {
12875
- if (logFileSource === void 0 && captureSink === void 0)
12876
- return;
12877
- try {
12878
- if (ORDER[level] > ORDER[configuredLevel()])
12879
- return;
12880
- const scrubbedMessage = redactor.redactStrings(message);
12881
- let scrubbedData;
12882
- try {
12883
- scrubbedData = redactor.redact(data);
12884
- } catch {
12885
- scrubbedData = "[unserializable]";
12886
- }
12887
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${level.toUpperCase()} [${channel3}] ${scrubbedMessage}` + (data === void 0 ? "" : safeSerialize(scrubbedData)) + "\n";
12888
- try {
12889
- captureSink?.({
12890
- channel: channel3,
12891
- level,
12892
- message: scrubbedMessage,
12893
- data: scrubbedData
12894
- });
12895
- } catch {
12896
- }
12897
- if (logFileSource === void 0)
12898
- return;
12899
- buffer.push(line);
12900
- if (buffer.length >= 50) {
12901
- const flushed = flushLogs3(false);
12902
- if (flushed instanceof Promise)
12903
- void flushed.catch(() => {
12904
- });
12905
- } else
12906
- schedule2();
12907
- } catch {
12908
- }
12909
- }
12910
- function createLogger5(channel3) {
12911
- return {
12912
- error: (m, d) => emit(channel3, "error", m, d),
12913
- warn: (m, d) => emit(channel3, "warn", m, d),
12914
- info: (m, d) => emit(channel3, "info", m, d),
12915
- debug: (m, d) => emit(channel3, "debug", m, d),
12916
- trace: (m, d) => emit(channel3, "trace", m, d)
12917
- };
12918
- }
12919
- function reset() {
12920
- if (windowsPrivateFiles)
12921
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
12922
- });
12923
- sinkError = void 0;
12924
- buffer = [];
12925
- if (timer) {
12926
- clearTimeout(timer);
12927
- timer = void 0;
12951
+ if (result)
12952
+ return result;
12953
+ await locks.releaseAll();
12954
+ if (attempt >= 1)
12955
+ throw refusal2("publishRoster", plan.operationId, "row-key-changed", "a named row changed lock key twice during publication", true);
12928
12956
  }
12929
- logFileSource = void 0;
12930
- initLevelSource = void 0;
12931
- runtimeLevel = void 0;
12932
- redactor = createRedactor();
12933
- captureSink = void 0;
12934
- }
12935
- if (options)
12936
- configure(options);
12937
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
12938
- }
12939
- function createLoggerInstance(options) {
12940
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
12941
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
12942
- }
12943
- function initLogger(options) {
12944
- defaultEngine.configure(options);
12945
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = defaultEngine;
12946
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
12947
- }
12948
- function setLogLevel(l) {
12949
- defaultEngine.setLogLevel(l);
12950
- }
12951
- function flushLogs() {
12952
- return defaultEngine.flushLogs();
12953
- }
12954
- function createLogger2(channel3) {
12955
- return defaultEngine.createLogger(channel3);
12956
- }
12957
- async function flushForTest() {
12958
- return defaultEngine.flushLogs();
12959
- }
12960
- function resetLoggerForTest() {
12961
- defaultEngine.reset();
12957
+ });
12962
12958
  }
12963
- var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
12964
- var init_engine = __esm({
12965
- "../core/dist/common-auth-embedded/logger/engine.js"() {
12959
+ var init_publication = __esm({
12960
+ "../core/dist/common-auth-embedded/store/publication.js"() {
12966
12961
  "use strict";
12967
- init_private_files();
12968
- init_redact();
12969
- ORDER = {
12970
- error: 0,
12971
- warn: 1,
12972
- info: 2,
12973
- debug: 3,
12974
- trace: 4
12975
- };
12976
- MAX_BYTES = 5 * 1024 * 1024;
12977
- ROTATE_KEEP = 3;
12978
- defaultEngine = createEngine();
12962
+ init_hooks();
12963
+ init_mutate();
12964
+ init_rows();
12965
+ init_runtime();
12966
+ init_schema();
12979
12967
  }
12980
12968
  });
12981
12969
 
12982
- // ../core/dist/common-auth-embedded/logger/index.js
12983
- var logger_exports = {};
12984
- __export(logger_exports, {
12985
- createCaptureSink: () => createCaptureSink,
12986
- createLogger: () => createLogger2,
12987
- createLoggerInstance: () => createLoggerInstance,
12988
- createRedactor: () => createRedactor,
12989
- flushForTest: () => flushForTest,
12990
- flushLogs: () => flushLogs,
12991
- initLogger: () => initLogger,
12992
- redact: () => redact,
12993
- redactStrings: () => redactStrings,
12994
- resetLoggerForTest: () => resetLoggerForTest,
12995
- setLogLevel: () => setLogLevel
12996
- });
12997
- var init_logger2 = __esm({
12998
- "../core/dist/common-auth-embedded/logger/index.js"() {
12970
+ // ../core/dist/common-auth-embedded/store/pull.js
12971
+ var PullScheduler;
12972
+ var init_pull = __esm({
12973
+ "../core/dist/common-auth-embedded/store/pull.js"() {
12999
12974
  "use strict";
13000
- init_capture_sink();
13001
- init_engine();
13002
- init_redact();
12975
+ init_attribution();
12976
+ init_errors();
12977
+ init_mutate();
12978
+ init_refresh_lock();
12979
+ init_runtime();
12980
+ PullScheduler = class {
12981
+ rt;
12982
+ hook;
12983
+ onFailure;
12984
+ firedAtLoad;
12985
+ logger;
12986
+ inflight = /* @__PURE__ */ new Set();
12987
+ constructor(rt, hook, onFailure, firedAtLoad, logger2) {
12988
+ this.rt = rt;
12989
+ this.hook = hook;
12990
+ this.onFailure = onFailure;
12991
+ this.firedAtLoad = firedAtLoad;
12992
+ this.logger = logger2;
12993
+ }
12994
+ fire(id, reason) {
12995
+ if (!this.hook)
12996
+ return;
12997
+ if (reason === "load") {
12998
+ if (this.firedAtLoad.has(id))
12999
+ return;
13000
+ this.firedAtLoad.add(id);
13001
+ }
13002
+ const run = this.run(id, reason);
13003
+ this.inflight.add(run);
13004
+ void run.finally(() => this.inflight.delete(run));
13005
+ }
13006
+ /** Resolves once every pull fired so far has settled. */
13007
+ async settled() {
13008
+ while (this.inflight.size > 0)
13009
+ await Promise.allSettled([...this.inflight]);
13010
+ }
13011
+ async run(id, reason) {
13012
+ const rt = this.rt();
13013
+ const { ctx } = rt;
13014
+ const locks = new LockStack(ctx.lockDefaults, ctx.lockEnv);
13015
+ const progress = { writes: 0 };
13016
+ try {
13017
+ const request2 = await withTransaction(ctx, locks, progress, { operation: "pull", rowId: id }, async (tx) => {
13018
+ if (tx.reservation(id) !== void 0)
13019
+ return void 0;
13020
+ await tx.completeTorn();
13021
+ const row = tx.row(id);
13022
+ if (row?.unbound && row.enabled && row.type === "oauth" && row.credential && !row.invalid)
13023
+ requireBound("pull", row);
13024
+ if (!row?.candidate || row.type !== "oauth")
13025
+ return void 0;
13026
+ if (!row.hasEntry) {
13027
+ tx.setEntry(id, { credentialEpoch: 1, needsFirstReading: true });
13028
+ await tx.commitConfig();
13029
+ }
13030
+ const current = tx.row(id);
13031
+ if (!current?.credential || current.credentialEpoch === void 0)
13032
+ return void 0;
13033
+ return {
13034
+ id,
13035
+ credential: current.credential,
13036
+ credentialEpoch: current.credentialEpoch,
13037
+ ...current.identity !== void 0 ? { identity: current.identity } : {},
13038
+ reason
13039
+ };
13040
+ }, { completeTorn: false });
13041
+ await locks.releaseAll();
13042
+ if (!request2) {
13043
+ this.firedAtLoad.delete(id);
13044
+ return;
13045
+ }
13046
+ await ctx.hold?.("pull-before-request", id);
13047
+ let observation;
13048
+ try {
13049
+ observation = await this.hook?.(request2);
13050
+ } catch (cause) {
13051
+ throw new PoolOperationError({
13052
+ operation: "pull",
13053
+ rowId: id,
13054
+ phase: "pull",
13055
+ retryable: true,
13056
+ kind: "pull",
13057
+ message: "the quota pull rejected",
13058
+ cause
13059
+ });
13060
+ }
13061
+ const publish = rt.publishQuota ?? ((rowId2, attribution, value) => recordQuota(rt, rowId2, attribution, value));
13062
+ await publish(id, {
13063
+ credentialEpoch: request2.credentialEpoch,
13064
+ ...request2.identity !== void 0 ? { identity: request2.identity } : {}
13065
+ }, observation);
13066
+ } catch (error) {
13067
+ this.firedAtLoad.delete(id);
13068
+ const failure = toFailure(error, "pull", id, progress);
13069
+ if (this.onFailure) {
13070
+ try {
13071
+ await this.onFailure(id, failure);
13072
+ } catch (hookError) {
13073
+ this.logger?.warn("pull failure hook threw", {
13074
+ rowId: id,
13075
+ error: hookError instanceof Error ? hookError.message : String(hookError)
13076
+ });
13077
+ }
13078
+ } else {
13079
+ this.logger?.warn("quota pull failed", {
13080
+ rowId: id,
13081
+ kind: failure.kind
13082
+ });
13083
+ }
13084
+ } finally {
13085
+ await locks.releaseAll();
13086
+ }
13087
+ }
13088
+ };
13003
13089
  }
13004
13090
  });
13005
13091
 
@@ -13498,9 +13584,9 @@ var init_refresh = __esm({
13498
13584
  // ../core/dist/common-auth-embedded/fs/file-read-cache.js
13499
13585
  import { lstat as lstat4, stat as stat4 } from "node:fs/promises";
13500
13586
  import { resolve as resolve6 } from "node:path";
13501
- async function identity(path2, followSymlinks) {
13587
+ async function identity(path2, probe) {
13502
13588
  try {
13503
- const metadata = await (followSymlinks ? stat4(path2) : lstat4(path2));
13589
+ const metadata = await probe(path2);
13504
13590
  return metadata.isFile() ? metadata : void 0;
13505
13591
  } catch (error) {
13506
13592
  return error.code === "ENOENT" ? "absent" : void 0;
@@ -13516,15 +13602,15 @@ var init_file_read_cache = __esm({
13516
13602
  "../core/dist/common-auth-embedded/fs/file-read-cache.js"() {
13517
13603
  "use strict";
13518
13604
  FileReadCache = class {
13519
- #followSymlinks;
13605
+ #probe;
13520
13606
  #entries = /* @__PURE__ */ new Map();
13521
13607
  constructor(options = {}) {
13522
- this.#followSymlinks = options.followSymlinks ?? false;
13608
+ this.#probe = options.followSymlinks ? (path2) => (options.stat ?? stat4)(path2) : (path2) => (options.lstat ?? lstat4)(path2);
13523
13609
  }
13524
13610
  async read(paths, read, validateHit) {
13525
13611
  const resolvedPaths = paths.map((path2) => resolve6(path2));
13526
13612
  const key = JSON.stringify(resolvedPaths);
13527
- const probed = await Promise.all(resolvedPaths.map((path2) => identity(path2, this.#followSymlinks)));
13613
+ const probed = await Promise.all(resolvedPaths.map((path2) => identity(path2, this.#probe)));
13528
13614
  const identities = probed.every((entry) => entry !== void 0) ? probed : void 0;
13529
13615
  const cached = this.#entries.get(key);
13530
13616
  if (identities && cached && identities.every((entry, index) => {
@@ -14627,15 +14713,30 @@ function addedText(name, result) {
14627
14713
  function failureMessage(error) {
14628
14714
  return projectFailure(error).text;
14629
14715
  }
14716
+ function settingsPort(options) {
14717
+ if (options.settings)
14718
+ return options.settings;
14719
+ const { store, extraLocks } = options;
14720
+ const locks = extraLocks ? { extraLocks } : {};
14721
+ return {
14722
+ async read() {
14723
+ const read = await store.readSettings();
14724
+ return read.status === "error" ? {} : read.settings;
14725
+ },
14726
+ async update(mutator) {
14727
+ await store.updateSettings(mutator, locks);
14728
+ }
14729
+ };
14730
+ }
14630
14731
  async function snapshot(options) {
14631
14732
  const { store } = options;
14632
14733
  const load = await store.read();
14633
- const read = await store.readSettings();
14734
+ const settings = await settingsPort(options).read();
14634
14735
  const vault = await options.routing?.vaultOrder?.();
14635
14736
  return {
14636
14737
  load,
14637
14738
  rows: distinctRows(load),
14638
- settings: read.status === "error" ? {} : read.settings,
14739
+ settings,
14639
14740
  ...vault ? { vault } : {}
14640
14741
  };
14641
14742
  }
@@ -14897,6 +14998,7 @@ function vaultNames(vault) {
14897
14998
  function routingSection(options, snap) {
14898
14999
  const { store, extraLocks } = options;
14899
15000
  const locks = extraLocks ? { extraLocks } : {};
15001
+ const port = settingsPort(options);
14900
15002
  const choices = [
14901
15003
  { value: "ordered", label: "Ordered (roster order)" },
14902
15004
  ...options.routing?.orderedVariants ?? [],
@@ -14925,10 +15027,10 @@ function routingSection(options, snap) {
14925
15027
  ],
14926
15028
  run: async ({ values }) => {
14927
15029
  const mode = String(values.mode);
14928
- await store.updateSettings((settings) => {
15030
+ await port.update((settings) => {
14929
15031
  settings.routing = { ...record(settings.routing), mode };
14930
15032
  return void 0;
14931
- }, locks);
15033
+ });
14932
15034
  return `Routing mode set to ${choices.find((choice) => choice.value === mode)?.label ?? mode}.`;
14933
15035
  }
14934
15036
  }
@@ -14981,13 +15083,13 @@ function routingSection(options, snap) {
14981
15083
  run: async ({ values }) => {
14982
15084
  const value = String(values.maxSameAccountWait);
14983
15085
  const maxSameAccountWait = value === "max" ? "max" : Number(value);
14984
- await store.updateSettings((settings) => {
15086
+ await port.update((settings) => {
14985
15087
  settings.routing = {
14986
15088
  ...record(settings.routing),
14987
15089
  maxSameAccountWait
14988
15090
  };
14989
15091
  return void 0;
14990
- }, locks);
15092
+ });
14991
15093
  return `${waitLabel} set to ${waitName(value)}.`;
14992
15094
  }
14993
15095
  });
@@ -15020,8 +15122,7 @@ function floorNames(options, snap) {
15020
15122
  return (label) => names.get(label) ?? label;
15021
15123
  }
15022
15124
  function limitsSection(options, snap) {
15023
- const { store, extraLocks } = options;
15024
- const locks = extraLocks ? { extraLocks } : {};
15125
+ const port = settingsPort(options);
15025
15126
  const killswitch = record(snap.settings.killswitch);
15026
15127
  const enabled = killswitch.enabled === true;
15027
15128
  const floors = record(killswitch.accounts);
@@ -15052,7 +15153,7 @@ function limitsSection(options, snap) {
15052
15153
  ...typeof own[label] === "number" ? { value: own[label] } : {}
15053
15154
  })),
15054
15155
  run: async ({ values }) => {
15055
- await store.updateSettings((settings) => {
15156
+ await port.update((settings) => {
15056
15157
  const next = record(settings.killswitch);
15057
15158
  const accounts = record(next.accounts);
15058
15159
  const mine = record(accounts[row.id]);
@@ -15073,7 +15174,7 @@ function limitsSection(options, snap) {
15073
15174
  delete next.accounts;
15074
15175
  settings.killswitch = next;
15075
15176
  return void 0;
15076
- }, locks);
15177
+ });
15077
15178
  return `Floors updated for ${name}.`;
15078
15179
  }
15079
15180
  }
@@ -15103,13 +15204,13 @@ function limitsSection(options, snap) {
15103
15204
  ],
15104
15205
  run: async ({ values }) => {
15105
15206
  const on = values.enabled === true;
15106
- await store.updateSettings((settings) => {
15207
+ await port.update((settings) => {
15107
15208
  settings.killswitch = {
15108
15209
  ...record(settings.killswitch),
15109
15210
  enabled: on
15110
15211
  };
15111
15212
  return void 0;
15112
- }, locks);
15213
+ });
15113
15214
  return `Killswitch ${on ? "on" : "off"}.`;
15114
15215
  }
15115
15216
  }
@@ -15247,6 +15348,7 @@ function createCommandMenu(options) {
15247
15348
  store,
15248
15349
  now,
15249
15350
  ...options.extraLocks ? { extraLocks: options.extraLocks } : {},
15351
+ ...options.settings ? { settings: options.settings } : {},
15250
15352
  ...options.accounts ? { accounts: options.accounts } : {},
15251
15353
  ...options.quota ? { quota: options.quota } : {},
15252
15354
  ...options.routing ? { routing: options.routing } : {},
@@ -17390,8 +17492,8 @@ var init_any_signal = __esm({
17390
17492
  // ../core/dist/common-auth-embedded/claustrum/enrollment.js
17391
17493
  import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID10 } from "node:crypto";
17392
17494
  import { constants as fsConstants } from "node:fs";
17393
- import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename7, stat as stat5, unlink as unlink6 } from "node:fs/promises";
17394
- import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join7, resolve as resolve8 } from "node:path";
17495
+ import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename7, stat as stat5, unlink as unlink7 } from "node:fs/promises";
17496
+ import { basename as basename4, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join7, resolve as resolve8 } from "node:path";
17395
17497
  import { ClaustrumCredentialError as ClaustrumCredentialError3, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
17396
17498
  function classifyEnrollmentError(error) {
17397
17499
  if (!(error instanceof ClaustrumCredentialError3))
@@ -17438,7 +17540,7 @@ function connectClaustrumEnrollmentClient(options) {
17438
17540
  }
17439
17541
  function getClaustrumEnrollmentPaths(tokenPath) {
17440
17542
  const extension = extname(tokenPath) || ".json";
17441
- const stem = basename3(tokenPath, extname(tokenPath));
17543
+ const stem = basename4(tokenPath, extname(tokenPath));
17442
17544
  return {
17443
17545
  statePath: join7(dirname9(tokenPath), `${stem}-state${extension}`),
17444
17546
  tokenPath
@@ -17690,7 +17792,7 @@ async function writeStateAtomic(path2, state, ancestorOptions = {}) {
17690
17792
  }
17691
17793
  if (windowsPrivateFiles)
17692
17794
  return writePrivateAtomic(path2, bytes);
17693
- const temporary = join7(parent, `.${basename3(path2)}.${process.pid}.${randomUUID10()}.tmp`);
17795
+ const temporary = join7(parent, `.${basename4(path2)}.${process.pid}.${randomUUID10()}.tmp`);
17694
17796
  let descriptor;
17695
17797
  let created = false;
17696
17798
  try {
@@ -17707,7 +17809,7 @@ async function writeStateAtomic(path2, state, ancestorOptions = {}) {
17707
17809
  await descriptor?.close().catch(() => {
17708
17810
  });
17709
17811
  if (created)
17710
- await unlink6(temporary).catch(() => {
17812
+ await unlink7(temporary).catch(() => {
17711
17813
  });
17712
17814
  }
17713
17815
  }
@@ -17844,7 +17946,7 @@ async function resetClaustrumEnrollmentState(paths, proposedName) {
17844
17946
  if (state.phase === "pending")
17845
17947
  return "refused-pending";
17846
17948
  await lock.assertOwned();
17847
- await unlink6(paths.statePath);
17949
+ await unlink7(paths.statePath);
17848
17950
  return "reset";
17849
17951
  } finally {
17850
17952
  await lock.release();
@@ -17852,7 +17954,7 @@ async function resetClaustrumEnrollmentState(paths, proposedName) {
17852
17954
  }
17853
17955
  async function removeIfPresent(path2) {
17854
17956
  try {
17855
- await unlink6(path2);
17957
+ await unlink7(path2);
17856
17958
  return true;
17857
17959
  } catch (error) {
17858
17960
  if (error.code === "ENOENT")
@@ -18089,7 +18191,7 @@ var init_enrollment = __esm({
18089
18191
  }
18090
18192
  if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE) {
18091
18193
  await lock.assertOwned();
18092
- await unlink6(this.#paths.statePath).catch((cause) => {
18194
+ await unlink7(this.#paths.statePath).catch((cause) => {
18093
18195
  if (cause.code !== "ENOENT")
18094
18196
  throw cause;
18095
18197
  });
@@ -20914,7 +21016,7 @@ var init_consumer = __esm({
20914
21016
  // ../core/dist/common-auth-embedded/claustrum/hub.js
20915
21017
  import { createHash as createHash7 } from "node:crypto";
20916
21018
  import { channel as channel2 } from "node:diagnostics_channel";
20917
- import { readdir, stat as stat7 } from "node:fs/promises";
21019
+ import { readdir as readdir2, stat as stat7 } from "node:fs/promises";
20918
21020
  import { dirname as dirname10, join as join8, resolve as resolve11 } from "node:path";
20919
21021
  function canonicalJson3(value, path2 = /* @__PURE__ */ new Set()) {
20920
21022
  if (value === null)
@@ -21648,7 +21750,7 @@ var init_hub = __esm({
21648
21750
  const name = `${entry.provider}.json`;
21649
21751
  const candidates = [join8(this.#generationDirectory, name)];
21650
21752
  try {
21651
- for (const key of await readdir(this.#generationDirectory))
21753
+ for (const key of await readdir2(this.#generationDirectory))
21652
21754
  if (key !== this.#key && FINGERPRINT.test(key))
21653
21755
  candidates.push(join8(this.#generationDirectory, key, name));
21654
21756
  } catch {
@@ -22230,7 +22332,7 @@ var init_lock = __esm({
22230
22332
  // ../core/dist/common-auth-embedded/pi-slot/slot.js
22231
22333
  import { createHash as createHash8 } from "node:crypto";
22232
22334
  import { constants as constants2 } from "node:fs";
22233
- import { lstat as lstat5, mkdir as mkdir10, open as open7, unlink as unlink7 } from "node:fs/promises";
22335
+ import { lstat as lstat5, mkdir as mkdir10, open as open7, unlink as unlink8 } from "node:fs/promises";
22234
22336
  import { dirname as dirname11, resolve as resolve12 } from "node:path";
22235
22337
  import { setTimeout as sleep2 } from "node:timers/promises";
22236
22338
  function rootSpans(text2) {
@@ -22508,7 +22610,7 @@ function createPiSlot(options, onStep, hooks) {
22508
22610
  }
22509
22611
  async function deleteStash(assertLock) {
22510
22612
  assertLock();
22511
- await unlink7(stashPath);
22613
+ await unlink8(stashPath);
22512
22614
  await syncDir(dirname11(stashPath));
22513
22615
  onStep?.("stash-deleted");
22514
22616
  }
@@ -23722,7 +23824,7 @@ var init_capture_sink2 = __esm({
23722
23824
 
23723
23825
  // src/common-auth-embedded/fs/private-files.js
23724
23826
  import { randomUUID as randomUUID11 } from "node:crypto";
23725
- import { lstat as lstat6, readFile as readFile7, rename as rename8, unlink as unlink8 } from "node:fs/promises";
23827
+ import { lstat as lstat6, readFile as readFile7, rename as rename8, unlink as unlink9 } from "node:fs/promises";
23726
23828
  import { tmpdir as tmpdir2 } from "node:os";
23727
23829
  import { dirname as dirname13, join as join10, resolve as resolve13 } from "node:path";
23728
23830
  function ioCode2(detail) {
@@ -23973,7 +24075,7 @@ async function writePrivateAtomic2(path2, bytes, options = {}) {
23973
24075
  Object.assign(error, outcome);
23974
24076
  if (created) {
23975
24077
  try {
23976
- await unlink8(stage);
24078
+ await unlink9(stage);
23977
24079
  } catch {
23978
24080
  error.orphanPath = stage;
23979
24081
  }
@@ -23983,7 +24085,7 @@ async function writePrivateAtomic2(path2, bytes, options = {}) {
23983
24085
  throw error;
23984
24086
  } finally {
23985
24087
  if (created)
23986
- await unlink8(stage).catch(() => {
24088
+ await unlink9(stage).catch(() => {
23987
24089
  });
23988
24090
  }
23989
24091
  }
@@ -24360,6 +24462,9 @@ function createLoggerInstance2(options) {
24360
24462
  const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine2(options);
24361
24463
  return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
24362
24464
  }
24465
+ function createLogger3(channel3) {
24466
+ return defaultEngine2.createLogger(channel3);
24467
+ }
24363
24468
  var ORDER2, MAX_BYTES2, ROTATE_KEEP2, defaultEngine2;
24364
24469
  var init_engine2 = __esm({
24365
24470
  "src/common-auth-embedded/logger/engine.js"() {
@@ -24714,7 +24819,7 @@ var init_process_heartbeat = __esm({
24714
24819
  });
24715
24820
 
24716
24821
  // src/version-fence.ts
24717
- import { readdir as readdir2, readFile as readFile9, stat as stat9, unlink as unlink9 } from "node:fs/promises";
24822
+ import { readdir as readdir3, readFile as readFile9, stat as stat9, unlink as unlink10 } from "node:fs/promises";
24718
24823
  import { homedir as homedir3, uptime } from "node:os";
24719
24824
  import { join as join12 } from "node:path";
24720
24825
  function defaultStateHome() {
@@ -24782,7 +24887,7 @@ function pidFrom(name, pattern) {
24782
24887
  }
24783
24888
  async function list2(dir) {
24784
24889
  try {
24785
- return { ok: true, names: await readdir2(dir) };
24890
+ return { ok: true, names: await readdir3(dir) };
24786
24891
  } catch (error) {
24787
24892
  const code2 = error.code;
24788
24893
  if (code2 === "ENOENT") return { ok: true, names: [] };
@@ -24844,7 +24949,7 @@ async function staleRecord(path2, record3, boot, heartbeat) {
24844
24949
  if (heartbeat) {
24845
24950
  try {
24846
24951
  if (await readFile9(path2, "utf8") === record3.text) {
24847
- await unlink9(path2);
24952
+ await unlink10(path2);
24848
24953
  log5.debug("Removed stale pre-boot heartbeat", { path: path2 });
24849
24954
  }
24850
24955
  } catch {
@@ -25055,14 +25160,14 @@ import { createHash as createHash10 } from "node:crypto";
25055
25160
  import {
25056
25161
  chmod as chmod4,
25057
25162
  mkdir as mkdir12,
25058
- readdir as readdir3,
25163
+ readdir as readdir4,
25059
25164
  readFile as readFile10,
25060
25165
  rename as rename10,
25061
25166
  rmdir as rmdir2,
25062
25167
  stat as stat10,
25063
- unlink as unlink10
25168
+ unlink as unlink11
25064
25169
  } from "node:fs/promises";
25065
- import { basename as basename4, dirname as dirname15, join as join13, resolve as resolve16 } from "node:path";
25170
+ import { basename as basename5, dirname as dirname15, join as join13, resolve as resolve16 } from "node:path";
25066
25171
  function refusalMessage(stateDir, errorClass2) {
25067
25172
  if (errorClass2 === "ERR_PRIVATE_FILES_SECURITY")
25068
25173
  return `antigravity-auth cannot start: ${stateDir} is not a folder only your user can access, or it is a link, so the plugin will not use it (${errorClass2}). Replace it with a plain folder of your own, then restart OpenCode.`;
@@ -25111,7 +25216,7 @@ function errorClass(error) {
25111
25216
  function errorFile(error) {
25112
25217
  const { path: path2, stage } = error ?? {};
25113
25218
  return {
25114
- ...typeof path2 === "string" && path2 ? { file: basename4(path2) } : {},
25219
+ ...typeof path2 === "string" && path2 ? { file: basename5(path2) } : {},
25115
25220
  ...typeof stage === "string" && stage ? { stage } : {}
25116
25221
  };
25117
25222
  }
@@ -25482,9 +25587,9 @@ function storeFolder(anchor) {
25482
25587
  return `${anchor}.store`;
25483
25588
  }
25484
25589
  async function storeArtefacts(anchor) {
25485
- const names = await readdir3(dirname15(anchor)).catch(() => []);
25486
- const store = basename4(storeFolder(anchor));
25487
- const pool = basename4(anchor);
25590
+ const names = await readdir4(dirname15(anchor)).catch(() => []);
25591
+ const store = basename5(storeFolder(anchor));
25592
+ const pool = basename5(anchor);
25488
25593
  return names.filter(
25489
25594
  (name) => name === store || name.startsWith(`${pool}.store.`) || name.startsWith(pool) && name.endsWith(".tmp")
25490
25595
  ).length;
@@ -25498,7 +25603,7 @@ async function abandonUnpublishedStore(location, stateAnchor, log9) {
25498
25603
  await rename10(folder, archived).catch((error) => {
25499
25604
  if (error.code !== "ENOENT") throw error;
25500
25605
  });
25501
- await unlink10(accountStorePointerPath(stateAnchor)).catch(() => {
25606
+ await unlink11(accountStorePointerPath(stateAnchor)).catch(() => {
25502
25607
  });
25503
25608
  log9.info(
25504
25609
  "antigravity-auth set an unfinished account store aside before starting its move again",
@@ -25629,7 +25734,7 @@ async function writeStateHomeStoreForward(id, stateAnchor, configAnchor = legacy
25629
25734
  const forward = {
25630
25735
  schemaVersion: 2,
25631
25736
  id,
25632
- directoryBasename: basename4(storeFolder(stateAnchor)),
25737
+ directoryBasename: basename5(storeFolder(stateAnchor)),
25633
25738
  relocatedTo: { legacyPath: stateAnchor, id }
25634
25739
  };
25635
25740
  const fs3 = await loadCommonAuthFs();
@@ -25690,7 +25795,7 @@ async function moveFiles(location, files, markerPath, layoutLock, input) {
25690
25795
  for (const path2 of listed) {
25691
25796
  if (wanted.has(path2)) continue;
25692
25797
  await layoutLock.assertOwned();
25693
- await unlink10(path2).catch((error) => {
25798
+ await unlink11(path2).catch((error) => {
25694
25799
  if (error.code !== "ENOENT") throw error;
25695
25800
  });
25696
25801
  }
@@ -25829,7 +25934,7 @@ async function removeOldSignatureCache(location, path2, layoutLock, steps, log9)
25829
25934
  try {
25830
25935
  if (!await exists2(path2)) return;
25831
25936
  await beforeRemove(path2, layoutLock, steps);
25832
- await unlink10(path2);
25937
+ await unlink11(path2);
25833
25938
  } catch (error) {
25834
25939
  if (error?.code === "ENOENT") return;
25835
25940
  logOnce(
@@ -25932,7 +26037,7 @@ async function removeMovedVaultStateLeftover(vaultDir, accountFile) {
25932
26037
  if (!marker?.oldDir || marker.oldDir !== location.key) return;
25933
26038
  const leftover = vaultStateFile(files).old;
25934
26039
  if (!await isVaultShapedKeptState(files)) return;
25935
- await unlink10(leftover).catch((error) => {
26040
+ await unlink11(leftover).catch((error) => {
25936
26041
  if (error.code !== "ENOENT") throw error;
25937
26042
  });
25938
26043
  await rmdir2(files.vault.old).catch(() => {
@@ -25941,7 +26046,7 @@ async function removeMovedVaultStateLeftover(vaultDir, accountFile) {
25941
26046
  async function vaultFiles(dir) {
25942
26047
  let entries;
25943
26048
  try {
25944
- entries = await readdir3(dir, { withFileTypes: true });
26049
+ entries = await readdir4(dir, { withFileTypes: true });
25945
26050
  } catch (error) {
25946
26051
  const code2 = error.code;
25947
26052
  if (code2 === "ENOENT" || code2 === "ENOTDIR") return [];
@@ -26050,7 +26155,7 @@ function isWindowsSharingError(error, platform) {
26050
26155
  const code2 = error?.code;
26051
26156
  return platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
26052
26157
  }
26053
- async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile10, unlink: unlink10 }) {
26158
+ async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile10, unlink: unlink11 }) {
26054
26159
  const started = performance.now();
26055
26160
  for (const delay3 of SHARING_RETRY_DELAYS_MS) {
26056
26161
  if (delay3 > 0) await new Promise((done) => setTimeout(done, delay3));
@@ -26182,7 +26287,7 @@ async function writeManifest(stateDir, paths) {
26182
26287
  );
26183
26288
  }
26184
26289
  async function removeManifest(stateDir) {
26185
- await unlink10(join13(stateDir, RUNTIME_LAYOUT_MANIFEST_FILE)).catch(
26290
+ await unlink11(join13(stateDir, RUNTIME_LAYOUT_MANIFEST_FILE)).catch(
26186
26291
  (error) => {
26187
26292
  if (error.code !== "ENOENT") throw error;
26188
26293
  }
@@ -28647,16 +28752,16 @@ async function select2(terminal, items, options) {
28647
28752
  // src/common-auth-embedded/claustrum/enrollment.js
28648
28753
  import { createHash as createHash12, randomBytes as randomBytes3, randomUUID as randomUUID15 } from "node:crypto";
28649
28754
  import { constants as fsConstants2 } from "node:fs";
28650
- import { chmod as chmod5, mkdir as mkdir14, open as open10, readFile as readFile12, realpath as realpath4, rename as rename12, stat as stat13, unlink as unlink11 } from "node:fs/promises";
28651
- import { basename as basename5, dirname as dirname19, extname as extname2, isAbsolute as isAbsolute4, join as join18, resolve as resolve21 } from "node:path";
28755
+ import { chmod as chmod5, mkdir as mkdir14, open as open10, readFile as readFile12, realpath as realpath4, rename as rename12, stat as stat13, unlink as unlink13 } from "node:fs/promises";
28756
+ import { basename as basename7, dirname as dirname19, extname as extname2, isAbsolute as isAbsolute4, join as join18, resolve as resolve21 } from "node:path";
28652
28757
  import { ClaustrumCredentialError as ClaustrumCredentialError9, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
28653
28758
 
28654
28759
  // src/common-auth-embedded/fs/file-read-cache.js
28655
28760
  import { lstat as lstat7, stat as stat11 } from "node:fs/promises";
28656
28761
  import { resolve as resolve19 } from "node:path";
28657
- async function identity2(path2, followSymlinks) {
28762
+ async function identity2(path2, probe) {
28658
28763
  try {
28659
- const metadata = await (followSymlinks ? stat11(path2) : lstat7(path2));
28764
+ const metadata = await probe(path2);
28660
28765
  return metadata.isFile() ? metadata : void 0;
28661
28766
  } catch (error) {
28662
28767
  return error.code === "ENOENT" ? "absent" : void 0;
@@ -28668,15 +28773,15 @@ function sameIdentity2(left, right) {
28668
28773
  return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
28669
28774
  }
28670
28775
  var FileReadCache2 = class {
28671
- #followSymlinks;
28776
+ #probe;
28672
28777
  #entries = /* @__PURE__ */ new Map();
28673
28778
  constructor(options = {}) {
28674
- this.#followSymlinks = options.followSymlinks ?? false;
28779
+ this.#probe = options.followSymlinks ? (path2) => (options.stat ?? stat11)(path2) : (path2) => (options.lstat ?? lstat7)(path2);
28675
28780
  }
28676
28781
  async read(paths, read, validateHit) {
28677
28782
  const resolvedPaths = paths.map((path2) => resolve19(path2));
28678
28783
  const key = JSON.stringify(resolvedPaths);
28679
- const probed = await Promise.all(resolvedPaths.map((path2) => identity2(path2, this.#followSymlinks)));
28784
+ const probed = await Promise.all(resolvedPaths.map((path2) => identity2(path2, this.#probe)));
28680
28785
  const identities = probed.every((entry) => entry !== void 0) ? probed : void 0;
28681
28786
  const cached = this.#entries.get(key);
28682
28787
  if (identities && cached && identities.every((entry, index) => {
@@ -28723,9 +28828,10 @@ var WRITER_LOCK_CONSTANTS2 = Object.freeze({
28723
28828
  init_private_files2();
28724
28829
 
28725
28830
  // src/common-auth-embedded/fs/refresh-file-lock.js
28831
+ init_logger3();
28726
28832
  import { randomUUID as randomUUID14 } from "node:crypto";
28727
- import { link as link3, lstat as lstat8, mkdir as mkdir13, open as open9, readFile as readFile11, rename as rename11, rm as rm6, stat as stat12 } from "node:fs/promises";
28728
- import { dirname as dirname18, join as join17 } from "node:path";
28833
+ import { link as link3, lstat as lstat8, mkdir as mkdir13, open as open9, readdir as readdir5, readFile as readFile11, rename as rename11, rm as rm6, stat as stat12, unlink as unlink12 } from "node:fs/promises";
28834
+ import { basename as basename6, dirname as dirname18, join as join17 } from "node:path";
28729
28835
 
28730
28836
  // src/common-auth-embedded/fs/lock-record.js
28731
28837
  init_private_files2();
@@ -28833,6 +28939,90 @@ async function writeExclusiveText2(path2, text2) {
28833
28939
  await handle.close();
28834
28940
  }
28835
28941
  }
28942
+ var STAGING_UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
28943
+ var STAGING_SWEEP_MIN_AGE_MS2 = 10 * 6e4;
28944
+ var STAGING_SWEEP_MAX_CANDIDATES2 = 256;
28945
+ var STAGING_SWEEP_MAX_BYTES2 = 4096;
28946
+ var sweptLockPaths2 = /* @__PURE__ */ new Set();
28947
+ var pendingStagingSweeps2 = /* @__PURE__ */ new Set();
28948
+ var stagingSweepTestHooks2;
28949
+ function isStagingName2(name, lockName) {
28950
+ const prefix = `${lockName}.`;
28951
+ const suffix = ".tmp";
28952
+ if (!name.startsWith(prefix) || !name.endsWith(suffix))
28953
+ return false;
28954
+ return STAGING_UUID2.test(name.slice(prefix.length, -suffix.length));
28955
+ }
28956
+ function sameStagingFile2(a, b) {
28957
+ return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.birthtimeMs === b.birthtimeMs;
28958
+ }
28959
+ async function readStagedOwner2(path2) {
28960
+ const before = await lstat8(path2);
28961
+ if (!before.isFile() || before.isSymbolicLink())
28962
+ return void 0;
28963
+ if (before.size > STAGING_SWEEP_MAX_BYTES2)
28964
+ return void 0;
28965
+ const handle = await open9(path2, "r");
28966
+ let text2;
28967
+ try {
28968
+ if (!sameStagingFile2(before, await handle.stat()))
28969
+ return void 0;
28970
+ text2 = await handle.readFile("utf8");
28971
+ } finally {
28972
+ await handle.close();
28973
+ }
28974
+ let record3;
28975
+ try {
28976
+ record3 = JSON.parse(text2);
28977
+ } catch {
28978
+ return void 0;
28979
+ }
28980
+ if (!record3 || typeof record3 !== "object" || Array.isArray(record3))
28981
+ return void 0;
28982
+ const keys = Object.keys(record3).sort();
28983
+ if (keys.length !== 2 || keys[0] !== "expiresAt" || keys[1] !== "ownerId")
28984
+ return void 0;
28985
+ const { ownerId, expiresAt } = record3;
28986
+ if (typeof ownerId !== "string" || !STAGING_UUID2.test(ownerId))
28987
+ return void 0;
28988
+ if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
28989
+ return void 0;
28990
+ return { identity: before, expiresAt };
28991
+ }
28992
+ async function sweepAbandonedStaging2(lockPath, ttlMs, now) {
28993
+ const directory = dirname18(lockPath);
28994
+ const lockName = basename6(lockPath);
28995
+ const hooks = stagingSweepTestHooks2;
28996
+ const names = await (hooks?.readdir ?? readdir5)(directory);
28997
+ const candidates = names.filter((name) => isStagingName2(name, lockName)).slice(0, STAGING_SWEEP_MAX_CANDIDATES2);
28998
+ const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS2);
28999
+ for (const name of candidates) {
29000
+ const path2 = join17(directory, name);
29001
+ try {
29002
+ if (now() - (await lstat8(path2)).mtimeMs < marginMs)
29003
+ continue;
29004
+ const staged = await readStagedOwner2(path2);
29005
+ if (!staged || !(staged.expiresAt < now() - marginMs))
29006
+ continue;
29007
+ if (hooks?.beforeUnlink)
29008
+ await hooks.beforeUnlink(path2);
29009
+ const current = await readStagedOwner2(path2);
29010
+ if (!current || !sameStagingFile2(staged.identity, current.identity) || !(current.expiresAt < now() - marginMs))
29011
+ continue;
29012
+ await (hooks?.unlink ?? unlink12)(path2);
29013
+ } catch {
29014
+ }
29015
+ }
29016
+ }
29017
+ function startStagingSweep2(lockPath, ttlMs, now) {
29018
+ if (sweptLockPaths2.has(lockPath))
29019
+ return;
29020
+ sweptLockPaths2.add(lockPath);
29021
+ const sweep = Promise.resolve().then(() => sweepAbandonedStaging2(lockPath, ttlMs, now)).catch(() => {
29022
+ });
29023
+ pendingStagingSweeps2.add(sweep);
29024
+ void sweep.finally(() => pendingStagingSweeps2.delete(sweep));
29025
+ }
28836
29026
  var setRefreshLockRenewalTimeout2 = globalThis.setTimeout.bind(globalThis);
28837
29027
  var clearRefreshLockRenewalTimeout2 = globalThis.clearTimeout.bind(globalThis);
28838
29028
  function isLostMarkerRaceError2(error) {
@@ -29529,6 +29719,7 @@ async function acquireRefreshFileLockWithClock2(options) {
29529
29719
  return null;
29530
29720
  }
29531
29721
  scheduleRenewal();
29722
+ startStagingSweep2(lockPath, options.ttlMs, now);
29532
29723
  return {
29533
29724
  ownerId,
29534
29725
  whenLost: () => lostPromise,
@@ -29592,17 +29783,15 @@ async function acquireRefreshFileLockWithClock2(options) {
29592
29783
  removalConfirmed = true;
29593
29784
  }, deadline);
29594
29785
  changingRecordError = void 0;
29595
- if (markerAcquired) {
29596
- if (windowsPrivateFiles2 && !removalConfirmed)
29597
- throw new PrivateFileError2(lockPath, "release-not-confirmed", {
29598
- code: "EIO"
29599
- });
29600
- releaseConfirmed = removalConfirmed;
29786
+ if (markerAcquired && removalConfirmed) {
29787
+ releaseConfirmed = true;
29601
29788
  return;
29602
29789
  }
29603
- if (signal?.aborted)
29604
- return;
29605
- await recoverStaleEvictionMarker(deadline);
29790
+ if (!markerAcquired) {
29791
+ if (signal?.aborted)
29792
+ return;
29793
+ await recoverStaleEvictionMarker(deadline);
29794
+ }
29606
29795
  } catch (error) {
29607
29796
  const changingRecord = windowsPrivateFiles2 && (isChangingLockCreate(error) || isWindowsAccessDeniedRead2(error, [
29608
29797
  lockPath,
@@ -29632,6 +29821,9 @@ async function acquireRefreshFileLockWithClock2(options) {
29632
29821
  throw changingRecordError ?? removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
29633
29822
  code: "ETIMEDOUT"
29634
29823
  });
29824
+ createLogger3("fs").warn("File lock release deadline expired", {
29825
+ lockPath
29826
+ });
29635
29827
  }
29636
29828
  };
29637
29829
  }
@@ -29797,7 +29989,7 @@ function connectClaustrumEnrollmentClient2(options) {
29797
29989
  }
29798
29990
  function getClaustrumEnrollmentPaths2(tokenPath) {
29799
29991
  const extension = extname2(tokenPath) || ".json";
29800
- const stem = basename5(tokenPath, extname2(tokenPath));
29992
+ const stem = basename7(tokenPath, extname2(tokenPath));
29801
29993
  return {
29802
29994
  statePath: join18(dirname19(tokenPath), `${stem}-state${extension}`),
29803
29995
  tokenPath
@@ -30049,7 +30241,7 @@ async function writeStateAtomic2(path2, state, ancestorOptions = {}) {
30049
30241
  }
30050
30242
  if (windowsPrivateFiles2)
30051
30243
  return writePrivateAtomic2(path2, bytes);
30052
- const temporary = join18(parent, `.${basename5(path2)}.${process.pid}.${randomUUID15()}.tmp`);
30244
+ const temporary = join18(parent, `.${basename7(path2)}.${process.pid}.${randomUUID15()}.tmp`);
30053
30245
  let descriptor;
30054
30246
  let created = false;
30055
30247
  try {
@@ -30066,7 +30258,7 @@ async function writeStateAtomic2(path2, state, ancestorOptions = {}) {
30066
30258
  await descriptor?.close().catch(() => {
30067
30259
  });
30068
30260
  if (created)
30069
- await unlink11(temporary).catch(() => {
30261
+ await unlink13(temporary).catch(() => {
30070
30262
  });
30071
30263
  }
30072
30264
  }
@@ -30348,7 +30540,7 @@ var ClaustrumEnrollmentManager2 = class {
30348
30540
  }
30349
30541
  if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE2) {
30350
30542
  await lock.assertOwned();
30351
- await unlink11(this.#paths.statePath).catch((cause) => {
30543
+ await unlink13(this.#paths.statePath).catch((cause) => {
30352
30544
  if (cause.code !== "ENOENT")
30353
30545
  throw cause;
30354
30546
  });
@@ -30440,7 +30632,7 @@ async function resetClaustrumEnrollmentState2(paths, proposedName) {
30440
30632
  if (state.phase === "pending")
30441
30633
  return "refused-pending";
30442
30634
  await lock.assertOwned();
30443
- await unlink11(paths.statePath);
30635
+ await unlink13(paths.statePath);
30444
30636
  return "reset";
30445
30637
  } finally {
30446
30638
  await lock.release();
@@ -30603,11 +30795,17 @@ async function confirmEnrollmentAccess(client, status, tokenPath, configuredGran
30603
30795
  grantCommand: `ck auth grant --principal ${shellArgument(`enrolled:${status.approvedName}`)} --selector-kind ${grant.selector.exact === void 0 ? "category" : "exact"} --selector ${shellArgument(grant.selector.exact ?? grant.selector.category)} --operation ${grant.operation}`
30604
30796
  }
30605
30797
  }));
30798
+ const access = {
30799
+ grants,
30800
+ ...status.requestedGrantsStatus !== void 0 && {
30801
+ requestedGrantsStatus: status.requestedGrantsStatus
30802
+ }
30803
+ };
30606
30804
  if (status.requestedGrantsStatus === "dropped")
30607
- return { state: "older-vault", grants };
30805
+ return { ...access, state: "older-vault" };
30608
30806
  try {
30609
30807
  if (!client.listScoped)
30610
- return { state: "unconfirmed", grants };
30808
+ return { ...access, state: "unconfirmed" };
30611
30809
  const { token } = await readClaustrumEnrollmentToken2(tokenPath);
30612
30810
  const inventory = await client.listScoped(token);
30613
30811
  const confirmed = grants.map((entry) => ({
@@ -30615,6 +30813,7 @@ async function confirmEnrollmentAccess(client, status, tokenPath, configuredGran
30615
30813
  reachableLogins: inventory.rows.filter((row) => row.operations.includes(entry.grant.operation) && (entry.grant.selector.exact !== void 0 ? row.id === entry.grant.selector.exact : row.categories.includes(entry.grant.selector.category))).length
30616
30814
  }));
30617
30815
  return {
30816
+ ...access,
30618
30817
  state: confirmed.every((entry) => entry.reachableLogins > 0) ? "reachable" : confirmed.some((entry) => entry.reachableLogins > 0) ? "partial" : "no-logins",
30619
30818
  grants: confirmed.map((entry) => {
30620
30819
  if (entry.reachableLogins === 0)
@@ -30624,10 +30823,12 @@ async function confirmEnrollmentAccess(client, status, tokenPath, configuredGran
30624
30823
  })
30625
30824
  };
30626
30825
  } catch {
30627
- return { state: "unconfirmed", grants };
30826
+ return { ...access, state: "unconfirmed" };
30628
30827
  }
30629
30828
  }
30630
- function enrollmentAccessLines(access) {
30829
+ function enrollmentAccessLines(access, grantFallback = "setup") {
30830
+ if (grantFallback === "plugin" && access.requestedGrantsStatus !== "sent")
30831
+ return [];
30631
30832
  const lines = [];
30632
30833
  const remedy = access.grants.some((entry) => entry.grantCommand) ? "run:" : "check ck auth status for the approved name before granting access.";
30633
30834
  if (access.state === "older-vault")
@@ -30689,8 +30890,9 @@ var OUTCOME_TEXT = {
30689
30890
  "not-enrolled": "not connected",
30690
30891
  unknown: "unknown, check with ck auth status"
30691
30892
  };
30692
- function setupEnrollmentLine({ host, outcome, access }) {
30693
- return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}${access ? ` \u2014 ${enrollmentAccessLines(access).join("\n")}` : ""}`;
30893
+ function setupEnrollmentLine({ host, outcome, access }, grantFallback = "setup") {
30894
+ const lines = access ? enrollmentAccessLines(access, grantFallback) : [];
30895
+ return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}${lines.length ? ` \u2014 ${lines.join("\n")}` : ""}`;
30694
30896
  }
30695
30897
  var recordedEnrollment = /* @__PURE__ */ new WeakMap();
30696
30898
  function recordSetupEnrollment(failure, enrollment) {
@@ -31228,7 +31430,7 @@ function approveCommand(requestId, name) {
31228
31430
  async function connectSetupHost(plugin, host, io, terminal, fence) {
31229
31431
  if (hasVaultHost2())
31230
31432
  throw new Error(VAULT_HOST_CONNECT_REFUSAL2);
31231
- const { name, displayName, requestedGrants, paths: input } = plugin.vault.hosts[host];
31433
+ const { name, displayName, requestedGrants, grantFallback, paths: input } = plugin.vault.hosts[host];
31232
31434
  const paths = hostEnrollmentPaths2(input);
31233
31435
  await fence();
31234
31436
  const client = await (io.connect ?? connectClaustrumEnrollmentClient2)({
@@ -31261,7 +31463,7 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
31261
31463
  printLine2(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
31262
31464
  const access = await confirmEnrollmentAccess(client, initial, paths.tokenPath, requestedGrants);
31263
31465
  if (access)
31264
- for (const line of enrollmentAccessLines(access))
31466
+ for (const line of enrollmentAccessLines(access, grantFallback))
31265
31467
  printLine2(terminal, line);
31266
31468
  return access;
31267
31469
  }
@@ -31277,7 +31479,7 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
31277
31479
  printLine2(terminal, `Connected ${host} to Claustrum.`);
31278
31480
  const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
31279
31481
  if (access)
31280
- for (const line of enrollmentAccessLines(access))
31482
+ for (const line of enrollmentAccessLines(access, grantFallback))
31281
31483
  printLine2(terminal, line);
31282
31484
  return access;
31283
31485
  }
@@ -31476,8 +31678,8 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
31476
31678
 
31477
31679
  // src/common-auth-embedded/setup/config-write.js
31478
31680
  import { randomUUID as randomUUID16 } from "node:crypto";
31479
- import { mkdir as mkdir15, open as open11, rename as rename13, stat as stat15, unlink as unlink12 } from "node:fs/promises";
31480
- import { basename as basename6, dirname as dirname20, join as join20 } from "node:path";
31681
+ import { mkdir as mkdir15, open as open11, rename as rename13, stat as stat15, unlink as unlink14 } from "node:fs/promises";
31682
+ import { basename as basename8, dirname as dirname20, join as join20 } from "node:path";
31481
31683
  import { setTimeout as delay2 } from "node:timers/promises";
31482
31684
  async function writeHostConfigAtomic(file, content, options = {}) {
31483
31685
  const windows = (options.platform ?? process.platform) === "win32";
@@ -31492,7 +31694,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
31492
31694
  throw error;
31493
31695
  }
31494
31696
  }
31495
- const stage = join20(parent, `.${basename6(file)}.${(options.stageName ?? randomUUID16)()}.tmp`);
31697
+ const stage = join20(parent, `.${basename8(file)}.${(options.stageName ?? randomUUID16)()}.tmp`);
31496
31698
  let created = false;
31497
31699
  try {
31498
31700
  const handle = await open11(stage, "wx", mode ?? 438);
@@ -31522,7 +31724,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
31522
31724
  }
31523
31725
  } finally {
31524
31726
  if (created)
31525
- await unlink12(stage).catch(() => {
31727
+ await unlink14(stage).catch(() => {
31526
31728
  });
31527
31729
  }
31528
31730
  }
@@ -31715,6 +31917,8 @@ function validatePlugin(plugin) {
31715
31917
  throw new Error("Setup requires lowercase vault names containing only letters, digits and dashes.");
31716
31918
  if (host.requestedGrants !== void 0 && !validEnrollmentRequestedGrants2(host.requestedGrants))
31717
31919
  throw new Error("invalid Claustrum enrollment requested grants");
31920
+ if (host.grantFallback !== void 0 && host.grantFallback !== "setup" && host.grantFallback !== "plugin")
31921
+ throw new Error("invalid Claustrum enrollment grant fallback");
31718
31922
  }
31719
31923
  }
31720
31924
  async function enrollmentReport(plugin, hosts, recorded, recordedAccess) {
@@ -31903,7 +32107,7 @@ ${write.content}`);
31903
32107
  const report = await enrollmentReport(plugin, hosts, enrollment, enrollmentAccess);
31904
32108
  recordSetupEnrollment(error, report);
31905
32109
  for (const entry of report)
31906
- printLine2(terminal, setupEnrollmentLine(entry));
32110
+ printLine2(terminal, setupEnrollmentLine(entry, plugin.vault.hosts[entry.host].grantFallback));
31907
32111
  } catch {
31908
32112
  }
31909
32113
  throw error;