@jini-ai/desktop-host 0.7.3-next.1 → 0.7.3-next.3

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 (118) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +217 -1
  3. package/dist/electron/electron-shell.js +5 -7
  4. package/dist/electron/handoff/index.d.ts +54 -0
  5. package/dist/electron/handoff/index.js +32 -0
  6. package/dist/electron/memory-sampler.d.ts +28 -0
  7. package/dist/electron/memory-sampler.js +41 -0
  8. package/dist/electron/partitions/cache-maintenance.d.ts +280 -0
  9. package/dist/electron/partitions/cache-maintenance.js +239 -0
  10. package/dist/electron/partitions/claim-sources.d.ts +54 -0
  11. package/dist/electron/partitions/claim-sources.js +36 -0
  12. package/dist/electron/partitions/holder-registry.d.ts +116 -0
  13. package/dist/electron/partitions/holder-registry.js +130 -0
  14. package/dist/electron/partitions/index.d.ts +10 -0
  15. package/dist/electron/partitions/index.js +10 -0
  16. package/dist/electron/partitions/maintenance-marker.d.ts +61 -0
  17. package/dist/electron/partitions/maintenance-marker.js +85 -0
  18. package/dist/electron/partitions/partition-inventory.d.ts +23 -0
  19. package/dist/electron/partitions/partition-inventory.js +19 -0
  20. package/dist/electron/partitions/partition-pass.d.ts +114 -0
  21. package/dist/electron/partitions/partition-pass.js +414 -0
  22. package/dist/electron/partitions/partition-root.d.ts +42 -0
  23. package/dist/electron/partitions/partition-root.js +52 -0
  24. package/dist/electron/partitions/profile-interlock.d.ts +141 -0
  25. package/dist/electron/partitions/profile-interlock.js +273 -0
  26. package/dist/electron/partitions/retirement-ledger.d.ts +116 -0
  27. package/dist/electron/partitions/retirement-ledger.js +149 -0
  28. package/dist/electron/preferences/index.d.ts +5 -0
  29. package/dist/electron/preferences/index.js +5 -0
  30. package/dist/electron/preferences/ipc.d.ts +35 -0
  31. package/dist/electron/preferences/ipc.js +21 -0
  32. package/dist/electron/preferences/menu.d.ts +103 -0
  33. package/dist/electron/preferences/menu.js +67 -0
  34. package/dist/electron/preferences/preference-file.d.ts +63 -0
  35. package/dist/electron/preferences/preference-file.js +51 -0
  36. package/dist/electron/preferences/values.d.ts +25 -0
  37. package/dist/electron/preferences/values.js +18 -0
  38. package/dist/electron/preload/index.d.ts +3 -0
  39. package/dist/electron/preload/index.js +2 -0
  40. package/dist/electron/preload/ipc-subscribe.d.ts +34 -0
  41. package/dist/electron/preload/ipc-subscribe.js +18 -0
  42. package/dist/electron/selftest/index.d.ts +3 -0
  43. package/dist/electron/selftest/index.js +3 -0
  44. package/dist/electron/selftest/selftest-tracker.d.ts +82 -0
  45. package/dist/electron/selftest/selftest-tracker.js +67 -0
  46. package/dist/electron/session-bootstrap/exchange.d.ts +50 -0
  47. package/dist/electron/session-bootstrap/exchange.js +41 -0
  48. package/dist/electron/session-bootstrap/header-arming.d.ts +18 -0
  49. package/dist/electron/session-bootstrap/header-arming.js +13 -0
  50. package/dist/electron/session-bootstrap/index.d.ts +11 -0
  51. package/dist/electron/session-bootstrap/index.js +10 -0
  52. package/dist/electron/session-bootstrap/partition.d.ts +17 -0
  53. package/dist/electron/session-bootstrap/partition.js +24 -0
  54. package/dist/electron/session-bootstrap/probe.d.ts +40 -0
  55. package/dist/electron/session-bootstrap/probe.js +29 -0
  56. package/dist/electron/session-bootstrap/types.d.ts +62 -0
  57. package/dist/electron/session-bootstrap/types.js +7 -0
  58. package/dist/electron/updates/desktop-updater.d.ts +90 -0
  59. package/dist/electron/updates/desktop-updater.js +124 -0
  60. package/dist/electron/updates/index.d.ts +4 -0
  61. package/dist/electron/updates/index.js +4 -0
  62. package/dist/electron/updates/instance-presence-strict.d.ts +27 -0
  63. package/dist/electron/updates/instance-presence-strict.js +46 -0
  64. package/dist/electron/updates/native-notices.d.ts +89 -0
  65. package/dist/electron/updates/native-notices.js +41 -0
  66. package/dist/electron/updates/update-check-now.d.ts +117 -0
  67. package/dist/electron/updates/update-check-now.js +88 -0
  68. package/dist/electron/usability/find-in-page-ipc.d.ts +3 -6
  69. package/dist/electron/usability/window-bounds-store.js +14 -12
  70. package/dist/electron/usability/zoom-menu.d.ts +1 -1
  71. package/dist/electron/webview/index.d.ts +2 -0
  72. package/dist/electron/webview/index.js +2 -0
  73. package/dist/electron/webview/webview-types.d.ts +66 -0
  74. package/dist/electron/webview/webview-types.js +12 -0
  75. package/dist/electron/windows/app-window.d.ts +83 -0
  76. package/dist/electron/windows/app-window.js +62 -0
  77. package/dist/electron/windows/dock-icon.d.ts +34 -0
  78. package/dist/electron/windows/dock-icon.js +32 -0
  79. package/dist/electron/windows/index.d.ts +3 -0
  80. package/dist/electron/windows/index.js +3 -0
  81. package/dist/logging.js +3 -1
  82. package/dist/node-toolchain/boot-setup.d.ts +63 -0
  83. package/dist/node-toolchain/boot-setup.js +59 -0
  84. package/dist/node-toolchain/index.d.ts +2 -0
  85. package/dist/node-toolchain/index.js +1 -0
  86. package/dist/shell/auto-update-controller.d.ts +34 -0
  87. package/dist/shell/auto-update-controller.js +27 -0
  88. package/dist/shell/copied-site-databases.d.ts +71 -0
  89. package/dist/shell/copied-site-databases.js +60 -0
  90. package/dist/shell/find-in-page-verify.d.ts +33 -0
  91. package/dist/shell/find-in-page-verify.js +30 -0
  92. package/dist/shell/find-menu.d.ts +33 -0
  93. package/dist/shell/find-menu.js +36 -0
  94. package/dist/shell/guest-navigation.d.ts +47 -0
  95. package/dist/shell/guest-navigation.js +58 -0
  96. package/dist/shell/instance-presence.d.ts +20 -0
  97. package/dist/shell/instance-presence.js +26 -0
  98. package/dist/shell/js-backslide-guard.d.ts +42 -0
  99. package/dist/shell/js-backslide-guard.js +44 -0
  100. package/dist/shell/node-toolchain.d.ts +34 -0
  101. package/dist/shell/node-toolchain.js +50 -0
  102. package/dist/shell/pty-helpers.d.ts +25 -0
  103. package/dist/shell/pty-helpers.js +50 -0
  104. package/dist/shell/site-presence.d.ts +32 -0
  105. package/dist/shell/site-presence.js +42 -0
  106. package/dist/shell/speech/mac-on-device-transcriber.d.ts +24 -0
  107. package/dist/shell/speech/mac-on-device-transcriber.js +81 -0
  108. package/dist/shell/speech/speech-ipc.d.ts +52 -0
  109. package/dist/shell/speech/speech-ipc.js +40 -0
  110. package/dist/shell/spellcheck-menu.d.ts +84 -0
  111. package/dist/shell/spellcheck-menu.js +63 -0
  112. package/dist/shell/supervised-site-url.d.ts +20 -0
  113. package/dist/shell/supervised-site-url.js +22 -0
  114. package/dist/speech/macos/mac-on-device-transcriber.d.ts +2 -1
  115. package/dist/speech/speech-bridge.d.ts +1 -8
  116. package/dist/speech/transcription-port.d.ts +1 -9
  117. package/dist/tauri/tauri-shell.js +8 -10
  118. package/package.json +154 -7
