@gregale/data 0.0.0-stage → 0.1.0

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 (55) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1022 -2
  3. package/dist/bulk.d.ts +61 -0
  4. package/dist/bulk.js +63 -0
  5. package/dist/client-fetch.d.ts +34 -0
  6. package/dist/client-fetch.js +62 -0
  7. package/dist/cursor-token.d.ts +52 -0
  8. package/dist/cursor-token.js +165 -0
  9. package/dist/cursor.d.ts +44 -0
  10. package/dist/cursor.js +75 -0
  11. package/dist/deadline.d.ts +19 -0
  12. package/dist/deadline.js +29 -0
  13. package/dist/errors.d.ts +17 -0
  14. package/dist/errors.js +68 -0
  15. package/dist/index.d.ts +47 -0
  16. package/dist/index.js +35 -0
  17. package/dist/indexeddb-mutation-store.d.ts +12 -0
  18. package/dist/indexeddb-mutation-store.js +139 -0
  19. package/dist/json.d.ts +34 -0
  20. package/dist/json.js +39 -0
  21. package/dist/live/client.d.ts +192 -0
  22. package/dist/live/client.js +508 -0
  23. package/dist/live/index.d.ts +31 -0
  24. package/dist/live/index.js +28 -0
  25. package/dist/live/protocol.d.ts +125 -0
  26. package/dist/live/protocol.js +271 -0
  27. package/dist/live/react.d.ts +22 -0
  28. package/dist/live/react.js +59 -0
  29. package/dist/live/seal.d.ts +38 -0
  30. package/dist/live/seal.js +98 -0
  31. package/dist/live/sql.d.ts +11 -0
  32. package/dist/live/sql.js +58 -0
  33. package/dist/mutation-journal.d.ts +78 -0
  34. package/dist/mutation-journal.js +223 -0
  35. package/dist/numeric.d.ts +8 -0
  36. package/dist/numeric.js +33 -0
  37. package/dist/optimistic.d.ts +24 -0
  38. package/dist/optimistic.js +18 -0
  39. package/dist/reconcile.d.ts +28 -0
  40. package/dist/reconcile.js +28 -0
  41. package/dist/replay-key.d.ts +8 -0
  42. package/dist/replay-key.js +27 -0
  43. package/dist/response.d.ts +33 -0
  44. package/dist/response.js +29 -0
  45. package/dist/rpc.d.ts +20 -0
  46. package/dist/rpc.js +31 -0
  47. package/dist/storage-uploads.d.ts +55 -0
  48. package/dist/storage-uploads.js +78 -0
  49. package/dist/storage.d.ts +74 -0
  50. package/dist/storage.js +89 -0
  51. package/dist/validation.d.ts +26 -0
  52. package/dist/validation.js +40 -0
  53. package/dist/versioned-mutation.d.ts +28 -0
  54. package/dist/versioned-mutation.js +13 -0
  55. package/package.json +19 -4
