@gregale/data 0.0.0-stage → 0.1.1
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.
- package/LICENSE +202 -0
- package/README.md +1031 -2
- package/dist/bulk.d.ts +61 -0
- package/dist/bulk.js +63 -0
- package/dist/client-fetch.d.ts +34 -0
- package/dist/client-fetch.js +62 -0
- package/dist/cursor-token.d.ts +53 -0
- package/dist/cursor-token.js +179 -0
- package/dist/cursor.d.ts +45 -0
- package/dist/cursor.js +78 -0
- package/dist/deadline.d.ts +19 -0
- package/dist/deadline.js +29 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +68 -0
- package/dist/exact-numeric.d.ts +15 -0
- package/dist/exact-numeric.js +125 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +39 -0
- package/dist/indexeddb-mutation-store.d.ts +12 -0
- package/dist/indexeddb-mutation-store.js +139 -0
- package/dist/json.d.ts +39 -0
- package/dist/json.js +39 -0
- package/dist/live/client.d.ts +192 -0
- package/dist/live/client.js +555 -0
- package/dist/live/index.d.ts +31 -0
- package/dist/live/index.js +28 -0
- package/dist/live/protocol.d.ts +125 -0
- package/dist/live/protocol.js +271 -0
- package/dist/live/react.d.ts +22 -0
- package/dist/live/react.js +59 -0
- package/dist/live/seal.d.ts +38 -0
- package/dist/live/seal.js +98 -0
- package/dist/live/sql.d.ts +11 -0
- package/dist/live/sql.js +58 -0
- package/dist/mutation-journal.d.ts +78 -0
- package/dist/mutation-journal.js +223 -0
- package/dist/numeric.d.ts +11 -0
- package/dist/numeric.js +40 -0
- package/dist/optimistic.d.ts +24 -0
- package/dist/optimistic.js +18 -0
- package/dist/reconcile.d.ts +28 -0
- package/dist/reconcile.js +28 -0
- package/dist/replay-key.d.ts +8 -0
- package/dist/replay-key.js +27 -0
- package/dist/response.d.ts +33 -0
- package/dist/response.js +29 -0
- package/dist/rpc.d.ts +20 -0
- package/dist/rpc.js +31 -0
- package/dist/storage-uploads.d.ts +63 -0
- package/dist/storage-uploads.js +104 -0
- package/dist/storage.d.ts +74 -0
- package/dist/storage.js +89 -0
- package/dist/validation.d.ts +26 -0
- package/dist/validation.js +40 -0
- package/dist/versioned-mutation.d.ts +28 -0
- package/dist/versioned-mutation.js +13 -0
- package/package.json +19 -4
package/dist/live/sql.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds a parameterised query: each interpolated value becomes $n and
|
|
3
|
+
* travels as PostgreSQL text, which the database parses as the parameter's
|
|
4
|
+
* type. Values never become SQL.
|
|
5
|
+
*
|
|
6
|
+
* sql`SELECT id, body FROM messages WHERE channel_id = ${id} ORDER BY id DESC LIMIT ${50}`
|
|
7
|
+
*/
|
|
8
|
+
export function sql(strings, ...values) {
|
|
9
|
+
let text = strings[0];
|
|
10
|
+
const params = [];
|
|
11
|
+
values.forEach((value, i) => {
|
|
12
|
+
params.push(toPostgresText(value));
|
|
13
|
+
text += `$${params.length}` + strings[i + 1];
|
|
14
|
+
});
|
|
15
|
+
return Object.freeze({ text, params: Object.freeze(params) });
|
|
16
|
+
}
|
|
17
|
+
/** PostgreSQL text form of a JavaScript value. */
|
|
18
|
+
export function toPostgresText(value) {
|
|
19
|
+
if (value === null || value === undefined)
|
|
20
|
+
return null;
|
|
21
|
+
switch (typeof value) {
|
|
22
|
+
case 'string':
|
|
23
|
+
return value;
|
|
24
|
+
case 'number':
|
|
25
|
+
if (!Number.isFinite(value))
|
|
26
|
+
throw new TypeError('live query parameters must be finite numbers');
|
|
27
|
+
return String(value);
|
|
28
|
+
case 'bigint':
|
|
29
|
+
return value.toString();
|
|
30
|
+
case 'boolean':
|
|
31
|
+
return value ? 'true' : 'false';
|
|
32
|
+
}
|
|
33
|
+
if (value instanceof Date) {
|
|
34
|
+
if (Number.isNaN(value.getTime()))
|
|
35
|
+
throw new TypeError('invalid Date parameter');
|
|
36
|
+
return value.toISOString();
|
|
37
|
+
}
|
|
38
|
+
if (value instanceof Uint8Array) {
|
|
39
|
+
return '\\x' + Array.from(value, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
40
|
+
}
|
|
41
|
+
if (Array.isArray(value))
|
|
42
|
+
return arrayLiteral(value);
|
|
43
|
+
if (typeof value === 'object')
|
|
44
|
+
return JSON.stringify(value);
|
|
45
|
+
throw new TypeError(`unsupported live query parameter of type ${typeof value}`);
|
|
46
|
+
}
|
|
47
|
+
// A PostgreSQL array literal; elements are quoted unless NULL.
|
|
48
|
+
function arrayLiteral(values) {
|
|
49
|
+
const items = values.map((v) => {
|
|
50
|
+
if (Array.isArray(v))
|
|
51
|
+
return arrayLiteral(v);
|
|
52
|
+
const text = toPostgresText(v);
|
|
53
|
+
if (text === null)
|
|
54
|
+
return 'NULL';
|
|
55
|
+
return '"' + text.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
|
|
56
|
+
});
|
|
57
|
+
return '{' + items.join(',') + '}';
|
|
58
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { JsonParser } from './validation.js';
|
|
2
|
+
import { type MutationReconciliation } from './reconcile.js';
|
|
3
|
+
export declare const MUTATION_JOURNAL_LIMITS: Readonly<{
|
|
4
|
+
maxRecords: 100;
|
|
5
|
+
maxBytes: 8388608;
|
|
6
|
+
maxEntryBytes: 1048576;
|
|
7
|
+
maxSlotBytes: 256;
|
|
8
|
+
maxDepth: 64;
|
|
9
|
+
}>;
|
|
10
|
+
export type MutationJournalErrorCode = 'storage_unavailable' | 'storage_full' | 'conflict' | 'invalid_record' | 'invalid_operation' | 'context_mismatch' | 'invalid_entry' | 'not_prepared' | 'not_confirmed';
|
|
11
|
+
export declare class MutationJournalError extends Error {
|
|
12
|
+
readonly code: MutationJournalErrorCode;
|
|
13
|
+
constructor(code: MutationJournalErrorCode);
|
|
14
|
+
}
|
|
15
|
+
export type MutationJournalContext = Readonly<{
|
|
16
|
+
apiURL: string;
|
|
17
|
+
schemaFingerprint: string | null;
|
|
18
|
+
subject: string;
|
|
19
|
+
tenant: string | null;
|
|
20
|
+
contract: string;
|
|
21
|
+
}>;
|
|
22
|
+
export type JournalOperation = MutationJournalContext & Readonly<{
|
|
23
|
+
key: string;
|
|
24
|
+
}>;
|
|
25
|
+
export type MutationJournalState = 'prepared' | 'uncertain' | 'confirmed';
|
|
26
|
+
export type MutationJournalEntry<Operation extends JournalOperation> = Readonly<{
|
|
27
|
+
slot: string;
|
|
28
|
+
revision: string;
|
|
29
|
+
state: MutationJournalState;
|
|
30
|
+
operation: Operation;
|
|
31
|
+
}>;
|
|
32
|
+
/** compareExchange must atomically compare exact bytes and commit across all
|
|
33
|
+
* users of this store before resolving true. A localStorage read/write pair
|
|
34
|
+
* does not satisfy this contract. get returns untrusted serialized data.
|
|
35
|
+
*/
|
|
36
|
+
export type MutationJournalStore = {
|
|
37
|
+
get(slot: string): Promise<unknown>;
|
|
38
|
+
compareExchange(slot: string, expected: string | null, next: string | null): Promise<boolean>;
|
|
39
|
+
};
|
|
40
|
+
export type JournalReconciliation<Operation extends JournalOperation, Row, Error> = {
|
|
41
|
+
result: MutationReconciliation<Row, Error>;
|
|
42
|
+
entry: MutationJournalEntry<Operation>;
|
|
43
|
+
persistence: 'unchanged' | 'saved' | 'conflict' | 'storage_failed';
|
|
44
|
+
};
|
|
45
|
+
type Response<Row, Error> = {
|
|
46
|
+
data: Row[] | null;
|
|
47
|
+
error: Error | null;
|
|
48
|
+
status: number;
|
|
49
|
+
};
|
|
50
|
+
export declare const journalByteLength: (value: string) => number;
|
|
51
|
+
export declare function journalSlot(slot: string): void;
|
|
52
|
+
/** Opt-in durable bookkeeping. Loading never sends requests. Only dispatch
|
|
53
|
+
* claims a prepared entry, and it commits uncertainty before calling send.
|
|
54
|
+
* Recovery callbacks must perform receipt reads. Nothing retries or expires
|
|
55
|
+
* an entry automatically; the database is authoritative about key expiry.
|
|
56
|
+
*/
|
|
57
|
+
export declare function createMutationJournal<Operation extends JournalOperation>(options: {
|
|
58
|
+
store: MutationJournalStore;
|
|
59
|
+
context: MutationJournalContext;
|
|
60
|
+
parser: JsonParser<Operation>;
|
|
61
|
+
}): {
|
|
62
|
+
prepare: (slot: string, operation: Operation) => Promise<MutationJournalEntry<Operation>>;
|
|
63
|
+
load: (slot: string) => Promise<MutationJournalEntry<Operation> | null>;
|
|
64
|
+
dispatch: <Result>(entry: MutationJournalEntry<Operation>, send: (operation: Operation) => PromiseLike<Result>) => Promise<{
|
|
65
|
+
entry: MutationJournalEntry<Operation>;
|
|
66
|
+
response: Awaited<Result>;
|
|
67
|
+
}>;
|
|
68
|
+
reconcile: {
|
|
69
|
+
<Row, Error, Matched extends Row>(entry: MutationJournalEntry<Operation>, response: Response<Row, Error>, matches: (row: Row) => row is Matched): Promise<JournalReconciliation<Operation, Matched, Error>>;
|
|
70
|
+
<Row, Error>(entry: MutationJournalEntry<Operation>, response: Response<Row, Error>, matches: (row: Row) => boolean): Promise<JournalReconciliation<Operation, Row, Error>>;
|
|
71
|
+
};
|
|
72
|
+
recover: {
|
|
73
|
+
<Row, Error, Matched extends Row>(entry: MutationJournalEntry<Operation>, lookup: (operation: Operation) => PromiseLike<Response<Row, Error>>, matches: (row: Row) => row is Matched): Promise<JournalReconciliation<Operation, Matched, Error>>;
|
|
74
|
+
<Row, Error>(entry: MutationJournalEntry<Operation>, lookup: (operation: Operation) => PromiseLike<Response<Row, Error>>, matches: (row: Row) => boolean): Promise<JournalReconciliation<Operation, Row, Error>>;
|
|
75
|
+
};
|
|
76
|
+
removeConfirmed: (entry: MutationJournalEntry<Operation>) => Promise<void>;
|
|
77
|
+
};
|
|
78
|
+
export {};
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { reconcileMutation } from './reconcile.js';
|
|
2
|
+
// Mirrored from pkg/api/limits.go, enforced by the contract parity test (ADR-1674).
|
|
3
|
+
export const MUTATION_JOURNAL_LIMITS = Object.freeze({ maxRecords: 100, maxBytes: 8388608, maxEntryBytes: 1048576, maxSlotBytes: 256, maxDepth: 64 });
|
|
4
|
+
export class MutationJournalError extends Error {
|
|
5
|
+
code;
|
|
6
|
+
constructor(code) {
|
|
7
|
+
super('Mutation journal: ' + code);
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.name = 'MutationJournalError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
const keyPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-7[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
|
|
13
|
+
const revisionPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
|
|
14
|
+
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
15
|
+
export const journalByteLength = (value) => new TextEncoder().encode(value).byteLength;
|
|
16
|
+
export function journalSlot(slot) {
|
|
17
|
+
if (typeof slot !== 'string' || !slot || slot.includes('\0') || journalByteLength(slot) > MUTATION_JOURNAL_LIMITS.maxSlotBytes)
|
|
18
|
+
throw new MutationJournalError('invalid_entry');
|
|
19
|
+
}
|
|
20
|
+
// Strict, bounded JSON serialization never invokes getters or toJSON. Sorting
|
|
21
|
+
// object keys makes restore validation independent of parser property order.
|
|
22
|
+
function canonicalJSON(value) {
|
|
23
|
+
const parts = [], ancestors = new Set();
|
|
24
|
+
let bytes = 0;
|
|
25
|
+
const append = (text) => {
|
|
26
|
+
bytes += journalByteLength(text);
|
|
27
|
+
if (bytes > MUTATION_JOURNAL_LIMITS.maxEntryBytes)
|
|
28
|
+
throw new Error();
|
|
29
|
+
parts.push(text);
|
|
30
|
+
};
|
|
31
|
+
const visit = (item, depth) => {
|
|
32
|
+
if (depth > MUTATION_JOURNAL_LIMITS.maxDepth)
|
|
33
|
+
throw new Error();
|
|
34
|
+
if (item === null || typeof item === 'boolean' || typeof item === 'string' || (typeof item === 'number' && Number.isFinite(item))) {
|
|
35
|
+
append(JSON.stringify(item));
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (typeof item !== 'object' || ancestors.has(item))
|
|
39
|
+
throw new Error();
|
|
40
|
+
const array = Array.isArray(item), proto = Object.getPrototypeOf(item);
|
|
41
|
+
if (array ? proto !== Array.prototype : proto !== Object.prototype && proto !== null)
|
|
42
|
+
throw new Error();
|
|
43
|
+
const keys = Reflect.ownKeys(item);
|
|
44
|
+
if (keys.some(key => typeof key !== 'string'))
|
|
45
|
+
throw new Error();
|
|
46
|
+
if (array && (item.length > MUTATION_JOURNAL_LIMITS.maxEntryBytes || keys.length !== item.length + 1))
|
|
47
|
+
throw new Error();
|
|
48
|
+
ancestors.add(item);
|
|
49
|
+
append(array ? '[' : '{');
|
|
50
|
+
const names = array ? Array.from({ length: item.length }, (_, index) => String(index)) : keys.sort();
|
|
51
|
+
names.forEach((name, index) => {
|
|
52
|
+
const field = Object.getOwnPropertyDescriptor(item, name);
|
|
53
|
+
if (!field || !('value' in field) || !field.enumerable)
|
|
54
|
+
throw new Error();
|
|
55
|
+
if (index)
|
|
56
|
+
append(',');
|
|
57
|
+
if (!array)
|
|
58
|
+
append(JSON.stringify(name) + ':');
|
|
59
|
+
visit(field.value, depth + 1);
|
|
60
|
+
});
|
|
61
|
+
append(array ? ']' : '}');
|
|
62
|
+
ancestors.delete(item);
|
|
63
|
+
};
|
|
64
|
+
visit(value, 0);
|
|
65
|
+
return parts.join('');
|
|
66
|
+
}
|
|
67
|
+
function freeze(value) {
|
|
68
|
+
if (value !== null && typeof value === 'object') {
|
|
69
|
+
Object.values(value).forEach(freeze);
|
|
70
|
+
Object.freeze(value);
|
|
71
|
+
}
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
function storageError(error) {
|
|
75
|
+
const allowed = ['storage_unavailable', 'storage_full', 'conflict', 'invalid_record'];
|
|
76
|
+
return new MutationJournalError(error instanceof MutationJournalError && allowed.includes(error.code) ? error.code : 'storage_unavailable');
|
|
77
|
+
}
|
|
78
|
+
/** Opt-in durable bookkeeping. Loading never sends requests. Only dispatch
|
|
79
|
+
* claims a prepared entry, and it commits uncertainty before calling send.
|
|
80
|
+
* Recovery callbacks must perform receipt reads. Nothing retries or expires
|
|
81
|
+
* an entry automatically; the database is authoritative about key expiry.
|
|
82
|
+
*/
|
|
83
|
+
export function createMutationJournal(options) {
|
|
84
|
+
let context;
|
|
85
|
+
try {
|
|
86
|
+
const input = JSON.parse(canonicalJSON(options.context));
|
|
87
|
+
if (!object(input) || Object.keys(input).sort().join(',') !== 'apiURL,contract,schemaFingerprint,subject,tenant' ||
|
|
88
|
+
typeof input.apiURL !== 'string' || typeof input.subject !== 'string' || !input.subject ||
|
|
89
|
+
!(input.tenant === null || typeof input.tenant === 'string' && input.tenant.length > 0) ||
|
|
90
|
+
typeof input.contract !== 'string' || !input.contract ||
|
|
91
|
+
!(input.schemaFingerprint === null || typeof input.schemaFingerprint === 'string' && /^[a-f0-9]{64}$/.test(input.schemaFingerprint)))
|
|
92
|
+
throw new Error();
|
|
93
|
+
const url = new URL(input.apiURL);
|
|
94
|
+
if (url.username || url.password || url.search || url.hash || url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))
|
|
95
|
+
throw new Error();
|
|
96
|
+
context = Object.freeze({ ...input, apiURL: url.toString().replace(/\/$/, '') });
|
|
97
|
+
if (typeof options.store.get !== 'function' || typeof options.store.compareExchange !== 'function' || typeof options.parser.parse !== 'function')
|
|
98
|
+
throw new Error();
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
throw new MutationJournalError('invalid_operation');
|
|
102
|
+
}
|
|
103
|
+
const handles = new WeakMap();
|
|
104
|
+
const validate = (value, code) => {
|
|
105
|
+
try {
|
|
106
|
+
const encoded = canonicalJSON(value), clean = JSON.parse(encoded);
|
|
107
|
+
if (!object(clean) || typeof clean.key !== 'string' || !keyPattern.test(clean.key))
|
|
108
|
+
throw new Error();
|
|
109
|
+
if (Object.entries(context).some(([field, expected]) => clean[field] !== expected))
|
|
110
|
+
throw new MutationJournalError('context_mismatch');
|
|
111
|
+
const parsed = options.parser.parse(clean);
|
|
112
|
+
if (parsed !== null && typeof parsed === 'object' && 'then' in parsed && typeof parsed.then === 'function') {
|
|
113
|
+
void Promise.resolve(parsed).catch(() => { });
|
|
114
|
+
throw new Error();
|
|
115
|
+
}
|
|
116
|
+
if (canonicalJSON(parsed) !== encoded)
|
|
117
|
+
throw new Error(); // Never normalize or replace saved inputs on restore.
|
|
118
|
+
return freeze(JSON.parse(encoded));
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (error instanceof MutationJournalError && error.code === 'context_mismatch')
|
|
122
|
+
throw new MutationJournalError('context_mismatch');
|
|
123
|
+
throw new MutationJournalError(code);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
const encode = (operation, state) => {
|
|
127
|
+
try {
|
|
128
|
+
return canonicalJSON({ version: 1, revision: crypto.randomUUID(), state, operation });
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
throw new MutationJournalError('invalid_operation');
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
const decode = (slot, raw) => {
|
|
135
|
+
try {
|
|
136
|
+
if (typeof raw !== 'string' || raw.length > MUTATION_JOURNAL_LIMITS.maxEntryBytes || journalByteLength(raw) > MUTATION_JOURNAL_LIMITS.maxEntryBytes)
|
|
137
|
+
throw new Error();
|
|
138
|
+
const value = JSON.parse(raw);
|
|
139
|
+
if (!object(value) || Object.keys(value).sort().join(',') !== 'operation,revision,state,version' || value.version !== 1 ||
|
|
140
|
+
typeof value.revision !== 'string' || !revisionPattern.test(value.revision) ||
|
|
141
|
+
!['prepared', 'uncertain', 'confirmed'].includes(value.state) || canonicalJSON(value) !== raw)
|
|
142
|
+
throw new Error();
|
|
143
|
+
const operation = validate(value.operation, 'invalid_record');
|
|
144
|
+
const entry = Object.freeze({ slot, revision: value.revision, state: value.state, operation });
|
|
145
|
+
handles.set(entry, raw);
|
|
146
|
+
return entry;
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
if (error instanceof MutationJournalError && error.code === 'context_mismatch')
|
|
150
|
+
throw new MutationJournalError('context_mismatch');
|
|
151
|
+
throw new MutationJournalError('invalid_record');
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
const original = (entry) => {
|
|
155
|
+
const raw = entry && handles.get(entry);
|
|
156
|
+
if (!raw)
|
|
157
|
+
throw new MutationJournalError('invalid_entry');
|
|
158
|
+
return raw;
|
|
159
|
+
};
|
|
160
|
+
const get = async (slot) => {
|
|
161
|
+
try {
|
|
162
|
+
return await options.store.get(slot);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
throw storageError(error);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const exchange = async (slot, expected, next) => {
|
|
169
|
+
try {
|
|
170
|
+
if (await options.store.compareExchange(slot, expected, next) !== true)
|
|
171
|
+
throw new MutationJournalError('conflict');
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
throw storageError(error);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
async function prepare(slot, operation) {
|
|
178
|
+
journalSlot(slot);
|
|
179
|
+
const raw = encode(validate(operation, 'invalid_operation'), 'prepared');
|
|
180
|
+
await exchange(slot, null, raw);
|
|
181
|
+
return decode(slot, raw);
|
|
182
|
+
}
|
|
183
|
+
async function load(slot) {
|
|
184
|
+
journalSlot(slot);
|
|
185
|
+
const raw = await get(slot);
|
|
186
|
+
return raw === null ? null : decode(slot, raw);
|
|
187
|
+
}
|
|
188
|
+
async function dispatch(entry, send) {
|
|
189
|
+
const before = original(entry);
|
|
190
|
+
if (entry.state !== 'prepared')
|
|
191
|
+
throw new MutationJournalError('not_prepared');
|
|
192
|
+
const next = encode(entry.operation, 'uncertain');
|
|
193
|
+
await exchange(entry.slot, before, next);
|
|
194
|
+
const claimed = decode(entry.slot, next);
|
|
195
|
+
return { entry: claimed, response: await send(claimed.operation) };
|
|
196
|
+
}
|
|
197
|
+
async function reconcile(entry, response, matches) {
|
|
198
|
+
const before = original(entry), result = reconcileMutation(response, matches);
|
|
199
|
+
if (result.outcome !== 'confirmed' || entry.state === 'confirmed')
|
|
200
|
+
return { result, entry, persistence: 'unchanged' };
|
|
201
|
+
try {
|
|
202
|
+
const next = encode(entry.operation, 'confirmed');
|
|
203
|
+
await exchange(entry.slot, before, next);
|
|
204
|
+
return { result, entry: decode(entry.slot, next), persistence: 'saved' };
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
return { result, entry, persistence: error instanceof MutationJournalError && error.code === 'conflict' ? 'conflict' : 'storage_failed' };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
async function recover(entry, lookup, matches) {
|
|
211
|
+
const before = original(entry);
|
|
212
|
+
if (await get(entry.slot) !== before)
|
|
213
|
+
throw new MutationJournalError('conflict');
|
|
214
|
+
return reconcile(entry, await lookup(entry.operation), matches);
|
|
215
|
+
}
|
|
216
|
+
async function removeConfirmed(entry) {
|
|
217
|
+
const raw = original(entry);
|
|
218
|
+
if (entry.state !== 'confirmed')
|
|
219
|
+
throw new MutationJournalError('not_confirmed');
|
|
220
|
+
await exchange(entry.slot, raw, null);
|
|
221
|
+
}
|
|
222
|
+
return { prepare, load, dispatch, reconcile, recover, removeConfirmed };
|
|
223
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Lossless mode represents every JSON number as its original decimal text. */
|
|
2
|
+
export type NumericMode = 'number' | 'lossless' | 'exact';
|
|
3
|
+
/** Decode numbers without first passing them through IEEE 754. Includes JSON columns. */
|
|
4
|
+
export declare function parseLosslessJSON(source: string): unknown;
|
|
5
|
+
export declare function usesExactNumbers(query: {
|
|
6
|
+
fetch?: unknown;
|
|
7
|
+
}): boolean;
|
|
8
|
+
export declare function usesLosslessNumbers(query: {
|
|
9
|
+
fetch?: unknown;
|
|
10
|
+
}): boolean;
|
|
11
|
+
export declare function numericFetch(send: typeof globalThis.fetch, mode?: NumericMode): typeof globalThis.fetch;
|
package/dist/numeric.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Decode numbers without first passing them through IEEE 754. Includes JSON columns. */
|
|
2
|
+
export function parseLosslessJSON(source) {
|
|
3
|
+
// Tokenize strings first so digits in identifiers, escapes and string values
|
|
4
|
+
// cannot be mistaken for numbers. JSON.parse still validates the grammar.
|
|
5
|
+
return JSON.parse(source.replace(/"(?:[^"\\]|\\[\s\S])*"|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/g, token => token[0] === '"' ? token : JSON.stringify(token)));
|
|
6
|
+
}
|
|
7
|
+
const losslessFetchers = new WeakSet();
|
|
8
|
+
const exactFetchers = new WeakSet();
|
|
9
|
+
export function usesExactNumbers(query) { return typeof query.fetch === 'function' && exactFetchers.has(query.fetch); }
|
|
10
|
+
export function usesLosslessNumbers(query) {
|
|
11
|
+
return typeof query.fetch === 'function' && losslessFetchers.has(query.fetch);
|
|
12
|
+
}
|
|
13
|
+
export function numericFetch(send, mode = 'number') {
|
|
14
|
+
if (mode !== 'number' && mode !== 'lossless' && mode !== 'exact')
|
|
15
|
+
throw new TypeError('numericMode must be number, lossless or exact');
|
|
16
|
+
if (mode === 'number')
|
|
17
|
+
return send;
|
|
18
|
+
if (mode === 'exact') {
|
|
19
|
+
const marked = (input, init) => send(input, init);
|
|
20
|
+
exactFetchers.add(marked);
|
|
21
|
+
return marked;
|
|
22
|
+
}
|
|
23
|
+
const fetcher = async (input, init) => {
|
|
24
|
+
const response = await send(input, init);
|
|
25
|
+
// PostgREST reads response.text() and parses it internally. Convert only
|
|
26
|
+
// successful JSON data, keeping error codes, CSV and empty bodies intact.
|
|
27
|
+
if (!response.ok || response.status === 204 || init?.method === 'HEAD' || !/\bjson\b/i.test(response.headers.get('content-type') ?? ''))
|
|
28
|
+
return response;
|
|
29
|
+
const source = await response.text();
|
|
30
|
+
if (!source)
|
|
31
|
+
return new Response(null, response);
|
|
32
|
+
const body = JSON.stringify(parseLosslessJSON(source));
|
|
33
|
+
const headers = new Headers(response.headers);
|
|
34
|
+
for (const name of ['content-length', 'content-encoding', 'etag'])
|
|
35
|
+
headers.delete(name);
|
|
36
|
+
return new Response(body, { status: response.status, statusText: response.statusText, headers });
|
|
37
|
+
};
|
|
38
|
+
losslessFetchers.add(fetcher);
|
|
39
|
+
return fetcher;
|
|
40
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
type MutationQuery<Row, Error> = PromiseLike<{
|
|
2
|
+
data: Row[] | null;
|
|
3
|
+
error: Error | null;
|
|
4
|
+
status: number;
|
|
5
|
+
}> & {
|
|
6
|
+
retry(enabled: boolean): unknown;
|
|
7
|
+
};
|
|
8
|
+
export type OptimisticResult<Row, Error> = {
|
|
9
|
+
outcome: 'applied';
|
|
10
|
+
row: Row;
|
|
11
|
+
} | {
|
|
12
|
+
outcome: 'conflict';
|
|
13
|
+
} | {
|
|
14
|
+
outcome: 'error';
|
|
15
|
+
error: Error;
|
|
16
|
+
status: number;
|
|
17
|
+
};
|
|
18
|
+
/** Execute a single-row conditional mutation with select() and no retries.
|
|
19
|
+
* Filter by the complete primary key and the previously read version. The
|
|
20
|
+
* database must advance versions atomically. A missing or RLS-hidden row has
|
|
21
|
+
* the same conflict outcome as a stale version; no existence information leaks.
|
|
22
|
+
*/
|
|
23
|
+
export declare function optimisticMutation<Row, Error>(query: MutationQuery<Row, Error> & (unknown extends Row ? never : unknown)): Promise<OptimisticResult<Row, Error>>;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Execute a single-row conditional mutation with select() and no retries.
|
|
2
|
+
* Filter by the complete primary key and the previously read version. The
|
|
3
|
+
* database must advance versions atomically. A missing or RLS-hidden row has
|
|
4
|
+
* the same conflict outcome as a stale version; no existence information leaks.
|
|
5
|
+
*/
|
|
6
|
+
export async function optimisticMutation(query) {
|
|
7
|
+
query.retry(false);
|
|
8
|
+
const result = await query;
|
|
9
|
+
if (result.error !== null)
|
|
10
|
+
return { outcome: 'error', error: result.error, status: result.status };
|
|
11
|
+
if (!Array.isArray(result.data))
|
|
12
|
+
throw new Error('Optimistic mutations require select() returning rows');
|
|
13
|
+
if (result.data.length === 0)
|
|
14
|
+
return { outcome: 'conflict' };
|
|
15
|
+
if (result.data.length !== 1)
|
|
16
|
+
throw new Error('Optimistic mutations must target one primary key');
|
|
17
|
+
return { outcome: 'applied', row: result.data[0] };
|
|
18
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
type ReceiptResponse<Row, Error> = {
|
|
2
|
+
data: Row[] | null;
|
|
3
|
+
error: Error | null;
|
|
4
|
+
status: number;
|
|
5
|
+
};
|
|
6
|
+
export type MutationReconciliation<Row, Error> = {
|
|
7
|
+
outcome: 'confirmed';
|
|
8
|
+
row: Row;
|
|
9
|
+
status: number;
|
|
10
|
+
} | {
|
|
11
|
+
outcome: 'payload_conflict';
|
|
12
|
+
error: Error;
|
|
13
|
+
status: number;
|
|
14
|
+
} | {
|
|
15
|
+
outcome: 'unresolved';
|
|
16
|
+
reason: 'not_found' | 'request_failed' | 'invalid_receipt' | 'replay_expired';
|
|
17
|
+
error: Error | null;
|
|
18
|
+
status: number;
|
|
19
|
+
};
|
|
20
|
+
/** Classify a completed read-only receipt lookup. This helper executes no
|
|
21
|
+
* requests, polling, or retries. matches must synchronously bind the returned
|
|
22
|
+
* receipt to the pending operation's API/identity/key/payload contract. Empty
|
|
23
|
+
* results never prove rollback: a write may be in flight or its receipt purged.
|
|
24
|
+
* Keep the original operation until the application explicitly resolves it.
|
|
25
|
+
*/
|
|
26
|
+
export declare function reconcileMutation<Row, Error, Matched extends Row>(result: ReceiptResponse<Row, Error>, matches: (row: Row) => row is Matched): MutationReconciliation<Matched, Error>;
|
|
27
|
+
export declare function reconcileMutation<Row, Error>(result: ReceiptResponse<Row, Error>, matches: (row: Row) => boolean): MutationReconciliation<Row, Error>;
|
|
28
|
+
export {};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { isReplayExpired } from './replay-key.js';
|
|
2
|
+
export function reconcileMutation(result, matches) {
|
|
3
|
+
const { data, error, status } = result;
|
|
4
|
+
if (error !== null || !(status >= 200 && status < 300)) {
|
|
5
|
+
if (status === 410 && isReplayExpired(error))
|
|
6
|
+
return { outcome: 'unresolved', reason: 'replay_expired', error, status };
|
|
7
|
+
if (status === 409 && error !== null && typeof error === 'object' &&
|
|
8
|
+
'code' in error && error.code === 'PT409' &&
|
|
9
|
+
'message' in error && error.message === 'idempotency_payload_conflict') {
|
|
10
|
+
return { outcome: 'payload_conflict', error, status };
|
|
11
|
+
}
|
|
12
|
+
return { outcome: 'unresolved', reason: 'request_failed', error, status };
|
|
13
|
+
}
|
|
14
|
+
if (Array.isArray(data) && data.length === 0)
|
|
15
|
+
return { outcome: 'unresolved', reason: 'not_found', error: null, status };
|
|
16
|
+
if (Array.isArray(data) && data.length === 1 && data[0] !== null && typeof data[0] === 'object' && !Array.isArray(data[0])) {
|
|
17
|
+
try {
|
|
18
|
+
const matched = matches(data[0]);
|
|
19
|
+
if (matched !== null && (typeof matched === 'object' || typeof matched === 'function') && typeof matched.then === 'function') {
|
|
20
|
+
void Promise.resolve(matched).catch(() => { });
|
|
21
|
+
}
|
|
22
|
+
if (matched === true)
|
|
23
|
+
return { outcome: 'confirmed', row: data[0], status };
|
|
24
|
+
}
|
|
25
|
+
catch { /* A predicate can include private context; omit its exception. */ }
|
|
26
|
+
}
|
|
27
|
+
return { outcome: 'unresolved', reason: 'invalid_receipt', error: null, status };
|
|
28
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Create a UUIDv7 for the opt-in v2 replay contract. Capture this key once,
|
|
2
|
+
* with the full payload and original API/identity, before sending a mutation.
|
|
3
|
+
* Its timestamp is immutable: retries must keep the entire original key.
|
|
4
|
+
* The database clock decides expiry; generating a key grants no retry safety.
|
|
5
|
+
*/
|
|
6
|
+
export declare function createReplayKeyV2(): string;
|
|
7
|
+
/** Exact server contract; a generic HTTP 410 must not imply replay expiry. */
|
|
8
|
+
export declare function isReplayExpired(error: unknown): boolean;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Create a UUIDv7 for the opt-in v2 replay contract. Capture this key once,
|
|
2
|
+
* with the full payload and original API/identity, before sending a mutation.
|
|
3
|
+
* Its timestamp is immutable: retries must keep the entire original key.
|
|
4
|
+
* The database clock decides expiry; generating a key grants no retry safety.
|
|
5
|
+
*/
|
|
6
|
+
export function createReplayKeyV2() {
|
|
7
|
+
const milliseconds = Date.now();
|
|
8
|
+
if (!Number.isSafeInteger(milliseconds) || milliseconds < 0 || milliseconds >= 2 ** 48) {
|
|
9
|
+
throw new RangeError('A valid UUIDv7 clock is required');
|
|
10
|
+
}
|
|
11
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
12
|
+
let timestamp = BigInt(milliseconds);
|
|
13
|
+
for (let i = 5; i >= 0; i--) {
|
|
14
|
+
bytes[i] = Number(timestamp & 255n);
|
|
15
|
+
timestamp >>= 8n;
|
|
16
|
+
}
|
|
17
|
+
bytes[6] = (bytes[6] & 15) | 112;
|
|
18
|
+
bytes[8] = (bytes[8] & 63) | 128;
|
|
19
|
+
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
20
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
21
|
+
}
|
|
22
|
+
/** Exact server contract; a generic HTTP 410 must not imply replay expiry. */
|
|
23
|
+
export function isReplayExpired(error) {
|
|
24
|
+
return error !== null && typeof error === 'object' &&
|
|
25
|
+
'code' in error && error.code === 'PT410' &&
|
|
26
|
+
'message' in error && error.message === 'idempotency_key_expired';
|
|
27
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { JsonParser } from './validation.js';
|
|
2
|
+
/** Omits rejected response values and parser exceptions, which may be private. */
|
|
3
|
+
export declare class RpcResponseValidationError extends Error {
|
|
4
|
+
readonly code = "RPC_RESPONSE_VALIDATION_FAILED";
|
|
5
|
+
constructor();
|
|
6
|
+
}
|
|
7
|
+
type RpcResponse = {
|
|
8
|
+
data: unknown;
|
|
9
|
+
error: unknown;
|
|
10
|
+
status: number;
|
|
11
|
+
};
|
|
12
|
+
type ParsedResponse<Result, Output> = Result extends unknown ? Omit<Result, 'data' | 'error'> & {
|
|
13
|
+
data: Output;
|
|
14
|
+
error: null;
|
|
15
|
+
} : never;
|
|
16
|
+
export type ValidatedRpcResponse<Result, Output> = {
|
|
17
|
+
outcome: 'validated';
|
|
18
|
+
result: ParsedResponse<Result, Output>;
|
|
19
|
+
} | {
|
|
20
|
+
outcome: 'request_failed';
|
|
21
|
+
result: Result;
|
|
22
|
+
} | {
|
|
23
|
+
outcome: 'validation_failed';
|
|
24
|
+
error: RpcResponseValidationError;
|
|
25
|
+
status: number;
|
|
26
|
+
};
|
|
27
|
+
/** Validate the entire data value of an already completed RPC response.
|
|
28
|
+
* Null/undefined successful data goes through the application-owned parser.
|
|
29
|
+
* Error/non-2xx results are returned unchanged without parsing. No requests or
|
|
30
|
+
* retries occur; response validation failure does not prove a write rolled back.
|
|
31
|
+
*/
|
|
32
|
+
export declare function validateRpcResponse<Result extends RpcResponse, Output>(result: Result, parser: JsonParser<Output> & (Extract<Output, PromiseLike<unknown>> extends never ? unknown : never)): ValidatedRpcResponse<Result, Output>;
|
|
33
|
+
export {};
|
package/dist/response.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Omits rejected response values and parser exceptions, which may be private. */
|
|
2
|
+
export class RpcResponseValidationError extends Error {
|
|
3
|
+
code = 'RPC_RESPONSE_VALIDATION_FAILED';
|
|
4
|
+
constructor() {
|
|
5
|
+
super('RPC response validation failed');
|
|
6
|
+
this.name = 'RpcResponseValidationError';
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/** Validate the entire data value of an already completed RPC response.
|
|
10
|
+
* Null/undefined successful data goes through the application-owned parser.
|
|
11
|
+
* Error/non-2xx results are returned unchanged without parsing. No requests or
|
|
12
|
+
* retries occur; response validation failure does not prove a write rolled back.
|
|
13
|
+
*/
|
|
14
|
+
export function validateRpcResponse(result, parser) {
|
|
15
|
+
if (result.error !== null || result.status < 200 || result.status >= 300) {
|
|
16
|
+
return { outcome: 'request_failed', result };
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
const data = parser.parse(result.data);
|
|
20
|
+
if (data !== null && (typeof data === 'object' || typeof data === 'function') && typeof data.then === 'function') {
|
|
21
|
+
void Promise.resolve(data).catch(() => { });
|
|
22
|
+
throw new Error();
|
|
23
|
+
}
|
|
24
|
+
return { outcome: 'validated', result: { ...result, data, error: null } };
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return { outcome: 'validation_failed', error: new RpcResponseValidationError(), status: result.status };
|
|
28
|
+
}
|
|
29
|
+
}
|
package/dist/rpc.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { JsonParser } from './validation.js';
|
|
2
|
+
/** Omits input and parser exceptions, which can contain private values. */
|
|
3
|
+
export declare class RpcValidationError extends Error {
|
|
4
|
+
readonly code = "RPC_ARGUMENT_VALIDATION_FAILED";
|
|
5
|
+
constructor();
|
|
6
|
+
}
|
|
7
|
+
export type ValidatedRpcResult<Result> = {
|
|
8
|
+
outcome: 'validation_failed';
|
|
9
|
+
error: RpcValidationError;
|
|
10
|
+
} | {
|
|
11
|
+
outcome: 'completed';
|
|
12
|
+
result: Result;
|
|
13
|
+
};
|
|
14
|
+
/** Parse untrusted arguments before constructing or executing an RPC query.
|
|
15
|
+
* The application parser owns validation, defaults and transformations. The
|
|
16
|
+
* query callback retains generated RPC argument and result inference, and may
|
|
17
|
+
* apply projections, cancellation or explicit retry settings. Server errors
|
|
18
|
+
* remain in the original result; thrown request errors propagate unchanged.
|
|
19
|
+
*/
|
|
20
|
+
export declare function validatedRpc<Args extends object, Query extends PromiseLike<unknown>>(input: unknown, parser: JsonParser<Args> & (Extract<Args, PromiseLike<unknown>> extends never ? unknown : never), createQuery: (args: Args) => Query): Promise<ValidatedRpcResult<Awaited<Query>>>;
|