@gregale/data 0.1.0 → 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/README.md +10 -1
- package/dist/client-fetch.d.ts +1 -1
- package/dist/cursor-token.d.ts +2 -1
- package/dist/cursor-token.js +16 -2
- package/dist/cursor.d.ts +2 -1
- package/dist/cursor.js +3 -0
- package/dist/exact-numeric.d.ts +15 -0
- package/dist/exact-numeric.js +125 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +5 -1
- package/dist/json.d.ts +8 -3
- package/dist/live/client.d.ts +2 -2
- package/dist/live/client.js +77 -30
- package/dist/numeric.d.ts +4 -1
- package/dist/numeric.js +9 -2
- package/dist/storage-uploads.d.ts +8 -0
- package/dist/storage-uploads.js +28 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -83,7 +83,7 @@ read.
|
|
|
83
83
|
|
|
84
84
|
With the optional upload-session SQL installed, use `uploadResumable` to retain
|
|
85
85
|
checksummed progress and a durable completion receipt. Save the session ID from
|
|
86
|
-
`
|
|
86
|
+
`onSessionId` before dispatch, then pass `sessionId` with the same file after an interruption.
|
|
87
87
|
`getUpload` reconciles completion; `abortUpload` cancels unfinished work.
|
|
88
88
|
`expectedVersion` accepts the version from `head()` or a previous upload, `null`
|
|
89
89
|
for create-only, or omission for unconditional replacement. A conflict returns
|
|
@@ -100,6 +100,15 @@ clients retain number decoding. This is a read codec: decoded JSON columns do
|
|
|
100
100
|
not retain the number-versus-string token distinction for subsequent writes.
|
|
101
101
|
See [numeric examples](../../docs/data-api/workflows.md#exact-numeric-decoding).
|
|
102
102
|
|
|
103
|
+
### Exact numeric writes
|
|
104
|
+
|
|
105
|
+
Generate `--numeric-mode exact` types and use `numericMode: 'exact'` to retain
|
|
106
|
+
JSON number-versus-string identity. Numbers decode to immutable `ExactNumber`
|
|
107
|
+
values, including RPC results, arrays, JSON columns and `liveRead` rows. Their
|
|
108
|
+
`source` holds the original literal; sending them back writes JSON numbers.
|
|
109
|
+
Use `parseExactJSON` / `stringifyExactJSON` for independent serialization.
|
|
110
|
+
See [round-trip examples](../../docs/data-api/workflows.md#exact-numeric-round-trips).
|
|
111
|
+
|
|
103
112
|
### Live reads
|
|
104
113
|
|
|
105
114
|
A live read is a Data API read whose result stays current: it arrives once,
|
package/dist/client-fetch.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export type DataResponseInfo = Readonly<{
|
|
|
7
7
|
export type DataClientBaseOptions = {
|
|
8
8
|
url: string;
|
|
9
9
|
fetch?: typeof globalThis.fetch;
|
|
10
|
-
/** Use matching
|
|
10
|
+
/** Use matching generated types: lossless gives decimal strings; exact gives ExactNumber values. */
|
|
11
11
|
numericMode?: import('./numeric.js').NumericMode;
|
|
12
12
|
/** Opt in to an exact serving-contract match before each REST/RPC operation. */
|
|
13
13
|
expectedSchemaFingerprint?: string;
|
package/dist/cursor-token.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ExactNumber } from './exact-numeric.js';
|
|
1
2
|
import { type CursorOrder, type CheckedOrder, type ReadQuery } from './cursor.js';
|
|
2
3
|
/** Derive this scope on the server from verified identity/tenant/permission claims. */
|
|
3
4
|
export type CursorScope = Readonly<{
|
|
@@ -17,7 +18,7 @@ export type CursorPageResult<Query> = {
|
|
|
17
18
|
hasMore: boolean;
|
|
18
19
|
direction: 'forward' | 'backward';
|
|
19
20
|
};
|
|
20
|
-
type Scalar = string | number | boolean | null;
|
|
21
|
+
type Scalar = string | number | boolean | null | ExactNumber;
|
|
21
22
|
type SelectedRow<Query> = Awaited<Query> extends {
|
|
22
23
|
data: infer Data;
|
|
23
24
|
} ? NonNullable<Data> extends readonly (infer Row)[] ? Row : never : never;
|
package/dist/cursor-token.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ExactNumber } from './exact-numeric.js';
|
|
1
2
|
import { cursorFrom, cursorPage } from './cursor.js';
|
|
2
3
|
export class CursorPaginationError extends Error {
|
|
3
4
|
code;
|
|
@@ -76,7 +77,7 @@ export async function createCursorPager(options) {
|
|
|
76
77
|
const issued = timestamp(now), expires = issued + ttlMs;
|
|
77
78
|
if (!Number.isSafeInteger(expires))
|
|
78
79
|
return fail('invalid_options', 'Invalid cursor expiry');
|
|
79
|
-
const bytes = encoder.encode(JSON.stringify({ v: 1, binding, issued, expires, values }));
|
|
80
|
+
const bytes = encoder.encode(JSON.stringify({ v: 1, binding, issued, expires, values: values.map(value => value instanceof ExactNumber ? { exactNumber: value.source } : value) }));
|
|
80
81
|
if (bytes.length > 8192)
|
|
81
82
|
return fail('invalid_response', 'Ordering values exceed cursor bounds');
|
|
82
83
|
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
@@ -107,7 +108,20 @@ export async function createCursorPager(options) {
|
|
|
107
108
|
return fail('expired_cursor', 'Continuation expired; restart pagination');
|
|
108
109
|
if (payload.issued > time || payload.binding !== binding)
|
|
109
110
|
return fail('incompatible_cursor', 'Continuation does not match this query, identity, ordering, page size or schema');
|
|
110
|
-
|
|
111
|
+
let values;
|
|
112
|
+
try {
|
|
113
|
+
values = payload.values.map(value => {
|
|
114
|
+
if (value === null || typeof value !== 'object')
|
|
115
|
+
return value;
|
|
116
|
+
if (Object.keys(value).length !== 1 || !Object.hasOwn(value, 'exactNumber') || typeof value.exactNumber !== 'string')
|
|
117
|
+
return fail('invalid_cursor', 'Invalid exact continuation value');
|
|
118
|
+
return new ExactNumber(value.exactNumber);
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return fail('invalid_cursor', 'Invalid continuation values');
|
|
123
|
+
}
|
|
124
|
+
const row = Object.fromEntries(order.map((field, i) => [field.column, values[i]]));
|
|
111
125
|
try {
|
|
112
126
|
return [...cursorFrom(row, order)];
|
|
113
127
|
}
|
package/dist/cursor.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { ExactNumber } from './exact-numeric.js';
|
|
1
2
|
import type { PostgrestFilterBuilder } from '@supabase/postgrest-js';
|
|
2
|
-
type Scalar = string | number | boolean | null;
|
|
3
|
+
type Scalar = string | number | boolean | null | ExactNumber;
|
|
3
4
|
export type CursorOrder = Readonly<{
|
|
4
5
|
column: string;
|
|
5
6
|
ascending?: boolean;
|
package/dist/cursor.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ExactNumber } from './exact-numeric.js';
|
|
1
2
|
function checkOrder(order) {
|
|
2
3
|
if (!order.length || order.at(-1)?.unique !== true)
|
|
3
4
|
throw new Error('Cursor ordering requires a final unique tie-breaker');
|
|
@@ -11,6 +12,8 @@ function checkOrder(order) {
|
|
|
11
12
|
}
|
|
12
13
|
}
|
|
13
14
|
function literal(value) {
|
|
15
|
+
if (value instanceof ExactNumber)
|
|
16
|
+
return value.source;
|
|
14
17
|
if (typeof value === 'string') {
|
|
15
18
|
if (/[\u0000-\u001f\u007f]/.test(value))
|
|
16
19
|
throw new Error('Cursor strings cannot contain control characters');
|
|
@@ -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
CHANGED
|
@@ -9,6 +9,7 @@ export type { NumericMode } from './numeric.js';
|
|
|
9
9
|
export { createStorageClient, StorageError } from './storage.js';
|
|
10
10
|
export type { StorageBucket, StorageClient, StorageObject, StorageUploadBody } from './storage.js';
|
|
11
11
|
export type { UploadSession, ResumableUploadOptions, StorageUploads } from './storage-uploads.js';
|
|
12
|
+
export { UploadSessionStartError } from './storage-uploads.js';
|
|
12
13
|
export { classifyDataError } from './errors.js';
|
|
13
14
|
export type { ClassifiedDataError, DataErrorCategory, DataErrorRecovery } from './errors.js';
|
|
14
15
|
export { validatedRpc, RpcValidationError } from './rpc.js';
|
|
@@ -16,7 +17,7 @@ export type { ValidatedRpcResult } from './rpc.js';
|
|
|
16
17
|
export { validateRpcResponse, RpcResponseValidationError } from './response.js';
|
|
17
18
|
export type { ValidatedRpcResponse } from './response.js';
|
|
18
19
|
export { jsonText, jsonValue, selectJson } from './json.js';
|
|
19
|
-
export type { Json, JsonPath, JsonProjection } from './json.js';
|
|
20
|
+
export type { Json, ExactJson, JsonPath, JsonProjection } from './json.js';
|
|
20
21
|
export { validateJson, JsonValidationError } from './validation.js';
|
|
21
22
|
export type { JsonParser, ValidatedJson } from './validation.js';
|
|
22
23
|
/** Preserve the exact projection and nested relationship types of a query. */
|
|
@@ -45,3 +46,4 @@ export type { CursorScope, CursorPagerOptions, CursorPageResult } from './cursor
|
|
|
45
46
|
export { createMutationJournal, MutationJournalError, MUTATION_JOURNAL_LIMITS } from './mutation-journal.js';
|
|
46
47
|
export type { MutationJournalContext, JournalOperation, MutationJournalState, MutationJournalEntry, MutationJournalStore, MutationJournalErrorCode, JournalReconciliation } from './mutation-journal.js';
|
|
47
48
|
export { createIndexedDBMutationStore } from './indexeddb-mutation-store.js';
|
|
49
|
+
export { ExactNumber, parseExactJSON, stringifyExactJSON } from './exact-numeric.js';
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { PostgrestClient } from '@supabase/postgrest-js';
|
|
2
2
|
import { authenticatedFetch, dataAPIBase } from './client-fetch.js';
|
|
3
|
+
import { exactClient } from './exact-numeric.js';
|
|
3
4
|
import { numericFetch } from './numeric.js';
|
|
4
5
|
/** Application tokens authenticate data access; account-management keys do not. */
|
|
5
6
|
export function createDataClient(options) {
|
|
@@ -13,11 +14,13 @@ export function createDataClient(options) {
|
|
|
13
14
|
const endpoint = expectedFingerprint === undefined ? restEndpoint : `${restEndpoint.slice(0, -'/rest/v1'.length)}/__gregale/contract/${expectedFingerprint}/rest/v1`;
|
|
14
15
|
// The generated contract retains the PostgREST schema shape and supports
|
|
15
16
|
// .schema('api'), typed inserts, filters, relationships and projections.
|
|
16
|
-
|
|
17
|
+
const client = new PostgrestClient(endpoint, { fetch: send });
|
|
18
|
+
return options.numericMode === 'exact' ? exactClient(client) : client;
|
|
17
19
|
}
|
|
18
20
|
export { PostgrestError } from '@supabase/postgrest-js';
|
|
19
21
|
export { parseLosslessJSON } from './numeric.js';
|
|
20
22
|
export { createStorageClient, StorageError } from './storage.js';
|
|
23
|
+
export { UploadSessionStartError } from './storage-uploads.js';
|
|
21
24
|
export { classifyDataError } from './errors.js';
|
|
22
25
|
export { validatedRpc, RpcValidationError } from './rpc.js';
|
|
23
26
|
export { validateRpcResponse, RpcResponseValidationError } from './response.js';
|
|
@@ -33,3 +36,4 @@ export { classifyVersionedMutation } from './versioned-mutation.js';
|
|
|
33
36
|
export { createCursorPager, CursorPaginationError } from './cursor-token.js';
|
|
34
37
|
export { createMutationJournal, MutationJournalError, MUTATION_JOURNAL_LIMITS } from './mutation-journal.js';
|
|
35
38
|
export { createIndexedDBMutationStore } from './indexeddb-mutation-store.js';
|
|
39
|
+
export { ExactNumber, parseExactJSON, stringifyExactJSON } from './exact-numeric.js';
|
package/dist/json.d.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
|
+
import type { ExactNumber } from './exact-numeric.js';
|
|
1
2
|
import type { PostgrestQueryBuilder, PostgrestFilterBuilder, UnstableGetResult } from '@supabase/postgrest-js';
|
|
2
3
|
/** JSON columns have no inferred key schema. JSON null is a valid value. */
|
|
3
4
|
export type Json = string | number | boolean | null | {
|
|
4
5
|
[key: string]: Json | undefined;
|
|
5
6
|
} | Json[];
|
|
7
|
+
export type ExactJson = string | ExactNumber | boolean | null | {
|
|
8
|
+
[key: string]: ExactJson | undefined;
|
|
9
|
+
} | ExactJson[];
|
|
6
10
|
export type JsonPath = readonly [string | number, ...(string | number)[]];
|
|
7
11
|
export type JsonProjection<Column extends string = string, Text extends boolean = boolean> = Readonly<{
|
|
8
12
|
column: Column;
|
|
@@ -18,12 +22,13 @@ type BaseResult<Source, Base extends string> = Base extends '' ? {} : Source ext
|
|
|
18
22
|
type CheckedFields<Source, Base extends string, Fields extends Record<string, JsonProjection>> = {
|
|
19
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;
|
|
20
24
|
};
|
|
21
|
-
type
|
|
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 {
|
|
22
27
|
error: true;
|
|
23
28
|
} ? Base : Base & {
|
|
24
|
-
-readonly [Key in keyof Fields as Key extends string | number ? Key : never]: Fields[Key]['text'] extends true ? string | null :
|
|
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']>;
|
|
25
30
|
};
|
|
26
|
-
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<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<BaseResult<Source, Base>, Fields>[] : Result<BaseResult<Source, Base>, Fields> : Result<BaseResult<Source, Base>, Fields>[], N, F, M, T> : never;
|
|
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;
|
|
27
32
|
/** Add nullable JSON aliases to a table/view, write or relation-set RPC projection.
|
|
28
33
|
* Base is the usual literal PostgREST select string; use '' for JSON aliases only.
|
|
29
34
|
* JSON aliases must not duplicate fields selected by Base.
|
package/dist/live/client.d.ts
CHANGED
|
@@ -125,14 +125,14 @@ export declare class LiveQueryClosedError extends Error {
|
|
|
125
125
|
export declare function parseLiveRow(values: ReadonlyArray<string | null>, columns: ReadonlyArray<LiveColumn>): Record<string, unknown>;
|
|
126
126
|
export declare function parseLiveValue(value: string | null, type: string): unknown;
|
|
127
127
|
/** Decodes a live row as the Data API (PostgREST) returns it in JSON. */
|
|
128
|
-
export declare function parseDataAPIRow(values: ReadonlyArray<string | null>, columns: ReadonlyArray<LiveColumn>, lossless?: boolean): Record<string, unknown>;
|
|
128
|
+
export declare function parseDataAPIRow(values: ReadonlyArray<string | null>, columns: ReadonlyArray<LiveColumn>, lossless?: boolean | 'exact'): Record<string, unknown>;
|
|
129
129
|
/**
|
|
130
130
|
* Decodes one PostgreSQL text value as PostgREST encodes it in JSON: numbers
|
|
131
131
|
* for integer, numeric and float types (non-finite values stay strings, as
|
|
132
132
|
* JSON has none), ISO 8601 timestamps, arrays element by element, and JSON.
|
|
133
133
|
* Embedded resources already arrive as JSON. Composite columns stay text.
|
|
134
134
|
*/
|
|
135
|
-
export declare function parseDataAPIValue(value: string | null, type: string, lossless?: boolean): unknown;
|
|
135
|
+
export declare function parseDataAPIValue(value: string | null, type: string, lossless?: boolean | 'exact'): unknown;
|
|
136
136
|
/**
|
|
137
137
|
* One connection to an app's realtime endpoint, carrying any number of live
|
|
138
138
|
* queries. It reconnects with backoff and resumes each query from the
|
package/dist/live/client.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { LIVE_TYPES, LiveProtocolError, LiveResult, parseLiveServerFrame } from './protocol.js';
|
|
2
|
-
import {
|
|
2
|
+
import { ExactNumber, parseExactJSON } from '../exact-numeric.js';
|
|
3
|
+
import { parseLosslessJSON, usesLosslessNumbers, usesExactNumbers } from '../numeric.js';
|
|
3
4
|
/** The realtime subprotocol that carries live frames. */
|
|
4
5
|
export const LIVE_SUBPROTOCOL = 'gregale.realtime.v2';
|
|
5
6
|
/**
|
|
@@ -31,8 +32,8 @@ export function liveRead(query) {
|
|
|
31
32
|
const headers = q.headers instanceof Headers ? q.headers : new Headers((q.headers ?? {}));
|
|
32
33
|
// postgrest-js keeps .schema() on the builder and sets the header when it runs.
|
|
33
34
|
const schema = typeof q.schema === 'string' ? q.schema : headers.get('Accept-Profile');
|
|
34
|
-
const lossless = usesLosslessNumbers(q);
|
|
35
|
-
const parse = (lossless ? (values, columns) => parseDataAPIRow(values, columns,
|
|
35
|
+
const lossless = usesExactNumbers(q) ? 'exact' : usesLosslessNumbers(q);
|
|
36
|
+
const parse = (lossless ? (values, columns) => parseDataAPIRow(values, columns, lossless) : parseDataAPIRow);
|
|
36
37
|
return { read: relation + q.url.search, ...(schema ? { schema } : {}), parse };
|
|
37
38
|
}
|
|
38
39
|
function isRead(options) {
|
|
@@ -99,13 +100,15 @@ export function parseDataAPIValue(value, type, lossless = false) {
|
|
|
99
100
|
case 'numeric':
|
|
100
101
|
case 'float4':
|
|
101
102
|
case 'float8': {
|
|
103
|
+
if (lossless === 'exact')
|
|
104
|
+
return ['NaN', 'Infinity', '-Infinity'].includes(value) ? value : new ExactNumber(value);
|
|
102
105
|
if (lossless)
|
|
103
106
|
return value;
|
|
104
107
|
const n = Number(value);
|
|
105
108
|
return Number.isFinite(n) ? n : value;
|
|
106
109
|
}
|
|
107
110
|
case 'json':
|
|
108
|
-
case 'jsonb': return lossless ? parseLosslessJSON(value) : JSON.parse(value);
|
|
111
|
+
case 'jsonb': return lossless === 'exact' ? parseExactJSON(value) : lossless ? parseLosslessJSON(value) : JSON.parse(value);
|
|
109
112
|
case 'timestamptz': return /^\d/.test(value) ? value.replace(' ', 'T').replace(offsetHours, '$1:00') : value;
|
|
110
113
|
case 'timestamp': return /^\d/.test(value) ? value.replace(' ', 'T') : value;
|
|
111
114
|
default: return value;
|
|
@@ -309,10 +312,14 @@ class LiveQueryHandle {
|
|
|
309
312
|
renewTimer;
|
|
310
313
|
attached = false;
|
|
311
314
|
finished = false;
|
|
315
|
+
generation = 0;
|
|
316
|
+
credentialAttempt = 0;
|
|
317
|
+
retryAttempt = 0;
|
|
312
318
|
constructor(conn, id, options) {
|
|
313
319
|
this.conn = conn;
|
|
314
320
|
this.id = id;
|
|
315
|
-
|
|
321
|
+
const { initialRows: _initialRows, ...configuration } = options;
|
|
322
|
+
this.options = configuration;
|
|
316
323
|
this.sealed = isRead(options) ? undefined : options.sealed;
|
|
317
324
|
this.state = Object.freeze({
|
|
318
325
|
status: 'connecting', rows: options.initialRows ?? [], keys: [], columns: [], snapshot: null, error: undefined,
|
|
@@ -332,29 +339,43 @@ class LiveQueryHandle {
|
|
|
332
339
|
if (again)
|
|
333
340
|
this.result.resubscribe();
|
|
334
341
|
this.attached = true;
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
342
|
+
const generation = ++this.generation;
|
|
343
|
+
this.conn.timers.clearTimeout(this.renewTimer);
|
|
344
|
+
this.retryAttempt = 0;
|
|
345
|
+
void this.sendSubscription(generation, again, resume);
|
|
346
|
+
}
|
|
347
|
+
async sendSubscription(generation, fresh, resume) {
|
|
348
|
+
const attempt = ++this.credentialAttempt;
|
|
349
|
+
const credential = await this.credential(fresh, generation, attempt);
|
|
350
|
+
if (!this.current(generation, attempt))
|
|
351
|
+
return;
|
|
352
|
+
if (!credential) {
|
|
353
|
+
this.retryCredential(() => { void this.sendSubscription(generation, fresh, resume); });
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
this.retryAttempt = 0;
|
|
357
|
+
const query = isRead(this.options)
|
|
358
|
+
? { database: this.options.database, rest: this.options.read, ...(this.options.schema ? { schema: this.options.schema } : {}) }
|
|
359
|
+
: {};
|
|
360
|
+
this.conn.send({ type: LIVE_TYPES.subscribe, subscription: this.id, ...query, ...credential, ...(resume > 0 ? { version: resume } : {}) });
|
|
344
361
|
}
|
|
345
362
|
awaitTxId(xid, options = {}) {
|
|
346
363
|
const target = BigInt(xid);
|
|
347
|
-
if (this.result.sees(target))
|
|
348
|
-
return Promise.resolve();
|
|
349
364
|
if (this.finished)
|
|
350
365
|
return Promise.reject(new LiveQueryClosedError(this.result.error));
|
|
366
|
+
if (options.signal?.aborted)
|
|
367
|
+
return Promise.reject(options.signal.reason);
|
|
368
|
+
if (this.result.sees(target))
|
|
369
|
+
return Promise.resolve();
|
|
351
370
|
return new Promise((resolve, reject) => {
|
|
352
|
-
const
|
|
353
|
-
|
|
354
|
-
|
|
371
|
+
const cleanup = () => options.signal?.removeEventListener('abort', aborted);
|
|
372
|
+
const waiter = { xid: target, resolve: () => { cleanup(); resolve(); }, reject: (error) => { cleanup(); reject(error); } };
|
|
373
|
+
const aborted = () => {
|
|
355
374
|
this.waiters = this.waiters.filter((w) => w !== waiter);
|
|
356
|
-
reject(options.signal?.reason);
|
|
357
|
-
}
|
|
375
|
+
waiter.reject(options.signal?.reason);
|
|
376
|
+
};
|
|
377
|
+
this.waiters.push(waiter);
|
|
378
|
+
options.signal?.addEventListener('abort', aborted, { once: true });
|
|
358
379
|
});
|
|
359
380
|
}
|
|
360
381
|
close() {
|
|
@@ -396,6 +417,7 @@ class LiveQueryHandle {
|
|
|
396
417
|
}
|
|
397
418
|
/** @internal */
|
|
398
419
|
disconnected() {
|
|
420
|
+
this.generation++;
|
|
399
421
|
this.conn.timers.clearTimeout(this.renewTimer);
|
|
400
422
|
if (this.state.status !== 'closed')
|
|
401
423
|
this.setState({ ...this.state, status: 'connecting' });
|
|
@@ -405,17 +427,20 @@ class LiveQueryHandle {
|
|
|
405
427
|
if (this.finished)
|
|
406
428
|
return;
|
|
407
429
|
this.finished = true;
|
|
430
|
+
this.generation++;
|
|
408
431
|
this.conn.timers.clearTimeout(this.renewTimer);
|
|
409
432
|
for (const w of this.waiters)
|
|
410
433
|
w.reject(new LiveQueryClosedError(frame));
|
|
411
434
|
this.waiters = [];
|
|
412
|
-
this.
|
|
435
|
+
this.result = new LiveResult();
|
|
436
|
+
this.rowCache.clear();
|
|
437
|
+
this.setState({ status: 'closed', rows: [], keys: [], columns: [], snapshot: null, error: frame });
|
|
413
438
|
}
|
|
414
439
|
/**
|
|
415
440
|
* The frame fields that authorize: a seal (fresh when asked), the user's
|
|
416
441
|
* current token, anonymous access or a server key.
|
|
417
442
|
*/
|
|
418
|
-
async credential(fresh) {
|
|
443
|
+
async credential(fresh, generation, attempt) {
|
|
419
444
|
const o = this.options;
|
|
420
445
|
if (isRead(o)) {
|
|
421
446
|
if (o.anonymous === true)
|
|
@@ -426,20 +451,36 @@ class LiveQueryHandle {
|
|
|
426
451
|
return { token: await o.token() };
|
|
427
452
|
}
|
|
428
453
|
catch {
|
|
429
|
-
return undefined;
|
|
454
|
+
return undefined;
|
|
430
455
|
}
|
|
431
456
|
}
|
|
432
457
|
if (fresh && o.refresh) {
|
|
433
458
|
try {
|
|
434
|
-
|
|
459
|
+
const sealed = await o.refresh();
|
|
460
|
+
if (this.current(generation, attempt))
|
|
461
|
+
this.sealed = sealed;
|
|
462
|
+
}
|
|
463
|
+
catch {
|
|
464
|
+
return undefined;
|
|
435
465
|
}
|
|
436
|
-
catch { /* the held seal may still be valid */ }
|
|
437
466
|
}
|
|
438
467
|
return this.sealed === undefined ? undefined : { sealed: this.sealed };
|
|
439
468
|
}
|
|
440
469
|
renewable() {
|
|
441
470
|
return isRead(this.options) || this.options.refresh !== undefined;
|
|
442
471
|
}
|
|
472
|
+
current(generation, attempt) {
|
|
473
|
+
return !this.finished && this.conn.isOpen && generation === this.generation && attempt === this.credentialAttempt;
|
|
474
|
+
}
|
|
475
|
+
retryCredential(work) {
|
|
476
|
+
this.conn.timers.clearTimeout(this.renewTimer);
|
|
477
|
+
const generation = this.generation;
|
|
478
|
+
const delay = Math.min(30_000, 1000 * 2 ** Math.min(this.retryAttempt++, 5));
|
|
479
|
+
this.renewTimer = this.conn.timers.setTimeout(() => {
|
|
480
|
+
if (!this.finished && this.conn.isOpen && generation === this.generation)
|
|
481
|
+
work();
|
|
482
|
+
}, delay);
|
|
483
|
+
}
|
|
443
484
|
scheduleRenewal() {
|
|
444
485
|
this.conn.timers.clearTimeout(this.renewTimer);
|
|
445
486
|
if (!this.renewable() || this.result.expires <= 0)
|
|
@@ -449,12 +490,18 @@ class LiveQueryHandle {
|
|
|
449
490
|
this.renewTimer = this.conn.timers.setTimeout(() => { void this.renew(); }, Math.max(0, left - early));
|
|
450
491
|
}
|
|
451
492
|
async renew() {
|
|
452
|
-
if (!this.renewable() || this.finished)
|
|
493
|
+
if (!this.renewable() || this.finished || !this.conn.isOpen)
|
|
494
|
+
return;
|
|
495
|
+
const generation = this.generation, attempt = ++this.credentialAttempt;
|
|
496
|
+
const credential = await this.credential(true, generation, attempt);
|
|
497
|
+
if (!this.current(generation, attempt))
|
|
453
498
|
return;
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
if (!credential || this.finished)
|
|
499
|
+
if (!credential) {
|
|
500
|
+
this.retryCredential(() => { void this.renew(); });
|
|
457
501
|
return;
|
|
502
|
+
}
|
|
503
|
+
this.conn.timers.clearTimeout(this.renewTimer);
|
|
504
|
+
this.retryAttempt = 0;
|
|
458
505
|
this.conn.send({ type: LIVE_TYPES.renew, subscription: this.id, ...credential });
|
|
459
506
|
}
|
|
460
507
|
publish() {
|
package/dist/numeric.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
/** Lossless mode represents every JSON number as its original decimal text. */
|
|
2
|
-
export type NumericMode = 'number' | 'lossless';
|
|
2
|
+
export type NumericMode = 'number' | 'lossless' | 'exact';
|
|
3
3
|
/** Decode numbers without first passing them through IEEE 754. Includes JSON columns. */
|
|
4
4
|
export declare function parseLosslessJSON(source: string): unknown;
|
|
5
|
+
export declare function usesExactNumbers(query: {
|
|
6
|
+
fetch?: unknown;
|
|
7
|
+
}): boolean;
|
|
5
8
|
export declare function usesLosslessNumbers(query: {
|
|
6
9
|
fetch?: unknown;
|
|
7
10
|
}): boolean;
|
package/dist/numeric.js
CHANGED
|
@@ -5,14 +5,21 @@ export function parseLosslessJSON(source) {
|
|
|
5
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
6
|
}
|
|
7
7
|
const losslessFetchers = new WeakSet();
|
|
8
|
+
const exactFetchers = new WeakSet();
|
|
9
|
+
export function usesExactNumbers(query) { return typeof query.fetch === 'function' && exactFetchers.has(query.fetch); }
|
|
8
10
|
export function usesLosslessNumbers(query) {
|
|
9
11
|
return typeof query.fetch === 'function' && losslessFetchers.has(query.fetch);
|
|
10
12
|
}
|
|
11
13
|
export function numericFetch(send, mode = 'number') {
|
|
12
|
-
if (mode !== 'number' && mode !== 'lossless')
|
|
13
|
-
throw new TypeError('numericMode must be number or
|
|
14
|
+
if (mode !== 'number' && mode !== 'lossless' && mode !== 'exact')
|
|
15
|
+
throw new TypeError('numericMode must be number, lossless or exact');
|
|
14
16
|
if (mode === 'number')
|
|
15
17
|
return send;
|
|
18
|
+
if (mode === 'exact') {
|
|
19
|
+
const marked = (input, init) => send(input, init);
|
|
20
|
+
exactFetchers.add(marked);
|
|
21
|
+
return marked;
|
|
22
|
+
}
|
|
16
23
|
const fetcher = async (input, init) => {
|
|
17
24
|
const response = await send(input, init);
|
|
18
25
|
// PostgREST reads response.text() and parses it internally. Convert only
|
|
@@ -19,6 +19,10 @@ export type ResumableUploadOptions = {
|
|
|
19
19
|
contentType?: string;
|
|
20
20
|
signal?: AbortSignal;
|
|
21
21
|
sessionId?: string;
|
|
22
|
+
/** Reuse this ID to reconcile an uncertain start through idempotent creation. */
|
|
23
|
+
id?: string;
|
|
24
|
+
/** Persist the recovery ID before any create request is sent. */
|
|
25
|
+
onSessionId?: (id: string) => void | Promise<void>;
|
|
22
26
|
/** Undefined replaces unconditionally, null creates only, otherwise compare the previous version. */
|
|
23
27
|
expectedVersion?: string | null;
|
|
24
28
|
/** Persist this ID to resume without re-uploading acknowledged chunks. */
|
|
@@ -29,6 +33,10 @@ export type ResumableUploadOptions = {
|
|
|
29
33
|
total: number;
|
|
30
34
|
}) => void;
|
|
31
35
|
};
|
|
36
|
+
export declare class UploadSessionStartError extends Error {
|
|
37
|
+
readonly sessionId: string;
|
|
38
|
+
constructor(sessionId: string, cause: unknown);
|
|
39
|
+
}
|
|
32
40
|
export type StorageUploads = {
|
|
33
41
|
startUpload(name: string, options: {
|
|
34
42
|
size: number;
|
package/dist/storage-uploads.js
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
export class UploadSessionStartError extends Error {
|
|
2
|
+
sessionId;
|
|
3
|
+
constructor(sessionId, cause) {
|
|
4
|
+
super('Upload session start could not be confirmed; reconcile this session ID before retrying', { cause });
|
|
5
|
+
this.sessionId = sessionId;
|
|
6
|
+
this.name = 'UploadSessionStartError';
|
|
7
|
+
}
|
|
8
|
+
}
|
|
1
9
|
const idPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
2
10
|
function parseSession(value, bucket) {
|
|
3
11
|
const session = value;
|
|
@@ -41,10 +49,28 @@ export function storageUploads(bucket, call, validateName) {
|
|
|
41
49
|
throw new Error('Invalid upload part');
|
|
42
50
|
return json(`${path(id)}/parts/${number}`, { method: 'PUT', headers: { 'content-type': 'application/octet-stream', 'x-content-sha256': await digest(body) }, body, signal });
|
|
43
51
|
},
|
|
44
|
-
async uploadResumable(name, value, { contentType, signal, sessionId, expectedVersion, onSession, onProgress } = {}) {
|
|
52
|
+
async uploadResumable(name, value, { contentType, signal, sessionId, id, expectedVersion, onSessionId, onSession, onProgress } = {}) {
|
|
53
|
+
validateName(name);
|
|
54
|
+
if (sessionId !== undefined && id !== undefined)
|
|
55
|
+
throw new Error('Use either sessionId to resume or id for idempotent creation');
|
|
45
56
|
const type = contentType ?? (value instanceof Blob && value.type ? value.type : 'application/octet-stream');
|
|
46
57
|
const body = blobOf(value, type);
|
|
47
|
-
let session
|
|
58
|
+
let session;
|
|
59
|
+
if (sessionId !== undefined)
|
|
60
|
+
session = await methods.getUpload(sessionId, { signal });
|
|
61
|
+
else {
|
|
62
|
+
const recoveryId = id ?? crypto.randomUUID();
|
|
63
|
+
if (!idPattern.test(recoveryId))
|
|
64
|
+
throw new Error('Invalid upload session ID');
|
|
65
|
+
signal?.throwIfAborted();
|
|
66
|
+
await onSessionId?.(recoveryId);
|
|
67
|
+
try {
|
|
68
|
+
session = await methods.startUpload(name, { size: body.size, contentType: type, expectedVersion, id: recoveryId, signal });
|
|
69
|
+
}
|
|
70
|
+
catch (cause) {
|
|
71
|
+
throw new UploadSessionStartError(recoveryId, cause);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
48
74
|
if (session.name !== name || session.size !== body.size || session.content_type !== type)
|
|
49
75
|
throw new Error('Upload session does not match this file');
|
|
50
76
|
await onSession?.(session);
|