package/dist/bulk.d.ts ADDED
@@ -0,0 +1,61 @@
1
+ type BulkQuery<Row, Error> = PromiseLike<{
2
+ data: Row[] | null;
3
+ error: Error | null;
4
+ status: number;
5
+ }> & {
6
+ abortSignal(signal: AbortSignal): unknown;
7
+ retry(enabled: boolean): unknown;
8
+ };
9
+ export type BulkOutcome<Row, Error> = {
10
+ index: number;
11
+ outcome: 'applied';
12
+ rows: Row[];
13
+ } | {
14
+ index: number;
15
+ outcome: 'conflict';
16
+ } | {
17
+ index: number;
18
+ outcome: 'error';
19
+ error: Error;
20
+ status: number;
21
+ } | {
22
+ index: number;
23
+ outcome: 'uncertain';
24
+ error: unknown;
25
+ status: number;
26
+ } | {
27
+ index: number;
28
+ outcome: 'skipped';
29
+ reason: 'cancelled';
30
+ } | {
31
+ index: number;
32
+ outcome: 'invalid';
33
+ error: unknown;
34
+ };
35
+ export type BulkProgress = Readonly<{
36
+ completed: number;
37
+ total: number;
38
+ applied: number;
39
+ conflicts: number;
40
+ errors: number;
41
+ uncertain: number;
42
+ skipped: number;
43
+ invalid: number;
44
+ }>;
45
+ export type BulkOptions = {
46
+ /** Items in a scheduling window; each item remains a separate transaction. */
47
+ batchSize?: number;
48
+ concurrency?: number;
49
+ timeoutMs?: number;
50
+ signal?: AbortSignal;
51
+ /** Synchronous observer; exceptions cannot interrupt writes. No row data is sent. */
52
+ onProgress?: (progress: BulkProgress) => void;
53
+ };
54
+ /** Execute fresh selected mutations once, preserving input order in the report.
55
+ * Windows and the overall run are not atomic. Reconcile uncertain writes before
56
+ * retrying; use idempotent RPCs or primary-key/version predicates where needed.
57
+ */
58
+ export declare function bulkMutations<Item, Row, Error extends {
59
+ code: string;
60
+ }>(items: readonly Item[], build: (item: Item, index: number) => BulkQuery<Row, Error> & (unknown extends Row ? never : unknown), options?: BulkOptions): Promise<BulkOutcome<Row, Error>[]>;
61
+ export {};
package/dist/bulk.js ADDED
@@ -0,0 +1,63 @@
1
+ import { dataRequest } from './deadline.js';
2
+ /** Execute fresh selected mutations once, preserving input order in the report.
3
+ * Windows and the overall run are not atomic. Reconcile uncertain writes before
4
+ * retrying; use idempotent RPCs or primary-key/version predicates where needed.
5
+ */
6
+ export async function bulkMutations(items, build, options = {}) {
7
+ const { batchSize = 100, concurrency = 2, timeoutMs = 5000, signal } = options;
8
+ for (const [name, value] of [['batchSize', batchSize], ['concurrency', concurrency]]) {
9
+ if (!Number.isSafeInteger(value) || value < 1)
10
+ throw new Error(`${name} must be a positive safe integer`);
11
+ }
12
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647)
13
+ throw new Error('Invalid bulk request timeout');
14
+ const input = [...items];
15
+ const results = new Array(input.length);
16
+ const counts = { completed: 0, total: input.length, applied: 0, conflicts: 0, errors: 0, uncertain: 0, skipped: 0, invalid: 0 };
17
+ const record = (result) => {
18
+ results[result.index] = result;
19
+ counts.completed++;
20
+ const field = result.outcome === 'conflict' ? 'conflicts' : result.outcome === 'error' ? 'errors' : result.outcome;
21
+ counts[field]++;
22
+ try {
23
+ void Promise.resolve(options.onProgress?.(Object.freeze({ ...counts }))).catch(() => { });
24
+ }
25
+ catch { /* Observers cannot interrupt mutations. */ }
26
+ };
27
+ for (let start = 0; start < input.length; start += batchSize) {
28
+ const end = Math.min(input.length, start + batchSize);
29
+ let next = start;
30
+ await Promise.all(Array.from({ length: Math.min(concurrency, end - start) }, async () => {
31
+ while (next < end) {
32
+ const index = next++;
33
+ if (signal?.aborted) {
34
+ record({ index, outcome: 'skipped', reason: 'cancelled' });
35
+ continue;
36
+ }
37
+ let query;
38
+ try {
39
+ query = build(input[index], index);
40
+ }
41
+ catch (error) {
42
+ record({ index, outcome: 'invalid', error });
43
+ continue;
44
+ }
45
+ try {
46
+ const result = await dataRequest(query, { timeoutMs, signal });
47
+ if (result.error)
48
+ record({ index, outcome: result.status === 0 || result.status >= 500 ? 'uncertain' : 'error', error: result.error, status: result.status });
49
+ else if (!Array.isArray(result.data))
50
+ record({ index, outcome: 'uncertain', error: new Error('Bulk mutations require select() returning rows'), status: result.status });
51
+ else if (!result.data.length)
52
+ record({ index, outcome: 'conflict' });
53
+ else
54
+ record({ index, outcome: 'applied', rows: result.data });
55
+ }
56
+ catch (error) {
57
+ record({ index, outcome: 'uncertain', error, status: 0 });
58
+ }
59
+ }
60
+ }));
61
+ }
62
+ return results;
63
+ }
@@ -0,0 +1,34 @@
1
+ export type DataResponseInfo = Readonly<{
2
+ requestId: string | null;
3
+ status: number;
4
+ /** Client time from token lookup to response headers; excludes body consumption. */
5
+ durationMs: number;
6
+ }>;
7
+ export type DataClientBaseOptions = {
8
+ url: string;
9
+ fetch?: typeof globalThis.fetch;
10
+ /** Use matching lossless generated types; all JSON numbers become decimal strings. */
11
+ numericMode?: import('./numeric.js').NumericMode;
12
+ /** Opt in to an exact serving-contract match before each REST/RPC operation. */
13
+ expectedSchemaFingerprint?: string;
14
+ /** Called per HTTP response. Callback failures do not affect requests. */
15
+ onResponse?: (response: DataResponseInfo) => void | Promise<void>;
16
+ };
17
+ export type DataClientOptions = DataClientBaseOptions & ({
18
+ accessToken: string | (() => string | Promise<string>);
19
+ anonymous?: false;
20
+ }
21
+ /**
22
+ * Requests without a token are anonymous. The Data API answers them only for
23
+ * relations the owner made public and GET calls of public RPCs
24
+ * (rpc(name, args, { get: true })). A token, when there is one, is sent as usual.
25
+ */
26
+ | {
27
+ anonymous: true;
28
+ accessToken?: string | null | (() => string | null | Promise<string | null>);
29
+ });
30
+ export declare function requestIdOf(response: Response): string | null;
31
+ /** The Data API's origin (and mount path), without /rest/v1, from a client URL. */
32
+ export declare function dataAPIBase(value: string): string;
33
+ /** A fetch that adds the application token, or none for an anonymous client. */
34
+ export declare function authenticatedFetch(options: DataClientOptions): typeof globalThis.fetch;
@@ -0,0 +1,62 @@
1
+ const requestIdPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
2
+ export function requestIdOf(response) {
3
+ const id = response.headers.get('X-Request-Id');
4
+ return id?.length === 36 && requestIdPattern.test(id) ? id : null;
5
+ }
6
+ async function resolveToken(value, signal) {
7
+ if (!signal)
8
+ return value;
9
+ signal.throwIfAborted();
10
+ return new Promise((resolve, reject) => {
11
+ const aborted = () => { signal.removeEventListener('abort', aborted); reject(signal.reason); };
12
+ signal.addEventListener('abort', aborted, { once: true });
13
+ Promise.resolve(value).then(resolve, reject).finally(() => signal.removeEventListener('abort', aborted));
14
+ });
15
+ }
16
+ /** The Data API's origin (and mount path), without /rest/v1, from a client URL. */
17
+ export function dataAPIBase(value) {
18
+ const url = new URL(value);
19
+ if (url.username || url.password || url.search || url.hash)
20
+ throw new Error('Data API URL must not contain credentials, a query or a fragment');
21
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))
22
+ throw new Error('Data API requires HTTPS');
23
+ const base = url.toString().replace(/\/$/, '');
24
+ return base.endsWith('/rest/v1') ? base.slice(0, -'/rest/v1'.length) : base;
25
+ }
26
+ /** A fetch that adds the application token, or none for an anonymous client. */
27
+ export function authenticatedFetch(options) {
28
+ if (options.anonymous !== undefined && typeof options.anonymous !== 'boolean')
29
+ throw new Error('anonymous must be a boolean');
30
+ const anonymous = options.anonymous === true;
31
+ const fetcher = options.fetch ?? globalThis.fetch;
32
+ return async (input, init) => {
33
+ const started = performance.now();
34
+ init?.signal?.throwIfAborted();
35
+ const source = options.accessToken;
36
+ const token = source === undefined || source === null ? null : await resolveToken(typeof source === 'function' ? source() : source, init?.signal);
37
+ init?.signal?.throwIfAborted();
38
+ // Only an explicit anonymous client sends no token, and only for an absent
39
+ // one; an empty or malformed token is an application bug either way.
40
+ const absent = anonymous && (token === null || token === undefined);
41
+ if (!absent && (typeof token !== 'string' || !token || /\s/.test(token)))
42
+ throw new Error('A valid application access token is required');
43
+ const headers = new Headers(init?.headers);
44
+ if (absent)
45
+ headers.delete('Authorization');
46
+ else
47
+ headers.set('Authorization', `Bearer ${token}`);
48
+ const response = await fetcher(input, { ...init, headers, credentials: 'omit', redirect: 'error' });
49
+ if (options.onResponse) {
50
+ const info = Object.freeze({
51
+ requestId: requestIdOf(response),
52
+ status: response.status,
53
+ durationMs: performance.now() - started,
54
+ });
55
+ try {
56
+ void Promise.resolve(options.onResponse(info)).catch(() => { });
57
+ }
58
+ catch { /* Diagnostics must not affect data access. */ }
59
+ }
60
+ return response;
61
+ };
62
+ }
@@ -0,0 +1,52 @@
1
+ import { type CursorOrder, type CheckedOrder, type ReadQuery } from './cursor.js';
2
+ /** Derive this scope on the server from verified identity/tenant/permission claims. */
3
+ export type CursorScope = Readonly<{
4
+ identity: string;
5
+ schemaFingerprint: string;
6
+ }>;
7
+ export type CursorPagerOptions = Readonly<{
8
+ key: Uint8Array | CryptoKey;
9
+ ttlMs?: number;
10
+ maxPageSize?: number;
11
+ now?: () => number;
12
+ }>;
13
+ export type CursorPageResult<Query> = {
14
+ result: Awaited<Query>;
15
+ nextCursor: string | null;
16
+ previousCursor: string | null;
17
+ hasMore: boolean;
18
+ direction: 'forward' | 'backward';
19
+ };
20
+ type Scalar = string | number | boolean | null;
21
+ type SelectedRow<Query> = Awaited<Query> extends {
22
+ data: infer Data;
23
+ } ? NonNullable<Data> extends readonly (infer Row)[] ? Row : never : never;
24
+ type SelectedOrder<Query, Order extends readonly CursorOrder[]> = {
25
+ [Index in keyof Order]: Order[Index]['column'] extends keyof SelectedRow<Query> ? SelectedRow<Query>[Order[Index]['column']] extends Scalar ? Order[Index] : never : never;
26
+ };
27
+ type Builder<Query> = {
28
+ order(column: string, options: {
29
+ ascending: boolean;
30
+ nullsFirst: boolean;
31
+ }): Query;
32
+ limit(count: number): Query;
33
+ or(filters: string): Query;
34
+ };
35
+ export declare class CursorPaginationError extends Error {
36
+ readonly code: 'invalid_options' | 'invalid_cursor' | 'expired_cursor' | 'incompatible_cursor' | 'invalid_response';
37
+ constructor(code: 'invalid_options' | 'invalid_cursor' | 'expired_cursor' | 'incompatible_cursor' | 'invalid_response', message: string);
38
+ }
39
+ /** Server-side encrypted continuations over typed schema-derived queries.
40
+ * Keep the key server-only. Scope must reflect verified identity/tenant/permissions.
41
+ * The caller declares the final ordering column unique within the filtered result.
42
+ */
43
+ export declare function createCursorPager(options: CursorPagerOptions): Promise<{
44
+ page<Query extends Builder<Query>, const Order extends readonly [CursorOrder, ...CursorOrder[]]>(query: Query & ReadQuery<Query>, request: {
45
+ order: Order & CheckedOrder<Query, Order> & SelectedOrder<Query, Order>;
46
+ size: number;
47
+ scope: CursorScope;
48
+ after?: string;
49
+ before?: string;
50
+ }): Promise<CursorPageResult<Query>>;
51
+ }>;
52
+ export {};
@@ -0,0 +1,165 @@
1
+ import { cursorFrom, cursorPage } from './cursor.js';
2
+ export class CursorPaginationError extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.code = code;
7
+ this.name = 'CursorPaginationError';
8
+ }
9
+ }
10
+ const fail = (code, message) => { throw new CursorPaginationError(code, message); };
11
+ const encoder = new TextEncoder(), decoder = new TextDecoder('utf-8', { fatal: true });
12
+ const additionalData = encoder.encode('gregale.data.cursor.v1');
13
+ function base64(bytes) { return btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); }
14
+ function unbase64(value) {
15
+ if (!/^[A-Za-z0-9_-]+$/.test(value))
16
+ return fail('invalid_cursor', 'Invalid continuation token');
17
+ const bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/')), character => character.charCodeAt(0));
18
+ if (base64(bytes) !== value)
19
+ return fail('invalid_cursor', 'Invalid continuation token');
20
+ return bytes;
21
+ }
22
+ function timestamp(now) { const time = now(); if (!Number.isSafeInteger(time) || time < 0)
23
+ return fail('invalid_options', 'Invalid cursor clock'); return time; }
24
+ function queryBinding(query, scope, order, size) {
25
+ // Inspect the pinned PostgREST builder before pagination mutates it. Fail closed
26
+ // on unsupported builder shapes; this binds actual filters, projection and schema.
27
+ const builder = query;
28
+ if (!(builder.url instanceof URL) || builder.method !== 'GET' || builder.headers === undefined)
29
+ return fail('invalid_options', 'Use a fresh selected GET query');
30
+ const url = builder.url;
31
+ if (['order', 'limit', 'offset'].some(key => url.searchParams.has(key)))
32
+ return fail('invalid_options', 'Apply ordering and page size only through the pager');
33
+ const headers = new Headers(builder.headers);
34
+ if (headers.get('Accept')?.includes('object+json') || headers.has('Range'))
35
+ return fail('invalid_options', 'Pagination requires a read returning rows without a range');
36
+ if (!scope || typeof scope.identity !== 'string' || !scope.identity || scope.identity.length > 4096 || typeof scope.schemaFingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(scope.schemaFingerprint))
37
+ return fail('invalid_options', 'Use a trusted identity scope and schema fingerprint');
38
+ const params = [];
39
+ url.searchParams.forEach((value, key) => params.push([key, value]));
40
+ params.sort(([a, av], [b, bv]) => a < b ? -1 : a > b ? 1 : av < bv ? -1 : av > bv ? 1 : 0);
41
+ return JSON.stringify([url.origin, url.pathname, params, builder.schema ?? null, headers.get('Accept'), headers.get('Prefer'), scope.identity, scope.schemaFingerprint, order.map(field => [field.column, field.ascending ?? true, field.nullsFirst ?? false, field.unique ?? false]), size]);
42
+ }
43
+ function rowValues(row, order) {
44
+ try {
45
+ const values = [...cursorFrom(row, order)];
46
+ if (values.some(value => typeof value === 'string' && value.length > 4096))
47
+ return fail('invalid_response', 'Ordering values exceed cursor bounds');
48
+ return values;
49
+ }
50
+ catch (error) {
51
+ if (error instanceof CursorPaginationError)
52
+ throw error;
53
+ return fail('invalid_response', 'Select valid scalar ordering columns and a non-null unique tie-breaker');
54
+ }
55
+ }
56
+ /** Server-side encrypted continuations over typed schema-derived queries.
57
+ * Keep the key server-only. Scope must reflect verified identity/tenant/permissions.
58
+ * The caller declares the final ordering column unique within the filtered result.
59
+ */
60
+ export async function createCursorPager(options) {
61
+ const ttlMs = options.ttlMs ?? 900000, maxPageSize = options.maxPageSize ?? 999, now = options.now ?? Date.now;
62
+ if (!Number.isSafeInteger(ttlMs) || ttlMs < 1 || ttlMs > 86400000 || !Number.isSafeInteger(maxPageSize) || maxPageSize < 1 || maxPageSize > 999 || typeof now !== 'function')
63
+ return fail('invalid_options', 'Use a TTL up to one day and maximum page size from 1 to 999 (one row is reserved for lookahead)');
64
+ let key;
65
+ if (options.key instanceof Uint8Array) {
66
+ if (options.key.byteLength !== 32)
67
+ return fail('invalid_options', 'Use a 256-bit cursor key');
68
+ key = await crypto.subtle.importKey('raw', new Uint8Array(options.key), 'AES-GCM', false, ['encrypt', 'decrypt']);
69
+ }
70
+ else {
71
+ key = options.key;
72
+ if (!key || key.type !== 'secret' || key.algorithm.name !== 'AES-GCM' || key.algorithm.length !== 256 || !key.usages.includes('encrypt') || !key.usages.includes('decrypt'))
73
+ return fail('invalid_options', 'Use an AES-GCM 256-bit encrypt/decrypt key');
74
+ }
75
+ async function seal(values, binding) {
76
+ const issued = timestamp(now), expires = issued + ttlMs;
77
+ if (!Number.isSafeInteger(expires))
78
+ return fail('invalid_options', 'Invalid cursor expiry');
79
+ const bytes = encoder.encode(JSON.stringify({ v: 1, binding, issued, expires, values }));
80
+ if (bytes.length > 8192)
81
+ return fail('invalid_response', 'Ordering values exceed cursor bounds');
82
+ const iv = crypto.getRandomValues(new Uint8Array(12));
83
+ const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData }, key, bytes);
84
+ return `gc1.${base64(iv)}.${base64(new Uint8Array(encrypted))}`;
85
+ }
86
+ async function open(token, binding, order) {
87
+ let payload;
88
+ try {
89
+ if (typeof token !== 'string' || token.length > 16384)
90
+ return fail('invalid_cursor', 'Invalid continuation token');
91
+ const parts = token.split('.');
92
+ if (parts.length !== 3 || parts[0] !== 'gc1')
93
+ return fail('invalid_cursor', 'Invalid continuation token version');
94
+ const iv = unbase64(parts[1]), encrypted = unbase64(parts[2]);
95
+ if (iv.length !== 12 || encrypted.length < 16 || encrypted.length > 8208)
96
+ return fail('invalid_cursor', 'Invalid continuation token');
97
+ const raw = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: new Uint8Array(iv), additionalData }, key, new Uint8Array(encrypted));
98
+ payload = JSON.parse(decoder.decode(raw));
99
+ if (!payload || payload.v !== 1 || !Number.isSafeInteger(payload.issued) || !Number.isSafeInteger(payload.expires) || payload.expires <= payload.issued || payload.expires - payload.issued > ttlMs || typeof payload.binding !== 'string' || !Array.isArray(payload.values) || payload.values.length !== order.length)
100
+ return fail('invalid_cursor', 'Invalid continuation token');
101
+ }
102
+ catch {
103
+ return fail('invalid_cursor', 'Invalid or tampered continuation token');
104
+ }
105
+ const time = timestamp(now);
106
+ if (payload.expires <= time)
107
+ return fail('expired_cursor', 'Continuation expired; restart pagination');
108
+ if (payload.issued > time || payload.binding !== binding)
109
+ return fail('incompatible_cursor', 'Continuation does not match this query, identity, ordering, page size or schema');
110
+ const row = Object.fromEntries(order.map((field, i) => [field.column, payload.values[i]]));
111
+ try {
112
+ return [...cursorFrom(row, order)];
113
+ }
114
+ catch {
115
+ return fail('invalid_cursor', 'Invalid continuation values');
116
+ }
117
+ }
118
+ return {
119
+ async page(query, request) {
120
+ if (!Number.isSafeInteger(request.size) || request.size < 1 || request.size > maxPageSize || request.after !== undefined && request.before !== undefined || !Array.isArray(request.order) || request.order.length > 16)
121
+ return fail('invalid_options', 'Use a bounded page size and either after or before');
122
+ const order = request.order.map(field => ({ ...field }));
123
+ // Validate ordering without mutating the real query or executing a request.
124
+ const probe = Object.fromEntries(order.map(field => [field.column, 0]));
125
+ try {
126
+ rowValues(probe, order);
127
+ }
128
+ catch {
129
+ return fail('invalid_options', 'Use distinct ordering columns and a final unique tie-breaker');
130
+ }
131
+ const queryState = queryBinding(query, request.scope, order, request.size);
132
+ const binding = base64(new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(queryState))));
133
+ const direction = request.before === undefined ? 'forward' : 'backward';
134
+ const token = request.before ?? request.after;
135
+ const values = token === undefined ? undefined : await open(token, binding, order);
136
+ // Detect mutation of a shared builder during asynchronous cursor validation.
137
+ if (queryBinding(query, request.scope, order, request.size) !== queryState)
138
+ return fail('invalid_options', 'Query changed during cursor validation');
139
+ const response = await cursorPage(query, { order, size: request.size + 1, ...(values === undefined ? {} : direction === 'forward' ? { after: values } : { before: values }) });
140
+ const result = response;
141
+ if (result.error)
142
+ return { result: response, nextCursor: null, previousCursor: null, hasMore: false, direction };
143
+ if (!Array.isArray(result.data))
144
+ return fail('invalid_response', 'Expected a successful array response');
145
+ const hasMore = result.data.length > request.size, rows = result.data.slice(0, request.size);
146
+ let nextCursor = null, previousCursor = null;
147
+ if (rows.length) {
148
+ const first = rowValues(rows[0], order), last = rowValues(rows.at(-1), order);
149
+ if (direction === 'forward') {
150
+ if (hasMore)
151
+ nextCursor = await seal(last, binding);
152
+ if (token !== undefined)
153
+ previousCursor = await seal(first, binding);
154
+ }
155
+ else {
156
+ if (hasMore)
157
+ previousCursor = await seal(last, binding);
158
+ if (token !== undefined)
159
+ nextCursor = await seal(first, binding);
160
+ }
161
+ }
162
+ return { result: { ...response, data: rows }, nextCursor, previousCursor, hasMore, direction };
163
+ },
164
+ };
165
+ }
@@ -0,0 +1,44 @@
1
+ import type { PostgrestFilterBuilder } from '@supabase/postgrest-js';
2
+ type Scalar = string | number | boolean | null;
3
+ export type CursorOrder = Readonly<{
4
+ column: string;
5
+ ascending?: boolean;
6
+ nullsFirst?: boolean;
7
+ unique?: boolean;
8
+ }>;
9
+ type Row<Query> = Query extends PostgrestFilterBuilder<infer _C, infer _S, infer R, infer _D, infer _N, infer _F, infer _M, infer _T> ? R : never;
10
+ export type ReadQuery<Query> = Query extends PostgrestFilterBuilder<infer _C, infer _S, infer _R, infer D, infer _N, infer _F, infer M, infer _T> ? M extends 'GET' ? D extends readonly unknown[] ? unknown : never : never : never;
11
+ export type CheckedOrder<Query, Order extends readonly CursorOrder[]> = {
12
+ [I in keyof Order]: Order[I]['column'] extends keyof Row<Query> ? Row<Query>[Order[I]['column']] extends Scalar ? Order[I] : never : never;
13
+ };
14
+ export type Cursor<Order extends readonly CursorOrder[]> = {
15
+ readonly [I in keyof Order]: Scalar;
16
+ };
17
+ type TypedCursor<Query, Order extends readonly CursorOrder[]> = {
18
+ readonly [I in keyof Order]: Order[I]['column'] extends keyof Row<Query> ? Row<Query>[Order[I]['column']] : never;
19
+ };
20
+ /** Extract a cursor from a selected row. Include every ordering column in select(). */
21
+ export declare function cursorFrom<const Order extends readonly [CursorOrder, ...CursorOrder[]], Data extends {
22
+ [Key in Order[number]['column']]: Scalar;
23
+ }>(row: Data, order: Order): {
24
+ readonly [I in keyof Order]: Data[Order[I]['column']];
25
+ };
26
+ /** Apply keyset pagination to a fresh selected query, preserving its projection.
27
+ * Keep the same filters and ordering across pages.
28
+ * before returns nearest preceding rows in reverse order; reverse data for display.
29
+ * The final column must be unique and non-null for the filtered result; uniqueness is caller-owned.
30
+ */
31
+ export declare function cursorPage<Query extends {
32
+ order(column: string, options: {
33
+ ascending: boolean;
34
+ nullsFirst: boolean;
35
+ }): Query;
36
+ limit(count: number): Query;
37
+ or(filters: string): Query;
38
+ }, const Order extends readonly [CursorOrder, ...CursorOrder[]]>(query: Query & ReadQuery<Query>, options: {
39
+ order: Order & CheckedOrder<Query, Order>;
40
+ size: number;
41
+ after?: TypedCursor<Query, Order>;
42
+ before?: TypedCursor<Query, Order>;
43
+ }): Query;
44
+ export {};
package/dist/cursor.js ADDED
@@ -0,0 +1,75 @@
1
+ function checkOrder(order) {
2
+ if (!order.length || order.at(-1)?.unique !== true)
3
+ throw new Error('Cursor ordering requires a final unique tie-breaker');
4
+ const seen = new Set();
5
+ for (const field of order) {
6
+ if (typeof field.column !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(field.column) || seen.has(field.column))
7
+ throw new Error('Cursor columns must be distinct simple column names');
8
+ if ((field.ascending !== undefined && typeof field.ascending !== 'boolean') || (field.nullsFirst !== undefined && typeof field.nullsFirst !== 'boolean'))
9
+ throw new Error('Invalid cursor ordering');
10
+ seen.add(field.column);
11
+ }
12
+ }
13
+ function literal(value) {
14
+ if (typeof value === 'string') {
15
+ if (/[\u0000-\u001f\u007f]/.test(value))
16
+ throw new Error('Cursor strings cannot contain control characters');
17
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
18
+ }
19
+ if (typeof value === 'number' && Number.isFinite(value) && (!Number.isInteger(value) || Number.isSafeInteger(value)) || typeof value === 'boolean')
20
+ return String(value);
21
+ throw new Error('Cursor values must be finite numbers, strings, booleans or null');
22
+ }
23
+ /** Extract a cursor from a selected row. Include every ordering column in select(). */
24
+ export function cursorFrom(row, order) {
25
+ checkOrder(order);
26
+ const values = order.map(field => {
27
+ if (!Object.hasOwn(row, field.column))
28
+ throw new Error('A cursor ordering column was not selected');
29
+ const value = row[field.column];
30
+ if (value !== null)
31
+ literal(value);
32
+ return value;
33
+ });
34
+ if (values.at(-1) === null)
35
+ throw new Error('Cursor tie-breaker must be non-null');
36
+ return Object.freeze(values);
37
+ }
38
+ /** Apply keyset pagination to a fresh selected query, preserving its projection.
39
+ * Keep the same filters and ordering across pages.
40
+ * before returns nearest preceding rows in reverse order; reverse data for display.
41
+ * The final column must be unique and non-null for the filtered result; uniqueness is caller-owned.
42
+ */
43
+ export function cursorPage(query, options) {
44
+ const { order, size } = options;
45
+ if (options.after !== undefined && options.before !== undefined)
46
+ throw new Error('Use either after or before, not both');
47
+ const after = options.before ?? options.after;
48
+ const traversal = options.before === undefined ? order : order.map(field => ({ ...field, ascending: !(field.ascending ?? true), nullsFirst: !(field.nullsFirst ?? false) }));
49
+ checkOrder(order);
50
+ if (!Number.isSafeInteger(size) || size < 1)
51
+ throw new Error('Cursor page size must be a positive safe integer');
52
+ const branches = [];
53
+ const prefix = [];
54
+ if (after !== undefined) {
55
+ if (!Array.isArray(after) || after.length !== order.length || after.at(-1) === null)
56
+ throw new Error('Cursor must contain one value per ordering column and a non-null tie-breaker');
57
+ for (let i = 0; i < order.length; i++) {
58
+ const { column, ascending = true, nullsFirst = false } = traversal[i];
59
+ const value = after[i];
60
+ const next = value === null ? nullsFirst ? `${column}.not.is.null` : undefined
61
+ : nullsFirst ? `${column}.${ascending ? 'gt' : 'lt'}.${literal(value)}`
62
+ : `or(${column}.${ascending ? 'gt' : 'lt'}.${literal(value)},${column}.is.null)`;
63
+ if (next)
64
+ branches.push(prefix.length ? `and(${[...prefix, next].join(',')})` : next);
65
+ prefix.push(value === null ? `${column}.is.null` : `${column}.eq.${literal(value)}`);
66
+ }
67
+ }
68
+ // Validate everything before mutating the SDK builder.
69
+ const builder = query;
70
+ for (const { column, ascending = true, nullsFirst = false } of traversal)
71
+ builder.order(column, { ascending, nullsFirst });
72
+ if (after !== undefined)
73
+ builder.or(branches.join(','));
74
+ return builder.limit(size);
75
+ }
@@ -0,0 +1,19 @@
1
+ import type { QueryResult } from './index.js';
2
+ type RequestQuery = PromiseLike<{
3
+ status: number;
4
+ error: {
5
+ code: string;
6
+ } | null;
7
+ }> & {
8
+ abortSignal(signal: AbortSignal): unknown;
9
+ retry(enabled: boolean): unknown;
10
+ };
11
+ /** Execute once with a deadline covering token lookup, transport and body reads.
12
+ * Cancelling a mutation does not prove it was rolled back. Reconcile its outcome
13
+ * before retrying. This helper disables automatic retries.
14
+ */
15
+ export declare function dataRequest<Query extends RequestQuery>(query: Query, options: {
16
+ timeoutMs: number;
17
+ signal?: AbortSignal;
18
+ }): Promise<QueryResult<Query>>;
19
+ export {};
@@ -0,0 +1,29 @@
1
+ /** Execute once with a deadline covering token lookup, transport and body reads.
2
+ * Cancelling a mutation does not prove it was rolled back. Reconcile its outcome
3
+ * before retrying. This helper disables automatic retries.
4
+ */
5
+ export async function dataRequest(query, options) {
6
+ if (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 2147483647)
7
+ throw new Error('Request timeout must be a positive integer at most 2147483647 ms');
8
+ const controller = new AbortController();
9
+ const cancel = () => controller.abort(new DOMException('Request cancelled', 'AbortError'));
10
+ if (options.signal?.aborted)
11
+ cancel();
12
+ else
13
+ options.signal?.addEventListener('abort', cancel, { once: true });
14
+ const timer = setTimeout(() => controller.abort(new DOMException('Request deadline exceeded', 'TimeoutError')), options.timeoutMs);
15
+ try {
16
+ query.abortSignal(controller.signal);
17
+ query.retry(false);
18
+ const result = await query;
19
+ if (result.status === 0 && controller.signal.aborted && result.error) {
20
+ const timeout = controller.signal.reason?.name === 'TimeoutError';
21
+ return { ...result, error: { ...result.error, code: timeout ? 'request_timeout' : 'request_cancelled' } };
22
+ }
23
+ return result;
24
+ }
25
+ finally {
26
+ clearTimeout(timer);
27
+ options.signal?.removeEventListener('abort', cancel);
28
+ }
29
+ }
@@ -0,0 +1,17 @@
1
+ export type DataErrorCategory = 'unique_violation' | 'foreign_key_violation' | 'authentication' | 'permission_denied' | 'contract_mismatch' | 'timeout' | 'cancelled' | 'unavailable' | 'no_response' | 'response_too_large' | 'rate_limited' | 'concurrency_limited' | 'lock_conflict' | 'deadlock' | 'replay_expired' | 'unknown';
2
+ export type DataErrorRecovery = 'change_input' | 'authenticate' | 'check_permissions' | 'refresh_contract' | 'reconcile' | 'check_service' | 'wait' | 'inspect';
3
+ export type ClassifiedDataError<Error = unknown> = Readonly<{
4
+ category: DataErrorCategory;
5
+ recovery: DataErrorRecovery;
6
+ code: string | null;
7
+ status: number | null;
8
+ /** The unchanged error may contain private database details; do not log blindly. */
9
+ original: Error;
10
+ }>;
11
+ /** Classify without executing, retrying or changing an error. HTTP status is
12
+ * optional because throwOnError() exceptions do not retain response status.
13
+ * Recovery is guidance, never permission to replay a mutation.
14
+ */
15
+ export declare function classifyDataError<Error>(error: Error, options?: {
16
+ status?: number;
17
+ }): ClassifiedDataError<NonNullable<Error>> | null;