@cortexkit/opencode-openai-auth 1.12.0 → 1.14.0

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 (55) hide show
  1. package/dist/bin.js +9 -9
  2. package/dist/{codex-request-DFeGDzpN.d.ts → codex-request-Cl6zEfsR.d.ts} +21 -3
  3. package/dist/{index-5p6vw484.js → index-1abcvt9p.js} +1 -1
  4. package/dist/{index-2xsz3z63.js → index-3c9pk6zn.js} +2 -2
  5. package/dist/{index-dcvxs9xj.js → index-4tpttpjw.js} +1 -1
  6. package/dist/index-4zpxwh8y.js +91 -0
  7. package/dist/{index-7p1s64b4.js → index-a9tzfpxy.js} +1 -1
  8. package/dist/index-bc2d4vma.js +64 -0
  9. package/dist/{index-wtmxk263.js → index-f7t7cc9b.js} +2 -2
  10. package/dist/{index-7qztyb1b.js → index-nfbmjq6g.js} +2 -2
  11. package/dist/{index-3pm1cvhy.js → index-q111b2h5.js} +1 -1
  12. package/dist/{index-3nwj0h10.js → index-wap9mf5f.js} +2 -2
  13. package/dist/{index-p4qaa85r.js → index-xxmaf5ks.js} +2 -2
  14. package/dist/index-yew3mp47.js +76 -0
  15. package/dist/index-zcpher1w.js +8 -0
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/rpc/port-file.js +1 -1
  19. package/dist/rpc/protocol.js +1 -1
  20. package/dist/rpc/rpc-client.js +1 -1
  21. package/dist/rpc/rpc-dir.js +1 -1
  22. package/dist/sidebar-state.js +1 -1
  23. package/dist/{token-dr80qm6g.js → token-6x4q5r2r.js} +1 -1
  24. package/dist/token-util-54mhq85x.js +1 -0
  25. package/dist/tui-preferences.js +1 -1
  26. package/dist/v2/server.d.ts +1 -1
  27. package/dist/v2/server.js +3 -3
  28. package/package.json +8 -7
  29. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +89 -31
  30. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +19 -13
  31. package/src/tui-compiled/raw/shared/549daf371622c304-index.tsx +49 -607
  32. package/src/tui-compiled/raw/shared/723b00f96290a097-lock-record.js +55 -0
  33. package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +9 -1
  34. package/src/tui-compiled/raw/shared/a75d0d866c227b3f-index.tsx +681 -0
  35. package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +21 -15
  36. package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +110 -2
  37. package/src/tui-compiled/raw/shared/c97089ed4243981c-host.js +11 -7
  38. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +148 -92
  39. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +1 -1
  40. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +89 -31
  41. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +19 -13
  42. package/src/tui-compiled/runtime/shared/549daf371622c304-index.js +36 -674
  43. package/src/tui-compiled/runtime/shared/723b00f96290a097-lock-record.js +55 -0
  44. package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +9 -1
  45. package/src/tui-compiled/runtime/shared/a75d0d866c227b3f-index.js +678 -0
  46. package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +21 -15
  47. package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +110 -2
  48. package/src/tui-compiled/runtime/shared/c97089ed4243981c-host.js +11 -7
  49. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +148 -92
  50. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +1 -1
  51. package/dist/index-2egbrywb.js +0 -8
  52. package/dist/index-dqk0c7wr.js +0 -64
  53. package/dist/index-n5jtwtrs.js +0 -76
  54. package/dist/index-phgm1zwn.js +0 -91
  55. package/dist/token-util-97td5ex3.js +0 -1
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { link, lstat, mkdir, open, readFile, rename, rm, stat, } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
+ import { DisappearedLockRecordError, isWindowsAccessDeniedCreate, isWindowsAccessDeniedRead, readLockRecord, } from "./723b00f96290a097-lock-record.js";
4
5
  import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, isWindowsSharingViolation, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from "./375d9cca2def037d-private-files.js";
5
6
  import { LockOwnershipError, lockPathFor } from "./4825e03209d6ae3e-with-lock.js";
6
7
  let leaseCreationTestHooks;
@@ -192,17 +193,22 @@ export async function acquireRefreshFileLockWithClock(options) {
192
193
  const evictOwnerId = randomUUID();
193
194
  const EVICT_TTL = 5_000;
194
195
  const MAX_STEAL_ATTEMPTS = 8;
196
+ function isChangingLockCreate(error) {
197
+ return (windowsPrivateFiles &&
198
+ (isWindowsAccessDeniedCreate(error, [lockPath], 'create') ||
199
+ isWindowsAccessDeniedCreate(error, [evictPath], 'directory-create')));
200
+ }
195
201
  async function readOwner() {
196
202
  if (windowsPrivateFiles) {
197
203
  try {
198
- return JSON.parse(await readPrivateText(lockPath, true));
204
+ return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
199
205
  }
200
206
  catch (error) {
201
207
  if (error.code !== 'EISDIR' &&
202
208
  error.reason !== 'wrong-kind')
203
209
  throw error;
204
- await verifyPrivate(lockPath, 'directory', true);
205
- return JSON.parse(await readPrivateText(legacyOwnerPath, true));
210
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, 'directory', true));
211
+ return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
206
212
  }
207
213
  }
