@oxidezap/baileyrs 0.3.9 → 0.3.11

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 (68) hide show
  1. package/README.md +29 -0
  2. package/lib/Bridge/schema.js +57 -16
  3. package/lib/Bridge/types.d.ts +26 -5
  4. package/lib/Compatibility/auth-state.js +2 -11
  5. package/lib/Compatibility/group-metadata.js +2 -2
  6. package/lib/Compatibility/host-auth-state.js +2 -0
  7. package/lib/Compatibility/internal/auth-state.js +6 -0
  8. package/lib/Compatibility/internal/host-auth-state.js +3 -0
  9. package/lib/Compatibility/legacy-store/adapter.js +137 -3
  10. package/lib/Compatibility/legacy-store/codecs/basic.js +5 -8
  11. package/lib/Compatibility/legacy-store/multi-file.d.ts +12 -1
  12. package/lib/Compatibility/legacy-store/multi-file.js +37 -25
  13. package/lib/Compatibility/legacy-store/record-files.d.ts +3 -0
  14. package/lib/Compatibility/legacy-store/record-files.js +5 -0
  15. package/lib/Compatibility/legacy-store/rollback.d.ts +8 -0
  16. package/lib/Compatibility/legacy-store/rollback.js +16 -0
  17. package/lib/Compatibility/legacy-store/snapshot.d.ts +7 -0
  18. package/lib/Compatibility/legacy-store/snapshot.js +53 -0
  19. package/lib/Compatibility/legacy-store/types.d.ts +4 -1
  20. package/lib/Compatibility/newsletter-results.d.ts +2 -3
  21. package/lib/Compatibility/newsletter-results.js +3 -3
  22. package/lib/Compatibility/reachout.d.ts +17 -0
  23. package/lib/Compatibility/reachout.js +47 -0
  24. package/lib/Socket/chat-actions.js +1 -1
  25. package/lib/Socket/communities.js +10 -5
  26. package/lib/Socket/core.js +10 -3
  27. package/lib/Socket/events-core.js +19 -10
  28. package/lib/Socket/groups.js +10 -5
  29. package/lib/Socket/index.d.ts +3 -717
  30. package/lib/Socket/newsletter.d.ts +3 -3
  31. package/lib/Socket/newsletter.js +5 -5
  32. package/lib/Socket/reachout.d.ts +1 -21
  33. package/lib/Socket/reachout.js +1 -49
  34. package/lib/Types/Auth.d.ts +5 -0
  35. package/lib/Types/Events.d.ts +6 -1
  36. package/lib/Utils/atomic-store.d.ts +20 -0
  37. package/lib/Utils/atomic-store.js +116 -0
  38. package/lib/Utils/durable-directory.d.ts +3 -0
  39. package/lib/Utils/durable-directory.js +35 -0
  40. package/lib/Utils/flush-deadline.d.ts +19 -0
  41. package/lib/Utils/flush-deadline.js +97 -0
  42. package/lib/Utils/index.d.ts +1 -0
  43. package/lib/Utils/index.js +1 -0
  44. package/lib/Utils/native-auth-rollback.d.ts +14 -0
  45. package/lib/Utils/native-auth-rollback.js +17 -0
  46. package/lib/Utils/process-file-lock.d.ts +6 -0
  47. package/lib/Utils/process-file-lock.js +38 -0
  48. package/lib/Utils/snapshot-rollback-proof.d.ts +9 -0
  49. package/lib/Utils/snapshot-rollback-proof.js +43 -0
  50. package/lib/Utils/snapshot-rollback.d.ts +5 -0
  51. package/lib/Utils/snapshot-rollback.js +69 -0
  52. package/lib/Utils/snapshot-transactions.d.ts +10 -0
  53. package/lib/Utils/snapshot-transactions.js +108 -0
  54. package/lib/Utils/store-migration.d.ts +10 -0
  55. package/lib/Utils/store-migration.js +16 -0
  56. package/lib/Utils/transactional-file-store.d.ts +7 -0
  57. package/lib/Utils/transactional-file-store.js +157 -0
  58. package/lib/Utils/use-bridge-store.d.ts +3 -49
  59. package/lib/Utils/use-bridge-store.js +121 -109
  60. package/lib/Utils/use-memory-store.js +17 -4
  61. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -1
  62. package/lib/Utils/use-multi-file-auth-state.js +2 -2
  63. package/lib/Utils/wrap-legacy-store.d.ts +1 -0
  64. package/lib/Utils/wrap-legacy-store.js +1 -0
  65. package/lib/host-types.d.ts +1 -15
  66. package/lib/node-surface.d.ts +2 -1
  67. package/lib/node-surface.js +2 -1
  68. package/package.json +10 -8
