@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.
Files changed (57) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1031 -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 +53 -0
  8. package/dist/cursor-token.js +179 -0
  9. package/dist/cursor.d.ts +45 -0
  10. package/dist/cursor.js +78 -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/exact-numeric.d.ts +15 -0
  16. package/dist/exact-numeric.js +125 -0
  17. package/dist/index.d.ts +49 -0
  18. package/dist/index.js +39 -0
  19. package/dist/indexeddb-mutation-store.d.ts +12 -0
  20. package/dist/indexeddb-mutation-store.js +139 -0
  21. package/dist/json.d.ts +39 -0
  22. package/dist/json.js +39 -0
  23. package/dist/live/client.d.ts +192 -0
  24. package/dist/live/client.js +555 -0
  25. package/dist/live/index.d.ts +31 -0
  26. package/dist/live/index.js +28 -0
  27. package/dist/live/protocol.d.ts +125 -0
  28. package/dist/live/protocol.js +271 -0
  29. package/dist/live/react.d.ts +22 -0
  30. package/dist/live/react.js +59 -0
  31. package/dist/live/seal.d.ts +38 -0
  32. package/dist/live/seal.js +98 -0
  33. package/dist/live/sql.d.ts +11 -0
  34. package/dist/live/sql.js +58 -0
  35. package/dist/mutation-journal.d.ts +78 -0
  36. package/dist/mutation-journal.js +223 -0
  37. package/dist/numeric.d.ts +11 -0
  38. package/dist/numeric.js +40 -0
  39. package/dist/optimistic.d.ts +24 -0
  40. package/dist/optimistic.js +18 -0
  41. package/dist/reconcile.d.ts +28 -0
  42. package/dist/reconcile.js +28 -0
  43. package/dist/replay-key.d.ts +8 -0
  44. package/dist/replay-key.js +27 -0
  45. package/dist/response.d.ts +33 -0
  46. package/dist/response.js +29 -0
  47. package/dist/rpc.d.ts +20 -0
  48. package/dist/rpc.js +31 -0
  49. package/dist/storage-uploads.d.ts +63 -0
  50. package/dist/storage-uploads.js +104 -0
  51. package/dist/storage.d.ts +74 -0
  52. package/dist/storage.js +89 -0
  53. package/dist/validation.d.ts +26 -0
  54. package/dist/validation.js +40 -0
  55. package/dist/versioned-mutation.d.ts +28 -0
  56. package/dist/versioned-mutation.js +13 -0
  57. package/package.json +19 -4
