@cortexkit/opencode-openai-auth 1.0.3 → 1.0.5

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 (91) hide show
  1. package/README.md +12 -60
  2. package/dist/bin.js +13 -0
  3. package/dist/index-116q849r.js +2 -0
  4. package/dist/index-4fnghj9e.js +65 -0
  5. package/dist/index-66asrje2.js +2 -0
  6. package/dist/index-826s1yxa.js +2 -0
  7. package/dist/index-a69gr76b.js +2 -0
  8. package/dist/index-fsky1rsh.js +12 -0
  9. package/dist/index-fsxbncpw.js +3 -0
  10. package/dist/index-h263aftt.js +157 -0
  11. package/dist/{index-hy9030jh.js → index-nx2qh047.js} +1 -1
  12. package/dist/{index-766sfrh5.js → index-pg305s90.js} +1 -1
  13. package/dist/index-ssj7m2rd.js +8 -0
  14. package/dist/index-y4gxyxqd.js +2 -0
  15. package/dist/index-ydz3hbhc.js +2 -0
  16. package/dist/index.d.ts +2 -56
  17. package/dist/index.js +1 -1
  18. package/dist/map-m6f5a_IA.d.ts +56 -0
  19. package/dist/{pool-lifecycle-YLz2B8A5.d.ts → pool-lifecycle-C_6YRmsh.d.ts} +99 -789
  20. package/dist/{port-file-Do3lQIEk.d.ts → port-file-ZPlxXB4G.d.ts} +1 -1
  21. package/dist/{protocol-BOBdkqqm.d.ts → protocol-DctqemRI.d.ts} +1 -1
  22. package/dist/rpc/port-file.d.ts +1 -1
  23. package/dist/rpc/port-file.js +1 -1
  24. package/dist/rpc/protocol.d.ts +1 -1
  25. package/dist/rpc/protocol.js +1 -1
  26. package/dist/rpc/rpc-client.d.ts +3 -3
  27. package/dist/rpc/rpc-client.js +1 -1
  28. package/dist/rpc/rpc-dir.js +1 -1
  29. package/dist/{sidebar-state-D6cUKgkm.d.ts → sidebar-state-z_M7Trnd.d.ts} +5 -3
  30. package/dist/sidebar-state.d.ts +1 -1
  31. package/dist/sidebar-state.js +1 -1
  32. package/dist/{token-ypk61xj0.js → token-bzhkgc29.js} +1 -1
  33. package/dist/token-util-4a2xxnpg.js +1 -0
  34. package/dist/tui-preferences.d.ts +2 -1
  35. package/dist/tui-preferences.js +3 -3
  36. package/dist/tui.d.ts +2 -2
  37. package/dist/v2/server.d.ts +1 -1
  38. package/dist/v2/server.js +3 -4
  39. package/package.json +13 -8
  40. package/src/tui-compiled/raw/logger.js +10 -2
  41. package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +65 -34
  42. package/src/tui-compiled/raw/shared/053cc17b5419261e-codec.js +2 -1
  43. package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +26 -10
  44. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +302 -0
  45. package/src/tui-compiled/raw/shared/39c3cb05738fcf6d-projection.js +3 -1
  46. package/src/tui-compiled/raw/shared/43fc9e6b994519c7-refresh-lock.js +5 -0
  47. package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +2 -2
  48. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +4 -0
  49. package/src/tui-compiled/raw/shared/4f36d333d081d040-merge.js +21 -5
  50. package/src/tui-compiled/raw/shared/7211cfec06a298bc-atomic-write.js +21 -0
  51. package/src/tui-compiled/raw/shared/905bffc0220f43d0-map.js +36 -1
  52. package/src/tui-compiled/raw/shared/a09b6a533c11858f-tui-preferences.js +6 -4
  53. package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +30 -8
  54. package/src/tui-compiled/raw/shared/c64d7afbc14ca125-sidebar-file.js +17 -8
  55. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +3 -0
  56. package/src/tui-compiled/raw/shared/cd94316a888b0a8e-schema.js +3 -2
  57. package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +2 -2
  58. package/src/tui-compiled/raw/shared/d7dcba96fea1685c-engine.js +126 -11
  59. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +254 -37
  60. package/src/tui-compiled/raw/shared/ec971142548df90e-index.js +1 -0
  61. package/src/tui-compiled/raw/shared/fbcdcd0f925e74c0-rpc-client.js +15 -1
  62. package/src/tui-compiled/runtime/logger.js +10 -2
  63. package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +65 -34
  64. package/src/tui-compiled/runtime/shared/053cc17b5419261e-codec.js +2 -1
  65. package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +26 -10
  66. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +302 -0
  67. package/src/tui-compiled/runtime/shared/39c3cb05738fcf6d-projection.js +3 -1
  68. package/src/tui-compiled/runtime/shared/43fc9e6b994519c7-refresh-lock.js +5 -0
  69. package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +2 -2
  70. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +4 -0
  71. package/src/tui-compiled/runtime/shared/4f36d333d081d040-merge.js +21 -5
  72. package/src/tui-compiled/runtime/shared/7211cfec06a298bc-atomic-write.js +21 -0
  73. package/src/tui-compiled/runtime/shared/905bffc0220f43d0-map.js +36 -1
  74. package/src/tui-compiled/runtime/shared/a09b6a533c11858f-tui-preferences.js +6 -4
  75. package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +30 -8
  76. package/src/tui-compiled/runtime/shared/c64d7afbc14ca125-sidebar-file.js +17 -8
  77. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +3 -0
  78. package/src/tui-compiled/runtime/shared/cd94316a888b0a8e-schema.js +3 -2
  79. package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +2 -2
  80. package/src/tui-compiled/runtime/shared/d7dcba96fea1685c-engine.js +126 -11
  81. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +254 -37
  82. package/src/tui-compiled/runtime/shared/ec971142548df90e-index.js +1 -0
  83. package/src/tui-compiled/runtime/shared/fbcdcd0f925e74c0-rpc-client.js +15 -1
  84. package/dist/index-8kj7sa1p.js +0 -12
  85. package/dist/index-b3q3j39x.js +0 -2
  86. package/dist/index-bmd7x5aq.js +0 -2
  87. package/dist/index-ff1jy44a.js +0 -222
  88. package/dist/index-jyr8y8k4.js +0 -7
  89. package/dist/index-rv08jmd4.js +0 -2
  90. package/dist/index-sjx8t1nr.js +0 -2
  91. package/dist/token-util-wdza526f.js +0 -1
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { mkdir, open, rename, rm } from "node:fs/promises";
3
3
  import { dirname } from "node:path";