@@ -34,9 +34,9 @@ export declare const makeNewsletterMethods: (ctx: SocketContext) => {
34
34
  newsletterSubscribe: (jid: string) => Promise<NewsletterMetadataResult>;
35
35
  newsletterUnsubscribe: (jid: string) => Promise<void>;
36
36
  /**
37
- * The follower-activity mute, which is the one a subscriber toggles. The
38
- * core's other newsletter mute is for admin activity and is a different
39
- * control, so the ambiguous alias is avoided here.
37
+ * Channel updates are admin activity. The Web client's
38
+ * WAWebNewsletterUpdateUserSettingJob writes MUTE_ADMIN_ACTIVITY to
39
+ * the chat mute state; follower activity is a separate admin setting.
40
40
  */
41
41
  newsletterMute: (jid: string) => Promise<void>;
42
42
  newsletterUnmute: (jid: string) => Promise<void>;
@@ -77,15 +77,15 @@ export const makeNewsletterMethods = (ctx) => {
77
77
  await ctx.withClient(client => client.newsletterUnsubscribe(jid));
78
78
  },
79
79
  /**
80
- * The follower-activity mute, which is the one a subscriber toggles. The
81
- * core's other newsletter mute is for admin activity and is a different
82
- * control, so the ambiguous alias is avoided here.
80
+ * Channel updates are admin activity. The Web client's
81
+ * WAWebNewsletterUpdateUserSettingJob writes MUTE_ADMIN_ACTIVITY to
82
+ * the chat mute state; follower activity is a separate admin setting.
83
83
  */
84
84
  newsletterMute: async (jid) => {
85
- await ctx.withClient(client => client.newsletterFollowerMute(jid, true));
85
+ await ctx.withClient(client => client.newsletterAdminMute(jid, true));
86
86
  },
87
87
  newsletterUnmute: async (jid) => {
88
- await ctx.withClient(client => client.newsletterFollowerMute(jid, false));
88
+ await ctx.withClient(client => client.newsletterAdminMute(jid, false));
89
89
  },
90
90
  newsletterSubscribers: async (jid) => {
91
91
  const metadata = await ctx.withClient(client => client.newsletterMetadata(jid));
@@ -1,22 +1,2 @@
1
- /**
2
- * Reachout-timelock mapping: server payload → public `ReachoutTimelockState`.
3
- * Shared between the push-notification path (`Event::MexNotification` with
4
- * op_name `NotificationUserReachoutTimelockUpdate`) and the on-demand
5
- * `fetchReachoutTimelock()` IQ. Both deliver the same field shape.
6
- */
7
- import { type ReachoutTimelockState } from '../Types/Reachout.js';
8
- /** Wire shape from `xwa2_fetch_account_reachout_timelock`. */
9
- export interface ReachoutTimelockWire {
10
- is_active?: boolean;
11
- /** Unix seconds as string. `"0"` or absent → cooldown not set. */
12
- time_enforcement_ends?: string;
13
- enforcement_type?: string;
14
- }
15
- /** Locate the timelock object inside an arbitrary payload — the bridge
16
- * hands us either the raw `xwa2_…` body (from `fetchReachoutTimelock`)
17
- * or a wrapping MEX response (from the push notification). */
18
- export declare function extractReachoutPayload(value: unknown): ReachoutTimelockWire | null;
19
- /** Map wire payload → public state. Returns `null` when the payload is
20
- * empty or unparseable so callers can skip the emit. */
21
- export declare function mapReachoutTimelock(value: unknown): ReachoutTimelockState | null;
1
+ export { extractReachoutPayload, mapReachoutTimelock, type ReachoutTimelockWire } from '../Compatibility/reachout.js';
22
2
  //# sourceMappingURL=reachout.d.ts.map
@@ -1,50 +1,2 @@
1
- /**
2
- * Reachout-timelock mapping: server payload → public `ReachoutTimelockState`.
3
- * Shared between the push-notification path (`Event::MexNotification` with
4
- * op_name `NotificationUserReachoutTimelockUpdate`) and the on-demand
5
- * `fetchReachoutTimelock()` IQ. Both deliver the same field shape.
6
- */
7
- import {} from '../Types/Reachout.js';
8
- /** Locate the timelock object inside an arbitrary payload — the bridge
9
- * hands us either the raw `xwa2_…` body (from `fetchReachoutTimelock`)
10
- * or a wrapping MEX response (from the push notification). */
11
- export function extractReachoutPayload(value) {
12
- if (!value || typeof value !== 'object')
13
- return null;
14
- const v = value;
15
- const nested = v['xwa2_fetch_account_reachout_timelock'];
16
- if (nested && typeof nested === 'object')
17
- return nested;
18
- const data = v['data'];
19
- if (data && typeof data === 'object') {
20
- const inner = data['xwa2_fetch_account_reachout_timelock'];
21
- if (inner && typeof inner === 'object')
22
- return inner;
23
- }
24
- // Caller already extracted — treat the value itself as the payload.
25
- if ('is_active' in v || 'time_enforcement_ends' in v || 'enforcement_type' in v) {
26
- return v;
27
- }
28
- return null;
29
- }
30
- /** Map wire payload → public state. Returns `null` when the payload is
31
- * empty or unparseable so callers can skip the emit. */
32
- export function mapReachoutTimelock(value) {
33
- const wire = extractReachoutPayload(value);
34
- if (!wire)
35
- return null;
36
- const state = {
37
- isActive: !!wire.is_active
38
- };
39
- if (wire.time_enforcement_ends && wire.time_enforcement_ends !== '0') {
40
- const seconds = parseInt(wire.time_enforcement_ends, 10);
41
- if (Number.isFinite(seconds) && seconds > 0) {
42
- state.timeEnforcementEnds = new Date(seconds * 1000);
43
- }
44
- }
45
- if (wire.enforcement_type) {
46
- state.enforcementType = wire.enforcement_type;
47
- }
48
- return state;
49
- }
1
+ export { extractReachoutPayload, mapReachoutTimelock } from '../Compatibility/reachout.js';
50
2
  //# sourceMappingURL=reachout.js.map
@@ -1,3 +1,4 @@
1
+ import type { LegacyKeysStore } from '../Compatibility/legacy-store/types.js';
1
2
  import type Long from 'long';
2
3
  import type { Buffer } from 'node:buffer';
3
4
  import type { JsStoreCallbacks } from '@oxidezap/whatsapp-rust-bridge';
@@ -108,6 +109,10 @@ export type SignalDataSet = {
108
109
  type Awaitable<T> = T | Promise<T>;
109
110
  /** @deprecated Signal keys are managed by the Rust bridge. */
110
111
  export type SignalKeyStore = {
112
+ /** Backend transaction, isolated against every writer in the device scope.
113
+ * Must commit all mutations durably or none, including native mirror rows.
114
+ * The upstream adapter-local transaction helper does not meet this contract. */
115
+ bridgeTransaction?<T>(work: (keys: LegacyKeysStore) => Promise<T>): Promise<T>;
111
116
  get<T extends keyof SignalDataTypeMap>(type: T, ids: string[]): Awaitable<{
112
117
  [id: string]: SignalDataTypeMap[T];
113
118
  }>;
@@ -1,3 +1,4 @@
1
+ import type { CanonicalLabelSublist } from '../Bridge/types.js';
1
2
  import type { proto } from '../WAProto/runtime.js';
2
3
  import type { Boom } from '../Utils/boom.js';
3
4
  import type { AuthenticationCreds, LIDMapping } from './Auth.js';
@@ -127,10 +128,14 @@ export type BaileysEventMap = {
127
128
  };
128
129
  /** Receive an update on a call, including when the call was received, rejected, accepted */
129
130
  call: WACallEvent[];
130
- 'labels.edit': Label;
131
+ 'labels.sublist': Omit<CanonicalLabelSublist, 'type'>;
132
+ 'labels.edit': Label & {
133
+ actionTimestamp?: string;
134
+ };
131
135
  'labels.association': {
132
136
  association: LabelAssociation;
133
137
  type: 'add' | 'remove';
138
+ actionTimestamp?: string;
134
139
  };
135
140
  /**
136
141
  * A batched app-state sync left collections unsynced. Not an upstream event:
@@ -0,0 +1,20 @@
1
+ import type { JsStoreCallbacks } from '@oxidezap/whatsapp-rust-bridge';
2
+ export type AtomicStoreCallbacks = Pick<JsStoreCallbacks, 'commitPatch' | 'touchTcTokenSenderTimestamp' | 'storeReceivedTcToken'>;
3
+ export type OrdinaryStoreCallbacks = Omit<JsStoreCallbacks, keyof AtomicStoreCallbacks> & {
4
+ flush?(): Promise<void>;
5
+ };
6
+ export type AtomicRows = Map<string, Uint8Array>;
7
+ export declare const rowKey: (store: string, key: string) => string;
8
+ export declare const signedTimestamp: (value: string) => bigint;
9
+ export type TokenRow = {
10
+ token: number[];
11
+ token_timestamp: bigint;
12
+ sender_timestamp: bigint | null;
13
+ };
14
+ export declare const decodeTokenRow: (bytes: Uint8Array) => TokenRow;
15
+ export declare const encodeTokenRow: (row: TokenRow) => Uint8Array;
16
+ /** The caller supplies a real transaction covering all reads and writes. */
17
+ export declare const atomicCallbacks: (transaction: (change: (rows: AtomicRows) => void) => Promise<void>) => AtomicStoreCallbacks;
18
+ /** Validate migration requirements before hydration or other storage I/O. */
19
+ export declare function assertStoreCallbacks(store: unknown): asserts store is JsStoreCallbacks;
20
+ //# sourceMappingURL=atomic-store.d.ts.map
@@ -0,0 +1,116 @@
1
+ export const rowKey = (store, key) => JSON.stringify([store, key]);
2
+ const encode = (value) => new TextEncoder().encode(JSON.stringify(value));
3
+ const decode = (value) => JSON.parse(new TextDecoder().decode(value));
4
+ export const signedTimestamp = (value) => {
5
+ if (!/^-?(0|[1-9]\d*)$/.test(value))
6
+ throw new TypeError('timestamp must be a signed i64 decimal string');
7
+ const result = BigInt(value);
8
+ if (result < -(1n << 63n) || result >= 1n << 63n)
9
+ throw new RangeError('timestamp is outside i64');
10
+ return result;
11
+ };
12
+ // Quote numeric tokens before parsing. String tokens are matched first, so their
13
+ // contents cannot be rewritten. This works on every supported Node version,
14
+ // without JSON.parse reviver context or rounding i64 through a JS number.
15
+ export const decodeTokenRow = (bytes) => {
16
+ const text = new TextDecoder().decode(bytes);
17
+ const original = JSON.parse(text);
18
+ if (!original ||
19
+ typeof original !== 'object' ||
20
+ !Array.isArray(original.token) ||
21
+ original.token.some((n) => typeof n !== 'number' || !Number.isInteger(n) || n < 0 || n > 255) ||
22
+ typeof original.token_timestamp !== 'number' ||
23
+ (original.sender_timestamp != null && typeof original.sender_timestamp !== 'number')) {
24
+ throw new TypeError('invalid TC token row');
25
+ }
26
+ const row = JSON.parse(text.replace(/"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, token => token.startsWith('"') ? token : JSON.stringify(token)));
27
+ if (!row ||
28
+ !Array.isArray(row.token) ||
29
+ row.token.some((n) => typeof n !== 'string' || !/^\d+$/.test(n) || Number(n) > 255)) {
30
+ throw new TypeError('invalid TC token row');
31
+ }
32
+ return {
33
+ token: row.token.map(Number),
34
+ token_timestamp: signedTimestamp(row.token_timestamp),
35
+ sender_timestamp: row.sender_timestamp == null ? null : signedTimestamp(row.sender_timestamp)
36
+ };
37
+ };
38
+ export const encodeTokenRow = (row) => new TextEncoder().encode(`{"token":${JSON.stringify(row.token)},"token_timestamp":${row.token_timestamp},"sender_timestamp":${row.sender_timestamp ?? 'null'}}`);
39
+ const readIndex = (rows, key) => {
40
+ const bytes = rows.get(rowKey('meta', key));
41
+ const value = bytes ? decode(bytes) : [];
42
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string'))
43
+ throw new TypeError(`invalid ${key} index`);
44
+ return new Set(value);
45
+ };
46
+ /** The caller supplies a real transaction covering all reads and writes. */
47
+ export const atomicCallbacks = (transaction) => ({
48
+ commitPatch(name, state, removed, added, maintainIndex) {
49
+ const snapshot = Uint8Array.from(state);
50
+ const additions = added.map(([key, bytes]) => [key, Uint8Array.from(bytes)]);
51
+ const removals = [...removed];
52
+ return transaction(rows => {
53
+ for (const key of removals)
54
+ rows.delete(rowKey('mutation_mac', key));
55
+ for (const [key, bytes] of additions)
56
+ rows.set(rowKey('mutation_mac', key), bytes);
57
+ rows.set(rowKey('sync_version', name), snapshot);
58
+ if (maintainIndex) {
59
+ const index = readIndex(rows, 'mutation_mac_keys');
60
+ for (const key of removals)
61
+ index.delete(key);
62
+ for (const [key] of additions)
63
+ index.add(key);
64
+ rows.set(rowKey('meta', 'mutation_mac_keys'), encode([...index]));
65
+ }
66
+ });
67
+ },
68
+ touchTcTokenSenderTimestamp(jid, timestamp) {
69
+ const incoming = signedTimestamp(timestamp);
70
+ return transaction(rows => {
71
+ const key = rowKey('tc_token', jid);
72
+ const bytes = rows.get(key);
73
+ const row = bytes ? decodeTokenRow(bytes) : { token: [], token_timestamp: incoming, sender_timestamp: null };
74
+ if (row.sender_timestamp === null || incoming > row.sender_timestamp)
75
+ row.sender_timestamp = incoming;
76
+ rows.set(key, encodeTokenRow(row));
77
+ const index = readIndex(rows, 'tc_token_jids');
78
+ index.add(jid);
79
+ rows.set(rowKey('meta', 'tc_token_jids'), encode([...index]));
80
+ });
81
+ },
82
+ storeReceivedTcToken(jid, token, timestamp) {
83
+ const incoming = signedTimestamp(timestamp);
84
+ const snapshot = [...token];
85
+ return transaction(rows => {
86
+ const key = rowKey('tc_token', jid);
87
+ const bytes = rows.get(key);
88
+ const row = bytes ? decodeTokenRow(bytes) : { token: [], token_timestamp: incoming, sender_timestamp: null };
89
+ if (row.token.length === 0 || incoming >= row.token_timestamp) {
90
+ row.token = snapshot;
91
+ row.token_timestamp = incoming;
92
+ }
93
+ rows.set(key, encodeTokenRow(row));
94
+ const index = readIndex(rows, 'tc_token_jids');
95
+ index.add(jid);
96
+ rows.set(rowKey('meta', 'tc_token_jids'), encode([...index]));
97
+ });
98
+ }
99
+ });
100
+ /** Validate migration requirements before hydration or other storage I/O. */
101
+ export function assertStoreCallbacks(store) {
102
+ if (!store || typeof store !== 'object')
103
+ throw new TypeError('auth store must implement the bridge storage contract');
104
+ for (const method of [
105
+ 'get',
106
+ 'set',
107
+ 'delete',
108
+ 'commitPatch',
109
+ 'touchTcTokenSenderTimestamp',
110
+ 'storeReceivedTcToken'
111
+ ]) {
112
+ if (typeof store[method] !== 'function')
113
+ throw new TypeError(`auth store requires ${method}; migrate to the six-callback atomic bridge storage contract or use useMemoryStore()`);
114
+ }
115
+ }
116
+ //# sourceMappingURL=atomic-store.js.map
@@ -0,0 +1,3 @@
1
+ export declare const isUnsupportedDirSync: (e: unknown, platform?: NodeJS.Platform) => boolean;
2
+ export declare const defaultSyncDir: (dir: string) => Promise<void>;
3
+ //# sourceMappingURL=durable-directory.d.ts.map
@@ -0,0 +1,35 @@
1
+ import { open } from 'node:fs/promises';
2
+ const errnoOf = (e) => e?.code;
3
+ export const isUnsupportedDirSync = (e, platform = process.platform) => {
4
+ const code = errnoOf(e);
5
+ if (code === 'ENOSYS' || code === 'ENOTSUP')
6
+ return true;
7
+ if (platform === 'win32' && (code === 'EINVAL' || code === 'EPERM' || code === 'EISDIR'))
8
+ return true;
9
+ return false;
10
+ };
11
+ export const defaultSyncDir = async (dir) => {
12
+ let handle;
13
+ try {
14
+ handle = await open(dir, 'r');
15
+ }
16
+ catch (e) {
17
+ // A store folder that cannot even be opened is not a platform
18
+ // quirk, except where the platform cannot open directory handles
19
+ // at all (classified above).
20
+ if (!isUnsupportedDirSync(e))
21
+ throw e;
22
+ return;
23
+ }
24
+ try {
25
+ await handle.sync();
26
+ }
27
+ catch (e) {
28
+ if (!isUnsupportedDirSync(e))
29
+ throw e;
30
+ }
31
+ finally {
32
+ await handle.close().catch(() => { });
33
+ }
34
+ };
35
+ //# sourceMappingURL=durable-directory.js.map
@@ -0,0 +1,19 @@
1
+ /** A timeout reports an incomplete barrier. It never cancels a backend
2
+ * transaction, clears its ownership, or certifies its pending writes.
3
+ */
4
+ export declare class StoreFlushTimeoutError extends Error {
5
+ readonly code = "ERR_STORE_FLUSH_TIMEOUT";
6
+ constructor(label: string);
7
+ }
8
+ type FlushFailures = Map<Promise<unknown>, unknown>;
9
+ /** Keep the original backend operations visible through a drain wrapper. */
10
+ export declare const trackFlushFailures: <T>(operation: Promise<T>, errors: FlushFailures) => Promise<T>;
11
+ /** Carry child failure identities through a public batch or sequential wrapper. */
12
+ export declare const withTrackedFailures: <T>(work: (observe: <R>(operation: Promise<R>) => Promise<R>) => Promise<T>) => Promise<T>;
13
+ export declare const recordFlushFailure: (errors: FlushFailures, operation: Promise<unknown>, error: unknown) => void;
14
+ export declare const flushDeadlineError: (label: string, errors: FlushFailures) => Error;
15
+ export declare function settleBeforeFlushDeadline(operations: Iterable<Promise<unknown>>, deadline: number, label: string, errors: FlushFailures): Promise<void>;
16
+ /** Preserve individual failures and keep their messages visible to callers. */
17
+ export declare const settledFlushError: (label: string, errors: Iterable<unknown>) => unknown;
18
+ export {};
19
+ //# sourceMappingURL=flush-deadline.d.ts.map
@@ -0,0 +1,97 @@
1
+ /** A timeout reports an incomplete barrier. It never cancels a backend
2
+ * transaction, clears its ownership, or certifies its pending writes.
3
+ */
4
+ export class StoreFlushTimeoutError extends Error {
5
+ constructor(label) {
6
+ super(`${label} did not quiesce within 30s; backend operations remain pending`);
7
+ this.code = 'ERR_STORE_FLUSH_TIMEOUT';
8
+ this.name = 'StoreFlushTimeoutError';
9
+ }
10
+ }
11
+ const origins = new WeakMap();
12
+ /** Keep the original backend operations visible through a drain wrapper. */
13
+ export const trackFlushFailures = (operation, errors) => {
14
+ origins.set(operation, errors);
15
+ return operation;
16
+ };
17
+ /** Carry child failure identities through a public batch or sequential wrapper. */
18
+ export const withTrackedFailures = (work) => {
19
+ const errors = new Map();
20
+ const observe = (operation) => operation.catch(error => {
21
+ recordFlushFailure(errors, operation, error);
22
+ throw error;
23
+ });
24
+ let operation;
25
+ try {
26
+ operation = work(observe);
27
+ }
28
+ catch (error) {
29
+ operation = Promise.reject(error);
30
+ }
31
+ return trackFlushFailures(operation, errors);
32
+ };
33
+ export const recordFlushFailure = (errors, operation, error) => {
34
+ const underlying = origins.get(operation);
35
+ if (underlying?.size) {
36
+ for (const [source, reason] of underlying)
37
+ errors.set(source, reason);
38
+ }
39
+ else
40
+ errors.set(operation, error);
41
+ };
42
+ export const flushDeadlineError = (label, errors) => {
43
+ const timeout = new StoreFlushTimeoutError(label);
44
+ const previous = [...errors.values()];
45
+ // The deadline is its own failed barrier, distinct from backend callbacks.
46
+ errors.set(Promise.resolve(), timeout);
47
+ return previous.length ? new AggregateError([...previous, timeout], timeout.message, { cause: timeout }) : timeout;
48
+ };
49
+ export async function settleBeforeFlushDeadline(operations, deadline, label, errors) {
50
+ // Capture each rejection when it settles. Waiting for allSettled first
51
+ // loses known backend failures if another operation exceeds the deadline.
52
+ const admitted = [...operations];
53
+ const observed = admitted.map(operation => operation.catch(error => {
54
+ recordFlushFailure(errors, operation, error);
55
+ throw error;
56
+ }));
57
+ let timer;
58
+ try {
59
+ await Promise.race([
60
+ Promise.allSettled(observed),
61
+ new Promise((_resolve, reject) => {
62
+ timer = setTimeout(() => {
63
+ // A backing drain may still be pending after some of its writes
64
+ // failed. Include those known failures without inventing a second
65
+ // identity for its wrapper or waiting for the stalled sibling.
66
+ for (const operation of admitted) {
67
+ const underlying = origins.get(operation);
68
+ if (underlying)
69
+ for (const [source, reason] of underlying)
70
+ errors.set(source, reason);
71
+ }
72
+ reject(flushDeadlineError(label, errors));
73
+ }, Math.max(0, deadline - Date.now()));
74
+ })
75
+ ]);
76
+ }
77
+ finally {
78
+ if (timer !== undefined)
79
+ clearTimeout(timer);
80
+ }
81
+ }
82
+ /** Preserve individual failures and keep their messages visible to callers. */
83
+ export const settledFlushError = (label, errors) => {
84
+ const failures = [...errors];
85
+ if (failures.length === 1)
86
+ return failures[0];
87
+ const messages = failures.map(error => {
88
+ try {
89
+ return String(error);
90
+ }
91
+ catch {
92
+ return '<unprintable backend rejection>';
93
+ }
94
+ });
95
+ return new AggregateError(failures, `${label}: ${messages.join('; ')}`);
96
+ };
97
+ //# sourceMappingURL=flush-deadline.js.map
@@ -18,4 +18,5 @@ export * from './companion-reg-client-utils.js';
18
18
  export * from './use-bridge-store.js';
19
19
  export * from './use-memory-store.js';
20
20
  export * from './wrap-legacy-store.js';
21
+ export { prepareNativeAuthRollback } from './native-auth-rollback.js';
21
22
  //# sourceMappingURL=index.d.ts.map
@@ -20,4 +20,5 @@ export * from './companion-reg-client-utils.js';
20
20
  export * from './use-bridge-store.js';
21
21
  export * from './use-memory-store.js';
22
22
  export * from './wrap-legacy-store.js';
23
+ export { prepareNativeAuthRollback } from './native-auth-rollback.js';
23
24
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,14 @@
1
+ export declare const nativeAtomicNamespaces: ReadonlySet<string>;
2
+ export declare const isNativeAtomicRecordFile: (name: string) => boolean;
3
+ /** Stop every auth writer and back up the entire directory, including hidden
4
+ * completion records and archives, first. On success the
5
+ * latest atomic rows are durable in the old per-key binary layout, removed
6
+ * records are deleted and the snapshot is archived. Do not open an older
7
+ * adapter after a rejection; finish this offline export successfully first.
8
+ * Missing state requires a valid completion proof. A never-migrated directory
9
+ * needs no export, but this function cannot certify that from missing files.
10
+ */
11
+ export declare function prepareNativeAuthRollback(folder: string, options: {
12
+ offline: true;
13
+ }): Promise<void>;
14
+ //# sourceMappingURL=native-auth-rollback.d.ts.map
@@ -0,0 +1,17 @@
1
+ import { exportAuthSnapshot } from './snapshot-rollback.js';
2
+ export const nativeAtomicNamespaces = new Set(['sync_version', 'mutation_mac', 'tc_token', 'meta']);
3
+ export const isNativeAtomicRecordFile = (name) => name.endsWith('.bin') && nativeAtomicNamespaces.has(name.slice(0, name.indexOf('-')));
4
+ /** Stop every auth writer and back up the entire directory, including hidden
5
+ * completion records and archives, first. On success the
6
+ * latest atomic rows are durable in the old per-key binary layout, removed
7
+ * records are deleted and the snapshot is archived. Do not open an older
8
+ * adapter after a rejection; finish this offline export successfully first.
9
+ * Missing state requires a valid completion proof. A never-migrated directory
10
+ * needs no export, but this function cannot certify that from missing files.
11
+ */
12
+ export async function prepareNativeAuthRollback(folder, options) {
13
+ if (options?.offline !== true)
14
+ throw new TypeError('native rollback requires { offline: true } after stopping every auth writer');
15
+ await exportAuthSnapshot(folder, 'bridge-atomic-v1.json', nativeAtomicNamespaces, (namespace, id) => `${namespace}-${encodeURIComponent(id)}.bin`, isNativeAtomicRecordFile);
16
+ }
17
+ //# sourceMappingURL=native-auth-rollback.js.map
@@ -0,0 +1,6 @@
1
+ /** The kernel owns this lock and releases it on close/process exit. Keep the
2
+ * lock file's inode stable: never unlink it while another adapter may exist.
3
+ * Native code is loaded only for file-backed auth, outside the host entrypoint.
4
+ */
5
+ export declare const withProcessFileLock: <T>(folder: string, name: string, work: () => Promise<T>) => Promise<T>;
6
+ //# sourceMappingURL=process-file-lock.d.ts.map
@@ -0,0 +1,38 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ /** The kernel owns this lock and releases it on close/process exit. Keep the
4
+ * lock file's inode stable: never unlink it while another adapter may exist.
5
+ * Native code is loaded only for file-backed auth, outside the host entrypoint.
6
+ */
7
+ export const withProcessFileLock = async (folder, name, work) => {
8
+ const { tryLock } = await import('fs-native-extensions');
9
+ const path = join(folder, name);
10
+ const handle = await open(path, 'a+', 0o600);
11
+ let outcome;
12
+ try {
13
+ const deadline = Date.now() + 10000;
14
+ while (!tryLock(handle.fd)) {
15
+ if (Date.now() >= deadline)
16
+ throw new Error(`snapshot lock timed out: ${path}`);
17
+ await new Promise(resolve => setTimeout(resolve, 10));
18
+ }
19
+ outcome = { ok: true, value: await work() };
20
+ }
21
+ catch (error) {
22
+ outcome = { ok: false, error };
23
+ }
24
+ try {
25
+ await handle.close();
26
+ }
27
+ catch (error) {
28
+ if (!outcome.ok)
29
+ throw new AggregateError([outcome.error, error], 'snapshot transaction and lock close failed', {
30
+ cause: error
31
+ });
32
+ throw error;
33
+ }
34
+ if (!outcome.ok)
35
+ throw outcome.error;
36
+ return outcome.value;
37
+ };
38
+ //# sourceMappingURL=process-file-lock.js.map
@@ -0,0 +1,9 @@
1
+ export declare const rollbackProofName: (snapshotName: string) => string;
2
+ export declare const snapshotDigest: (bytes: Uint8Array) => string;
3
+ /** A new snapshot generation must never reuse proof from an older rollback. */
4
+ export declare function clearRollbackProof(folder: string, snapshotName: string, syncDir: (path: string) => Promise<void>): Promise<void>;
5
+ /** Missing active state is not success unless this exact archived generation
6
+ * has a durable completion record. Never infer success from an older archive.
7
+ */
8
+ export declare function verifyRollbackProof(folder: string, snapshotName: string): Promise<void>;
9
+ //# sourceMappingURL=snapshot-rollback-proof.d.ts.map
@@ -0,0 +1,43 @@
1
+ import { readFile, unlink } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ export const rollbackProofName = (snapshotName) => `.${snapshotName}.rollback-proof.json`;
5
+ export const snapshotDigest = (bytes) => createHash('sha256').update(bytes).digest('hex');
6
+ /** A new snapshot generation must never reuse proof from an older rollback. */
7
+ export async function clearRollbackProof(folder, snapshotName, syncDir) {
8
+ try {
9
+ await unlink(join(folder, rollbackProofName(snapshotName)));
10
+ }
11
+ catch (error) {
12
+ if (error?.code === 'ENOENT')
13
+ return;
14
+ throw error;
15
+ }
16
+ await syncDir(folder);
17
+ }
18
+ /** Missing active state is not success unless this exact archived generation
19
+ * has a durable completion record. Never infer success from an older archive.
20
+ */
21
+ export async function verifyRollbackProof(folder, snapshotName) {
22
+ try {
23
+ const proof = JSON.parse(await readFile(join(folder, rollbackProofName(snapshotName)), 'utf8'));
24
+ if (!proof ||
25
+ typeof proof !== 'object' ||
26
+ !('version' in proof) ||
27
+ proof.version !== 1 ||
28
+ !('archive' in proof) ||
29
+ typeof proof.archive !== 'string' ||
30
+ /[\\/\0]/.test(proof.archive) ||
31
+ !proof.archive.startsWith(`${snapshotName}.rollback-`) ||
32
+ !('sha256' in proof) ||
33
+ typeof proof.sha256 !== 'string' ||
34
+ !/^[a-f0-9]{64}$/.test(proof.sha256))
35
+ throw new Error('invalid rollback proof');
36
+ if (snapshotDigest(await readFile(join(folder, proof.archive))) !== proof.sha256)
37
+ throw new Error('rollback archive does not match its proof');
38
+ }
39
+ catch (error) {
40
+ throw new Error('cannot verify rollback: authoritative snapshot or valid completion proof is missing; a never-migrated directory needs no export, otherwise restore its backup', { cause: error });
41
+ }
42
+ }
43
+ //# sourceMappingURL=snapshot-rollback-proof.js.map
@@ -0,0 +1,5 @@
1
+ /** Caller has stopped every writer. Keep the snapshot authoritative until all
2
+ * exported records and deletions are durable, then archive it for recovery.
3
+ */
4
+ export declare function exportAuthSnapshot(folder: string, snapshotName: string, namespaces: ReadonlySet<string>, recordFile: (namespace: string, id: string) => string | undefined, isRecordFile: (name: string) => boolean, syncDir?: (folder: string) => Promise<void>): Promise<void>;
5
+ //# sourceMappingURL=snapshot-rollback.d.ts.map