package/dist/rpc.js ADDED
@@ -0,0 +1,31 @@
1
+ /** Omits input and parser exceptions, which can contain private values. */
2
+ export class RpcValidationError extends Error {
3
+ code = 'RPC_ARGUMENT_VALIDATION_FAILED';
4
+ constructor() {
5
+ super('RPC argument validation failed');
6
+ this.name = 'RpcValidationError';
7
+ }
8
+ }
9
+ /** Parse untrusted arguments before constructing or executing an RPC query.
10
+ * The application parser owns validation, defaults and transformations. The
11
+ * query callback retains generated RPC argument and result inference, and may
12
+ * apply projections, cancellation or explicit retry settings. Server errors
13
+ * remain in the original result; thrown request errors propagate unchanged.
14
+ */
15
+ export async function validatedRpc(input, parser, createQuery) {
16
+ let args;
17
+ try {
18
+ args = parser.parse(input);
19
+ if (args !== null && (typeof args === 'object' || typeof args === 'function') && typeof args.then === 'function') {
20
+ void Promise.resolve(args).catch(() => { });
21
+ throw new Error();
22
+ }
23
+ if (args === null || typeof args !== 'object' || Array.isArray(args))
24
+ throw new Error();
25
+ }
26
+ catch {
27
+ return { outcome: 'validation_failed', error: new RpcValidationError() };
28
+ }
29
+ // Deliberately outside the parser catch: request failures are not validation failures.
30
+ return { outcome: 'completed', result: await createQuery(args) };
31
+ }
@@ -0,0 +1,63 @@
1
+ import type { StorageObject, StorageUploadBody } from './storage.js';
2
+ export type UploadSession = Readonly<{
3
+ id: string;
4
+ bucket: string;
5
+ name: string;
6
+ size: number;
7
+ content_type: string;
8
+ state: 'uploading' | 'finishing' | 'complete' | 'aborted';
9
+ expires_at: string;
10
+ chunk_size: number;
11
+ parts: ReadonlyArray<{
12
+ number: number;
13
+ size: number;
14
+ sha256: string;
15
+ }>;
16
+ object?: StorageObject;
17
+ }>;
18
+ export type ResumableUploadOptions = {
19
+ contentType?: string;
20
+ signal?: AbortSignal;
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>;
26
+ /** Undefined replaces unconditionally, null creates only, otherwise compare the previous version. */
27
+ expectedVersion?: string | null;
28
+ /** Persist this ID to resume without re-uploading acknowledged chunks. */
29
+ onSession?: (session: UploadSession) => void | Promise<void>;
30
+ onProgress?: (progress: {
31
+ sessionId: string;
32
+ uploaded: number;
33
+ total: number;
34
+ }) => void;
35
+ };
36
+ export declare class UploadSessionStartError extends Error {
37
+ readonly sessionId: string;
38
+ constructor(sessionId: string, cause: unknown);
39
+ }
40
+ export type StorageUploads = {
41
+ startUpload(name: string, options: {
42
+ size: number;
43
+ contentType?: string;
44
+ expectedVersion?: string | null;
45
+ id?: string;
46
+ signal?: AbortSignal;
47
+ }): Promise<UploadSession>;
48
+ getUpload(id: string, options?: {
49
+ signal?: AbortSignal;
50
+ }): Promise<UploadSession>;
51
+ abortUpload(id: string, options?: {
52
+ signal?: AbortSignal;
53
+ }): Promise<UploadSession>;
54
+ completeUpload(id: string, options?: {
55
+ signal?: AbortSignal;
56
+ }): Promise<UploadSession>;
57
+ uploadPart(id: string, number: number, body: Blob, options?: {
58
+ signal?: AbortSignal;
59
+ }): Promise<UploadSession>;
60
+ /** Stops on errors; call again with the saved sessionId to reconcile and resume. */
61
+ uploadResumable(name: string, body: StorageUploadBody, options?: ResumableUploadOptions): Promise<StorageObject>;
62
+ };
63
+ export declare function storageUploads(bucket: string, call: (path: string, init: RequestInit) => Promise<Response>, validateName: (name: string) => unknown): StorageUploads;
@@ -0,0 +1,104 @@
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
+ }
9
+ const idPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
10
+ function parseSession(value, bucket) {
11
+ const session = value;
12
+ if (!session || !idPattern.test(session.id) || session.bucket !== bucket || typeof session.name !== 'string' || !session.name || !Number.isSafeInteger(session.size) || session.size < 0 || session.size > 104857600 || session.chunk_size !== 5242880 || typeof session.content_type !== 'string' || !['uploading', 'finishing', 'complete', 'aborted'].includes(session.state) || !Number.isFinite(Date.parse(session.expires_at)) || !Array.isArray(session.parts) || session.parts.length > 20 || new Set(session.parts.map(p => p.number)).size !== session.parts.length || session.parts.some(p => !p || !Number.isInteger(p.number) || p.number < 1 || p.number > Math.ceil(session.size / session.chunk_size) || p.size !== Math.min(session.chunk_size, session.size - (p.number - 1) * session.chunk_size) || !/^[a-f0-9]{64}$/.test(p.sha256)))
13
+ throw new Error('Invalid upload session response');
14
+ if (session.state === 'complete' && (!session.object || session.object.bucket !== bucket || session.object.name !== session.name || session.object.size !== session.size))
15
+ throw new Error('Invalid upload receipt');
16
+ return session;
17
+ }
18
+ function blobOf(value, type) {
19
+ if (value instanceof Blob)
20
+ return value;
21
+ if (ArrayBuffer.isView(value))
22
+ return new Blob([new Uint8Array(value.buffer, value.byteOffset, value.byteLength).slice().buffer], { type });
23
+ return new Blob([value], { type });
24
+ }
25
+ async function digest(body) {
26
+ return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', await body.arrayBuffer())), byte => byte.toString(16).padStart(2, '0')).join('');
27
+ }
28
+ export function storageUploads(bucket, call, validateName) {
29
+ const path = (id) => {
30
+ if (!/^[a-z][a-z0-9_]{0,62}$/.test(bucket))
31
+ throw new Error('Invalid bucket name');
32
+ if (id !== undefined && !idPattern.test(id))
33
+ throw new Error('Invalid upload session ID');
34
+ return `upload/${bucket}${id ? `/${id}` : ''}`;
35
+ };
36
+ const json = async (target, init) => parseSession(await (await call(target, init)).json(), bucket);
37
+ const methods = {
38
+ async startUpload(name, { size, contentType = 'application/octet-stream', expectedVersion, id = crypto.randomUUID(), signal }) {
39
+ validateName(name);
40
+ if (!idPattern.test(id) || !Number.isSafeInteger(size) || size < 0 || size > 104857600 || (expectedVersion !== undefined && expectedVersion !== null && (typeof expectedVersion !== 'string' || !/^[0-9a-f]{32}$/.test(expectedVersion))))
41
+ throw new Error('Invalid upload session');
42
+ return json(path(), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id, name, size, content_type: contentType, ...(expectedVersion !== undefined ? { expected_version: expectedVersion } : {}) }), signal });
43
+ },
44
+ getUpload: async (id, { signal } = {}) => json(path(id), { method: 'GET', signal }),
45
+ abortUpload: async (id, { signal } = {}) => json(path(id), { method: 'DELETE', signal }),
46
+ completeUpload: async (id, { signal } = {}) => json(`${path(id)}/complete`, { method: 'POST', signal }),
47
+ async uploadPart(id, number, body, { signal } = {}) {
48
+ if (!Number.isInteger(number) || number < 1 || number > 20 || body.size > 5242880)
49
+ throw new Error('Invalid upload part');
50
+ return json(`${path(id)}/parts/${number}`, { method: 'PUT', headers: { 'content-type': 'application/octet-stream', 'x-content-sha256': await digest(body) }, body, signal });
51
+ },
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');
56
+ const type = contentType ?? (value instanceof Blob && value.type ? value.type : 'application/octet-stream');
57
+ const body = blobOf(value, type);
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
+ }
74
+ if (session.name !== name || session.size !== body.size || session.content_type !== type)
75
+ throw new Error('Upload session does not match this file');
76
+ await onSession?.(session);
77
+ if (session.state === 'aborted')
78
+ throw new Error('Upload session was aborted');
79
+ {
80
+ let uploaded = 0;
81
+ for (let offset = 0, number = 1; offset < body.size; offset += session.chunk_size, number++) {
82
+ signal?.throwIfAborted();
83
+ const part = body.slice(offset, offset + session.chunk_size);
84
+ const known = session.parts.find(p => p.number === number);
85
+ if (known && (known.size !== part.size || known.sha256 !== await digest(part)))
86
+ throw new Error('Upload session contains different file bytes');
87
+ if (!known) {
88
+ if (session.state !== 'uploading')
89
+ throw new Error('Upload receipt is missing a file checksum');
90
+ session = await methods.uploadPart(session.id, number, part, { signal });
91
+ }
92
+ uploaded += part.size;
93
+ onProgress?.({ sessionId: session.id, uploaded, total: body.size });
94
+ }
95
+ }
96
+ if (session.state !== 'complete')
97
+ session = await methods.completeUpload(session.id, { signal });
98
+ if (!session.object)
99
+ throw new Error('Upload receipt unavailable; reconcile the session before retrying');
100
+ return session.object;
101
+ },
102
+ };
103
+ return methods;
104
+ }
@@ -0,0 +1,74 @@
1
+ import { type DataClientOptions } from './client-fetch.js';
2
+ import { type StorageUploads } from './storage-uploads.js';
3
+ /**
4
+ * A stored file's row in storage_objects (ADR-20261021101510). The owner's
5
+ * row-level security policies on that table decide who may upload, download
6
+ * and remove each file.
7
+ */
8
+ export type StorageObject = Readonly<{
9
+ bucket: string;
10
+ name: string;
11
+ owner: string | null;
12
+ size: number;
13
+ content_type: string;
14
+ created_at: string;
15
+ updated_at: string;
16
+ /** Opaque version for conditional replacement; absent on older runtimes. */
17
+ version?: string | null;
18
+ }>;
19
+ /** A refused or failed storage request, with the Data API's stable code. */
20
+ export declare class StorageError extends Error {
21
+ readonly status: number;
22
+ readonly code: string;
23
+ readonly requestId: string | null;
24
+ /** Preserve the upload session and reconcile its receipt before retrying. */
25
+ readonly uncertain: boolean;
26
+ constructor(status: number, code: string, requestId: string | null);
27
+ }
28
+ export type StorageUploadBody = Blob | ArrayBuffer | ArrayBufferView | string;
29
+ export type StorageBucket = StorageUploads & {
30
+ /** Stores a file, replacing any file of the same name the caller may update. */
31
+ upload(name: string, body: StorageUploadBody, options?: {
32
+ contentType?: string;
33
+ signal?: AbortSignal;
34
+ }): Promise<StorageObject>;
35
+ /** Read the current opaque version before a conditional replacement. */
36
+ head(name: string, options?: {
37
+ signal?: AbortSignal;
38
+ }): Promise<{
39
+ size: number;
40
+ contentType: string;
41
+ version: string | null;
42
+ }>;
43
+ /** Fetches a file; read it with blob(), arrayBuffer() or its body stream. */
44
+ download(name: string, options?: {
45
+ range?: {
46
+ start: number;
47
+ end?: number;
48
+ };
49
+ signal?: AbortSignal;
50
+ }): Promise<Response>;
51
+ /** A link that works for 60 seconds without a token, for img, video and download links. */
52
+ signedUrl(name: string, options?: {
53
+ signal?: AbortSignal;
54
+ }): Promise<{
55
+ url: string;
56
+ expiresAt: string;
57
+ }>;
58
+ /** Removes a file. */
59
+ remove(name: string, options?: {
60
+ signal?: AbortSignal;
61
+ }): Promise<void>;
62
+ };
63
+ export type StorageClient = {
64
+ from(bucket: string): StorageBucket;
65
+ };
66
+ /**
67
+ * Files stored through the Data API, governed by the same tokens and RLS as
68
+ * its rows. Accepts the options of createDataClient.
69
+ *
70
+ * const storage = createStorageClient({ url, accessToken: () => session.token })
71
+ * await storage.from('uploads').upload(`${userId}/avatar.png`, file)
72
+ * const { url } = await storage.from('uploads').signedUrl(`${userId}/avatar.png`)
73
+ */
74
+ export declare function createStorageClient(options: DataClientOptions): StorageClient;
@@ -0,0 +1,89 @@
1
+ import { authenticatedFetch, dataAPIBase, requestIdOf } from './client-fetch.js';
2
+ import { storageUploads } from './storage-uploads.js';
3
+ /** A refused or failed storage request, with the Data API's stable code. */
4
+ export class StorageError extends Error {
5
+ status;
6
+ code;
7
+ requestId;
8
+ /** Preserve the upload session and reconcile its receipt before retrying. */
9
+ uncertain;
10
+ constructor(status, code, requestId) {
11
+ super(`storage request failed: ${code} (${status})`);
12
+ this.name = 'StorageError';
13
+ this.status = status;
14
+ this.code = code;
15
+ this.requestId = requestId;
16
+ this.uncertain = code === 'storage_commit_unknown';
17
+ }
18
+ }
19
+ const bucketPattern = /^[a-z][a-z0-9_]{0,62}$/;
20
+ function objectPath(bucket, name) {
21
+ if (!bucketPattern.test(bucket))
22
+ throw new Error('Invalid bucket name');
23
+ const segments = name.split('/');
24
+ if (!name || segments.some(s => s === '' || s === '.' || s === '..'))
25
+ throw new Error('Invalid object name');
26
+ return `${bucket}/${segments.map(encodeURIComponent).join('/')}`;
27
+ }
28
+ async function failure(response) {
29
+ let code = 'storage_request_failed';
30
+ try {
31
+ const body = await response.json();
32
+ if (typeof body.code === 'string')
33
+ code = body.code;
34
+ }
35
+ catch { /* The status still explains it. */ }
36
+ return new StorageError(response.status, code, requestIdOf(response));
37
+ }
38
+ /**
39
+ * Files stored through the Data API, governed by the same tokens and RLS as
40
+ * its rows. Accepts the options of createDataClient.
41
+ *
42
+ * const storage = createStorageClient({ url, accessToken: () => session.token })
43
+ * await storage.from('uploads').upload(`${userId}/avatar.png`, file)
44
+ * const { url } = await storage.from('uploads').signedUrl(`${userId}/avatar.png`)
45
+ */
46
+ export function createStorageClient(options) {
47
+ const base = `${dataAPIBase(options.url)}/storage/v1`;
48
+ const send = authenticatedFetch(options);
49
+ const call = async (path, init) => {
50
+ const response = await send(`${base}/${path}`, init);
51
+ if (!response.ok)
52
+ throw await failure(response);
53
+ return response;
54
+ };
55
+ return {
56
+ from(bucket) {
57
+ return {
58
+ ...storageUploads(bucket, call, name => objectPath(bucket, name)),
59
+ async upload(name, body, { contentType, signal } = {}) {
60
+ const type = contentType ?? (typeof Blob !== 'undefined' && body instanceof Blob && body.type ? body.type : 'application/octet-stream');
61
+ const response = await call(`object/${objectPath(bucket, name)}`, { method: 'PUT', body: body, headers: { 'Content-Type': type }, signal });
62
+ return await response.json();
63
+ },
64
+ async download(name, { range, signal } = {}) {
65
+ const headers = {};
66
+ if (range) {
67
+ if (!Number.isSafeInteger(range.start) || range.start < 0 || (range.end !== undefined && (!Number.isSafeInteger(range.end) || range.end < range.start)))
68
+ throw new Error('Invalid range');
69
+ headers.Range = `bytes=${range.start}-${range.end ?? ''}`;
70
+ }
71
+ return call(`object/${objectPath(bucket, name)}`, { method: 'GET', headers, signal });
72
+ },
73
+ async head(name, { signal } = {}) {
74
+ const response = await call(`object/${objectPath(bucket, name)}`, { method: 'HEAD', signal });
75
+ const version = response.headers.get('x-gregale-storage-version');
76
+ return { size: Number(response.headers.get('content-length')), contentType: response.headers.get('content-type') ?? 'application/octet-stream', version: version && /^[a-f0-9]{32}$/.test(version) ? version : null };
77
+ },
78
+ async signedUrl(name, { signal } = {}) {
79
+ const response = await call(`sign/${objectPath(bucket, name)}`, { method: 'POST', signal });
80
+ const body = await response.json();
81
+ return { url: body.url, expiresAt: body.expires_at };
82
+ },
83
+ async remove(name, { signal } = {}) {
84
+ await call(`object/${objectPath(bucket, name)}`, { method: 'DELETE', signal });
85
+ },
86
+ };
87
+ },
88
+ };
89
+ }
@@ -0,0 +1,26 @@
1
+ /** A synchronous parser, such as a Zod schema. Null fields are passed through it. */
2
+ export type JsonParser<Output = unknown> = {
3
+ parse(value: unknown): Output;
4
+ };
5
+ type Parsers = Record<string, JsonParser>;
6
+ type Row<Data> = NonNullable<Data> extends readonly (infer Item)[] ? Item : NonNullable<Data>;
7
+ type CheckedParsers<Data, Fields extends Parsers> = {
8
+ [Key in keyof Fields]: Key extends string ? Key extends keyof Row<Data> ? Extract<ReturnType<Fields[Key]['parse']>, PromiseLike<unknown>> extends never ? Fields[Key] : never : never : never;
9
+ };
10
+ type Parsed<Row, Fields extends Parsers> = Omit<Row, keyof Fields> & {
11
+ -readonly [Key in keyof Fields]: ReturnType<Fields[Key]['parse']>;
12
+ };
13
+ export type ValidatedJson<Data, Fields extends Parsers> = Data extends null ? null : Data extends readonly (infer Item)[] ? Parsed<Item, Fields>[] : Parsed<Data, Fields>;
14
+ /** Deliberately omits the input and original parser error, which may contain secrets. */
15
+ export declare class JsonValidationError extends Error {
16
+ readonly rowIndex: number | null;
17
+ readonly field: string;
18
+ readonly code = "JSON_VALIDATION_FAILED";
19
+ constructor(rowIndex: number | null, field: string);
20
+ }
21
+ /** Validate selected top-level fields without mutating the input.
22
+ * Call after checking the query error. A null single-row result stays null.
23
+ * Array row indexes in errors are zero-based; single-row errors use null.
24
+ */
25
+ export declare function validateJson<Data extends object | readonly object[] | null, const Fields extends Parsers>(data: Data, fields: Fields & CheckedParsers<Data, Fields> & (string extends keyof Fields ? never : unknown)): ValidatedJson<Data, Fields>;
26
+ export {};
@@ -0,0 +1,40 @@
1
+ /** Deliberately omits the input and original parser error, which may contain secrets. */
2
+ export class JsonValidationError extends Error {
3
+ rowIndex;
4
+ field;
5
+ code = 'JSON_VALIDATION_FAILED';
6
+ constructor(rowIndex, field) {
7
+ super(`JSON validation failed at ${rowIndex === null ? 'row' : `row ${rowIndex}`}, field ${JSON.stringify(field)}`);
8
+ this.rowIndex = rowIndex;
9
+ this.field = field;
10
+ this.name = 'JsonValidationError';
11
+ }
12
+ }
13
+ /** Validate selected top-level fields without mutating the input.
14
+ * Call after checking the query error. A null single-row result stays null.
15
+ * Array row indexes in errors are zero-based; single-row errors use null.
16
+ */
17
+ export function validateJson(data, fields) {
18
+ const entries = Object.entries(fields);
19
+ const parseRow = (row, index) => {
20
+ const result = { ...row };
21
+ for (const [field, parser] of entries) {
22
+ try {
23
+ if (!Object.hasOwn(row, field))
24
+ throw new Error();
25
+ const value = parser.parse(row[field]);
26
+ if (value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function') {
27
+ // Avoid an unhandled rejection from an accidentally asynchronous parser.
28
+ void Promise.resolve(value).catch(() => { });
29
+ throw new Error();
30
+ }
31
+ Object.defineProperty(result, field, { value, enumerable: true, writable: true, configurable: true });
32
+ }
33
+ catch {
34
+ throw new JsonValidationError(index, field);
35
+ }
36
+ }
37
+ return result;
38
+ };
39
+ return (data === null ? null : Array.isArray(data) ? data.map((row, index) => parseRow(row, index)) : parseRow(data, null));
40
+ }
@@ -0,0 +1,28 @@
1
+ import { type MutationReconciliation } from './reconcile.js';
2
+ export type VersionedMutationResult<Row, Error> = {
3
+ outcome: 'applied';
4
+ row: Row;
5
+ status: number;
6
+ } | {
7
+ outcome: 'version_conflict';
8
+ error: Error;
9
+ status: number;
10
+ } | Exclude<MutationReconciliation<Row, Error>, {
11
+ outcome: 'confirmed';
12
+ }>;
13
+ /** Classify a completed v2 conditional-write response, without executing or
14
+ * retrying a request. matches must bind its selected snapshot to the original
15
+ * identity, target and expected result. Missing rows and expired keys remain
16
+ * unresolved; neither permits replacing the original pending operation.
17
+ * Use reconcileMutation for read-only receipt lookups.
18
+ */
19
+ export declare function classifyVersionedMutation<Row, Error, Matched extends Row>(response: {
20
+ data: Row[] | null;
21
+ error: Error | null;
22
+ status: number;
23
+ }, matches: (row: Row) => row is Matched): VersionedMutationResult<Matched, Error>;
24
+ export declare function classifyVersionedMutation<Row, Error>(response: {
25
+ data: Row[] | null;
26
+ error: Error | null;
27
+ status: number;
28
+ }, matches: (row: Row) => boolean): VersionedMutationResult<Row, Error>;
@@ -0,0 +1,13 @@
1
+ import { reconcileMutation } from './reconcile.js';
2
+ export function classifyVersionedMutation(response, matches) {
3
+ const { error, status } = response;
4
+ if (status === 409 && error !== null && typeof error === 'object' &&
5
+ 'code' in error && error.code === 'PT409' &&
6
+ 'message' in error && error.message === 'idempotency_version_conflict') {
7
+ return { outcome: 'version_conflict', error, status };
8
+ }
9
+ const result = reconcileMutation(response, matches);
10
+ return result.outcome === 'confirmed'
11
+ ? { outcome: 'applied', row: result.row, status: result.status }
12
+ : result;
13
+ }
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "@gregale/data",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Typed PostgreSQL Data API client for Gregale",
5
+ "license": "Apache-2.0",
6
+ "publishConfig": {"access": "public"},
7
+ "type": "module",
8
+ "types": "./dist/index.d.ts",
9
+ "files": ["dist", "README.md", "LICENSE"],
10
+ "engines": {"node": ">=22"},
11
+ "exports": {
12
+ ".": {"types": "./dist/index.d.ts", "import": "./dist/index.js"},
13
+ "./live": {"types": "./dist/live/index.d.ts", "import": "./dist/live/index.js"},
14
+ "./live/react": {"types": "./dist/live/react.d.ts", "import": "./dist/live/react.js"}
15
+ },
16
+ "scripts": {"build": "tsc -p tsconfig.json", "test": "npm run build && tsc -p tsconfig.declarations.json && tsc -p tsconfig.test.json && node --test test/*.test.mjs"},
17
+ "dependencies": {"@supabase/postgrest-js": "2.117.3"},
18
+ "peerDependencies": {"react": ">=18"},
19
+ "peerDependenciesMeta": {"react": {"optional": true}},
20
+ "devDependencies": {"@types/react": "19.1.8", "@types/react-dom": "19.1.6", "react": "19.1.0", "react-dom": "19.1.0", "typescript": "5.9.3"}
21
+ }