@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/errors.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { isReplayExpired } from './replay-key.js';
|
|
2
|
+
const categories = Object.freeze({
|
|
3
|
+
'23505': 'unique_violation',
|
|
4
|
+
'23503': 'foreign_key_violation',
|
|
5
|
+
'42501': 'permission_denied',
|
|
6
|
+
'55P03': 'lock_conflict',
|
|
7
|
+
'40P01': 'deadlock',
|
|
8
|
+
token_required: 'authentication',
|
|
9
|
+
token_invalid: 'authentication',
|
|
10
|
+
PGRST301: 'authentication',
|
|
11
|
+
PGRST302: 'authentication',
|
|
12
|
+
PGRST303: 'authentication',
|
|
13
|
+
origin_not_allowed: 'permission_denied',
|
|
14
|
+
schema_contract_mismatch: 'contract_mismatch',
|
|
15
|
+
query_timeout: 'timeout',
|
|
16
|
+
request_deadline_exceeded: 'timeout',
|
|
17
|
+
data_api_sql_deadline_exceeded: 'timeout',
|
|
18
|
+
response_too_large: 'response_too_large',
|
|
19
|
+
request_timeout: 'timeout',
|
|
20
|
+
request_cancelled: 'cancelled',
|
|
21
|
+
'57014': 'cancelled',
|
|
22
|
+
data_api_unavailable: 'unavailable',
|
|
23
|
+
data_api_shared_budget_unavailable: 'unavailable',
|
|
24
|
+
data_api_budget_identity_required: 'permission_denied',
|
|
25
|
+
data_api_overloaded: 'unavailable',
|
|
26
|
+
data_api_rate_limited: 'rate_limited',
|
|
27
|
+
data_api_concurrency_limited: 'concurrency_limited',
|
|
28
|
+
serving_contract_unavailable: 'unavailable',
|
|
29
|
+
data_api_refresh_unavailable: 'unavailable',
|
|
30
|
+
});
|
|
31
|
+
const recoveries = {
|
|
32
|
+
unique_violation: 'change_input', foreign_key_violation: 'change_input',
|
|
33
|
+
authentication: 'authenticate', permission_denied: 'check_permissions',
|
|
34
|
+
contract_mismatch: 'refresh_contract', timeout: 'reconcile', cancelled: 'reconcile',
|
|
35
|
+
unavailable: 'check_service', no_response: 'reconcile', response_too_large: 'reconcile', rate_limited: 'wait', concurrency_limited: 'wait', lock_conflict: 'wait', deadlock: 'wait', replay_expired: 'reconcile', unknown: 'inspect',
|
|
36
|
+
};
|
|
37
|
+
/** Classify without executing, retrying or changing an error. HTTP status is
|
|
38
|
+
* optional because throwOnError() exceptions do not retain response status.
|
|
39
|
+
* Recovery is guidance, never permission to replay a mutation.
|
|
40
|
+
*/
|
|
41
|
+
export function classifyDataError(error, options = {}) {
|
|
42
|
+
if (error === null || error === undefined)
|
|
43
|
+
return null;
|
|
44
|
+
const rawCode = typeof error === 'object' && 'code' in error ? error.code : undefined;
|
|
45
|
+
const code = typeof rawCode === 'string' ? rawCode : null;
|
|
46
|
+
const status = Number.isInteger(options.status) && (options.status === 0 || (options.status >= 100 && options.status <= 599)) ? options.status : null;
|
|
47
|
+
// Own-property lookup prevents arbitrary codes such as "constructor" from
|
|
48
|
+
// acquiring a category. The v2 expiry contract needs its exact SQLSTATE/message
|
|
49
|
+
// pair because PT410 is also available to unrelated customer RPCs.
|
|
50
|
+
let category = code !== null && Object.hasOwn(categories, code) ? categories[code] : 'unknown';
|
|
51
|
+
if (isReplayExpired(error) && (status === null || status === 410))
|
|
52
|
+
category = 'replay_expired';
|
|
53
|
+
if (category === 'unknown') {
|
|
54
|
+
if (status === 401)
|
|
55
|
+
category = 'authentication';
|
|
56
|
+
else if (status === 403)
|
|
57
|
+
category = 'permission_denied';
|
|
58
|
+
else if (status === 429)
|
|
59
|
+
category = 'rate_limited';
|
|
60
|
+
else if (status === 503)
|
|
61
|
+
category = 'unavailable';
|
|
62
|
+
else if (status === 504)
|
|
63
|
+
category = 'timeout';
|
|
64
|
+
else if (status === 0)
|
|
65
|
+
category = 'no_response';
|
|
66
|
+
}
|
|
67
|
+
return Object.freeze({ category, recovery: recoveries[category], code, status, original: error });
|
|
68
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** An exact JSON number, distinct from a string containing decimal text. */
|
|
2
|
+
export declare class ExactNumber {
|
|
3
|
+
readonly source: string;
|
|
4
|
+
constructor(source: string);
|
|
5
|
+
toString(): string;
|
|
6
|
+
valueOf(): never;
|
|
7
|
+
toJSON(): unknown;
|
|
8
|
+
}
|
|
9
|
+
/** Decode numeric literals, including JSON columns, without rounding. */
|
|
10
|
+
export declare function parseExactJSON(source: string): unknown;
|
|
11
|
+
/** Serialize exact values as numbers, including on runtimes without rawJSON. */
|
|
12
|
+
export declare function stringifyExactJSON(value: unknown): string | undefined;
|
|
13
|
+
/** Keep postgrest-js's builders and inference; decode from original response
|
|
14
|
+
* bytes and serialize bodies before its ordinary JSON encoder sees them. */
|
|
15
|
+
export declare function exactClient<T extends object>(client: T): T;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/** An exact JSON number, distinct from a string containing decimal text. */
|
|
2
|
+
export class ExactNumber {
|
|
3
|
+
source;
|
|
4
|
+
constructor(source) {
|
|
5
|
+
if (typeof source !== 'string' || !/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(source))
|
|
6
|
+
throw new TypeError('Use a JSON numeric literal');
|
|
7
|
+
this.source = source;
|
|
8
|
+
Object.freeze(this);
|
|
9
|
+
}
|
|
10
|
+
toString() { return this.source; }
|
|
11
|
+
valueOf() { throw new TypeError('ExactNumber requires an explicit conversion'); }
|
|
12
|
+
toJSON() {
|
|
13
|
+
const raw = JSON.rawJSON;
|
|
14
|
+
if (!raw)
|
|
15
|
+
throw new TypeError('Use stringifyExactJSON to serialize exact numbers');
|
|
16
|
+
return raw(this.source);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const jsonTokens = /"(?:[^"\\]|\\[\s\S])*"|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/g;
|
|
20
|
+
/** Decode numeric literals, including JSON columns, without rounding. */
|
|
21
|
+
export function parseExactJSON(source) {
|
|
22
|
+
// Temporary tags use a key absent from every decoded source string, so an
|
|
23
|
+
// application's object or string can never be mistaken for a number.
|
|
24
|
+
const strings = new Set();
|
|
25
|
+
source.replace(jsonTokens, token => { if (token[0] === '"')
|
|
26
|
+
strings.add(JSON.parse(token)); return token; });
|
|
27
|
+
let key = '$gregale.exact.number';
|
|
28
|
+
while (strings.has(key))
|
|
29
|
+
key += '_';
|
|
30
|
+
const transformed = source.replace(jsonTokens, token => token[0] === '"' ? token : `{${JSON.stringify(key)}:${JSON.stringify(token)}}`);
|
|
31
|
+
return JSON.parse(transformed, (_name, value) => value && typeof value === 'object' && Object.hasOwn(value, key)
|
|
32
|
+
? new ExactNumber(value[key]) : value);
|
|
33
|
+
}
|
|
34
|
+
/** Serialize exact values as numbers, including on runtimes without rawJSON. */
|
|
35
|
+
export function stringifyExactJSON(value) {
|
|
36
|
+
const ancestors = new Set();
|
|
37
|
+
const encode = (item, key) => {
|
|
38
|
+
if (item instanceof ExactNumber)
|
|
39
|
+
return item.source;
|
|
40
|
+
if (item && typeof item === 'object' && 'toJSON' in item && typeof item.toJSON === 'function')
|
|
41
|
+
item = item.toJSON(key);
|
|
42
|
+
if (item instanceof ExactNumber)
|
|
43
|
+
return item.source;
|
|
44
|
+
if (item instanceof Number || item instanceof String || item instanceof Boolean)
|
|
45
|
+
item = item.valueOf();
|
|
46
|
+
if (!item || typeof item !== 'object')
|
|
47
|
+
return JSON.stringify(item);
|
|
48
|
+
if (ancestors.has(item))
|
|
49
|
+
throw new TypeError('Cannot serialize cyclic JSON');
|
|
50
|
+
ancestors.add(item);
|
|
51
|
+
try {
|
|
52
|
+
if (Array.isArray(item))
|
|
53
|
+
return '[' + Array.from(item, (v, i) => encode(v, String(i)) ?? 'null').join(',') + ']';
|
|
54
|
+
const fields = [];
|
|
55
|
+
for (const name of Object.keys(item)) {
|
|
56
|
+
const encoded = encode(item[name], name);
|
|
57
|
+
if (encoded !== undefined)
|
|
58
|
+
fields.push(JSON.stringify(name) + ':' + encoded);
|
|
59
|
+
}
|
|
60
|
+
return '{' + fields.join(',') + '}';
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
ancestors.delete(item);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
return encode(value, '');
|
|
67
|
+
}
|
|
68
|
+
/** Keep postgrest-js's builders and inference; decode from original response
|
|
69
|
+
* bytes and serialize bodies before its ordinary JSON encoder sees them. */
|
|
70
|
+
export function exactClient(client) {
|
|
71
|
+
const proxies = new WeakMap();
|
|
72
|
+
const wrap = (target) => {
|
|
73
|
+
const existing = proxies.get(target);
|
|
74
|
+
if (existing)
|
|
75
|
+
return existing;
|
|
76
|
+
const proxy = new Proxy(target, { get(object, property, receiver) {
|
|
77
|
+
const value = Reflect.get(object, property, receiver);
|
|
78
|
+
if (property === 'fetch')
|
|
79
|
+
return value;
|
|
80
|
+
if (property === 'then' && typeof value === 'function') {
|
|
81
|
+
return (fulfilled, rejected) => {
|
|
82
|
+
const original = object;
|
|
83
|
+
const builder = Object.assign(Object.create(Object.getPrototypeOf(object)), original);
|
|
84
|
+
if (original.headers)
|
|
85
|
+
builder.headers = new Headers(original.headers);
|
|
86
|
+
let data, captured = false;
|
|
87
|
+
const body = original.body === undefined ? undefined : stringifyExactJSON(original.body);
|
|
88
|
+
if (original.body !== undefined)
|
|
89
|
+
builder.body = {};
|
|
90
|
+
builder.fetch = async (input, init) => {
|
|
91
|
+
const response = await original.fetch(input, { ...init, ...(body !== undefined ? { body } : {}) });
|
|
92
|
+
captured = false;
|
|
93
|
+
if (!response.ok || response.status === 204 || init?.method === 'HEAD' || !/\bjson\b/i.test(response.headers.get('content-type') ?? ''))
|
|
94
|
+
return response;
|
|
95
|
+
const source = await response.text();
|
|
96
|
+
if (source) {
|
|
97
|
+
data = parseExactJSON(source);
|
|
98
|
+
captured = true;
|
|
99
|
+
}
|
|
100
|
+
return new Response(source || null, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
101
|
+
};
|
|
102
|
+
return Promise.resolve(builder).then(response => {
|
|
103
|
+
if (response.error || !captured || response.data === null)
|
|
104
|
+
return response;
|
|
105
|
+
const exact = original.isMaybeSingle && Array.isArray(data) ? data[0] ?? null : data;
|
|
106
|
+
return { ...response, data: exact };
|
|
107
|
+
}).then(fulfilled, rejected);
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
if (typeof value !== 'function')
|
|
111
|
+
return value;
|
|
112
|
+
return (...args) => {
|
|
113
|
+
const rpcOptions = args[2];
|
|
114
|
+
if (property === 'rpc' && args[1] && typeof args[1] === 'object' && (rpcOptions?.get || rpcOptions?.head)) {
|
|
115
|
+
args[1] = Object.fromEntries(Object.entries(args[1]).map(([name, arg]) => [name, arg instanceof ExactNumber ? arg.source : arg && typeof arg === 'object' && !Array.isArray(arg) ? stringifyExactJSON(arg) : arg]));
|
|
116
|
+
}
|
|
117
|
+
const result = Reflect.apply(value, object, args);
|
|
118
|
+
return result && typeof result === 'object' ? wrap(result) : result;
|
|
119
|
+
};
|
|
120
|
+
} });
|
|
121
|
+
proxies.set(target, proxy);
|
|
122
|
+
return proxy;
|
|
123
|
+
};
|
|
124
|
+
return wrap(client);
|
|
125
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { PostgrestClient } from '@supabase/postgrest-js';
|
|
2
|
+
import { type DataClientOptions } from './client-fetch.js';
|
|
3
|
+
export type { DataClientOptions, DataResponseInfo } from './client-fetch.js';
|
|
4
|
+
/** Application tokens authenticate data access; account-management keys do not. */
|
|
5
|
+
export declare function createDataClient<Database>(options: DataClientOptions): PostgrestClient<Database>;
|
|
6
|
+
export { PostgrestError } from '@supabase/postgrest-js';
|
|
7
|
+
export { parseLosslessJSON } from './numeric.js';
|
|
8
|
+
export type { NumericMode } from './numeric.js';
|
|
9
|
+
export { createStorageClient, StorageError } from './storage.js';
|
|
10
|
+
export type { StorageBucket, StorageClient, StorageObject, StorageUploadBody } from './storage.js';
|
|
11
|
+
export type { UploadSession, ResumableUploadOptions, StorageUploads } from './storage-uploads.js';
|
|
12
|
+
export { UploadSessionStartError } from './storage-uploads.js';
|
|
13
|
+
export { classifyDataError } from './errors.js';
|
|
14
|
+
export type { ClassifiedDataError, DataErrorCategory, DataErrorRecovery } from './errors.js';
|
|
15
|
+
export { validatedRpc, RpcValidationError } from './rpc.js';
|
|
16
|
+
export type { ValidatedRpcResult } from './rpc.js';
|
|
17
|
+
export { validateRpcResponse, RpcResponseValidationError } from './response.js';
|
|
18
|
+
export type { ValidatedRpcResponse } from './response.js';
|
|
19
|
+
export { jsonText, jsonValue, selectJson } from './json.js';
|
|
20
|
+
export type { Json, ExactJson, JsonPath, JsonProjection } from './json.js';
|
|
21
|
+
export { validateJson, JsonValidationError } from './validation.js';
|
|
22
|
+
export type { JsonParser, ValidatedJson } from './validation.js';
|
|
23
|
+
/** Preserve the exact projection and nested relationship types of a query. */
|
|
24
|
+
export type QueryResult<Query> = Query extends PromiseLike<infer Result> ? Result : never;
|
|
25
|
+
export type QueryData<Query> = QueryResult<Query> extends {
|
|
26
|
+
data: infer Data;
|
|
27
|
+
} ? NonNullable<Data> : never;
|
|
28
|
+
export type QueryError<Query> = QueryResult<Query> extends {
|
|
29
|
+
error: infer Error;
|
|
30
|
+
} ? NonNullable<Error> : never;
|
|
31
|
+
export type { PostgrestResponse, PostgrestSingleResponse, PostgrestMaybeSingleResponse } from '@supabase/postgrest-js';
|
|
32
|
+
export { cursorPage, cursorFrom } from './cursor.js';
|
|
33
|
+
export type { Cursor, CursorOrder } from './cursor.js';
|
|
34
|
+
export { dataRequest } from './deadline.js';
|
|
35
|
+
export { optimisticMutation } from './optimistic.js';
|
|
36
|
+
export type { OptimisticResult } from './optimistic.js';
|
|
37
|
+
export { bulkMutations } from './bulk.js';
|
|
38
|
+
export type { BulkOutcome, BulkProgress, BulkOptions } from './bulk.js';
|
|
39
|
+
export { reconcileMutation } from './reconcile.js';
|
|
40
|
+
export type { MutationReconciliation } from './reconcile.js';
|
|
41
|
+
export { createReplayKeyV2 } from './replay-key.js';
|
|
42
|
+
export { classifyVersionedMutation } from './versioned-mutation.js';
|
|
43
|
+
export type { VersionedMutationResult } from './versioned-mutation.js';
|
|
44
|
+
export { createCursorPager, CursorPaginationError } from './cursor-token.js';
|
|
45
|
+
export type { CursorScope, CursorPagerOptions, CursorPageResult } from './cursor-token.js';
|
|
46
|
+
export { createMutationJournal, MutationJournalError, MUTATION_JOURNAL_LIMITS } from './mutation-journal.js';
|
|
47
|
+
export type { MutationJournalContext, JournalOperation, MutationJournalState, MutationJournalEntry, MutationJournalStore, MutationJournalErrorCode, JournalReconciliation } from './mutation-journal.js';
|
|
48
|
+
export { createIndexedDBMutationStore } from './indexeddb-mutation-store.js';
|
|
49
|
+
export { ExactNumber, parseExactJSON, stringifyExactJSON } from './exact-numeric.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { PostgrestClient } from '@supabase/postgrest-js';
|
|
2
|
+
import { authenticatedFetch, dataAPIBase } from './client-fetch.js';
|
|
3
|
+
import { exactClient } from './exact-numeric.js';
|
|
4
|
+
import { numericFetch } from './numeric.js';
|
|
5
|
+
/** Application tokens authenticate data access; account-management keys do not. */
|
|
6
|
+
export function createDataClient(options) {
|
|
7
|
+
const send = numericFetch(authenticatedFetch(options), options.numericMode);
|
|
8
|
+
const restEndpoint = `${dataAPIBase(options.url)}/rest/v1`;
|
|
9
|
+
const expectedFingerprint = options.expectedSchemaFingerprint;
|
|
10
|
+
if (expectedFingerprint !== undefined && (typeof expectedFingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(expectedFingerprint)))
|
|
11
|
+
throw new Error('Expected schema fingerprint must be 64 lowercase hexadecimal characters');
|
|
12
|
+
// A distinct route fails closed on runtimes that predate the guard. A header
|
|
13
|
+
// alone could be ignored by an older gateway before executing a mutation.
|
|
14
|
+
const endpoint = expectedFingerprint === undefined ? restEndpoint : `${restEndpoint.slice(0, -'/rest/v1'.length)}/__gregale/contract/${expectedFingerprint}/rest/v1`;
|
|
15
|
+
// The generated contract retains the PostgREST schema shape and supports
|
|
16
|
+
// .schema('api'), typed inserts, filters, relationships and projections.
|
|
17
|
+
const client = new PostgrestClient(endpoint, { fetch: send });
|
|
18
|
+
return options.numericMode === 'exact' ? exactClient(client) : client;
|
|
19
|
+
}
|
|
20
|
+
export { PostgrestError } from '@supabase/postgrest-js';
|
|
21
|
+
export { parseLosslessJSON } from './numeric.js';
|
|
22
|
+
export { createStorageClient, StorageError } from './storage.js';
|
|
23
|
+
export { UploadSessionStartError } from './storage-uploads.js';
|
|
24
|
+
export { classifyDataError } from './errors.js';
|
|
25
|
+
export { validatedRpc, RpcValidationError } from './rpc.js';
|
|
26
|
+
export { validateRpcResponse, RpcResponseValidationError } from './response.js';
|
|
27
|
+
export { jsonText, jsonValue, selectJson } from './json.js';
|
|
28
|
+
export { validateJson, JsonValidationError } from './validation.js';
|
|
29
|
+
export { cursorPage, cursorFrom } from './cursor.js';
|
|
30
|
+
export { dataRequest } from './deadline.js';
|
|
31
|
+
export { optimisticMutation } from './optimistic.js';
|
|
32
|
+
export { bulkMutations } from './bulk.js';
|
|
33
|
+
export { reconcileMutation } from './reconcile.js';
|
|
34
|
+
export { createReplayKeyV2 } from './replay-key.js';
|
|
35
|
+
export { classifyVersionedMutation } from './versioned-mutation.js';
|
|
36
|
+
export { createCursorPager, CursorPaginationError } from './cursor-token.js';
|
|
37
|
+
export { createMutationJournal, MutationJournalError, MUTATION_JOURNAL_LIMITS } from './mutation-journal.js';
|
|
38
|
+
export { createIndexedDBMutationStore } from './indexeddb-mutation-store.js';
|
|
39
|
+
export { ExactNumber, parseExactJSON, stringifyExactJSON } from './exact-numeric.js';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type MutationJournalStore } from './mutation-journal.js';
|
|
2
|
+
/** A dedicated, explicitly selected IndexedDB database. Read/write transactions
|
|
3
|
+
* serialize CAS and aggregate limits across tabs. Strict durability is required;
|
|
4
|
+
* storage errors never fall back to an in-memory or localStorage write.
|
|
5
|
+
*/
|
|
6
|
+
export declare function createIndexedDBMutationStore(options: {
|
|
7
|
+
databaseName: string;
|
|
8
|
+
maxRecords?: number;
|
|
9
|
+
maxBytes?: number;
|
|
10
|
+
}): MutationJournalStore & {
|
|
11
|
+
close(): void;
|
|
12
|
+
};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { MutationJournalError, MUTATION_JOURNAL_LIMITS, journalByteLength, journalSlot } from './mutation-journal.js';
|
|
2
|
+
/** A dedicated, explicitly selected IndexedDB database. Read/write transactions
|
|
3
|
+
* serialize CAS and aggregate limits across tabs. Strict durability is required;
|
|
4
|
+
* storage errors never fall back to an in-memory or localStorage write.
|
|
5
|
+
*/
|
|
6
|
+
export function createIndexedDBMutationStore(options) {
|
|
7
|
+
const databaseName = options.databaseName;
|
|
8
|
+
journalSlot(databaseName);
|
|
9
|
+
const maxRecords = options.maxRecords ?? MUTATION_JOURNAL_LIMITS.maxRecords;
|
|
10
|
+
const maxBytes = options.maxBytes ?? MUTATION_JOURNAL_LIMITS.maxBytes;
|
|
11
|
+
if (!Number.isSafeInteger(maxRecords) || maxRecords < 1 || maxRecords > MUTATION_JOURNAL_LIMITS.maxRecords ||
|
|
12
|
+
!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MUTATION_JOURNAL_LIMITS.maxBytes)
|
|
13
|
+
throw new MutationJournalError('invalid_entry');
|
|
14
|
+
let connection, closed = false;
|
|
15
|
+
const open = () => {
|
|
16
|
+
if (closed)
|
|
17
|
+
return Promise.reject(new MutationJournalError('storage_unavailable'));
|
|
18
|
+
return connection ??= new Promise((resolve, reject) => {
|
|
19
|
+
let failed = false;
|
|
20
|
+
try {
|
|
21
|
+
const factory = globalThis.indexedDB;
|
|
22
|
+
if (!factory)
|
|
23
|
+
throw new Error();
|
|
24
|
+
const request = factory.open(databaseName, 1);
|
|
25
|
+
request.onupgradeneeded = () => { request.result.createObjectStore('entries'); };
|
|
26
|
+
request.onerror = request.onblocked = () => { failed = true; reject(new MutationJournalError('storage_unavailable')); };
|
|
27
|
+
request.onsuccess = () => {
|
|
28
|
+
const db = request.result;
|
|
29
|
+
if (closed || failed) {
|
|
30
|
+
db.close();
|
|
31
|
+
reject(new MutationJournalError('storage_unavailable'));
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
db.onversionchange = () => { closed = true; db.close(); };
|
|
35
|
+
resolve(db);
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
reject(new MutationJournalError('storage_unavailable'));
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
async function get(slot) {
|
|
44
|
+
journalSlot(slot);
|
|
45
|
+
const db = await open();
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
try {
|
|
48
|
+
const transaction = db.transaction('entries', 'readonly');
|
|
49
|
+
const request = transaction.objectStore('entries').openCursor(slot);
|
|
50
|
+
let value = null, invalid = false;
|
|
51
|
+
request.onsuccess = () => {
|
|
52
|
+
if (request.result) {
|
|
53
|
+
value = request.result.value;
|
|
54
|
+
if (typeof value !== 'string') {
|
|
55
|
+
invalid = true;
|
|
56
|
+
transaction.abort();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
transaction.oncomplete = () => resolve(value);
|
|
61
|
+
transaction.onabort = () => reject(new MutationJournalError(invalid ? 'invalid_record' : 'storage_unavailable'));
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
reject(new MutationJournalError('storage_unavailable'));
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
async function compareExchange(slot, expected, next) {
|
|
69
|
+
journalSlot(slot);
|
|
70
|
+
for (const value of [expected, next])
|
|
71
|
+
if (value !== null && (typeof value !== 'string' || journalByteLength(value) > MUTATION_JOURNAL_LIMITS.maxEntryBytes))
|
|
72
|
+
throw new MutationJournalError('invalid_record');
|
|
73
|
+
const db = await open();
|
|
74
|
+
return new Promise((resolve, reject) => {
|
|
75
|
+
try {
|
|
76
|
+
const transaction = db.transaction('entries', 'readwrite', { durability: 'strict' });
|
|
77
|
+
if (transaction.durability !== 'strict') {
|
|
78
|
+
transaction.abort();
|
|
79
|
+
reject(new MutationJournalError('storage_unavailable'));
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const store = transaction.objectStore('entries');
|
|
83
|
+
let matched = false, failure;
|
|
84
|
+
const abort = (code) => { failure = new MutationJournalError(code); transaction.abort(); };
|
|
85
|
+
transaction.oncomplete = () => resolve(matched);
|
|
86
|
+
transaction.onabort = () => reject(failure ?? new MutationJournalError(transaction.error?.name === 'QuotaExceededError' ? 'storage_full' : 'storage_unavailable'));
|
|
87
|
+
const current = store.openCursor(slot);
|
|
88
|
+
current.onsuccess = () => {
|
|
89
|
+
const saved = current.result ? current.result.value : null;
|
|
90
|
+
if (current.result && typeof saved !== 'string') {
|
|
91
|
+
abort('invalid_record');
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (saved !== expected)
|
|
95
|
+
return;
|
|
96
|
+
matched = true;
|
|
97
|
+
let count = 0, bytes = 0;
|
|
98
|
+
const scan = store.openCursor();
|
|
99
|
+
scan.onsuccess = () => {
|
|
100
|
+
const cursor = scan.result;
|
|
101
|
+
if (cursor) {
|
|
102
|
+
if (typeof cursor.key !== 'string' || typeof cursor.value !== 'string' || cursor.value.length > MUTATION_JOURNAL_LIMITS.maxEntryBytes) {
|
|
103
|
+
abort('invalid_record');
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
count++;
|
|
107
|
+
bytes += journalByteLength(cursor.value);
|
|
108
|
+
if (count > MUTATION_JOURNAL_LIMITS.maxRecords || bytes > MUTATION_JOURNAL_LIMITS.maxBytes) {
|
|
109
|
+
abort('storage_full');
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
cursor.continue();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (next === null) {
|
|
116
|
+
store.delete(slot);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const nextCount = count + (expected === null ? 1 : 0);
|
|
120
|
+
const nextBytes = bytes - (expected === null ? 0 : journalByteLength(expected)) + journalByteLength(next);
|
|
121
|
+
if (nextCount > maxRecords || nextBytes > maxBytes) {
|
|
122
|
+
abort('storage_full');
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
store.put(next, slot);
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
reject(new MutationJournalError('storage_unavailable'));
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
function close() {
|
|
135
|
+
closed = true;
|
|
136
|
+
void connection?.then(db => db.close()).catch(() => { });
|
|
137
|
+
}
|
|
138
|
+
return { get, compareExchange, close };
|
|
139
|
+
}
|
package/dist/json.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { ExactNumber } from './exact-numeric.js';
|
|
2
|
+
import type { PostgrestQueryBuilder, PostgrestFilterBuilder, UnstableGetResult } from '@supabase/postgrest-js';
|
|
3
|
+
/** JSON columns have no inferred key schema. JSON null is a valid value. */
|
|
4
|
+
export type Json = string | number | boolean | null | {
|
|
5
|
+
[key: string]: Json | undefined;
|
|
6
|
+
} | Json[];
|
|
7
|
+
export type ExactJson = string | ExactNumber | boolean | null | {
|
|
8
|
+
[key: string]: ExactJson | undefined;
|
|
9
|
+
} | ExactJson[];
|
|
10
|
+
export type JsonPath = readonly [string | number, ...(string | number)[]];
|
|
11
|
+
export type JsonProjection<Column extends string = string, Text extends boolean = boolean> = Readonly<{
|
|
12
|
+
column: Column;
|
|
13
|
+
path: JsonPath;
|
|
14
|
+
text: Text;
|
|
15
|
+
}>;
|
|
16
|
+
/** Extract text; missing paths, SQL NULL and JSON null yield null. */
|
|
17
|
+
export declare function jsonText<Column extends string>(column: Column, ...path: JsonPath): JsonProjection<Column, true>;
|
|
18
|
+
/** Extract arbitrary JSON; missing paths and SQL NULL also yield null. */
|
|
19
|
+
export declare function jsonValue<Column extends string>(column: Column, ...path: JsonPath): JsonProjection<Column, false>;
|
|
20
|
+
type SourceRow<Source> = Source extends PostgrestQueryBuilder<infer _C, infer _S, infer R, infer _N, infer _F> ? R['Row'] : Source extends PostgrestFilterBuilder<infer _C, infer _S, infer R, infer _D, infer _N, infer _F, infer _M, infer _T> ? R : never;
|
|
21
|
+
type BaseResult<Source, Base extends string> = Base extends '' ? {} : Source extends PostgrestQueryBuilder<infer C, infer S, infer R, infer N, infer F> ? UnstableGetResult<S, R['Row'], N, F, Base, C> : Source extends PostgrestFilterBuilder<infer C, infer S, infer R, infer _D, infer N, infer F, infer _M, infer _T> ? UnstableGetResult<S, R, N, F, Base, C> : never;
|
|
22
|
+
type CheckedFields<Source, Base extends string, Fields extends Record<string, JsonProjection>> = {
|
|
23
|
+
[Key in keyof Fields]: Fields[Key]['column'] extends keyof SourceRow<Source> ? Key extends string | number ? `${Key}` extends keyof BaseResult<Source, Base> ? never : Fields[Key] : never : never;
|
|
24
|
+
};
|
|
25
|
+
type ColumnJson<Source, Column> = Column extends keyof SourceRow<Source> ? Extract<SourceRow<Source>[Column], ExactNumber> extends never ? Json : ExactJson : Json;
|
|
26
|
+
type Result<Source, Base, Fields extends Record<string, JsonProjection>> = Base extends {
|
|
27
|
+
error: true;
|
|
28
|
+
} ? Base : Base & {
|
|
29
|
+
-readonly [Key in keyof Fields as Key extends string | number ? Key : never]: Fields[Key]['text'] extends true ? string | null : ColumnJson<Source, Fields[Key]['column']>;
|
|
30
|
+
};
|
|
31
|
+
type Selection<Source, Base extends string, Fields extends Record<string, JsonProjection>> = Source extends PostgrestQueryBuilder<infer C, infer S, infer R, infer N, infer F> ? PostgrestFilterBuilder<C, S, R['Row'], Result<Source, BaseResult<Source, Base>, Fields>[], N, F, 'GET'> : Source extends PostgrestFilterBuilder<infer C, infer S, infer R, infer D, infer N, infer F, infer M, infer T> ? PostgrestFilterBuilder<C, S, R, M extends 'RPC' ? D extends unknown[] ? Result<Source, BaseResult<Source, Base>, Fields>[] : Result<Source, BaseResult<Source, Base>, Fields> : Result<Source, BaseResult<Source, Base>, Fields>[], N, F, M, T> : never;
|
|
32
|
+
/** Add nullable JSON aliases to a table/view, write or relation-set RPC projection.
|
|
33
|
+
* Base is the usual literal PostgREST select string; use '' for JSON aliases only.
|
|
34
|
+
* JSON aliases must not duplicate fields selected by Base.
|
|
35
|
+
*/
|
|
36
|
+
export declare function selectJson<Source extends {
|
|
37
|
+
select(columns: string): unknown;
|
|
38
|
+
}, const Base extends string, const Fields extends Record<string, JsonProjection>>(source: Source, base: Base & (string extends Base ? never : unknown), fields: Fields & CheckedFields<Source, Base, Fields> & (string extends keyof Fields ? never : number extends keyof Fields ? never : unknown)): Selection<Source, Base, Fields>;
|
|
39
|
+
export {};
|
package/dist/json.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
function identifier(value) {
|
|
2
|
+
if (!value || /["\\\u0000-\u001f\u007f]/.test(value))
|
|
3
|
+
throw new Error('JSON projection names must be nonempty and cannot contain quotes, backslashes or control characters');
|
|
4
|
+
return `"${value}"`;
|
|
5
|
+
}
|
|
6
|
+
function expression(projection) {
|
|
7
|
+
if (!projection || typeof projection.column !== 'string' || typeof projection.text !== 'boolean' || !Array.isArray(projection.path) || !projection.path.length)
|
|
8
|
+
throw new Error('Invalid JSON projection');
|
|
9
|
+
return identifier(projection.column) + projection.path.map((part, i) => {
|
|
10
|
+
if (typeof part !== 'string' && (typeof part !== 'number' || !Number.isSafeInteger(part)))
|
|
11
|
+
throw new Error('JSON array indexes must be safe integers');
|
|
12
|
+
const key = typeof part === 'string' ? identifier(part) : String(part);
|
|
13
|
+
return `${projection.text && i === projection.path.length - 1 ? '->>' : '->'}${key}`;
|
|
14
|
+
}).join('');
|
|
15
|
+
}
|
|
16
|
+
function projection(column, path, text) {
|
|
17
|
+
const result = Object.freeze({ column, path: Object.freeze([...path]), text });
|
|
18
|
+
expression(result);
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
/** Extract text; missing paths, SQL NULL and JSON null yield null. */
|
|
22
|
+
export function jsonText(column, ...path) {
|
|
23
|
+
return projection(column, path, true);
|
|
24
|
+
}
|
|
25
|
+
/** Extract arbitrary JSON; missing paths and SQL NULL also yield null. */
|
|
26
|
+
export function jsonValue(column, ...path) {
|
|
27
|
+
return projection(column, path, false);
|
|
28
|
+
}
|
|
29
|
+
/** Add nullable JSON aliases to a table/view, write or relation-set RPC projection.
|
|
30
|
+
* Base is the usual literal PostgREST select string; use '' for JSON aliases only.
|
|
31
|
+
* JSON aliases must not duplicate fields selected by Base.
|
|
32
|
+
*/
|
|
33
|
+
export function selectJson(source, base, fields) {
|
|
34
|
+
const aliases = Object.entries(fields).map(([alias, field]) => `${identifier(alias)}:${expression(field)}`);
|
|
35
|
+
if (!aliases.length)
|
|
36
|
+
throw new Error('At least one JSON projection is required');
|
|
37
|
+
// The SDK handles URL encoding, credentials, filters, cardinality and errors.
|
|
38
|
+
return source.select([...(base.trim() ? [base] : []), ...aliases].join(','));
|
|
39
|
+
}
|