@@ -0,0 +1,273 @@
1
+ import path from 'node:path';
2
+ import { readClaimsStrict } from './claim-sources.js';
3
+ import { createHolderRegistry, readHoldersStrict } from './holder-registry.js';
4
+ import { resolvePartitionRoot } from './partition-root.js';
5
+ export class PartitionBusyError extends Error {
6
+ name = 'PartitionBusyError';
7
+ }
8
+ export class PartitionOpenRefusedError extends Error {
9
+ name = 'PartitionOpenRefusedError';
10
+ }
11
+ export class PartitionNotHeldError extends Error {
12
+ partition;
13
+ name = 'PartitionNotHeldError';
14
+ constructor(partition) {
15
+ super(`Partition ${partition} was used before it was acquired.`);
16
+ this.partition = partition;
17
+ }
18
+ }
19
+ const POLL_MS = 50;
20
+ const WRITER_TIMEOUT_MS = 2000;
21
+ const code = (error) => error?.code;
22
+ /** Electron names a persistent partition `persist:<dir>`; claims and files use the directory name. */
23
+ export const partitionDirName = ({ partition }, _optional = {}) => partition.replace(/^persist:/, '');
24
+ function parseTarget(text) {
25
+ try {
26
+ const t = JSON.parse(text);
27
+ const target = t.target === null || typeof t.target === 'string';
28
+ const valid = t.v === 1 && typeof t.lockToken === 'string' && target && typeof t.seq === 'number';
29
+ return valid ? { lockToken: t.lockToken, target: t.target, seq: t.seq } : null;
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ /**
36
+ * Reads the target fence for `name`. The writer publishes its target before it reads claims and the
37
+ * acquirer publishes its intent before it gets here, so a missing target, a cleared one, a free lock,
38
+ * or a lock token that no longer matches all mean the writer that will act next must still read the
39
+ * intent. Only a live or unknown owner of the matching token keeps the fence.
40
+ */
41
+ async function readFence(name, ctx) {
42
+ let text;
43
+ try {
44
+ text = await ctx.fs.readFile({ path: ctx.targetPath });
45
+ }
46
+ catch (error) {
47
+ return code(error) === 'ENOENT' ? { state: 'clear' } : { state: 'busy', seq: undefined };
48
+ }
49
+ const target = parseTarget(text);
50
+ if (!target)
51
+ return { state: 'busy', seq: undefined };
52
+ if (target.target !== '*' && target.target !== name)
53
+ return { state: 'clear' };
54
+ const owner = await ctx.lock.readToken({ lockPath: ctx.lockPath });
55
+ if (owner.state === 'free')
56
+ return { state: 'clear' };
57
+ if (owner.state === 'unknown')
58
+ return { state: 'busy', seq: target.seq };
59
+ const fenced = owner.token === target.lockToken && owner.owner !== 'dead';
60
+ return fenced ? { state: 'busy', seq: target.seq } : { state: 'clear' };
61
+ }
62
+ const describe = (error) => String(code(error) ?? error);
63
+ const refuse = (message, cause) => new PartitionOpenRefusedError(message, { cause });
64
+ async function publishIntent(ctx, name) {
65
+ ctx.registry.intents.add(name);
66
+ try {
67
+ await ctx.registry.publish();
68
+ }
69
+ catch (error) {
70
+ ctx.registry.intents.delete(name);
71
+ throw refuse(ctx.required.messages.unregistered({ directory: ctx.required.paths.interlockDir }), error);
72
+ }
73
+ }
74
+ async function withdrawIntent(ctx, name) {
75
+ ctx.registry.intents.delete(name);
76
+ try {
77
+ await ctx.registry.publish();
78
+ }
79
+ catch (error) {
80
+ ctx.required.log({ event: 'intent-withdraw-failed', partition: name, detail: describe(error) });
81
+ }
82
+ }
83
+ /**
84
+ * Live or unknown writers keep the fence until the wait cap, then the open is refused as busy.
85
+ * Quiet `seq` is diagnostic only (`abandonMs` logs): a writer suspended by system sleep or a
86
+ * debugger is quiet and alive, so quiet does not mean dead and never authorizes walking past it.
87
+ */
88
+ async function waitForFence(ctx, name) {
89
+ const { fs, lock, clock, scheduler, log, messages } = ctx.required;
90
+ const start = clock.mono();
91
+ const quiet = { seq: undefined, since: start, logged: false };
92
+ for (;;) {
93
+ const fence = await readFence(name, { fs, lock, targetPath: ctx.targetPath, lockPath: ctx.lockPath });
94
+ if (fence.state === 'clear')
95
+ return;
96
+ const now = clock.mono();
97
+ if (fence.seq !== quiet.seq)
98
+ Object.assign(quiet, { seq: fence.seq, since: now });
99
+ if (!quiet.logged && now - quiet.since >= ctx.abandonMs) {
100
+ quiet.logged = true;
101
+ log({ event: 'writer-quiet', partition: name, detail: `${now - quiet.since}ms` });
102
+ }
103
+ if (now - start >= ctx.waitCapMs)
104
+ throw new PartitionBusyError(messages.busy);
105
+ await scheduler.sleep({ ms: POLL_MS });
106
+ }
107
+ }
108
+ /** Step 2.5: maintenance only when no other live holder lists the partition; doubt skips maintenance, not the open. */
109
+ async function runOpenMaintenance(ctx, name, subjectDir) {
110
+ const holders = await ctx.readHolders();
111
+ if (holders.state === 'unknown') {
112
+ ctx.required.log({ event: 'maintenance-skipped', partition: name, detail: holders.reason });
113
+ return 'skipped-unknown-holders';
114
+ }
115
+ const other = holders.value.some(h => h.token !== ctx.registry.token && (h.intents.includes(name) || h.held.includes(name)));
116
+ if (other)
117
+ return 'skipped-other-holder';
118
+ try {
119
+ await ctx.required.openMaintenance({ partition: name, subjectDir });
120
+ return 'ran';
121
+ }
122
+ catch (error) {
123
+ ctx.required.log({ event: 'maintenance-failed', partition: name, detail: describe(error) });
124
+ return 'failed';
125
+ }
126
+ }
127
+ async function markHeld(ctx, name) {
128
+ ctx.registry.held.add(name);
129
+ ctx.registry.intents.delete(name);
130
+ // On failure the record still lists the intent, which protects the partition just as well.
131
+ try {
132
+ await ctx.registry.publish();
133
+ }
134
+ catch (error) {
135
+ ctx.required.log({ event: 'held-publish-failed', partition: name, detail: describe(error) });
136
+ }
137
+ }
138
+ /**
139
+ * The intent is persisted before the target is read (Dekker ordering over files): if the acquirer
140
+ * read first, a writer could publish its target and read claims in the gap, see no intent, and
141
+ * mutate the partition this process is about to open. Held is sticky and set before any session use.
142
+ */
143
+ async function acquireOnce(ctx, name, subjectDir) {
144
+ if (ctx.registry.held.has(name))
145
+ return { state: 'held', partition: name, maintenance: 'already-held' };
146
+ await publishIntent(ctx, name);
147
+ try {
148
+ try {
149
+ await ctx.required.invalidateRetirement({ partition: name, subjectDir, reason: 'reacquired' });
150
+ }
151
+ catch (error) {
152
+ throw refuse(ctx.required.messages.refused, error);
153
+ }
154
+ await waitForFence(ctx, name);
155
+ }
156
+ catch (error) {
157
+ await withdrawIntent(ctx, name);
158
+ throw error;
159
+ }
160
+ const maintenance = await runOpenMaintenance(ctx, name, subjectDir);
161
+ await markHeld(ctx, name);
162
+ return { state: 'held', partition: name, maintenance };
163
+ }
164
+ async function runFenced(ctx, held, run) {
165
+ const { fs, process, paths, claimSources, log } = ctx.required;
166
+ let seq = 0;
167
+ const setTarget = async ({ target }) => {
168
+ await held.assertHeld();
169
+ seq += 1;
170
+ const temp = `${ctx.targetPath}.${ctx.registry.token}.${held.token}.${seq}.tmp`;
171
+ await fs.writeFile({ path: temp, data: JSON.stringify({ v: 1, lockToken: held.token, target, seq }) });
172
+ await fs.rename({ oldPath: temp, newPath: ctx.targetPath });
173
+ };
174
+ await setTarget({ target: '*' });
175
+ try {
176
+ return await run({
177
+ assertHeld: () => held.assertHeld(),
178
+ setTarget,
179
+ readClaims: () => readClaimsStrict({ selfPid: process.pid, holders: ctx.readHolders, sources: claimSources }),
180
+ resolveRoot: () => resolvePartitionRoot({ sessionDataDir: paths.sessionDataDir, fs }),
181
+ });
182
+ }
183
+ finally {
184
+ try {
185
+ await setTarget({ target: null });
186
+ }
187
+ catch (error) {
188
+ log({ event: 'target-clear-failed', detail: describe(error) });
189
+ }
190
+ }
191
+ }
192
+ /**
193
+ * Exclusive mutation of the partition set. The lock must be the async one, held through every
194
+ * awaited rename: a sync JSON lock releases when its callback returns, i.e. at the first await.
195
+ */
196
+ async function withWriter(ctx, run) {
197
+ let entered = false;
198
+ try {
199
+ const value = await ctx.required.lock.withFileLock({ lockPath: ctx.lockPath, run: async (held) => { entered = true; return runFenced(ctx, held, run); } }, { staleMs: Number.POSITIVE_INFINITY, timeoutMs: WRITER_TIMEOUT_MS, createParent: true });
200
+ return { state: 'ran', value };
201
+ }
202
+ catch (error) {
203
+ if (entered)
204
+ throw error;
205
+ ctx.required.log({ event: 'writer-busy', detail: describe(error) });
206
+ return { state: 'skipped', reason: 'writer-busy' };
207
+ }
208
+ }
209
+ /** Startup, synchronous, before any window/guest/session. Never throws: failure blocks every open instead. */
210
+ function registerWith(ctx, heartbeatMs) {
211
+ if (ctx.registry.registered)
212
+ return { state: 'registered', heartbeat: null };
213
+ try {
214
+ ctx.registry.register();
215
+ }
216
+ catch (error) {
217
+ ctx.required.log({ event: 'register-failed', detail: describe(error) });
218
+ return { state: 'failed', reason: describe(error) };
219
+ }
220
+ const heartbeat = ctx.required.scheduler.every({ ms: heartbeatMs, run: () => {
221
+ ctx.registry.publish().catch(error => ctx.required.log({ event: 'heartbeat-failed', detail: describe(error) }));
222
+ } });
223
+ return { state: 'registered', heartbeat };
224
+ }
225
+ /** Serializes acquisitions per partition in this process so one intent/held transition runs at a time. */
226
+ function acquireSerialized(ctx, inflight, partition, subjectDir) {
227
+ const name = partitionDirName({ partition });
228
+ if (!ctx.registry.registered)
229
+ return Promise.reject(refuse(ctx.required.messages.unregistered({ directory: ctx.required.paths.interlockDir })));
230
+ if (!ctx.required.isManaged(name))
231
+ return Promise.reject(refuse(ctx.required.messages.refused));
232
+ const next = (inflight.get(name) ?? Promise.resolve()).catch(() => { }).then(() => acquireOnce(ctx, name, subjectDir));
233
+ inflight.set(name, next);
234
+ void next.finally(() => { if (inflight.get(name) === next)
235
+ inflight.delete(name); }).catch(() => { });
236
+ return next;
237
+ }
238
+ /** @complexity O(1) to construct; see each method. */
239
+ export function createPartitionInterlock(required, { heartbeatMs = 5000, waitCapMs = 30_000, abandonMs = 5000 } = {}) {
240
+ const { paths, fs, process, clock, scheduler } = required;
241
+ const registry = createHolderRegistry({ interlockDir: paths.interlockDir, fs, process, clock });
242
+ const readHolders = () => readHoldersStrict({ interlockDir: paths.interlockDir, fs, process, scheduler });
243
+ const ctx = {
244
+ required, registry, waitCapMs, abandonMs, readHolders,
245
+ targetPath: path.join(paths.interlockDir, 'target.json'), lockPath: path.join(paths.interlockDir, 'writer.lock'),
246
+ };
247
+ const inflight = new Map();
248
+ let heartbeat = null;
249
+ const isHeld = (partition) => registry.held.has(partitionDirName({ partition }));
250
+ return {
251
+ registerHolder: () => {
252
+ const result = registerWith(ctx, heartbeatMs);
253
+ if (result.state === 'failed')
254
+ return result;
255
+ heartbeat = result.heartbeat ?? heartbeat;
256
+ return { state: 'registered' };
257
+ },
258
+ unregisterHolder: () => { heartbeat?.cancel(); heartbeat = null; registry.unregister(); },
259
+ acquireSiteSession: ({ partition, subjectDir }, _optional = {}) => acquireSerialized(ctx, inflight, partition, subjectDir),
260
+ assertHeld: ({ partition }, _optional = {}) => {
261
+ if (required.isManaged(partitionDirName({ partition })) && !isHeld(partition))
262
+ throw new PartitionNotHeldError(partition);
263
+ },
264
+ siteSession: ({ partition }, _optional = {}) => {
265
+ if (!isHeld(partition))
266
+ throw new PartitionNotHeldError(partition);
267
+ return required.fromPartition({ partition });
268
+ },
269
+ withPartitionWriter: ({ run }, _optional = {}) => withWriter(ctx, run),
270
+ readHoldersStrict: readHolders,
271
+ };
272
+ }
273
+ //# sourceMappingURL=profile-interlock.js.map
@@ -0,0 +1,116 @@
1
+ import type { FileLockOptions, JsonFileRead, QuarantineNotice } from '@jini-ai/core/contracts/site/fs-durable-json';
2
+ /** Synchronous durable JSON (atomic replace, quarantine, token lock); `createDurableJsonFile` satisfies it. */
3
+ export interface RetirementLedgerStore {
4
+ read(required: Record<string, never>): JsonFileRead;
5
+ write(required: {
6
+ value: unknown;
7
+ }): void;
8
+ quarantine(required: {
9
+ notice: QuarantineNotice;
10
+ }): boolean;
11
+ withLock<T>(required: {
12
+ critical: () => T;
13
+ }, optional?: FileLockOptions): T;
14
+ }
15
+ export interface RetirementDirIdentity {
16
+ dev: number;
17
+ ino: number;
18
+ birthtimeMs: number;
19
+ }
20
+ /** Proof captured by the erase arm: identity before the erase, written only after the folder is gone. */
21
+ export interface ErasedRetirementCandidate {
22
+ basis: 'erased';
23
+ profile: string;
24
+ sessionRoot: string;
25
+ partition: string;
26
+ subjectId: string;
27
+ subjectDir: string;
28
+ dirIdentity: RetirementDirIdentity;
29
+ parentDir: string;
30
+ parentDev: number;
31
+ eraseVersion: string;
32
+ erasedAt: string;
33
+ }
34
+ /** Written by owner-confirmed manual removal; never actionable by an automatic pass. */
35
+ export interface OwnerRetirementCandidate {
36
+ basis: 'owner-dialog';
37
+ profile: string;
38
+ sessionRoot: string;
39
+ partition: string;
40
+ }
41
+ export type RetirementCandidate = ErasedRetirementCandidate | OwnerRetirementCandidate;
42
+ export type RetirementState = 'pending' | 'removed' | 'invalidated';
43
+ export type RetirementRecord = RetirementCandidate & {
44
+ id: string;
45
+ state: RetirementState;
46
+ attempts: number;
47
+ recordedAt: string;
48
+ lastReason?: string;
49
+ asideIdentity?: string;
50
+ closedAt?: string;
51
+ };
52
+ export type RetirementRead = {
53
+ state: 'ok';
54
+ records: RetirementRecord[];
55
+ } | {
56
+ state: 'unknown';
57
+ reason: string;
58
+ };
59
+ export type RetirementTransition = {
60
+ state: 'ok';
61
+ record: RetirementRecord;
62
+ } | {
63
+ state: 'conflict';
64
+ current: RetirementState | 'missing' | 'aside-mismatch';
65
+ } | {
66
+ state: 'illegal';
67
+ from: RetirementState;
68
+ to: RetirementState;
69
+ } | {
70
+ state: 'unknown';
71
+ reason: string;
72
+ };
73
+ export interface RetirementLedgerRequired {
74
+ profile: string;
75
+ durableJson: RetirementLedgerStore;
76
+ clock: {
77
+ now(): number;
78
+ };
79
+ id: () => string;
80
+ }
81
+ interface TransitionInput {
82
+ id: string;
83
+ from: RetirementState;
84
+ to: RetirementState;
85
+ reason?: string;
86
+ asideIdentity?: string;
87
+ }
88
+ /**
89
+ * Positive-proof ledger for whole-partition removal, bound to one profile. Every mutation runs under
90
+ * the store's synchronous lock and re-reads the file, so transitions are compare-and-set by record ID.
91
+ * @complexity O(records) per call.
92
+ */
93
+ export declare function createRetirementLedger(required: RetirementLedgerRequired, { terminalRetentionDays }?: {
94
+ terminalRetentionDays?: number;
95
+ }): {
96
+ profile: string;
97
+ append: (input: {
98
+ candidate: RetirementCandidate;
99
+ }, _optional?: Record<string, never>) => RetirementRecord;
100
+ invalidate: (input: {
101
+ partition: string;
102
+ reason: string;
103
+ }, _optional?: Record<string, never>) => {
104
+ invalidated: number;
105
+ };
106
+ transition: (input: TransitionInput, _optional?: Record<string, never>) => RetirementTransition;
107
+ readStrict: (_required?: Record<string, never>, _optional?: Record<string, never>) => RetirementRead;
108
+ pruneTerminal: (input: {
109
+ unresolvedAsideIds: readonly string[];
110
+ }, _optional?: Record<string, never>) => {
111
+ pruned: number;
112
+ };
113
+ };
114
+ export type RetirementLedger = ReturnType<typeof createRetirementLedger>;
115
+ export {};
116
+ //# sourceMappingURL=retirement-ledger.d.ts.map
@@ -0,0 +1,149 @@
1
+ /** Only `pending` moves; `removed` and `invalidated` are terminal ("kept" is pending with a reason). */
2
+ const LEGAL = {
3
+ pending: ['pending', 'removed', 'invalidated'], removed: [], invalidated: [],
4
+ };
5
+ const NOTICE = {
6
+ label: 'website sign-in removal list',
7
+ consequence: 'sign-ins of deleted websites will be kept and listed instead of removed automatically.',
8
+ };
9
+ const DAY_MS = 86_400_000;
10
+ const isStr = (v) => typeof v === 'string';
11
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
12
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
13
+ function isErasedShape(r) {
14
+ const id = r.dirIdentity;
15
+ const identity = isObj(id) && isNum(id.dev) && isNum(id.ino) && isNum(id.birthtimeMs);
16
+ return identity && [r.subjectId, r.subjectDir, r.parentDir, r.eraseVersion, r.erasedAt].every(isStr) && isNum(r.parentDev);
17
+ }
18
+ function isRecord(r) {
19
+ if (!isObj(r) || ![r.id, r.profile, r.sessionRoot, r.partition, r.recordedAt].every(isStr))
20
+ return false;
21
+ if (!(isStr(r.state) && r.state in LEGAL) || !Number.isSafeInteger(r.attempts))
22
+ return false;
23
+ const optional = [r.lastReason, r.asideIdentity, r.closedAt].every(v => v === undefined || isStr(v));
24
+ return optional && (r.basis === 'owner-dialog' || (r.basis === 'erased' && isErasedShape(r)));
25
+ }
26
+ /** A file bound to another profile, or any malformed record, is as untrustworthy as torn bytes. */
27
+ function parse(read, profile) {
28
+ if (read.state === 'missing')
29
+ return { state: 'ok', records: [] };
30
+ if (read.state === 'unreadable')
31
+ return { state: 'unknown', reason: 'ledger unreadable' };
32
+ const v = read.value;
33
+ if (!isObj(v) || v.v !== 1 || !Array.isArray(v.records))
34
+ return { state: 'unknown', reason: 'ledger malformed' };
35
+ if (v.profile !== profile)
36
+ return { state: 'unknown', reason: 'ledger belongs to another profile' };
37
+ if (!v.records.every(isRecord))
38
+ return { state: 'unknown', reason: 'ledger record malformed' };
39
+ return { state: 'ok', records: v.records };
40
+ }
41
+ const iso = (ctx) => new Date(ctx.clock.now()).toISOString();
42
+ const save = (ctx, records) => ctx.durableJson.write({ value: { v: 1, profile: ctx.profile, records } });
43
+ const close = (ctx, record, state, reason) => Object.assign(record, { state, closedAt: iso(ctx) }, reason === undefined ? {} : { lastReason: reason });
44
+ /** Append starts a fresh file over a damaged one only after the damaged bytes were moved aside. */
45
+ function recordsForAppend(ctx) {
46
+ const read = parse(ctx.durableJson.read({}), ctx.profile);
47
+ if (read.state === 'ok')
48
+ return read.records;
49
+ if (!ctx.durableJson.quarantine({ notice: NOTICE }))
50
+ throw new Error('The sign-in removal list is damaged and could not be moved aside; nothing was recorded.');
51
+ return [];
52
+ }
53
+ function append(ctx, { candidate }) {
54
+ if (candidate.profile !== ctx.profile)
55
+ throw new TypeError('Retirement candidate belongs to another profile.');
56
+ return ctx.durableJson.withLock({ critical: () => {
57
+ const records = recordsForAppend(ctx);
58
+ for (const old of records)
59
+ if (old.state === 'pending' && old.partition === candidate.partition)
60
+ close(ctx, old, 'invalidated', 'superseded');
61
+ const record = { ...candidate, id: ctx.id(), state: 'pending', attempts: 0, recordedAt: iso(ctx) };
62
+ save(ctx, [...records, record]);
63
+ return record;
64
+ } });
65
+ }
66
+ function invalidate(ctx, { partition, reason }) {
67
+ return ctx.durableJson.withLock({ critical: () => {
68
+ const read = parse(ctx.durableJson.read({}), ctx.profile);
69
+ // A damaged ledger already grants nothing, so there is nothing to invalidate; append quarantines it.
70
+ if (read.state === 'unknown')
71
+ return { invalidated: 0 };
72
+ const hits = read.records.filter(r => r.state === 'pending' && r.partition === partition);
73
+ hits.forEach(r => close(ctx, r, 'invalidated', reason));
74
+ if (hits.length > 0)
75
+ save(ctx, read.records);
76
+ return { invalidated: hits.length };
77
+ } });
78
+ }
79
+ function applyTransition(ctx, record, input) {
80
+ if (input.to === 'pending') {
81
+ record.attempts += 1;
82
+ if (input.reason !== undefined)
83
+ record.lastReason = input.reason;
84
+ if (input.asideIdentity !== undefined)
85
+ record.asideIdentity = input.asideIdentity;
86
+ return { state: 'ok', record };
87
+ }
88
+ // The commit names the exact aside folder recorded before the rename; any other folder is not proven.
89
+ if (input.to === 'removed' && (input.asideIdentity === undefined || record.asideIdentity !== input.asideIdentity)) {
90
+ return { state: 'conflict', current: 'aside-mismatch' };
91
+ }
92
+ close(ctx, record, input.to, input.reason);
93
+ return { state: 'ok', record };
94
+ }
95
+ function transition(ctx, input) {
96
+ if (!LEGAL[input.from].includes(input.to))
97
+ return { state: 'illegal', from: input.from, to: input.to };
98
+ return ctx.durableJson.withLock({ critical: () => {
99
+ const read = parse(ctx.durableJson.read({}), ctx.profile);
100
+ if (read.state === 'unknown')
101
+ return read;
102
+ const record = read.records.find(r => r.id === input.id);
103
+ if (!record)
104
+ return { state: 'conflict', current: 'missing' };
105
+ if (record.state !== input.from)
106
+ return { state: 'conflict', current: record.state };
107
+ const result = applyTransition(ctx, record, input);
108
+ if (result.state === 'ok')
109
+ save(ctx, read.records);
110
+ return result;
111
+ } });
112
+ }
113
+ /**
114
+ * A terminal record whose aside folder is still on disk cannot be pruned: a `removed` record is the
115
+ * only authority to delete that folder, and without it the next pass must treat the folder as
116
+ * unproven and restore it, bringing a deleted website's sign-ins back as an unowned partition.
117
+ */
118
+ function pruneTerminal(ctx, { unresolvedAsideIds }) {
119
+ const unresolved = new Set(unresolvedAsideIds);
120
+ const cutoff = ctx.clock.now() - ctx.retentionMs;
121
+ const expired = (r) => r.state !== 'pending' && r.closedAt !== undefined && Date.parse(r.closedAt) <= cutoff
122
+ && !(r.asideIdentity !== undefined && unresolved.has(r.asideIdentity));
123
+ return ctx.durableJson.withLock({ critical: () => {
124
+ const read = parse(ctx.durableJson.read({}), ctx.profile);
125
+ if (read.state === 'unknown')
126
+ return { pruned: 0 };
127
+ const kept = read.records.filter(r => !expired(r));
128
+ if (kept.length !== read.records.length)
129
+ save(ctx, kept);
130
+ return { pruned: read.records.length - kept.length };
131
+ } });
132
+ }
133
+ /**
134
+ * Positive-proof ledger for whole-partition removal, bound to one profile. Every mutation runs under
135
+ * the store's synchronous lock and re-reads the file, so transitions are compare-and-set by record ID.
136
+ * @complexity O(records) per call.
137
+ */
138
+ export function createRetirementLedger(required, { terminalRetentionDays = 90 } = {}) {
139
+ const ctx = { ...required, retentionMs: terminalRetentionDays * DAY_MS };
140
+ return {
141
+ profile: required.profile,
142
+ append: (input, _optional = {}) => append(ctx, input),
143
+ invalidate: (input, _optional = {}) => invalidate(ctx, input),
144
+ transition: (input, _optional = {}) => transition(ctx, input),
145
+ readStrict: (_required = {}, _optional = {}) => parse(required.durableJson.read({}), required.profile),
146
+ pruneTerminal: (input, _optional = {}) => pruneTerminal(ctx, input),
147
+ };
148
+ }
149
+ //# sourceMappingURL=retirement-ledger.js.map
@@ -0,0 +1,5 @@
1
+ export * from './preference-file.js';
2
+ export * from './values.js';
3
+ export * from './menu.js';
4
+ export * from './ipc.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ export * from './preference-file.js';
2
+ export * from './values.js';
3
+ export * from './menu.js';
4
+ export * from './ipc.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,35 @@
1
+ /** A trusted read/write IPC handler pair for one preference; the host owns channels and storage. */
2
+ /** The `ipcMain` slice the pair needs; `removeHandler` is optional for minimal fakes. */
3
+ export interface PreferenceIpcMain<Sender, T> {
4
+ handle: (channel: string, handler: (event: {
5
+ sender: Sender;
6
+ }, value?: unknown) => T) => void;
7
+ removeHandler?: (channel: string) => void;
8
+ }
9
+ /**
10
+ * Register read and write handlers that refuse untrusted senders before touching storage, and parse
11
+ * the written value before saving. `read`/`write` run only for an authorized (and, for writes,
12
+ * valid) request, so a host may resolve its storage lazily inside them.
13
+ * @returns Teardown that removes both handlers. O(1) registration.
14
+ */
15
+ export declare function registerPreferenceIpc<Sender, T>({ ipcMain, channels, allowed, untrustedError, parse, read, write }: {
16
+ ipcMain: PreferenceIpcMain<Sender, T>;
17
+ channels: {
18
+ read: string;
19
+ write: string;
20
+ };
21
+ allowed: (args: {
22
+ sender: Sender;
23
+ }) => boolean;
24
+ /** Error message thrown to a refused sender. */
25
+ untrustedError: string;
26
+ /** Answer the accepted value, or throw the host's own validation error. */
27
+ parse: (args: {
28
+ value: unknown;
29
+ }) => T;
30
+ read: () => T;
31
+ write: (args: {
32
+ value: T;
33
+ }) => T;
34
+ }, _optional?: {}): () => void;
35
+ //# sourceMappingURL=ipc.d.ts.map
@@ -0,0 +1,21 @@
1
+ /** A trusted read/write IPC handler pair for one preference; the host owns channels and storage. */
2
+ /**
3
+ * Register read and write handlers that refuse untrusted senders before touching storage, and parse
4
+ * the written value before saving. `read`/`write` run only for an authorized (and, for writes,
5
+ * valid) request, so a host may resolve its storage lazily inside them.
6
+ * @returns Teardown that removes both handlers. O(1) registration.
7
+ */
8
+ export function registerPreferenceIpc({ ipcMain, channels, allowed, untrustedError, parse, read, write }, _optional = {}) {
9
+ const trusted = ({ sender }) => { if (!allowed({ sender }))
10
+ throw new Error(untrustedError); };
11
+ ipcMain.handle(channels.read, ({ sender }) => { trusted({ sender }); return read(); });
12
+ ipcMain.handle(channels.write, ({ sender }, value) => {
13
+ trusted({ sender });
14
+ return write({ value: parse({ value }) });
15
+ });
16
+ return () => {
17
+ ipcMain.removeHandler?.(channels.read);
18
+ ipcMain.removeHandler?.(channels.write);
19
+ };
20
+ }
21
+ //# sourceMappingURL=ipc.js.map