208
214
  try {
@@ -280,8 +286,8 @@ export async function acquireRefreshFileLockWithClock(options) {
280
286
  await options.onStep('lease-contention-read-ready');
281
287
  try {
282
288
  if (code === 'EISDIR') {
283
- await verifyPrivate(lockPath, 'directory', true);
284
- await readPrivateText(legacyOwnerPath, true);
289
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, 'directory', true));
290
+ await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
285
291
  }
286
292
  else
287
293
  await readOwner();
@@ -337,6 +343,10 @@ export async function acquireRefreshFileLockWithClock(options) {
337
343
  owner = await readOwner();
338
344
  }
339
345
  catch (error) {
346
+ // A delete-pending owner that disappeared is a create opportunity,
347
+ // never an ownerless legacy directory eligible for stale eviction.
348
+ if (error instanceof DisappearedLockRecordError)
349
+ return { status: 'missing' };
340
350
  if (windowsPrivateFiles &&
341
351
  error.code !== 'ENOENT')
342
352
  throw error;
@@ -395,7 +405,7 @@ export async function acquireRefreshFileLockWithClock(options) {
395
405
  // Fail-closed: any read error means we do NOT own the marker.
396
406
  async function ownsEvictionMarker() {
397
407
  try {
398
- const owner = JSON.parse(await readPrivateText(evictOwnerPath, windowsPrivateFiles));
408
+ const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
399
409
  return owner?.ownerId === evictOwnerId;
400
410
  }
401
411
  catch (error) {
@@ -581,7 +591,7 @@ export async function acquireRefreshFileLockWithClock(options) {
581
591
  }
582
592
  if (windowsPrivateFiles) {
583
593
  try {
584
- await verifyPrivate(evictPath, 'directory', true);
594
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, 'directory', true));
585
595
  }
586
596
  catch (error) {
587
597
  // The marker's holder can remove it between the stat above and this
@@ -654,8 +664,8 @@ export async function acquireRefreshFileLockWithClock(options) {
654
664
  if (error.code === 'EEXIST') {
655
665
  if (windowsPrivateFiles) {
656
666
  try {
657
- await verifyPrivate(evictPath, 'directory', true);
658
- await readPrivateText(evictOwnerPath, true);
667
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, 'directory', true));
668
+ await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, true));
659
669
  }
660
670
  catch (ownerError) {
661
671
  // A marker removed by its holder after the failed create is free:
@@ -681,10 +691,16 @@ export async function acquireRefreshFileLockWithClock(options) {
681
691
  await releaseEvictionMarker(deadline);
682
692
  }
683
693
  catch (error) {
684
- // Cleanup sharing failures must not replace the lock's original
685
- // sharing refusal when both removals exhaust the same deadline.
686
- if (isRetryableRemoval(actionError, lockPath) &&
687
- isRetryableRemoval(error, evictPath))
694
+ // Cleanup IO failures must not replace the original lock refusal when
695
+ // both operations use the same deadline.
696
+ if ((isRetryableRemoval(actionError, lockPath) ||
697
+ isWindowsAccessDeniedRead(actionError, [
698
+ lockPath,
699
+ legacyOwnerPath,
700
+ evictOwnerPath,
701
+ ])) &&
702
+ (isRetryableRemoval(error, evictPath) ||
703
+ isWindowsAccessDeniedRead(error, [evictOwnerPath])))
688
704
  throw actionError;
689
705
  throw error;
690
706
  }
@@ -705,7 +721,8 @@ export async function acquireRefreshFileLockWithClock(options) {
705
721
  owner = await readOwner();
706
722
  }
707
723
  catch (error) {
708
- if (windowsPrivateFiles)
724
+ if (windowsPrivateFiles &&
725
+ !(error instanceof DisappearedLockRecordError))
709
726
  throw error;
710
727
  return;
711
728
  }
@@ -789,7 +806,9 @@ export async function acquireRefreshFileLockWithClock(options) {
789
806
  }
790
807
  }
791
808
  catch (error) {
792
- if (windowsPrivateFiles && error instanceof PrivateFileError) {
809
+ if (windowsPrivateFiles &&
810
+ error instanceof PrivateFileError &&
811
+ !isChangingLockCreate(error)) {
793
812
  terminalIOError = error;
794
813
  recordLoss('renewal-failed');
795
814
  shouldReschedule = false;
@@ -844,90 +863,112 @@ export async function acquireRefreshFileLockWithClock(options) {
844
863
  }
845
864
  return null;
846
865
  }
847
- let acquired = await tryAcquire();
866
+ let acquired = false;
867
+ let changingCreateError;
868
+ try {
869
+ acquired = await tryAcquire();
870
+ }
871
+ catch (error) {
872
+ if (!isChangingLockCreate(error))
873
+ throw error;
874
+ changingCreateError = error;
875
+ }
848
876
  if (!acquired) {
849
877
  for (let attempt = 0; attempt < MAX_STEAL_ATTEMPTS; attempt++) {
850
- acquired = await tryAcquire();
851
- if (acquired)
852
- break;
853
- const observed = await readLockState();
854
- if (observed.status === 'live')
855
- return contended();
856
- // Absence is a create opportunity, never evidence of an expired lease.
857
- if (observed.status === 'missing')
858
- continue;
859
- if (options.onStep)
860
- await options.onStep('stale-lock-observed');
861
878
  try {
862
- if (!(await tryAcquireEvictionMarker())) {
863
- await backoff();
864
- continue;
865
- }
866
- }
867
- catch (evictError) {
868
- const code = evictError.code;
869
- if (code !== 'EEXIST')
870
- throw evictError;
871
- const recovered = await recoverStaleEvictionMarker();
872
- if (recovered === 'fresh')
873
- return null;
874
- await backoff();
875
- continue;
876
- }
877
- try {
878
- const confirmed = await readLockState();
879
- if (confirmed.status === 'live')
879
+ acquired = await tryAcquire();
880
+ if (acquired)
881
+ break;
882
+ const observed = await readLockState();
883
+ if (observed.status === 'live')
880
884
  return contended();
881
- if (!sameStaleLock(observed.identity, confirmed))
885
+ // Absence is a create opportunity, never evidence of an expired lease.
886
+ if (observed.status === 'missing')
882
887
  continue;
883
- // Verify marker ownership before removing a lock found not live.
884
- if (!(await ownsEvictionMarker()))
885
- return null;
886
888
  if (options.onStep)
887
- await options.onStep('stale-lock-confirmed');
888
- // The onStep callback can pause while another contender renames
889
- // our marker, so verify ownership again after the callback.
890
- if (!(await ownsEvictionMarker()))
891
- return null;
892
- // Do not await a callback between this ownership check and the lock read.
893
- const current = await readLockState(false);
894
- if (!sameStaleLock(observed.identity, current))
889
+ await options.onStep('stale-lock-observed');
890
+ try {
891
+ if (!(await tryAcquireEvictionMarker())) {
892
+ await backoff();
893
+ continue;
894
+ }
895
+ }
896
+ catch (evictError) {
897
+ const code = evictError.code;
898
+ if (code !== 'EEXIST')
899
+ throw evictError;
900
+ const recovered = await recoverStaleEvictionMarker();
901
+ if (recovered === 'fresh')
902
+ return null;
903
+ await backoff();
895
904
  continue;
896
- // The final read and removal are not atomic. While this stale file
897
- // exists, wx cannot create a successor; the marker excludes other
898
- // evictors and release/renewal. An expired holder cannot renew: renewal
899
- // rechecks expiry and marker ownership immediately before publishing.
900
- // With the marker still owned, cooperating users cannot replace it in
901
- // this window. Arbitrary suspension across marker expiry or filesystem
902
- // changes still need a kernel lock for an atomic guarantee.
903
- await removeLeaseObject(lockPath);
904
- // Fence check 3: re-verify ownership after removing the stale lock.
905
- if (!(await ownsEvictionMarker()))
906
- return null;
907
- if (options.onStep)
908
- await options.onStep('stale-lock-removed');
909
- acquired = await tryAcquire();
910
- if (!acquired)
911
- return null;
912
- if (options.onStep)
913
- await options.onStep('stale-lock-recreated');
914
- // Fence check 4: re-verify ownership after acquiring the lock. If the
915
- // marker was stolen between tryAcquire and this check, release the
916
- // just-acquired lock and return null (fail-closed).
917
- if (!(await ownsEvictionMarker())) {
918
- await relinquishLockAfterMarkerLoss();
919
- acquired = false;
920
- return null;
921
905
  }
922
- break;
906
+ try {
907
+ const confirmed = await readLockState();
908
+ if (confirmed.status === 'live')
909
+ return contended();
910
+ if (!sameStaleLock(observed.identity, confirmed))
911
+ continue;
912
+ // Verify marker ownership before removing a lock found not live.
913
+ if (!(await ownsEvictionMarker()))
914
+ return null;
915
+ if (options.onStep)
916
+ await options.onStep('stale-lock-confirmed');
917
+ // The onStep callback can pause while another contender renames
918
+ // our marker, so verify ownership again after the callback.
919
+ if (!(await ownsEvictionMarker()))
920
+ return null;
921
+ // Do not await a callback between this ownership check and the lock read.
922
+ const current = await readLockState(false);
923
+ if (!sameStaleLock(observed.identity, current))
924
+ continue;
925
+ // The final read and removal are not atomic. While this stale file
926
+ // exists, exclusive creation cannot publish a successor; the marker
927
+ // excludes other evictors and release/renewal. An expired holder cannot
928
+ // renew: renewal rechecks expiry and marker ownership before publishing.
929
+ // With the marker still owned, cooperating users cannot replace it in
930
+ // this window. Arbitrary suspension across marker expiry or filesystem
931
+ // changes still need a kernel lock for an atomic guarantee.
932
+ await removeLeaseObject(lockPath);
933
+ // Fence check 3: re-verify ownership after removing the stale lock.
934
+ if (!(await ownsEvictionMarker()))
935
+ return null;
936
+ if (options.onStep)
937
+ await options.onStep('stale-lock-removed');
938
+ acquired = await tryAcquire();
939
+ if (!acquired)
940
+ return null;
941
+ if (options.onStep)
942
+ await options.onStep('stale-lock-recreated');
943
+ // Fence check 4: re-verify ownership after acquiring the lock. If the
944
+ // marker was stolen between tryAcquire and this check, release the
945
+ // just-acquired lock and return null (fail-closed).
946
+ if (!(await ownsEvictionMarker())) {
947
+ await relinquishLockAfterMarkerLoss();
948
+ acquired = false;
949
+ return null;
950
+ }
951
+ break;
952
+ }
953
+ finally {
954
+ await releaseEvictionMarker();
955
+ }
923
956
  }
924
- finally {
925
- await releaseEvictionMarker();
957
+ catch (error) {
958
+ if (!isChangingLockCreate(error))
959
+ throw error;
960
+ // A refused create is busy, not stale. Retry exclusive creation before
961
+ // any owner read or eviction, retaining the first persistent refusal.
962
+ changingCreateError ??= error;
963
+ await backoff();
926
964
  }
927
965
  }
928
966
  }
929
- if (!acquired)
967
+ if (!acquired) {
968
+ if (changingCreateError)
969
+ throw changingCreateError;
930
970
  return null;
971
+ }
931
972
  scheduleRenewal();
932
973
  return {
933
974
  ownerId,
@@ -977,6 +1018,7 @@ export async function acquireRefreshFileLockWithClock(options) {
977
1018
  const deadline = performance.now() + EVICT_TTL + 1_000;
978
1019
  let delayMs = 5;
979
1020
  let removalError;
1021
+ let changingRecordError;
980
1022
  for (;;) {
981
1023
  try {
982
1024
  let removalConfirmed = false;
@@ -1004,6 +1046,7 @@ export async function acquireRefreshFileLockWithClock(options) {
1004
1046
  await removeLeaseObject(lockPath);
1005
1047
  removalConfirmed = true;
1006
1048
  }, deadline);
1049
+ changingRecordError = undefined;
1007
1050
  if (markerAcquired) {
1008
1051
  if (windowsPrivateFiles && !removalConfirmed)
1009
1052
  throw new PrivateFileError(lockPath, 'release-not-confirmed', {
@@ -1017,15 +1060,27 @@ export async function acquireRefreshFileLockWithClock(options) {
1017
1060
  await recoverStaleEvictionMarker(deadline);
1018
1061
  }
1019
1062
  catch (error) {
1020
- if (!isRetryableRemoval(error, lockPath)) {
1063
+ const changingRecord = windowsPrivateFiles &&
1064
+ (isChangingLockCreate(error) ||
1065
+ isWindowsAccessDeniedRead(error, [
1066
+ lockPath,
1067
+ legacyOwnerPath,
1068
+ evictPath,
1069
+ evictOwnerPath,
1070
+ ]));
1071
+ if (!isRetryableRemoval(error, lockPath) && !changingRecord) {
1021
1072
  if (windowsPrivateFiles)
1022
1073
  throw error;
1023
1074
  return;
1024
1075
  }
1025
- // Like rename, a fenced delete can be refused by a reader's Windows
1026
- // handle without invalidating ownership. Drop the marker, back off,
1027
- // and re-confirm the owner under a new marker before trying again.
1028
- removalError ??= error;
1076
+ // Neither a refused delete nor an ambiguous record read or create
1077
+ // establishes loss or expiry. Back off under the release deadline and
1078
+ // re-confirm ownership before any removal; keep the original error
1079
+ // if the refusal persists.
1080
+ if (changingRecord)
1081
+ changingRecordError ??= error;
1082
+ else
1083
+ removalError ??= error;
1029
1084
  }
1030
1085
  const remainingMs = deadline - performance.now();
1031
1086
  if (remainingMs <= 0)
@@ -1038,7 +1093,8 @@ export async function acquireRefreshFileLockWithClock(options) {
1038
1093
  // Do not delete by pathname without the marker: bounded retries leave the
1039
1094
  // lease to expire rather than risking removal of a successor's lock.
1040
1095
  if (windowsPrivateFiles)
1041
- throw (removalError ??
1096
+ throw (changingRecordError ??
1097
+ removalError ??
1042
1098
  new PrivateFileError(lockPath, 'release-not-confirmed', {
1043
1099
  code: 'ETIMEDOUT',
1044
1100
  }));
@@ -10,7 +10,7 @@ export { ClaustrumCredentialError, } from "@cortexkit/claustrum-client";
10
10
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, } from "./94f53cfd572ba4bb-availability.js";
11
11
  export { ClaustrumConsumer, DEFAULT_CONNECT_TIMEOUT_MS, } from "./169b2b4bf30909bc-consumer.js";
12
12
  export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, SERVING_MARGIN_MS, } from "./0f77ebc3c914c9c6-custody.js";
13
- export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, vaultAuthority, } from "./b9588ad4725c1d10-enrollment.js";
13
+ export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, validEnrollmentDisplayName, validEnrollmentRequestedGrants, vaultAuthority, } from "./b9588ad4725c1d10-enrollment.js";
14
14
  export { ClaustrumConsumerError, } from "./ca0fccaba1d87af4-errors.js";
15
15
  export { connectVaultHost, hasVaultHost, VAULT_HOST_CONNECT_REFUSAL, VAULT_HOST_STATUS, } from "./c97089ed4243981c-host.js";
16
16
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from "./d9d2892a4c371301-host-slot.js";
@@ -1,8 +0,0 @@
1
- import{$f as C,_f as $,ag as y,bg as S0,dg as A,eg as i,fg as f,gg as n,hg as A0,jg as k}from"./index-7qztyb1b.js";import{randomUUID as g}from"node:crypto";import{link as O0,lstat as T,mkdir as x0,open as t,readFile as F0,rename as j0,rm as R,stat as b}from"node:fs/promises";import{dirname as s,join as q0}from"node:path";import{join as L0,resolve as b0}from"node:path";function d(z,H){return`${z}.${H}.lock`}class D0 extends Error{details;constructor(z){super(`Timed out acquiring ${z.name} lock for ${z.target}`);this.name="LockContentionError",this.details=z}}class L extends Error{details;constructor(z){super(`Lost ${z.name} lock for ${z.target}`);this.name="LockOwnershipError",this.details=z}}function g0(z,H,Y){if(!y(z)||z.stage!=="read"&&z.stage!=="verify")return!1;let Z=b0(d(H,Y));return z.path===Z||z.path===L0(Z,"owner.json")}async function s0(z,H,Y){let Z=performance.now();for(;;){H.signal?.throwIfAborted();let J,W;try{J=await V0({path:z,name:H.name,ttlMs:H.ttlMs,renew:H.renew??!1,...H.onStep?{onStep:H.onStep}:{},...H.onRenewalTimer?{onRenewalTimer:H.onRenewalTimer}:{}})}catch(V){if(!g0(V,z,H.name))throw V;J=null,W=V}if(J)try{return H.signal?.throwIfAborted(),await Y(J)}finally{await J.release(H.signal)}let X=H.timeoutMs-(performance.now()-Z);if(X<=0){if(W)throw W;throw new D0({target:z,name:H.name,timeoutMs:H.timeoutMs})}await new Promise((V)=>setTimeout(V,Math.min(25,Math.ceil(X))))}}var M;async function E0(z,H){let Y=`${z}.${g()}.tmp`,Z;try{Z=await t(Y,"wx",384);try{if(M?.beforeWrite)await M.beforeWrite(Y);await Z.writeFile(H,"utf8")}finally{await Z.close()}try{if(M?.beforeLink)await M.beforeLink(Y,z);await O0(Y,z)}catch(J){let W=J.code;if(W!=="EPERM"&&W!=="ENOTSUP"&&W!=="EOPNOTSUPP"&&W!=="EXDEV")throw J;await I0(z,H)}}finally{if(Z)await R(Y,{force:!0}).catch(()=>{})}}async function I0(z,H){let Y=await t(z,"wx",384),Z;try{Z=await Y.stat()}catch{Z=void 0}try{if(M?.beforeWrite)await M.beforeWrite(z);await Y.writeFile(H,"utf8")}catch(J){try{let W=await T(z).catch(()=>{return});if(Z&&W&&W.dev===Z.dev&&W.ino===Z.ino)await R(z,{force:!0}).catch(()=>{})}catch{}throw J}finally{await Y.close()}}var y0=globalThis.setTimeout.bind(globalThis),k0=globalThis.clearTimeout.bind(globalThis);function P0(z){let H=z?.code;return H==="ENOENT"||!$&&(H==="EINVAL"||H==="ENOTDIR")}var C0;function a(z,H){if(z.dev!==H.dev||z.ino!==H.ino)return!1;if(z.ino===0&&z.birthtimeMs!==H.birthtimeMs)return!1;return!0}var u0=1000;function V0(z){return m0({...z,now:Date.now})}async function m0(z){let H=d(z.path,z.name),Y=q0(H,"owner.json"),Z=g(),J=z.now??Date.now,W=null,X=!1,V=!1,D,e,T0=new Promise((N)=>{e=N});function z0(N){try{let B=z.onRenewalTimer?.(N);if(B&&(typeof B==="object"||typeof B==="function")&&"then"in B&&typeof B.then==="function")Promise.resolve(B).catch(()=>{})}catch{}}function N0(){if(!W)return;k0(W),W=null,z0("cancelled")}function j(N,B){if(D||X)return;D=Object.freeze({reason:N,expectedOwnerId:Z,...typeof B?.ownerId==="string"?{observedOwnerId:B.ownerId}:{},...typeof B?.expiresAt==="number"?{observedExpiresAt:B.expiresAt}:{}}),N0(),e(D)}let u,O=null,U=`${H}.evicting`,q=q0(U,"owner.json"),B0=g(),m=5000,G0=8;async function F(){if($)try{return JSON.parse(await f(H,!0))}catch(N){if(N.code!=="EISDIR"&&N.reason!=="wrong-kind")throw N;return await A(H,"directory",!0),JSON.parse(await f(Y,!0))}try{return JSON.parse(await F0(H,"utf8"))}catch(N){if(N.code!=="EISDIR")throw N;return JSON.parse(await F0(Y,"utf8"))}}async function R0(){if($){let K=await F(),Q=Number(K?.expiresAt)-J();await k(H,`${JSON.stringify({ownerId:Z,expiresAt:J()+z.ttlMs})}
2
- `,{deadline:performance.now()+Math.max(0,Q),beforeRename:async()=>{let _=await F();if(_?.ownerId!==Z||!(Number(_?.expiresAt)>J())||!await x())throw new L({target:z.path,name:z.name})}});return}let N=`${H}.${g()}.tmp`,B,G=!1;try{B=await t(N,"wx",384),G=!0,await B.writeFile(`${JSON.stringify({ownerId:Z,expiresAt:J()+z.ttlMs})}
3
- `,"utf8"),await B.chmod(384),await B.close(),B=void 0;let K=await F();if(K?.ownerId!==Z||!(Number(K?.expiresAt)>J())||!await x())throw new L({target:z.path,name:z.name});await j0(N,H),G=!1}finally{if(await B?.close().catch(()=>{}),G)await R(N,{force:!0}).catch(()=>{})}}async function H0(){let N=`${JSON.stringify({ownerId:Z,expiresAt:J()+z.ttlMs})}
4
- `;if($)await n(H,N);else await E0(H,N)}async function K0(N){let B=N.code;if(B!=="EEXIST"&&B!=="EISDIR")return!1;if($){if(z.onStep)await z.onStep("lease-contention-read-ready");try{if(B==="EISDIR")await A(H,"directory",!0),await f(Y,!0);else await F()}catch(G){if(G.code!=="ENOENT")throw G}}return!0}async function w(){if($)await i(s(H));try{return await H0(),!0}catch(N){let B=N.code;if(await K0(N))return!1;if(B==="ENOENT"){if($)await i(s(H));else await x0(s(H),{recursive:!0});try{return await H0(),!0}catch(G){if(await K0(G))return!1;throw G}}throw N}}async function v(){await new Promise((N)=>setTimeout(N,Math.floor(Math.random()*4)))}async function h(N=!0){if(N&&z.onStep)await z.onStep("lock-read-ready");let B;try{B=await F()}catch(K){if($&&K.code!=="ENOENT")throw K}let G=Number(B?.expiresAt);if(Number.isFinite(G)&&G>J())return{status:"live"};if(typeof B?.ownerId==="string"&&Number.isFinite(G))return{status:"stale",identity:{kind:"owner",ownerId:B.ownerId,expiresAt:G}};try{let K=await b(H),Q=Number.isFinite(G)?G:K.mtimeMs+z.ttlMs;if(Q>J())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:K.dev,ino:K.ino,mtimeMs:K.mtimeMs,expiresAt:Q}}}catch(K){if(K.code==="ENOENT"){if(z.onStep)await z.onStep("lock-missing");return{status:"missing"}}throw K}}function Q0(N,B){if(B.status!=="stale")return!1;let G=B.identity;if(N.kind==="owner"&&G.kind==="owner")return N.ownerId===G.ownerId&&N.expiresAt===G.expiresAt;return N.kind==="stat"&&G.kind==="stat"&&N.dev===G.dev&&N.ino===G.ino&&N.mtimeMs===G.mtimeMs&&N.expiresAt===G.expiresAt}async function x(){try{return JSON.parse(await f(q,$))?.ownerId===B0}catch(N){if($&&N.code!=="ENOENT")throw N;return!1}}async function p(N){if($)await S0(N,"remove",()=>R(N,{recursive:!0,force:!0}));else await R(N,{recursive:!0,force:!0}).catch(()=>{})}function E(N,B){if(!$||!(N instanceof C)||N.stage!=="remove"||N.path!==B)return!1;return y(N)||N.win32Code===void 0&&N.reason===void 0&&(N.code==="EBUSY"||N.code==="EPERM")}async function c(N,B,G=performance.now()+m+1000){let K,Q=5;while(await B()){try{await p(N);return}catch(I){if(!E(I,N))throw I;K??=I}let _=G-performance.now();if(_<=0)throw K;if(await new Promise((I)=>setTimeout(I,Math.min(Q,_))),performance.now()>=G)throw K;Q=Math.min(Q*2,50)}}async function l(N){let B;await c(U,async()=>{if(!$)return x();let G=await T(U).catch((K)=>{if(K.code!=="ENOENT")throw K;return});if(!G||B&&!a(B,G))return!1;if(await x())return B=G,!0;if(!B)return!1;try{return await b(q),!1}catch(K){if(K.code!=="ENOENT")throw K;return!0}},N)}async function M0(N,B){if(!N)return!1;let G=!1;try{await c(U,async()=>{G=!1;let K=await T(U).catch(()=>{return});if(!K||!a(N,K))return!1;G=!0;try{return await b(q),!1}catch(Q){return Q.code==="ENOENT"}},B)}catch{}return G}async function Y0(N){if($)await A0(U);else await x0(U);let B;try{let G=await T(U);B={dev:G.dev,ino:G.ino,birthtimeMs:G.birthtimeMs}}catch{B=void 0}try{await C0?.beforeOwnerWrite?.(U,q);let G=await C0?.failOwnerWrite?.(U,q);if(G!==void 0)throw G;let K=`${JSON.stringify({ownerId:B0,createdAt:J()})}
5
- `;if($)await n(q,K);else await I0(q,K)}catch(G){let K=await M0(B,N);if(P0(G)&&!K)return!1;try{await l(N)}catch{}throw G}if(z.onStep)await z.onStep("eviction-marker-acquired");return!0}async function Z0(N){let B;try{B=await b(U)}catch(Q){if(Q.code==="ENOENT")return"missing";throw Q}if($)try{await A(U,"directory",!0)}catch(Q){if(Q.code==="ENOENT")return"missing";throw Q}if(B.mtimeMs+m>J()){let Q=!0;try{await b(q)}catch(_){if(_.code==="ENOENT")Q=!1;else return"fresh"}if(Q)return"fresh";if(B.mtimeMs+u0>J())return"fresh"}if(z.onStep)await z.onStep("stale-marker-stat");let G=`${U}.${g()}`;try{await j0(U,G)}catch(Q){if(Q.code==="ENOENT")return"missing";throw Q}if(z.onStep)await z.onStep("stale-marker-claimed");let K=$?await T(G):void 0;return await c(G,async()=>{if(!K)return!0;let Q=await T(G).catch((_)=>{if(_.code!=="ENOENT")throw _;return});return!!Q&&a(K,Q)},N),"recovered"}async function $0(N,B){try{if(!await Y0(B))return!1}catch(Q){if(Q.code==="EEXIST"){if($)try{await A(U,"directory",!0),await f(q,!0)}catch(_){if(_.code!=="ENOENT")throw _}return!1}throw Q}let G=!1,K;try{await N()}catch(Q){G=!0,K=Q}try{await l(B)}catch(Q){if(E(K,H)&&E(Q,U))throw K;throw Q}if(G)throw K;return!0}async function J0(){for(let N=0;N<G0;N++){if(z.onStep)await z.onStep("relinquish-read");let B;try{B=await F()}catch(G){if($)throw G;return}if(B?.ownerId!==Z)return;try{await R(H,{recursive:!0,force:!0});return}catch(G){if($)throw G;await v()}}}function W0(){if(!z.renew||X||D)return;let N=z.renewIntervalMs??Math.max(1000,Math.floor(z.ttlMs/3));if(W=y0(()=>{W=null;let B=(async()=>{let G=!X;try{if(!await $0(async()=>{let Q=await F(),_=J();if(X||D){G=!1;return}if(Q?.ownerId!==Z){j("taken-over",Q),G=!1;return}if(!(Number(Q?.expiresAt)>_)){j("expired",Q),G=!1;return}if(z.onStep)await z.onStep("renewal-owner-confirmed");if(X||D){G=!1;return}if(!await x())return;if(z.onStep)await z.onStep("renewal-write-fenced");if(X||D){G=!1;return}if(!await x())return;if(z.onStep)await z.onStep("renewal-write-ready");if(X||D){G=!1;return}if(await R0(),z.onStep)await z.onStep("renewal-write-finished");if(!await x()){j("marker-lost"),G=!1,await J0();return}})&&z.onStep)await z.onStep("renewal-marker-unavailable")}catch(K){if($&&K instanceof C)u=K,j("renewal-failed"),G=!1;try{let Q=await F();if(Q?.ownerId!==Z)j("taken-over",Q);else if(!(Number(Q?.expiresAt)>J()))j("expired",Q)}catch{j("renewal-failed")}}finally{if(z.onStep)try{await z.onStep("renewal-finished")}catch{}if(G&&!X&&!D)W0()}})();O=B,B.finally(()=>{if(O===B)O=null})},N),"unref"in W)W.unref();z0("scheduled")}function _0(){try{let N=z.onContended?.();if(N&&(typeof N==="object"||typeof N==="function")&&"then"in N&&typeof N.then==="function")Promise.resolve(N).catch(()=>{})}catch{}return null}let S=await w();if(!S)for(let N=0;N<G0;N++){if(S=await w(),S)break;let B=await h();if(B.status==="live")return _0();if(B.status==="missing")continue;if(z.onStep)await z.onStep("stale-lock-observed");try{if(!await Y0()){await v();continue}}catch(G){if(G.code!=="EEXIST")throw G;if(await Z0()==="fresh")return null;await v();continue}try{let G=await h();if(G.status==="live")return _0();if(!Q0(B.identity,G))continue;if(!await x())return null;if(z.onStep)await z.onStep("stale-lock-confirmed");if(!await x())return null;let K=await h(!1);if(!Q0(B.identity,K))continue;if(await p(H),!await x())return null;if(z.onStep)await z.onStep("stale-lock-removed");if(S=await w(),!S)return null;if(z.onStep)await z.onStep("stale-lock-recreated");if(!await x())return await J0(),S=!1,null;break}finally{await l()}}if(!S)return null;return W0(),{ownerId:Z,whenLost:()=>T0,hasLost:()=>D!==void 0,assertOwned:async()=>{if(u)throw u;let N;try{let B=await F();if(N=B,!X&&!D&&B?.ownerId===Z&&Number(B?.expiresAt)>J())return;j(B?.ownerId!==Z?"taken-over":"expired",B)}catch(B){if(j("unreadable"),$&&B instanceof C)throw B}throw new L({target:z.path,name:z.name,expectedOwnerId:Z,...typeof N?.ownerId==="string"?{observedOwnerId:N.ownerId}:{},...typeof N?.expiresAt==="number"?{observedExpiresAt:N.expiresAt}:{}})},release:async(N)=>{if($&&V)return;X=!0,N0(),await O;let B=performance.now()+m+1000,G=5,K;for(;;){try{let _=!1;if(await $0(async()=>{let X0;try{X0=await F()}catch(U0){if($&&U0.code==="ENOENT"){_=!0;return}throw U0}if(X0?.ownerId!==Z){_=!0;return}if(z.onStep)await z.onStep("release-owner-confirmed");if(!await x())return;await p(H),_=!0},B)){if($&&!_)throw new C(H,"release-not-confirmed",{code:"EIO"});V=_;return}if(N?.aborted)return;await Z0(B)}catch(_){if(!E(_,H)){if($)throw _;return}K??=_}let Q=B-performance.now();if(Q<=0)break;if(await new Promise((_)=>setTimeout(_,Math.min(G,Q))),$&&performance.now()>=B)break;G=Math.min(G*2,50)}if($)throw K??new C(H,"release-not-confirmed",{code:"ETIMEDOUT"})}}}import{randomUUID as f0}from"node:crypto";import{mkdir as w0,open as P,rename as v0,rm as h0}from"node:fs/promises";import{dirname as o}from"node:path";class r extends Error{constructor(z){super("file or directory sync failed",{cause:z});this.name="AtomicSyncError"}}async function Hz(z,H,Y={}){await p0(z,H,Y)}async function p0(z,H,Y,Z){if($)return k(z,Y.serialize?Y.serialize(H):`${JSON.stringify(H,null,2)}
6
- `,{beforeRename:Y.beforeRename,stagePath:`${z}.${(Y.stageName??f0)()}.tmp`,onRenamed:Z,durable:Y.durable,durability:Y.durability,onOutcome:Y.onOutcome});await w0(o(z),{recursive:!0});let J=`${z}.${(Y.stageName??f0)()}.tmp`,W,X=!1;try{if(W=await P(J,"wx",384),X=!0,await W.writeFile(Y.serialize?Y.serialize(H):`${JSON.stringify(H,null,2)}
7
- `,"utf8"),await W.chmod(384),Y.durable)try{await W.sync()}catch(V){throw new r(V)}if(await W.close(),W=void 0,await Y.beforeRename?.(),await v0(J,z),X=!1,Z?.(),Y.durable){let V=await P(o(z),"r");try{await V.sync()}catch(D){throw new r(D)}finally{await V.close()}}}finally{if(await W?.close().catch(()=>{}),X)await h0(J,{force:!0}).catch(()=>{})}}async function Kz(z){if($){await A(z,"file");let Z=new C(z,"directory-sync-unsupported",{code:"ENOTSUP"});throw Z.published=!0,Z}let H=await P(z,"r");try{await H.sync()}finally{await H.close()}let Y=await P(o(z),"r");try{await Y.sync()}finally{await Y.close()}}var Yz=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});
8
- export{r as pf,Hz as qf,p0 as rf,Kz as sf,V0 as tf,d as uf,D0 as vf,L as wf,s0 as xf,Yz as yf};