4
+ import { PrivateFileError, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from "./375d9cca2def037d-private-files.js";
4
5
  /** Internal classification of fsync failures, including a failure after rename. */
5
6
  export class AtomicSyncError extends Error {
6
7
  constructor(cause) {
@@ -16,6 +17,18 @@ export async function writeJsonAtomic(path, value, options = {}) {
16
17
  * and removed ids here, because a later directory sync cannot undo the rename.
17
18
  */
18
19
  export async function writeJsonAtomicTracked(path, value, options, onRenamed) {
20
+ if (windowsPrivateFiles) {
21
+ return writePrivateAtomic(path, options.serialize
22
+ ? options.serialize(value)
23
+ : `${JSON.stringify(value, null, 2)}\n`, {
24
+ beforeRename: options.beforeRename,
25
+ stagePath: `${path}.${(options.stageName ?? randomUUID)()}.tmp`,
26
+ onRenamed,
27
+ durable: options.durable,
28
+ durability: options.durability,
29
+ onOutcome: options.onOutcome,
30
+ });
31
+ }
19
32
  await mkdir(dirname(path), { recursive: true });
20
33
  const tempPath = `${path}.${(options.stageName ?? randomUUID)()}.tmp`;
21
34
  let handle;
@@ -63,6 +76,14 @@ export async function writeJsonAtomicTracked(path, value, options, onRenamed) {
63
76
  }
64
77
  /** Make an already renamed file and its directory durable without rewriting bytes. */
65
78
  export async function syncJsonFile(path) {
79
+ if (windowsPrivateFiles) {
80
+ await verifyPrivate(path, 'file');
81
+ const error = new PrivateFileError(path, 'directory-sync-unsupported', {
82
+ code: 'ENOTSUP',
83
+ });
84
+ error.published = true;
85
+ throw error;
86
+ }
66
87
  const file = await open(path, 'r');
67
88
  try {
68
89
  await file.sync();
@@ -83,6 +83,40 @@ export function isCreditBudgetEntry(value) {
83
83
  optional(value, 'remaining', isFiniteNumber) &&
84
84
  optional(value, 'unit', isString));
85
85
  }
86
+ function isQuotaCounter(value) {
87
+ return (isRecord(value) &&
88
+ isFiniteNumber(value.value) &&
89
+ Number.isInteger(value.value) &&
90
+ value.value >= 0 &&
91
+ isFiniteNumber(value.checkedAt));
92
+ }
93
+ export function isQuotaCounters(value) {
94
+ return isRecord(value) && Object.values(value).every(isQuotaCounter);
95
+ }
96
+ /** Keep usable counters without letting one malformed count hide a quota map. */
97
+ export function readQuotaCounters(value) {
98
+ if (!isRecord(value))
99
+ return undefined;
100
+ const entries = Object.entries(value).filter(([, entry]) => isQuotaCounter(entry));
101
+ return entries.length === 0
102
+ ? undefined
103
+ : Object.fromEntries(entries);
104
+ }
105
+ /** Decode persisted quota, dropping malformed counters but not limit evidence. */
106
+ export function decodeQuotaMap(value) {
107
+ // A valid map is returned as the same object, so stored quota keeps the
108
+ // identity it had before counters existed; only a map with a malformed
109
+ // counter is copied without it.
110
+ if (isQuotaMap(value))
111
+ return value;
112
+ if (!isRecord(value))
113
+ return undefined;
114
+ const { counters: rawCounters, ...rest } = value;
115
+ if (!isQuotaMap(rest))
116
+ return undefined;
117
+ const counters = readQuotaCounters(rawCounters);
118
+ return { ...rest, ...(counters === undefined ? {} : { counters }) };
119
+ }
86
120
  /**
87
121
  * True when `value` is a well-formed quota map. Unrecognised top-level keys
88
122
  * are tolerated (and preserved by merge) so a newer writer's additions
@@ -101,5 +135,6 @@ export function isQuotaMap(value) {
101
135
  return false;
102
136
  seen.add(key);
103
137
  }
104
- return optional(value, 'budget', isCreditBudgetEntry);
138
+ return (optional(value, 'budget', isCreditBudgetEntry) &&
139
+ optional(value, 'counters', isQuotaCounters));
105
140
  }
@@ -1,7 +1,7 @@
1
- import { readFile } from "node:fs/promises";
2
1
  import { applyEdits, modify, parse } from "jsonc-parser";
3
2
  import { writeJsonAtomic } from "./7211cfec06a298bc-atomic-write.js";
4
3
  import { WRITER_LOCK_CONSTANTS } from "./9b4da614c45f9cd0-lock-constants.js";
4
+ import { PrivateFileError, readPrivateText, windowsPrivateFiles, } from "./375d9cca2def037d-private-files.js";
5
5
  import { withLock } from "./4825e03209d6ae3e-with-lock.js";
6
6
  function isRecord(value) {
7
7
  return value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -10,12 +10,14 @@ function isRecord(value) {
10
10
  export async function readTuiPreferencesFile(file) {
11
11
  try {
12
12
  const errors = [];
13
- const root = parse(await readFile(file, 'utf8'), errors, {
13
+ const root = parse(await readPrivateText(file, windowsPrivateFiles), errors, {
14
14
  allowTrailingComma: true,
15
15
  });
16
16
  return errors.length === 0 && isRecord(root) ? root : {};
17
17
  }
18
- catch {
18
+ catch (error) {
19
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT')
20
+ throw error;
19
21
  return {};
20
22
  }
21
23
  }
@@ -42,7 +44,7 @@ export function createTuiPreferenceWriter(options) {
42
44
  await withLock(file, lockOptions, async (lock) => {
43
45
  let text;
44
46
  try {
45
- text = await readFile(file, 'utf8');
47
+ text = await readPrivateText(file, windowsPrivateFiles);
46
48
  }
47
49
  catch (error) {
48
50
  if (error.code !== 'ENOENT')
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { chmod, mkdir, open, readdir, readFile, rename, rmdir, stat, unlink, } from "node:fs/promises";
2
+ import { chmod, mkdir, open, readdir, rename, rmdir, stat, unlink, } from "node:fs/promises";
3
3
  import { join, resolve } from "node:path";
4
+ import { ensurePrivateDirectory, PrivateFileError, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from "./375d9cca2def037d-private-files.js";
4
5
  /**
5
6
  * A PID a liveness probe may address. `process.kill(0 | negative, 0)` signals
6
7
  * a process group rather than a process, and an unsafe integer cannot name a
@@ -68,6 +69,15 @@ export async function writePortFile(dir, entry, options = {}) {
68
69
  // persistent ENOENT (e.g. permission, read-only parent) will surface on
69
70
  // the second attempt — failing fast beats an unbounded loop.
70
71
  const writeOnce = async () => {
72
+ const target = join(dir, `port-${entry.pid}.json`);
73
+ if (windowsPrivateFiles) {
74
+ await ensurePrivateDirectory(dir, options.secureDir ?? false);
75
+ await options.beforeWrite?.();
76
+ await writePrivateAtomic(target, JSON.stringify({ ...entry, startedAt: Date.now() }), {
77
+ stagePath: `${target}.${(options.stageName ?? randomUUID)()}.tmp`,
78
+ });
79
+ return target;
80
+ }
71
81
  await mkdir(dir, {
72
82
  recursive: true,
73
83
  mode: options.secureDir ? 0o700 : undefined,
@@ -76,7 +86,6 @@ export async function writePortFile(dir, entry, options = {}) {
76
86
  await chmod(dir, 0o700);
77
87
  await options.beforeWrite?.();
78
88
  const full = { ...entry, startedAt: Date.now() };
79
- const target = join(dir, `port-${entry.pid}.json`);
80
89
  const tmp = `${target}.${(options.stageName ?? randomUUID)()}.tmp`;
81
90
  let handle;
82
91
  let created = false;
@@ -139,9 +148,11 @@ export async function sweepRpcState(root, activeDir, isManagedDir, log) {
139
148
  const portFile = join(dir, name);
140
149
  let raw;
141
150
  try {
142
- raw = await readFile(portFile, 'utf8');
151
+ raw = await readPrivateText(portFile);
143
152
  }
144
- catch {
153
+ catch (error) {
154
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT')
155
+ throw error;
145
156
  continue;
146
157
  }
147
158
  if (raw === undefined)
@@ -172,19 +183,27 @@ export async function portFileIdentity(dir, entry) {
172
183
  return null;
173
184
  const path = join(resolve(dir), `port-${entry.pid}.json`);
174
185
  try {
186
+ if (windowsPrivateFiles)
187
+ await verifyPrivate(path, 'file');
175
188
  const info = await stat(path);
176
189
  return `${path}:${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
177
190
  }
178
- catch {
191
+ catch (error) {
192
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT')
193
+ throw error;
179
194
  return null;
180
195
  }
181
196
  }
182
197
  export async function discoverPortFile(dir, expectedPid, options = {}) {
183
198
  let names;
184
199
  try {
200
+ if (windowsPrivateFiles)
201
+ await verifyPrivate(dir, 'directory');
185
202
  names = await readdir(dir);
186
203
  }
187
- catch {
204
+ catch (error) {
205
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT')
206
+ throw error;
188
207
  return null;
189
208
  }
190
209
  const live = [];
@@ -192,7 +211,7 @@ export async function discoverPortFile(dir, expectedPid, options = {}) {
192
211
  if (!name.startsWith('port-') || !name.endsWith('.json'))
193
212
  continue;
194
213
  try {
195
- const parsed = JSON.parse(await readFile(join(dir, name), 'utf8'));
214
+ const parsed = JSON.parse(await readPrivateText(join(dir, name)));
196
215
  if (isUsablePortFileEntry(parsed, name)) {
197
216
  if (pidAlive(parsed.pid))
198
217
  live.push(parsed);
@@ -200,7 +219,10 @@ export async function discoverPortFile(dir, expectedPid, options = {}) {
200
219
  await unlink(join(dir, name)).catch(() => { });
201
220
  }
202
221
  }
203
- catch { }
222
+ catch (error) {
223
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT')
224
+ throw error;
225
+ }
204
226
  }
205
227
  if (live.length === 0)
206
228
  return null;
@@ -1,6 +1,7 @@
1
- import { chmod, mkdir, readFile } from "node:fs/promises";
1
+ import { chmod, mkdir } from "node:fs/promises";
2
2
  import { dirname } from "node:path";
3
3
  import { LockContentionError, LockOwnershipError, WRITER_LOCK_CONSTANTS, withLock, writeJsonAtomic, } from "./ec971142548df90e-index.js";
4
+ import { ensurePrivateDirectory, PrivateFileError, readPrivateText, windowsPrivateFiles, } from "./375d9cca2def037d-private-files.js";
4
5
  /** Binds generic persistence to a caller's path and normalization policy. */
5
6
  export function createSidebarFile(options) {
6
7
  const { path, defaultValue, normalize } = options;
@@ -17,7 +18,9 @@ export function createSidebarFile(options) {
17
18
  };
18
19
  const readRaw = async () => {
19
20
  try {
20
- return await readFile(path, 'utf8');
21
+ if (windowsPrivateFiles)
22
+ await ensurePrivateDirectory(dirname(path), options.secureDir ?? true);
23
+ return await readPrivateText(path, windowsPrivateFiles);
21
24
  }
22
25
  catch (error) {
23
26
  if (error.code === 'ENOENT')
@@ -29,7 +32,9 @@ export function createSidebarFile(options) {
29
32
  try {
30
33
  return parse(await readRaw());
31
34
  }
32
- catch {
35
+ catch (error) {
36
+ if (error instanceof PrivateFileError)
37
+ throw error;
33
38
  return defaultValue;
34
39
  }
35
40
  };
@@ -109,11 +114,15 @@ export function createSidebarFile(options) {
109
114
  const hooks = writeOptions;
110
115
  const parent = dirname(path);
111
116
  const secureDir = options.secureDir ?? true;
112
- await mkdir(parent, { recursive: true, mode: 0o700 });
113
- if (secureDir) {
114
- await chmod(parent, 0o700).catch((error) => {
115
- options.logger?.warn('sidebar directory permission remediation failed', { error: error instanceof Error ? error.message : String(error) });
116
- });
117
+ if (windowsPrivateFiles)
118
+ await ensurePrivateDirectory(parent, secureDir);
119
+ else {
120
+ await mkdir(parent, { recursive: true, mode: 0o700 });
121
+ if (secureDir) {
122
+ await chmod(parent, 0o700).catch((error) => {
123
+ options.logger?.warn('sidebar directory permission remediation failed', { error: error instanceof Error ? error.message : String(error) });
124
+ });
125
+ }
117
126
  }
118
127
  const committed = await withLock(path, lockOptions, async (lock) => {
119
128
  const commit = async (value) => ({
@@ -60,6 +60,9 @@ export function openPoolStore(options) {
60
60
  now: options.now ?? Date.now,
61
61
  ...(options.onLockEvent ? { onLockEvent: options.onLockEvent } : {}),
62
62
  ...(options.onLockStep ? { onLockStep: options.onLockStep } : {}),
63
+ ...(options.onRenewalTimer
64
+ ? { onRenewalTimer: options.onRenewalTimer }
65
+ : {}),
63
66
  },
64
67
  removedIds: memory.removedIds,
65
68
  requireCredentialStamps: options.requireCredentialStamps === true,
@@ -420,7 +420,8 @@ function parseEntry(raw, codec) {
420
420
  return undefined;
421
421
  if ('disabledReason' in raw && typeof raw.disabledReason !== 'string')
422
422
  return undefined;
423
- if ('quota' in raw && !codec.validate(raw.quota))
423
+ const quota = 'quota' in raw && codec.decode ? codec.decode(raw.quota) : raw.quota;
424
+ if ('quota' in raw && !codec.validate(quota))
424
425
  return undefined;
425
426
  if ('staged' in raw && !parseReservation(raw.staged))
426
427
  return undefined;
@@ -430,7 +431,7 @@ function parseEntry(raw, codec) {
430
431
  ...(typeof raw.disabledReason === 'string'
431
432
  ? { disabledReason: raw.disabledReason }
432
433
  : {}),
433
- ...('quota' in raw ? { quota: raw.quota } : {}),
434
+ ...('quota' in raw ? { quota } : {}),
434
435
  };
435
436
  }
436
437
  function credentialFor(raw, stateEntry) {
@@ -1,5 +1,5 @@
1
1
  export { quotaCodec } from "./053cc17b5419261e-codec.js";
2
- export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from "./0332701351b3eeec-format.js";
3
- export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, emptyQuotaMap, isQuotaMap, } from "./905bffc0220f43d0-map.js";
2
+ export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, quotaWindowParts, } from "./0332701351b3eeec-format.js";
3
+ export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, decodeQuotaMap, emptyQuotaMap, isQuotaMap, } from "./905bffc0220f43d0-map.js";
4
4
  export { isQuotaObservation, mergeQuotaObservation, QuotaCodecError, } from "./4f36d333d081d040-merge.js";
5
5
  export { budgetExhaustedResetAt, futureResetAt, projectQuota, readsExhausted, } from "./39c3cb05738fcf6d-projection.js";
@@ -1,4 +1,7 @@
1
1
  import { appendFileSync, chmodSync, existsSync, renameSync, statSync, } from "node:fs";
2
+ import { open } from "node:fs/promises";
3
+ import { dirname, resolve } from "node:path";
4
+ import { createPrivateBytes, ensurePrivateDirectory, privateOperation, replaceWindowsFile, verifyPrivate, windowsPrivateFiles, } from "./375d9cca2def037d-private-files.js";
2
5
  import { createRedactor } from "./d319517e3ea6ad70-redact.js";
3
6
  const ORDER = {
4
7
  error: 0,
@@ -36,6 +39,75 @@ function rotateIfNeeded(f) {
36
39
  /* never throw */
37
40
  }
38
41
  }
42
+ async function closeWindowsFile(sink) {
43
+ const { file, handle } = sink;
44
+ sink.file = undefined;
45
+ sink.handle = undefined;
46
+ if (file && handle)
47
+ await privateOperation(file, 'log-close', () => handle.close());
48
+ }
49
+ async function openWindowsFile(sink, file) {
50
+ await ensurePrivateDirectory(dirname(file));
51
+ try {
52
+ await verifyPrivate(file, 'file', true);
53
+ }
54
+ catch (error) {
55
+ if (error.code !== 'ENOENT')
56
+ throw error;
57
+ try {
58
+ await createPrivateBytes(file, '');
59
+ }
60
+ catch (creationError) {
61
+ if (creationError.code !== 'EEXIST')
62
+ throw creationError;
63
+ await verifyPrivate(file, 'file', true);
64
+ }
65
+ }
66
+ // The safe-parent policy denies other ordinary users the ability to create, replace or link entries between verification and fs.open.
67
+ // This protects against other ordinary users, not the owner or administrators, whose ability to change that namespace is outside our threat model.
68
+ sink.handle = await privateOperation(file, 'log-open', () => open(file, 'a'));
69
+ sink.file = file;
70
+ return sink.handle;
71
+ }
72
+ async function flushWindowsFile(sink, file, text) {
73
+ file = resolve(file);
74
+ try {
75
+ if (sink.file !== file)
76
+ await closeWindowsFile(sink);
77
+ let handle = sink.handle ?? (await openWindowsFile(sink, file));
78
+ const info = await privateOperation(file, 'log-stat', () => handle.stat());
79
+ if (info.size >= MAX_BYTES) {
80
+ await closeWindowsFile(sink);
81
+ for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
82
+ const source = i === 0 ? file : `${file}.${i}`;
83
+ const target = `${file}.${i + 1}`;
84
+ try {
85
+ await verifyPrivate(source, 'file', true);
86
+ }
87
+ catch (error) {
88
+ if (error.code === 'ENOENT')
89
+ continue;
90
+ throw error;
91
+ }
92
+ try {
93
+ await verifyPrivate(target, 'file', true);
94
+ }
95
+ catch (error) {
96
+ if (error.code !== 'ENOENT')
97
+ throw error;
98
+ }
99
+ await replaceWindowsFile(source, target);
100
+ await verifyPrivate(target, 'file');
101
+ }
102
+ handle = await openWindowsFile(sink, file);
103
+ }
104
+ await privateOperation(file, 'log-append', () => handle.appendFile(text, 'utf8'));
105
+ }
106
+ catch (error) {
107
+ await closeWindowsFile(sink).catch(() => { });
108
+ throw error;
109
+ }
110
+ }
39
111
  function safeSerialize(data) {
40
112
  try {
41
113
  return ` ${JSON.stringify(data)}`;
@@ -63,7 +135,19 @@ function createEngine(options) {
63
135
  let captureSink;
64
136
  let buffer = [];
65
137
  let timer;
138
+ let orderedSink = Promise.resolve();
139
+ let sinkError;
140
+ const windowsFile = {};
141
+ function queueWindows(operation) {
142
+ const next = orderedSink.then(operation);
143
+ orderedSink = next.catch((error) => {
144
+ sinkError = error;
145
+ });
146
+ return next;
147
+ }
66
148
  function configure(next) {
149
+ if (windowsPrivateFiles && next.file !== logFileSource)
150
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => { });
67
151
  logFileSource = next.file;
68
152
  initLevelSource = next.level;
69
153
  redactor = createRedactor(next);
@@ -89,25 +173,49 @@ function createEngine(options) {
89
173
  return floor;
90
174
  return 'info';
91
175
  }
92
- function flushLogs() {
176
+ function flushLogs(close = true) {
93
177
  if (timer) {
94
178
  clearTimeout(timer);
95
179
  timer = undefined;
96
180
  }
97
- if (!buffer.length)
181
+ if (!buffer.length) {
182
+ if (windowsPrivateFiles)
183
+ return queueWindows(async () => {
184
+ if (close)
185
+ await closeWindowsFile(windowsFile);
186
+ if (sinkError)
187
+ throw sinkError;
188
+ });
98
189
  return;
190
+ }
99
191
  let file;
100
192
  try {
101
193
  file = logFilePath();
102
194
  }
103
195
  catch {
104
196
  buffer = [];
197
+ if (windowsPrivateFiles && close)
198
+ return queueWindows(() => closeWindowsFile(windowsFile));
105
199
  return;
106
200
  }
107
201
  const text = buffer.join('');
108
202
  buffer = [];
109
- if (!file)
203
+ if (!file) {
204
+ if (windowsPrivateFiles && close)
205
+ return queueWindows(() => closeWindowsFile(windowsFile));
110
206
  return;
207
+ }
208
+ if (windowsPrivateFiles) {
209
+ return queueWindows(async () => {
210
+ try {
211
+ await flushWindowsFile(windowsFile, file, text);
212
+ }
213
+ finally {
214
+ if (close)
215
+ await closeWindowsFile(windowsFile);
216
+ }
217
+ });
218
+ }
111
219
  try {
112
220
  rotateIfNeeded(file);
113
221
  if (existsSync(file))
@@ -122,7 +230,9 @@ function createEngine(options) {
122
230
  if (!timer)
123
231
  timer = setTimeout(() => {
124
232
  timer = undefined;
125
- flushLogs();
233
+ const flushed = flushLogs(false);
234
+ if (flushed instanceof Promise)
235
+ void flushed.catch(() => { });
126
236
  }, 500);
127
237
  }
128
238
  function emit(channel, level, message, data) {
@@ -157,8 +267,11 @@ function createEngine(options) {
157
267
  if (logFileSource === undefined)
158
268
  return;
159
269
  buffer.push(line);
160
- if (buffer.length >= 50)
161
- flushLogs();
270
+ if (buffer.length >= 50) {
271
+ const flushed = flushLogs(false);
272
+ if (flushed instanceof Promise)
273
+ void flushed.catch(() => { });
274
+ }
162
275
  else
163
276
  schedule();
164
277
  }
@@ -176,6 +289,9 @@ function createEngine(options) {
176
289
  };
177
290
  }
178
291
  function reset() {
292
+ if (windowsPrivateFiles)
293
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => { });
294
+ sinkError = undefined;
179
295
  buffer = [];
180
296
  if (timer) {
181
297
  clearTimeout(timer);
@@ -222,18 +338,17 @@ export function setLogLevel(l) {
222
338
  defaultEngine.setLogLevel(l);
223
339
  }
224
340
  /**
225
- * Write whatever the default logger has buffered. Safe to call synchronously
226
- * from a process-exit handler, which is how each host drains the buffer on
227
- * shutdown.
341
+ * Write whatever the default logger has buffered. On Windows await the
342
+ * promise before shutdown; POSIX keeps synchronous process-exit flushing.
228
343
  */
229
344
  export function flushLogs() {
230
- defaultEngine.flushLogs();
345
+ return defaultEngine.flushLogs();
231
346
  }
232
347
  export function createLogger(channel) {
233
348
  return defaultEngine.createLogger(channel);
234
349
  }
235
350
  export async function flushForTest() {
236
- defaultEngine.flushLogs();
351
+ return defaultEngine.flushLogs();
237
352
  }
238
353
  /**
239
354
  * Return the default logger to its uninitialised state. Only a test needs