@sequenceholdings/orm 2.6.0 → 2.6.2
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 +32 -1
- package/dist/client.cjs +79 -13
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +22 -3
- package/dist/client.d.ts +22 -3
- package/dist/client.js +79 -13
- package/dist/client.js.map +1 -1
- package/package.json +1 -1
- package/templates/orm-namespace/package.json +2 -0
- package/templates/orm-namespace/schema/tables.ts +7 -3
package/README.md
CHANGED
|
@@ -131,7 +131,7 @@ Execute uses the `/_data/v2` endpoint by default. Set
|
|
|
131
131
|
`SEQUENCE_ORM_ATLAS_EXECUTE_V2=1` to opt into Atlas's `/api/data/v2` endpoint.
|
|
132
132
|
This client rollout switch does not bypass server feature flags or authorization.
|
|
133
133
|
|
|
134
|
-
## Default read-only SQL (
|
|
134
|
+
## Default read-only SQL (introduced in 2.6.0)
|
|
135
135
|
|
|
136
136
|
With the matching SDK and Atlas rollout, every active v2 namespace supports
|
|
137
137
|
runtime-supplied SQL without an authored operation or Function:
|
|
@@ -154,6 +154,37 @@ Separate protected execution targets cannot be joined. Existing registered
|
|
|
154
154
|
operations remain supported; supply a manifest when executing them by name.
|
|
155
155
|
Source versions alone do not prove package publication or server availability.
|
|
156
156
|
|
|
157
|
+
## Source-publication read receipts (planned 2.6.2)
|
|
158
|
+
|
|
159
|
+
The upcoming `@sequenceholdings/orm/client` factories add
|
|
160
|
+
`executeWithReadReceipt()` for reads enrolled in a host publication guard.
|
|
161
|
+
Confirm package publication and the matching host rollout before using it.
|
|
162
|
+
The method accepts only queries classified by the supplied manifest or the
|
|
163
|
+
built-in SQL read. Known mutations, conflicting classifications and unclassified
|
|
164
|
+
raw or typed selectors fail locally with `OrmClientError` before dispatch.
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
const first = await db.executeWithReadReceipt('ReadSourcePage', { after: null })
|
|
168
|
+
const next = await db.executeWithReadReceipt('ReadSourcePage', { after: cursor }, {
|
|
169
|
+
expectedSourceGeneration: first.sourceGeneration,
|
|
170
|
+
})
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The result is `{ data, sourceGeneration }`. Treat the lowercase 64-character
|
|
174
|
+
hexadecimal receipt as opaque. The host binds it to the authenticated actor,
|
|
175
|
+
database and validated publication, and checks continuation inside the same
|
|
176
|
+
locked read-only repeatable-read transaction as the query. Current permissions
|
|
177
|
+
and row policies are checked again on every request. A receipt can cross
|
|
178
|
+
admitted operations for the same publication, but it does not preserve a row
|
|
179
|
+
snapshot: mutable data can change between reads without a new publication.
|
|
180
|
+
|
|
181
|
+
Missing, malformed or mismatched acknowledgements fail with
|
|
182
|
+
`OrmOperationError` / `OBJECT_UNAVAILABLE`. Unsupported scopes, explain and
|
|
183
|
+
mutations cannot use continuation. Do not retry without the expectation when
|
|
184
|
+
that would combine different source publications. Plain `execute()` still
|
|
185
|
+
returns only data; supplying `expectedSourceGeneration` also requires a valid
|
|
186
|
+
matching acknowledgement. Existing calls without that option are unchanged.
|
|
187
|
+
|
|
157
188
|
## Public exports
|
|
158
189
|
|
|
159
190
|
- `@sequenceholdings/orm/authoring` — namespace, table, policy, and view DSL
|
package/dist/client.cjs
CHANGED
|
@@ -193,6 +193,20 @@ function readOperationResponse({
|
|
|
193
193
|
}
|
|
194
194
|
return payload.data;
|
|
195
195
|
}
|
|
196
|
+
function readOperationResponseWithReceipt({
|
|
197
|
+
ok,
|
|
198
|
+
status,
|
|
199
|
+
body,
|
|
200
|
+
expectedSourceGeneration
|
|
201
|
+
}) {
|
|
202
|
+
const data = readOperationResponse({ ok, status, body });
|
|
203
|
+
const extensions = isRecord(body) && isRecord(body.extensions) ? body.extensions : null;
|
|
204
|
+
const sourceGeneration = extensions?.sourceGeneration;
|
|
205
|
+
if (typeof sourceGeneration !== "string" || !/^[a-f0-9]{64}$/.test(sourceGeneration) || expectedSourceGeneration !== void 0 && expectedSourceGeneration !== sourceGeneration) {
|
|
206
|
+
throw new OrmOperationError("Source generation unavailable", status, "OBJECT_UNAVAILABLE");
|
|
207
|
+
}
|
|
208
|
+
return { data, sourceGeneration };
|
|
209
|
+
}
|
|
196
210
|
|
|
197
211
|
// src/client/sql.ts
|
|
198
212
|
var BUILTIN_SQL_READ_HASH = "sha256:a50c477c952a5e0fe68ed158a4530e4aab573c09bcbb1a8ac454dc88a39a6258";
|
|
@@ -203,6 +217,11 @@ function validateIdempotencyKey(key) {
|
|
|
203
217
|
throw new OrmClientError("idempotencyKey must be 1\u2013128 letters, digits, dots, underscores, colons or hyphens");
|
|
204
218
|
}
|
|
205
219
|
}
|
|
220
|
+
function validateExpectedSourceGeneration(value) {
|
|
221
|
+
if (value !== void 0 && (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value))) {
|
|
222
|
+
throw new OrmClientError("expectedSourceGeneration must be a lowercase 64-character hexadecimal receipt");
|
|
223
|
+
}
|
|
224
|
+
}
|
|
206
225
|
var dataPlanePath = (namespace) => `/_data/v2/${namespace}`;
|
|
207
226
|
function resolveOpHash(manifest, op) {
|
|
208
227
|
if (op.startsWith("sha256:")) return op;
|
|
@@ -215,6 +234,23 @@ function resolveOpHash(manifest, op) {
|
|
|
215
234
|
}
|
|
216
235
|
return entry.hash;
|
|
217
236
|
}
|
|
237
|
+
function createReadReceiptOperationResolver({ operations }) {
|
|
238
|
+
const hashesByName = /* @__PURE__ */ new Map();
|
|
239
|
+
const readHashes = /* @__PURE__ */ new Set([BUILTIN_SQL_READ_HASH]);
|
|
240
|
+
const mutationHashes = /* @__PURE__ */ new Set();
|
|
241
|
+
for (const [name, entry] of operations) {
|
|
242
|
+
hashesByName.set(name, entry.hash);
|
|
243
|
+
if (entry.kind === "query" && /^sha256:[a-f0-9]{64}$/.test(entry.hash)) readHashes.add(entry.hash);
|
|
244
|
+
if (entry.kind === "mutation") mutationHashes.add(entry.hash);
|
|
245
|
+
}
|
|
246
|
+
return ({ selector, hashOnly = false }) => {
|
|
247
|
+
const hash = selector.startsWith("sha256:") ? selector : hashOnly ? void 0 : hashesByName.get(selector);
|
|
248
|
+
if (!hash || !readHashes.has(hash) || mutationHashes.has(hash)) {
|
|
249
|
+
throw new OrmClientError("read receipts require a registered query or the built-in SQL read");
|
|
250
|
+
}
|
|
251
|
+
return hash;
|
|
252
|
+
};
|
|
253
|
+
}
|
|
218
254
|
function createOperationExecutor({
|
|
219
255
|
baseUrl,
|
|
220
256
|
namespace,
|
|
@@ -228,25 +264,42 @@ function createOperationExecutor({
|
|
|
228
264
|
throw new OrmClientError("provide exactly one of getToken (bearer) or getDataToken (delegated)");
|
|
229
265
|
}
|
|
230
266
|
const root = baseUrl.replace(/\/+$/, "");
|
|
231
|
-
|
|
267
|
+
const resolveReceiptOperation = createReadReceiptOperationResolver({ operations: Object.entries(manifest.operations) });
|
|
268
|
+
async function request({ op, variables, options, requireReadReceipt = false }) {
|
|
232
269
|
validateIdempotencyKey(options.idempotencyKey);
|
|
270
|
+
validateExpectedSourceGeneration(options.expectedSourceGeneration);
|
|
233
271
|
if (typeof op !== "string" && op.namespace !== namespace) throw new OrmClientError("operation belongs to a different namespace");
|
|
234
|
-
const hash = typeof op === "string" ? resolveOpHash(manifest, op) : op.hash;
|
|
272
|
+
const hash = requireReadReceipt ? resolveReceiptOperation({ selector: typeof op === "string" ? op : op.hash, hashOnly: typeof op !== "string" }) : typeof op === "string" ? resolveOpHash(manifest, op) : op.hash;
|
|
235
273
|
const token = await (getDataToken ?? getToken)();
|
|
236
274
|
if (!token) throw new OrmClientError("not authenticated \u2014 no token available");
|
|
237
275
|
const auth = getDataToken ? { [ORM_DATA_TOKEN_HEADER]: token } : { Authorization: `Bearer ${token}` };
|
|
238
276
|
const response = await fetchImpl(`${root}${dataPlanePath(namespace)}`, {
|
|
239
277
|
method: "POST",
|
|
240
278
|
headers: { ...auth, "Content-Type": "application/json" },
|
|
241
|
-
body: JSON.stringify({
|
|
279
|
+
body: JSON.stringify({
|
|
280
|
+
op: hash,
|
|
281
|
+
variables,
|
|
282
|
+
idempotencyKey: options.idempotencyKey,
|
|
283
|
+
expectedSourceGeneration: options.expectedSourceGeneration
|
|
284
|
+
})
|
|
242
285
|
});
|
|
243
|
-
return
|
|
286
|
+
return {
|
|
244
287
|
ok: response.ok,
|
|
245
288
|
status: response.status,
|
|
246
289
|
body: await response.json().catch(() => null)
|
|
247
|
-
}
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
async function execute(op, variables = {}, options = {}) {
|
|
293
|
+
const executionOptions = { ...options };
|
|
294
|
+
const response = await request({ op, variables, options: executionOptions });
|
|
295
|
+
return executionOptions.expectedSourceGeneration === void 0 ? readOperationResponse(response) : readOperationResponseWithReceipt({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration }).data;
|
|
296
|
+
}
|
|
297
|
+
async function executeWithReadReceipt(op, variables = {}, options = {}) {
|
|
298
|
+
const executionOptions = { ...options };
|
|
299
|
+
const response = await request({ op, variables, options: executionOptions, requireReadReceipt: true });
|
|
300
|
+
return readOperationResponseWithReceipt({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration });
|
|
248
301
|
}
|
|
249
|
-
return { execute, sql: (variables) => execute(BUILTIN_SQL_READ_HASH, variables) };
|
|
302
|
+
return { execute, executeWithReadReceipt, sql: (variables) => execute(BUILTIN_SQL_READ_HASH, variables) };
|
|
250
303
|
}
|
|
251
304
|
var configured = null;
|
|
252
305
|
function configureOrmOperations(config) {
|
|
@@ -315,33 +368,46 @@ function readManifestHashes(manifest) {
|
|
|
315
368
|
if (!/^[_A-Za-z][_0-9A-Za-z]*$/.test(name) || !isRecord(entry) || typeof entry.hash !== "string" || !operationHash.test(entry.hash) || entry.kind !== "query" && entry.kind !== "mutation") {
|
|
316
369
|
throw new OrmClientError(`invalid operations manifest entry "${name}" \u2014 regenerate the manifest`);
|
|
317
370
|
}
|
|
318
|
-
hashes.set(name, entry.hash);
|
|
371
|
+
hashes.set(name, { hash: entry.hash, kind: entry.kind });
|
|
319
372
|
}
|
|
320
373
|
return hashes;
|
|
321
374
|
}
|
|
322
375
|
function createOperationExecutorWithTransport({ namespace, manifest, transport }) {
|
|
323
376
|
if (typeof namespace !== "string" || !NAMESPACE_PATTERN.test(namespace)) throw new OrmClientError("invalid ORM namespace \u2014 expected a lowercase identifier of at most 41 characters");
|
|
324
377
|
const hashes = manifest === void 0 ? /* @__PURE__ */ new Map() : readManifestHashes(manifest);
|
|
325
|
-
const knownHashes = new Set(hashes.values());
|
|
326
|
-
|
|
378
|
+
const knownHashes = new Set([...hashes.values()].map((entry) => entry.hash));
|
|
379
|
+
const resolveReceiptOperation = createReadReceiptOperationResolver({ operations: hashes });
|
|
380
|
+
async function request({ op, variables, options, requireReadReceipt = false }) {
|
|
327
381
|
validateIdempotencyKey(options.idempotencyKey);
|
|
382
|
+
validateExpectedSourceGeneration(options.expectedSourceGeneration);
|
|
328
383
|
if (typeof op !== "string" && op.namespace !== namespace) throw new OrmClientError("operation belongs to a different namespace");
|
|
329
384
|
const selector = typeof op === "string" ? op : op.hash;
|
|
330
|
-
const hash = selector === BUILTIN_SQL_READ_HASH ? selector : hashes.get(selector) ?? (knownHashes.has(selector) ? selector : void 0);
|
|
385
|
+
const hash = requireReadReceipt ? resolveReceiptOperation({ selector, hashOnly: typeof op !== "string" }) : selector === BUILTIN_SQL_READ_HASH ? selector : hashes.get(selector)?.hash ?? (knownHashes.has(selector) ? selector : void 0);
|
|
331
386
|
if (!hash) throw new OrmClientError(`unknown operation "${op}" \u2014 not in the manifest (${hashes.size} known). Re-run seq-studio orm generate.`);
|
|
332
387
|
if (!isRecord(variables)) throw new OrmClientError("operation variables must be an object");
|
|
333
388
|
const response = await transport({
|
|
334
389
|
namespace,
|
|
335
390
|
op: hash,
|
|
336
391
|
variables,
|
|
337
|
-
...options.idempotencyKey === void 0 ? {} : { idempotencyKey: options.idempotencyKey }
|
|
392
|
+
...options.idempotencyKey === void 0 ? {} : { idempotencyKey: options.idempotencyKey },
|
|
393
|
+
...options.expectedSourceGeneration === void 0 ? {} : { expectedSourceGeneration: options.expectedSourceGeneration }
|
|
338
394
|
});
|
|
339
395
|
if (!response || typeof response.ok !== "boolean" || !Number.isInteger(response.status) || response.status < 100 || response.status > 599 || response.ok !== (response.status >= 200 && response.status < 300)) {
|
|
340
396
|
throw new OrmOperationError("malformed transport response", null, null);
|
|
341
397
|
}
|
|
342
|
-
return
|
|
398
|
+
return response;
|
|
399
|
+
}
|
|
400
|
+
async function execute(op, variables = {}, options = {}) {
|
|
401
|
+
const executionOptions = { ...options };
|
|
402
|
+
const response = await request({ op, variables, options: executionOptions });
|
|
403
|
+
return executionOptions.expectedSourceGeneration === void 0 ? readOperationResponse(response) : readOperationResponseWithReceipt({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration }).data;
|
|
404
|
+
}
|
|
405
|
+
async function executeWithReadReceipt(op, variables = {}, options = {}) {
|
|
406
|
+
const executionOptions = { ...options };
|
|
407
|
+
const response = await request({ op, variables, options: executionOptions, requireReadReceipt: true });
|
|
408
|
+
return readOperationResponseWithReceipt({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration });
|
|
343
409
|
}
|
|
344
|
-
return { execute, sql: (variables) => execute(BUILTIN_SQL_READ_HASH, variables) };
|
|
410
|
+
return { execute, executeWithReadReceipt, sql: (variables) => execute(BUILTIN_SQL_READ_HASH, variables) };
|
|
345
411
|
}
|
|
346
412
|
|
|
347
413
|
// src/client/index.ts
|
package/dist/client.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/constants.ts","../src/client/errors.ts","../src/client/transport.ts","../src/client/query-builder.ts","../src/client/response.ts","../src/client/sql.ts","../src/client/operations.ts","../src/client/transport-executor.ts","../src/client/index.ts"],"names":[],"mappings":";;;AAIO,IAAM,iBAAA,GAAoB;AAG1B,IAAM,qBAAA,GAAwB;AAG9B,IAAM,6BAAA,GAAgC;AAwGtC,IAAM,iBAAA,GAAoB,iBAAA;AACM,IAAA,CAAK,SA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","sourcesContent":["/** Shared grammar for namespace identifiers; never interpolate arbitrary paths.\n * orm_events and orm_native_sources are migration-owned control-plane schemas,\n * not builder namespaces. Exclude their suffixes at every API/authoring entry.\n */\nexport const NAMESPACE_PATTERN = /^(?!(?:events|native_sources)$)[a-z][a-z0-9_]{0,40}$/\n\n/** Caller-scoped delegated data credential, supplied by an authenticated host. */\nexport const ORM_DATA_TOKEN_HEADER = 'x-sequence-data-token'\n\n/** Separate service-identity credential; never used as an implicit fallback. */\nexport const ORM_SERVICE_DATA_TOKEN_HEADER = 'x-sequence-data-token-service'\n\nexport const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/\n/** Native source columns may have one leading underscore; relation names may not. */\nexport const COLUMN_IDENTIFIER_PATTERN = /^_?[a-z][a-z0-9_]*$/\nexport const MAX_IDENTIFIER_LENGTH = 63\n\n/**\n * Custom Roles & Capabilities claim keys as policies reference them: a\n * host-scoped registry key, an org pin's `org/<key>`, or an Application\n * capability pin's `app/<application-id>/<key>`. Matches the registry\n * key grammar EXACTLY (`[a-z0-9-]`, 1–64 chars, no `_` — the FGA object-id\n * delimiter) so any capability that's declarable/attachable in namespace.yaml\n * can also be referenced here — a stricter pattern would let a valid key\n * register yet fail at apply (e.g. `org/2fa`, a one-char or digit-led key).\n */\nexport const CAPABILITY_KEY_PATTERN = /^(?:org\\/|app\\/[a-z][a-z0-9-]{0,63}\\/)?[a-z0-9-]{1,64}$/\n\n/** Hard ceiling for an explicitly authored flat persisted GraphQL read. */\nexport const MAX_PERSISTED_READ_ROWS = 50_001\n\nexport const CLAIM_KEY_PATTERN = /^[a-z][a-z0-9_]*$/\n\n/** Qualified reference to a table outside the defining file: `<schema>.<table>`. */\nexport const QUALIFIED_TABLE_PATTERN = /^[a-z][a-z0-9_]{0,62}\\.[a-z][a-z0-9_]{0,62}$/\n\n/** Qualified source syntax only; the serving installation controls authorized backing. */\nexport const SYNCED_SOURCE_PATTERN = QUALIFIED_TABLE_PATTERN\n\nexport const ORM_SCHEMA_PREFIX = 'orm_'\nexport const CONSUMER_ROLE_SUFFIX = '_consumer'\n\nexport const ormSchemaName = (namespace: string): string => {\n if (!NAMESPACE_PATTERN.test(namespace)) throw new Error(`invalid or reserved ORM namespace '${namespace}'`)\n return `${ORM_SCHEMA_PREFIX}${namespace}`\n}\nexport const consumerRoleName = (namespace: string): string =>\n `${ormSchemaName(namespace)}${CONSUMER_ROLE_SUFFIX}`\n\nexport const DEFINITION_FILE_EXTENSIONS = ['.yml', '.yaml'] as const\n\n/** Reserved basenames for the namespace-level config file (description, org capability pins). */\nexport const NAMESPACE_CONFIG_FILENAMES = new Set(['namespace.yaml', 'namespace.yml'])\n\nexport const HASH_DOMAIN = 'sequence-orm-definitions\\0'\n\n/**\n * A per-file byte cap where the loader reads untrusted YAML into memory — a real failure mode, not a product\n * limit. Counts of tables/indexes/params and policy/SQL lengths are\n * deliberately uncapped; Postgres enforces its own limits loudly at apply.\n */\nexport const MAX_DEFINITION_FILE_BYTES = 1024 * 1024\n\n/** Generated SDL aggregates every table/view; it is not an individual source file. */\nexport const MAX_GENERATED_SDL_BYTES = 16 * 1024 * 1024\n\n/** Registration and reviewed exports carry SDL, canonical metadata, snapshots and migrations. */\nexport const ORM_REGISTRATION_MAX_BYTES = 64 * 1024 * 1024\n\n/** `/api/data/<ns>/actions/…` and `/api/data/<ns>/query` share the table path segment. */\nexport const RESERVED_TABLE_NAMES = new Set(['actions', 'query'])\n\n/**\n * The Data API's query-string grammar owns these parameter names — a column\n * with one of them could never be filtered over the wire, so definitions\n * refuse it up front (\"validate rejects only what can never work\").\n */\nexport const RESERVED_COLUMN_NAMES = new Set(['select', 'order', 'limit', 'offset'])\n\n/**\n * Per-cell metadata (`cellMetadata: true`, and every resolved-table source) is\n * stored as typed system columns beside each tracked column `c`:\n *\n * - `c__at` timestamptz — when the cell was last written (NULL: never / no opinion)\n * - `c__by` text — who wrote it\n * - `c__rev` uuid — a resolved table's manual source only: the edit's\n * identity, so an async writeback confirmation clears\n * only the exact edit it delivered\n *\n * A resolved view additionally exposes, per resolved column, the winner's\n * `c__src` (source name) and `c__lost` (newer candidates that lost, jsonb).\n * None of these are GraphQL columns: they surface through the typed `cells`\n * object and are never client-writable.\n */\nexport const CELL_PARTS = ['at', 'by', 'rev', 'source', 'conflicts'] as const\nexport type CellPart = (typeof CELL_PARTS)[number]\nexport const CELL_PART_SUFFIX: Readonly<Record<CellPart, string>> = {\n at: '__at', by: '__by', rev: '__rev', source: '__src', conflicts: '__lost',\n}\n/** Longest physical column name that can carry cell parts (63 minus the longest suffix). */\nexport const MAX_TRACKED_COLUMN_NAME = MAX_IDENTIFIER_LENGTH - 6\n/** GraphQL field carrying a row's per-cell metadata object. */\nexport const CELLS_FIELD = 'cells'\n\n/** Physical (and logical) name of one cell part of a column. */\nexport function cellColumnName(column: string, part: CellPart): string {\n return `${column}${CELL_PART_SUFFIX[part]}`\n}\n\n/**\n * Actor recorded when the data plane computes a materialized resolved table's\n * rows for every caller. Its claims are what the compute view's synced\n * sources see (materialized ETL sources must be readable by anyone).\n */\nexport const MATERIALIZE_ACTOR = 'orm:materialize'\nexport const MATERIALIZE_CLAIMS_JSON = JSON.stringify({ sub: MATERIALIZE_ACTOR, org: null, roles: [], capabilities: [] })\n\n/**\n * Apply-generated function that reconciles a materialized resolved table with\n * its compute view: `SELECT * FROM orm_<ns>.\"<table>__refresh\"(wait)` returns\n * `(upserted, deleted, locked)`; without `wait` it skips when another refresh\n * holds the table's lock. The one refresh implementation — the Atlas\n * reconcile, the post-ETL hook, and an operator in psql all call it.\n */\nexport function materializedRefreshFunctionName(table: string): string {\n return `${table}__refresh`\n}\n\n/**\n * Advisory-lock key serializing a materialized table's refreshes (hashed with\n * `hashtext`). A full refresh holds it exclusively and every ORM write's\n * per-row refresh holds it shared, both before reading the compute view — so\n * a full refresh never reads a snapshot older than a write it then overwrites.\n */\nexport function materializeLockKey(schema: string, table: string): string {\n return `orm:materialize:${schema}.${table}`\n}\n","export class OrmClientError extends Error {\n override readonly name: string = 'OrmClientError'\n\n constructor(message: string, readonly status: number | null = null) {\n super(message)\n }\n}\n\nexport interface OperationErrorEntry {\n readonly message: string\n readonly extensions?: { readonly code?: string }\n}\n\nexport class OrmOperationError extends OrmClientError {\n override readonly name = 'OrmOperationError'\n\n constructor(\n message: string,\n status: number | null,\n readonly code: string | null,\n readonly errors: readonly OperationErrorEntry[] = [],\n ) {\n super(message, status)\n }\n}\n","/**\n * Fetch-based transport for the Data API. Deliberately free of node builtins\n * so the client runs anywhere a `fetch` exists — browsers, artifact bridges,\n * Cloud Functions, `node:vm` sandboxes.\n */\nimport { ORM_DATA_TOKEN_HEADER } from '../constants.js'\n\nimport { OrmClientError } from './errors.js'\nexport { OrmClientError } from './errors.js'\n\nexport interface OrmTransport {\n get(path: string, params: URLSearchParams): Promise<unknown>\n post(path: string, body: unknown): Promise<unknown>\n}\n\nexport function createFetchTransport({\n baseUrl,\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: {\n baseUrl: string\n /** App-user / session bearer → `Authorization: Bearer`. */\n getToken?: () => Promise<string | null> | string | null\n /** Delegated, attenuated function token → the `ORM_DATA_TOKEN_HEADER`. */\n getDataToken?: () => Promise<string | null> | string | null\n fetchImpl?: typeof globalThis.fetch\n}): OrmTransport {\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n\n const request = async (path: string, init: Omit<RequestInit, 'headers'>): Promise<unknown> => {\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n // The delegated token rides its own header; the app-user bearer rides Authorization.\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n const response = await fetchImpl(`${root}${path}`, {\n ...init,\n headers: { ...auth, 'Content-Type': 'application/json' },\n })\n const payload: unknown = await response.json().catch(() => null)\n if (!response.ok) {\n const detail =\n payload && typeof payload === 'object' && 'detail' in payload\n ? String((payload as { detail: unknown }).detail)\n : `HTTP ${response.status}`\n throw new OrmClientError(detail, response.status)\n }\n return payload\n }\n\n return {\n get: (path, params) => {\n // Not params.size — that's Node 19.8+/2023-browser surface, newer than\n // the fetch this module documents as its only requirement.\n const serialized = params.toString()\n return request(serialized === '' ? path : `${path}?${serialized}`, {})\n },\n post: (path, body) => request(path, { method: 'POST', body: JSON.stringify(body ?? {}) }),\n }\n}\n","import { OrmClientError, type OrmTransport } from './transport.js'\n\n/**\n * Fluent read query over one table. Serializes to exactly the PostgREST\n * subset the Data API's query parser accepts — the round-trip contract is\n * asserted server-side (builder output → parseReadQuery) so the two ends\n * can't drift apart silently.\n *\n * IMMUTABLE: every method returns a new query, so narrowing `select()` can\n * never leave an alias holding a stale wider row type, and a base query can\n * be safely forked into variants.\n */\n\nexport type FilterValue = string | number | boolean\n\nexport interface ReadResponse<Row> {\n readonly rows: readonly Row[]\n readonly limit: number\n readonly offset: number\n}\n\n/** Characters the in-list grammar cannot carry — there is no escaping, so the builder hard-fails. */\nconst IN_LIST_UNREPRESENTABLE = /[,()]/\n\ninterface QueryState {\n readonly filters: ReadonlyArray<[column: string, expression: string]>\n readonly orderings: readonly string[]\n readonly selection: readonly string[] | null\n readonly limitValue: number | null\n readonly offsetValue: number | null\n}\n\nconst EMPTY_STATE: QueryState = {\n filters: [],\n orderings: [],\n selection: null,\n limitValue: null,\n offsetValue: null,\n}\n\n/**\n * `Row` is the TABLE's row (filters and order always accept every column);\n * `Result` is what rows() yields — narrowed by select(), re-widenable by a\n * later select() since keys always come from Row.\n */\nexport class TableQuery<Row extends Record<string, unknown>, Result = Row> {\n constructor(\n private readonly transport: OrmTransport,\n private readonly namespace: string,\n private readonly table: string,\n private readonly state: QueryState = EMPTY_STATE,\n ) {}\n\n private with(patch: Partial<QueryState>): TableQuery<Row, Result> {\n return new TableQuery(this.transport, this.namespace, this.table, { ...this.state, ...patch })\n }\n\n select<K extends keyof Row & string>(...columns: [K, ...K[]]): TableQuery<Row, Pick<Row, K>> {\n return new TableQuery<Row, Pick<Row, K>>(this.transport, this.namespace, this.table, {\n ...this.state,\n selection: columns,\n })\n }\n\n eq<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'eq', value)\n }\n\n ne<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'ne', value)\n }\n\n gt<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'gt', value)\n }\n\n gte<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'gte', value)\n }\n\n lt<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'lt', value)\n }\n\n lte<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'lte', value)\n }\n\n like<K extends keyof Row & string>(column: K, pattern: string): TableQuery<Row, Result> {\n return this.filter(column, 'like', pattern)\n }\n\n ilike<K extends keyof Row & string>(column: K, pattern: string): TableQuery<Row, Result> {\n return this.filter(column, 'ilike', pattern)\n }\n\n in<K extends keyof Row & string>(column: K, values: readonly FilterValue[]): TableQuery<Row, Result> {\n // An empty list is representable — `in.()` matches nothing, the same\n // semantics the server executes. Blank entries are legitimate values in\n // multi-entry lists (`in.(a,)` carries ['a','']), but a LONE '' renders\n // as `in.()` and silently becomes the empty list — unrepresentable.\n // Beyond that only characters the grammar can't escape, and whitespace\n // padding the server-side split would silently swallow, are refused.\n const rendered = values.map((value) => {\n const text = String(value)\n if (IN_LIST_UNREPRESENTABLE.test(text) || text !== text.trim()) {\n throw new OrmClientError(`in() value '${text}' cannot be represented — the list grammar has no escaping`)\n }\n return text\n })\n if (rendered.length === 1 && rendered[0] === '') {\n throw new OrmClientError(\"in() with a lone '' cannot be represented — it would read as the empty list\")\n }\n return this.with({ filters: [...this.state.filters, [column, `in.(${rendered.join(',')})`]] })\n }\n\n is<K extends keyof Row & string>(column: K, value: null | boolean): TableQuery<Row, Result> {\n return this.with({\n filters: [...this.state.filters, [column, `is.${value === null ? 'null' : value}`]],\n })\n }\n\n order<K extends keyof Row & string>(column: K, direction: 'asc' | 'desc' = 'asc'): TableQuery<Row, Result> {\n return this.with({ orderings: [...this.state.orderings, `${column}.${direction}`] })\n }\n\n limit(value: number): TableQuery<Row, Result> {\n return this.with({ limitValue: value })\n }\n\n offset(value: number): TableQuery<Row, Result> {\n return this.with({ offsetValue: value })\n }\n\n /** The exact query string sent to the Data API — exposed for debugging and the grammar contract test. */\n searchParams(): URLSearchParams {\n const params = new URLSearchParams()\n for (const [column, expression] of this.state.filters) params.append(column, expression)\n if (this.state.orderings.length > 0) params.set('order', this.state.orderings.join(','))\n if (this.state.selection) params.set('select', this.state.selection.join(','))\n if (this.state.limitValue !== null) params.set('limit', String(this.state.limitValue))\n if (this.state.offsetValue !== null) params.set('offset', String(this.state.offsetValue))\n return params\n }\n\n async rows(): Promise<Result[]> {\n const payload = await this.transport.get(\n `/api/data/${this.namespace}/${this.table}`,\n this.searchParams(),\n )\n if (!payload || typeof payload !== 'object' || !Array.isArray((payload as { rows?: unknown }).rows)) {\n throw new OrmClientError('unexpected Data API response shape — missing rows array')\n }\n return (payload as { rows: Result[] }).rows\n }\n\n private filter(column: string, op: string, value: FilterValue): TableQuery<Row, Result> {\n return this.with({ filters: [...this.state.filters, [column, `${op}.${String(value)}`]] })\n }\n}\n","import { OrmOperationError, type OperationErrorEntry } from './errors.js'\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isOperationError(value: unknown): value is OperationErrorEntry {\n if (!isRecord(value) || typeof value.message !== 'string') return false\n if (value.extensions === undefined) return true\n return isRecord(value.extensions) && (value.extensions.code === undefined || typeof value.extensions.code === 'string')\n}\n\nexport function readOperationResponse<TData>({\n ok, status, body,\n}: { ok: boolean; status: number; body: unknown }): TData {\n const payload = isRecord(body) ? body : null\n const rawErrors = payload?.errors\n if (rawErrors !== undefined && (!Array.isArray(rawErrors) || !rawErrors.every(isOperationError))) {\n throw new OrmOperationError('malformed response: invalid errors', status, null)\n }\n const errors: OperationErrorEntry[] = rawErrors ?? []\n if (!ok || errors.length > 0) {\n const first = errors[0]\n throw new OrmOperationError(first?.message ?? `HTTP ${status}`, status, first?.extensions?.code ?? null, errors)\n }\n if (!payload || payload.data === undefined || payload.data === null) {\n throw new OrmOperationError('malformed response: missing data', status, null)\n }\n if (!isRecord(payload.data)) {\n throw new OrmOperationError('malformed response: data must be an object', status, null)\n }\n // Generated consumer types describe operation data; envelope validation\n // cannot prove an application's selection-specific TData at runtime.\n return payload.data as TData\n}\n","/** Runtime SQL inputs are values, never interpolated into the submitted SQL. */\n// SHA-256 of \"sequence-orm-builtin-sql-read-v1\". This identifies server-owned\n// behavior, independent of a namespace's authored operation manifest.\nexport const BUILTIN_SQL_READ_HASH = 'sha256:a50c477c952a5e0fe68ed158a4530e4aab573c09bcbb1a8ac454dc88a39a6258'\n\nexport type SqlQueryParameter =\n | { type: 'text' | 'uuid' | 'date' | 'timestamptz' | 'numeric' | 'bigint'; value: string | null }\n | { type: 'integer' | 'double'; value: number | null }\n | { type: 'boolean'; value: boolean | null }\n\nexport type SqlQueryVariables = {\n sql: string\n parameters?: Record<string, SqlQueryParameter>\n}\n\nexport interface SqlQueryResult {\n columns: Array<{ name: string; type: string; nullable: boolean }>\n rows: Array<Array<string | number | boolean | null>>\n truncated: boolean\n}\n","/**\n * Persisted-operation client for the v2 data plane. The wire carries only\n * `{ op: <hash>, variables, idempotencyKey? }`. Runtime SQL contracts accept SQL in variables;\n * GraphQL and fixed SQL operations keep their documents server-side. This runtime\n * is deliberately free of node builtins and third-\n * party deps (no @apollo/client import): Apollo integration happens through a\n * fetch-compatible shim (`createOrmFetch`) handed to `HttpLink({ fetch })`.\n */\nimport { OrmClientError } from './errors.js'\nimport { readOperationResponse } from './response.js'\nimport { ORM_DATA_TOKEN_HEADER } from '../constants.js'\nimport { BUILTIN_SQL_READ_HASH, type SqlQueryVariables, type SqlQueryResult } from './sql.js'\n\nexport { OrmOperationError, type OperationErrorEntry } from './errors.js'\n\n/** One entry of `operations.manifest.json` (generated by `orm generate`). */\nexport interface ManifestOperation {\n readonly hash: string\n readonly kind: 'query' | 'mutation'\n readonly requires: { readonly capability?: string; readonly role?: string } | null\n}\n\nexport interface OperationsManifest {\n readonly schemaHash: string\n readonly opsHash?: string\n readonly operations: Readonly<Record<string, ManifestOperation>>\n}\n\nexport interface OperationExecutorConfig {\n /** Deployment host root, e.g. `https://atlas.seqholdings.com`. */\n baseUrl: string\n namespace: string\n manifest?: OperationsManifest\n /** App-user / session bearer → `Authorization: Bearer`. */\n getToken?: () => Promise<string | null> | string | null\n /** Delegated, attenuated function token → the `ORM_DATA_TOKEN_HEADER`. */\n getDataToken?: () => Promise<string | null> | string | null\n fetchImpl?: typeof globalThis.fetch\n}\n\nexport interface OperationExecutionOptions {\n /** Reuse only when retrying the same logical mutation. */\n idempotencyKey?: string\n}\n\nexport function validateIdempotencyKey(key: string | undefined): void {\n if (key !== undefined && !/^[A-Za-z0-9._:-]{1,128}$/.test(key)) {\n throw new OrmClientError('idempotencyKey must be 1–128 letters, digits, dots, underscores, colons or hyphens')\n }\n}\n\nexport interface OperationExecutor {\n /** Execute a manifest operation by name (or a raw `sha256:` hash). */\n execute<TData = Record<string, unknown>>(\n op: string,\n variables?: Record<string, unknown>,\n options?: OperationExecutionOptions,\n ): Promise<TData>\n}\n\n/** Additive factory result; existing host wrappers implementing OperationExecutor remain valid. */\nexport interface SqlOperationExecutor extends OperationExecutor {\n /** Default read-only ontology SQL; no authored operation or manifest needed. */\n sql(variables: SqlQueryVariables): Promise<SqlQueryResult>\n}\n\nexport interface TypedOperationExecutor extends OperationExecutor {\n execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n}\n\n/** Factory result adds SQL without requiring it on existing typed host wrappers. */\nexport type TypedSqlOperationExecutor = TypedOperationExecutor & SqlOperationExecutor\n\nconst dataPlanePath = (namespace: string): string => `/_data/v2/${namespace}`\n\n/** Generated handle identifies the registered contract; optional types are phantom. */\nexport interface OperationReference<TVariables extends Record<string, unknown>, TData> {\n readonly namespace: string\n readonly hash: string\n readonly variables?: TVariables\n readonly result?: TData\n}\n\nfunction resolveOpHash(manifest: OperationsManifest, op: string): string {\n if (op.startsWith('sha256:')) return op\n const entry = manifest.operations[op]\n if (!entry) {\n const known = Object.keys(manifest.operations).sort()\n throw new OrmClientError(\n `unknown operation \"${op}\" — not in the manifest (${known.length} known). ` +\n 'Re-run `seq-studio orm generate` after editing graphql documents.',\n )\n }\n return entry.hash\n}\n\nexport function createOperationExecutor({\n baseUrl,\n namespace,\n manifest = { schemaHash: 'builtin', operations: {} },\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: OperationExecutorConfig): TypedSqlOperationExecutor {\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n\n function execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n function execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n async function execute<TData = Record<string, unknown>>(\n op: string | OperationReference<Record<string, unknown>, TData>,\n variables: Record<string, unknown> = {},\n options: OperationExecutionOptions = {},\n ): Promise<TData> {\n validateIdempotencyKey(options.idempotencyKey)\n if (typeof op !== 'string' && op.namespace !== namespace) throw new OrmClientError('operation belongs to a different namespace')\n const hash = typeof op === 'string' ? resolveOpHash(manifest, op) : op.hash\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n const response = await fetchImpl(`${root}${dataPlanePath(namespace)}`, {\n method: 'POST',\n headers: { ...auth, 'Content-Type': 'application/json' },\n body: JSON.stringify({ op: hash, variables, idempotencyKey: options.idempotencyKey }),\n })\n return readOperationResponse<TData>({\n ok: response.ok,\n status: response.status,\n body: await response.json().catch(() => null),\n })\n }\n return { execute, sql: variables => execute<SqlQueryResult>(BUILTIN_SQL_READ_HASH, variables) }\n}\n\n// ---------------------------------------------------------------------------\n// Module-level convenience for generated server functions (`db<Name>`)\n// ---------------------------------------------------------------------------\n\nlet configured: OperationExecutor | null = null\n\n/**\n * Configure the process-wide executor the generated `db<Name>` server\n * functions call through. Call once at startup (server-side); browser apps\n * should prefer Apollo + `createOrmFetch` or an explicit executor.\n */\nexport function configureOrmOperations(config: OperationExecutorConfig): OperationExecutor {\n configured = createOperationExecutor(config)\n return configured\n}\n\n/** Used by generated code: `executeOperation({ op: 'getOpenDeals', variables })`. */\nexport async function executeOperation<TData = Record<string, unknown>>({\n op,\n variables,\n idempotencyKey,\n}: {\n op: string\n variables?: Record<string, unknown>\n idempotencyKey?: string\n}): Promise<TData> {\n if (!configured) {\n throw new OrmClientError(\n 'ORM operations client not configured — call configureOrmOperations({ baseUrl, namespace, manifest, getToken }) at startup',\n )\n }\n return configured.execute<TData>(op, variables, idempotencyKey === undefined ? {} : { idempotencyKey })\n}\n\n// ---------------------------------------------------------------------------\n// Apollo integration without an @apollo/client dependency\n// ---------------------------------------------------------------------------\n\n/**\n * A fetch-compatible function for `new HttpLink({ uri: '/unused', fetch: createOrmFetch(...) })`.\n * Intercepts Apollo's GraphQL POST, swaps the body for the persisted-op\n * envelope (`{ op: <hash>, variables }`) resolved via the manifest's\n * operationName, rewrites the URL to the data plane, and attaches auth.\n * The GraphQL-spec response body passes through untouched, so InMemoryCache\n * and error links behave exactly as they do against a GraphQL server.\n */\nexport function createOrmFetch({\n baseUrl,\n namespace,\n manifest,\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: OperationExecutorConfig): typeof globalThis.fetch {\n if (!manifest) throw new OrmClientError('createOrmFetch requires an operations manifest')\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n const url = `${root}${dataPlanePath(namespace)}`\n\n // Derived from `globalThis.fetch` rather than naming `RequestInfo` (a DOM-lib\n // global this module compiles without). The input is ignored — Apollo's\n // HttpLink calls the injected fetch with a string URI, and the real target\n // URL is fixed at `url` above.\n return async (_input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit): Promise<Response> => {\n const raw = typeof init?.body === 'string' ? init.body : null\n const parsed = raw\n ? (JSON.parse(raw) as { operationName?: string; variables?: Record<string, unknown> })\n : {}\n const name = parsed.operationName\n if (!name) {\n throw new OrmClientError(\n 'createOrmFetch requires named operations (Apollo sends operationName for named documents)',\n )\n }\n const hash = resolveOpHash(manifest, name)\n const idempotencyKey = new Headers(init?.headers).get('Idempotency-Key') ?? undefined\n validateIdempotencyKey(idempotencyKey)\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n return fetchImpl(url, {\n method: 'POST',\n headers: { ...auth, 'Content-Type': 'application/json' },\n body: JSON.stringify({ op: hash, variables: parsed.variables ?? {}, idempotencyKey }),\n ...(init?.signal ? { signal: init.signal } : {}),\n })\n }\n}\n","import { NAMESPACE_PATTERN } from '../constants.js'\nimport { OrmClientError, OrmOperationError } from './errors.js'\nimport { validateIdempotencyKey, type TypedSqlOperationExecutor, type OperationReference, type OperationExecutionOptions } from './operations.js'\nimport { isRecord, readOperationResponse } from './response.js'\nimport { BUILTIN_SQL_READ_HASH, type SqlQueryResult } from './sql.js'\n\nexport interface OperationTransportRequest {\n namespace: string\n op: string\n variables: Record<string, unknown>\n idempotencyKey?: string\n}\n\nexport interface OperationTransportResponse {\n ok: boolean\n status: number\n body: unknown\n}\n\nexport type OperationTransport = (request: OperationTransportRequest) => Promise<OperationTransportResponse>\n\nconst operationHash = /^sha256:[a-f0-9]{64}$/\n\nfunction readManifestHashes(manifest: unknown): ReadonlyMap<string, string> {\n if (!isRecord(manifest) || typeof manifest.schemaHash !== 'string' || !manifest.schemaHash || !isRecord(manifest.operations)) {\n throw new OrmClientError('invalid operations manifest — use operations.manifest.json from seq-studio orm generate')\n }\n const hashes = new Map<string, string>()\n for (const [name, entry] of Object.entries(manifest.operations)) {\n if (!/^[_A-Za-z][_0-9A-Za-z]*$/.test(name) || !isRecord(entry) || typeof entry.hash !== 'string' || !operationHash.test(entry.hash)\n || (entry.kind !== 'query' && entry.kind !== 'mutation')) {\n throw new OrmClientError(`invalid operations manifest entry \"${name}\" — regenerate the manifest`)\n }\n hashes.set(name, entry.hash)\n }\n return hashes\n}\n\n/**\n * Execute generated operations through a host-owned authenticated transport.\n * No credential handling, retries, or global configuration. The manifest is\n * validated once and copied, so later caller mutation cannot alter the target.\n */\nexport function createOperationExecutorWithTransport({ namespace, manifest, transport }: {\n namespace: string\n /** Accept generated JSON imports directly; validate them at construction. */\n manifest?: unknown\n transport: OperationTransport\n}): TypedSqlOperationExecutor {\n if (typeof namespace !== 'string' || !NAMESPACE_PATTERN.test(namespace)) throw new OrmClientError('invalid ORM namespace — expected a lowercase identifier of at most 41 characters')\n const hashes = manifest === undefined ? new Map<string, string>() : readManifestHashes(manifest)\n const knownHashes = new Set(hashes.values())\n function execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n function execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n async function execute<TData = Record<string, unknown>>(op: string | OperationReference<Record<string, unknown>, TData>, variables: Record<string, unknown> = {}, options: OperationExecutionOptions = {}): Promise<TData> {\n validateIdempotencyKey(options.idempotencyKey)\n if (typeof op !== 'string' && op.namespace !== namespace) throw new OrmClientError('operation belongs to a different namespace')\n const selector = typeof op === 'string' ? op : op.hash\n const hash = selector === BUILTIN_SQL_READ_HASH ? selector : hashes.get(selector) ?? (knownHashes.has(selector) ? selector : undefined)\n if (!hash) throw new OrmClientError(`unknown operation \"${op}\" — not in the manifest (${hashes.size} known). Re-run seq-studio orm generate.`)\n if (!isRecord(variables)) throw new OrmClientError('operation variables must be an object')\n const response = await transport({ namespace, op: hash, variables,\n ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),\n })\n if (!response || typeof response.ok !== 'boolean' || !Number.isInteger(response.status) || response.status < 100 || response.status > 599\n || response.ok !== (response.status >= 200 && response.status < 300)) {\n throw new OrmOperationError('malformed transport response', null, null)\n }\n return readOperationResponse<TData>(response)\n }\n return { execute, sql: variables => execute<SqlQueryResult>(BUILTIN_SQL_READ_HASH, variables) }\n}\n","import { OrmClientError, createFetchTransport, type OrmTransport } from './transport.js'\nimport { TableQuery } from './query-builder.js'\n\n/** Bindable scalar for `query()` placeholders ($1, $2, …). */\nexport type QueryParam = string | number | boolean | null\n\n/** Shape of one action in the generated `<Ns>Actions` map — params in, result out. */\nexport interface OrmActionShape {\n readonly params?: Record<string, unknown>\n readonly result: unknown\n}\n\n/** The generated `<Ns>Actions` map: action name → its param and result shapes. */\nexport type OrmActions = Record<string, OrmActionShape>\n\n/**\n * `action()`'s argument list: `params` is required when the action declares a\n * required field, optional otherwise. The empty-object type is assignable to\n * the params shape only when every field is optional, so that assignability is\n * the discriminant.\n */\ntype ActionArgs<Action extends OrmActionShape> =\n Record<string, never> extends NonNullable<Action['params']>\n ? [params?: NonNullable<Action['params']>]\n : [params: NonNullable<Action['params']>]\n\n/**\n * Typed read client for one namespace's Data API. `Tables` comes from\n * `types.gen.ts` (wire types the apply refreshes from the YAML definitions),\n * so column names and row shapes are checked at compile time; the server\n * re-validates everything and Postgres RLS decides row visibility.\n *\n * ```ts\n * const client = createOrmClient<LendingTables>({ namespace: 'lending', baseUrl, getToken })\n * const rows = await client.table('loans').select('id', 'balance').gte('balance', 1000).rows()\n * const top = await client.query<{ officer: string; total: string }>(\n * 'select officer, sum(balance) as total from loans group by officer order by total desc limit $1',\n * [5],\n * )\n * ```\n */\nexport interface OrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n> {\n table<Name extends keyof Tables & string>(name: Name): TableQuery<Tables[Name]>\n /**\n * Raw read-only SQL for everything the filter grammar can't say —\n * aggregates, joins, OR, expressions, CTEs. The same sandbox as every\n * read: the namespace consumer role (grants stop at the namespace schema),\n * Postgres RLS over the caller's claims, and a READ ONLY transaction —\n * Postgres itself rejects writes, which stay on declared actions. Values\n * bind as $1, $2, … placeholders; never interpolate them into the string.\n */\n query<Row = Record<string, unknown>>(sql: string, params?: readonly QueryParam[]): Promise<Row[]>\n /**\n * Invoke a declared action — the only write path the Data API exposes. The\n * params and result are typed from the namespace's `<Ns>Actions`: an action\n * with `returns:` resolves to `{ rows: Row[] }`, a count action to\n * `{ rowsAffected: number }`.\n */\n action<Name extends keyof Actions & string>(\n name: Name,\n ...args: ActionArgs<Actions[Name]>\n ): Promise<Actions[Name]['result']>\n}\n\nexport function createOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>({\n namespace,\n baseUrl,\n getToken,\n fetchImpl,\n transport,\n dataToken,\n}: {\n namespace: string\n baseUrl?: string\n /** App-user / session bearer (CLI, browser). Mutually exclusive with dataToken. */\n getToken?: () => Promise<string | null> | string | null\n /**\n * Delegated function data token — the inbound `ORM_DATA_TOKEN_HEADER` value a\n * managed function receives. Pass it and the client authenticates as the\n * invoking user, scoped to the function's declared refs; no manual transport.\n */\n dataToken?: string | (() => Promise<string | null> | string | null)\n fetchImpl?: typeof globalThis.fetch\n /** Injected transport (tests, bridges); overrides baseUrl/getToken/dataToken. */\n transport?: OrmTransport\n}): OrmClient<Tables, Actions> {\n const resolved =\n transport ??\n createFetchTransport({\n baseUrl: requireOption(baseUrl, 'baseUrl'),\n ...(dataToken !== undefined\n ? { getDataToken: typeof dataToken === 'function' ? dataToken : () => dataToken }\n : { getToken: requireOption(getToken, 'getToken') }),\n fetchImpl,\n })\n\n return buildOrmClient<Tables, Actions>(resolved, namespace)\n}\n\n/**\n * The ESCALATION path — use only deliberately. A managed function receives a\n * separate *service* data token on `ORM_SERVICE_DATA_TOKEN_HEADER`; pass that\n * value here and the client authenticates as the function's SERVICE IDENTITY,\n * not the invoking user. Reads run with the service identity's grants (clamped\n * to the function's declared refs), NOT the caller's — so the caller's own row\n * visibility does not apply. The invoking user is still recorded for audit.\n *\n * Default to `createOrmClient` (acts as the invoking user, full per-user RLS).\n * Reach for this only when the function must intentionally act beyond the\n * caller — e.g. enforcing per-user rules in code over a coarse upstream that\n * has no granular permissions of its own. The distinct name is the guardrail:\n * choosing the service identity is always explicit and greppable.\n *\n * ```ts\n * const client = createServiceOrmClient<LendingTables>({\n * namespace: 'lending',\n * baseUrl,\n * serviceDataToken: req.headers['x-sequence-data-token-service'],\n * })\n * ```\n */\nexport function createServiceOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>({\n namespace,\n baseUrl,\n serviceDataToken,\n fetchImpl,\n transport,\n}: {\n namespace: string\n baseUrl?: string\n /** The inbound `ORM_SERVICE_DATA_TOKEN_HEADER` value — the function's service token. */\n serviceDataToken?: string | (() => Promise<string | null> | string | null)\n fetchImpl?: typeof globalThis.fetch\n /** Injected transport (tests, bridges); overrides baseUrl/serviceDataToken. */\n transport?: OrmTransport\n}): OrmClient<Tables, Actions> {\n const resolved =\n transport ??\n createFetchTransport({\n baseUrl: requireOption(baseUrl, 'baseUrl'),\n getDataToken:\n typeof serviceDataToken === 'function'\n ? serviceDataToken\n : () => requireOption(serviceDataToken, 'serviceDataToken'),\n fetchImpl,\n })\n\n return buildOrmClient<Tables, Actions>(resolved, namespace)\n}\n\n/** Shared client surface over a resolved transport — the token/identity choice is made by the factory above. */\nfunction buildOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>(resolved: OrmTransport, namespace: string): OrmClient<Tables, Actions> {\n return {\n table(name) {\n return new TableQuery(resolved, namespace, name)\n },\n async query(sql, params) {\n const payload = await resolved.post(`/api/data/${namespace}/query`, {\n sql,\n ...(params ? { params: [...params] } : {}),\n })\n if (!payload || typeof payload !== 'object' || !Array.isArray((payload as { rows?: unknown }).rows)) {\n throw new OrmClientError('unexpected Data API response shape — missing rows array')\n }\n return (payload as { rows: never[] }).rows\n },\n async action(name, ...args) {\n const payload = await resolved.post(`/api/data/${namespace}/actions/${name}`, args[0] ?? {})\n if (payload && typeof payload === 'object') {\n // A returns action responds with `rows`; a count action with\n // `rows_affected` (mapped to `rowsAffected` for the client).\n if (Array.isArray((payload as { rows?: unknown }).rows)) {\n return { rows: (payload as { rows: unknown[] }).rows } as Awaited<ReturnType<OrmClient<Tables, Actions>['action']>>\n }\n if ('rows_affected' in payload) {\n const rowsAffected = Number((payload as { rows_affected: unknown }).rows_affected)\n if (!Number.isNaN(rowsAffected)) {\n return { rowsAffected } as Awaited<ReturnType<OrmClient<Tables, Actions>['action']>>\n }\n }\n }\n throw new OrmClientError('unexpected action response shape — expected rows or rows_affected')\n },\n }\n}\n\nfunction requireOption<T>(value: T | undefined, name: string): T {\n if (value === undefined) throw new Error(`createOrmClient requires ${name} when no transport is injected`)\n return value\n}\n\nexport { TableQuery, type FilterValue, type ReadResponse } from './query-builder.js'\nexport { createFetchTransport, OrmClientError, type OrmTransport } from './transport.js'\n\nexport {\n OrmOperationError,\n configureOrmOperations,\n createOperationExecutor,\n createOrmFetch,\n executeOperation,\n} from './operations.js'\nexport type {\n ManifestOperation,\n OperationErrorEntry,\n OperationExecutor,\n SqlOperationExecutor,\n OperationReference,\n TypedOperationExecutor,\n TypedSqlOperationExecutor,\n OperationExecutorConfig,\n OperationsManifest,\n} from './operations.js'\n\nexport { NAMESPACE_PATTERN, ORM_DATA_TOKEN_HEADER, ORM_SERVICE_DATA_TOKEN_HEADER } from '../constants.js'\nexport type { SqlQueryParameter, SqlQueryVariables, SqlQueryResult } from './sql.js'\nexport { BUILTIN_SQL_READ_HASH } from './sql.js'\nexport {\n createOperationExecutorWithTransport,\n type OperationTransport, type OperationTransportRequest, type OperationTransportResponse,\n} from './transport-executor.js'\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/constants.ts","../src/client/errors.ts","../src/client/transport.ts","../src/client/query-builder.ts","../src/client/response.ts","../src/client/sql.ts","../src/client/operations.ts","../src/client/transport-executor.ts","../src/client/index.ts"],"names":[],"mappings":";;;AAIO,IAAM,iBAAA,GAAoB;AAG1B,IAAM,qBAAA,GAAwB;AAG9B,IAAM,6BAAA,GAAgC;AAwGtC,IAAM,iBAAA,GAAoB,iBAAA;AACM,IAAA,CAAK,SAAA,CAAU,EAAE,KAAK,iBAAA,EAAmB,GAAA,EAAK,IAAA,EAAM,KAAA,EAAO,EAAC,EAAG,YAAA,EAAc,IAAI;;;ACnHjH,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EAGxC,WAAA,CAAY,OAAA,EAA0B,MAAA,GAAwB,IAAA,EAAM;AAClE,IAAA,KAAA,CAAM,OAAO,CAAA;AADuB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAEtC;AAAA,EAJkB,IAAA,GAAe,gBAAA;AAKnC;AAOO,IAAM,iBAAA,GAAN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,KAAA,CAAM,YAAY,CAAA,EAAG;AAC/B,YAAA,OAAO,EAAE,YAAA,EAAa;AAAA,UACxB;AAAA,QACF;AAAA,MACF;AACA,MAAA,MAAM,IAAI,eAAe,wEAAmE,CAAA;AAAA,IAC9F;AAAA,GACF;AACF;AAEA,SAAS,aAAA,CAAiB,OAAsB,IAAA,EAAiB;AAC/D,EAAA,IAAI,UAAU,MAAA,EAAW,MAAM,IAAI,KAAA,CAAM,CAAA,yBAAA,EAA4B,IAAI,CAAA,8BAAA,CAAgC,CAAA;AACzG,EAAA,OAAO,KAAA;AACT","file":"client.cjs","sourcesContent":["/** Shared grammar for namespace identifiers; never interpolate arbitrary paths.\n * orm_events and orm_native_sources are migration-owned control-plane schemas,\n * not builder namespaces. Exclude their suffixes at every API/authoring entry.\n */\nexport const NAMESPACE_PATTERN = /^(?!(?:events|native_sources)$)[a-z][a-z0-9_]{0,40}$/\n\n/** Caller-scoped delegated data credential, supplied by an authenticated host. */\nexport const ORM_DATA_TOKEN_HEADER = 'x-sequence-data-token'\n\n/** Separate service-identity credential; never used as an implicit fallback. */\nexport const ORM_SERVICE_DATA_TOKEN_HEADER = 'x-sequence-data-token-service'\n\nexport const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/\n/** Native source columns may have one leading underscore; relation names may not. */\nexport const COLUMN_IDENTIFIER_PATTERN = /^_?[a-z][a-z0-9_]*$/\nexport const MAX_IDENTIFIER_LENGTH = 63\n\n/**\n * Custom Roles & Capabilities claim keys as policies reference them: a\n * host-scoped registry key, an org pin's `org/<key>`, or an Application\n * capability pin's `app/<application-id>/<key>`. Matches the registry\n * key grammar EXACTLY (`[a-z0-9-]`, 1–64 chars, no `_` — the FGA object-id\n * delimiter) so any capability that's declarable/attachable in namespace.yaml\n * can also be referenced here — a stricter pattern would let a valid key\n * register yet fail at apply (e.g. `org/2fa`, a one-char or digit-led key).\n */\nexport const CAPABILITY_KEY_PATTERN = /^(?:org\\/|app\\/[a-z][a-z0-9-]{0,63}\\/)?[a-z0-9-]{1,64}$/\n\n/** Hard ceiling for an explicitly authored flat persisted GraphQL read. */\nexport const MAX_PERSISTED_READ_ROWS = 50_001\n\nexport const CLAIM_KEY_PATTERN = /^[a-z][a-z0-9_]*$/\n\n/** Qualified reference to a table outside the defining file: `<schema>.<table>`. */\nexport const QUALIFIED_TABLE_PATTERN = /^[a-z][a-z0-9_]{0,62}\\.[a-z][a-z0-9_]{0,62}$/\n\n/** Qualified source syntax only; the serving installation controls authorized backing. */\nexport const SYNCED_SOURCE_PATTERN = QUALIFIED_TABLE_PATTERN\n\nexport const ORM_SCHEMA_PREFIX = 'orm_'\nexport const CONSUMER_ROLE_SUFFIX = '_consumer'\n\nexport const ormSchemaName = (namespace: string): string => {\n if (!NAMESPACE_PATTERN.test(namespace)) throw new Error(`invalid or reserved ORM namespace '${namespace}'`)\n return `${ORM_SCHEMA_PREFIX}${namespace}`\n}\nexport const consumerRoleName = (namespace: string): string =>\n `${ormSchemaName(namespace)}${CONSUMER_ROLE_SUFFIX}`\n\nexport const DEFINITION_FILE_EXTENSIONS = ['.yml', '.yaml'] as const\n\n/** Reserved basenames for the namespace-level config file (description, org capability pins). */\nexport const NAMESPACE_CONFIG_FILENAMES = new Set(['namespace.yaml', 'namespace.yml'])\n\nexport const HASH_DOMAIN = 'sequence-orm-definitions\\0'\n\n/**\n * A per-file byte cap where the loader reads untrusted YAML into memory — a real failure mode, not a product\n * limit. Counts of tables/indexes/params and policy/SQL lengths are\n * deliberately uncapped; Postgres enforces its own limits loudly at apply.\n */\nexport const MAX_DEFINITION_FILE_BYTES = 1024 * 1024\n\n/** Generated SDL aggregates every table/view; it is not an individual source file. */\nexport const MAX_GENERATED_SDL_BYTES = 16 * 1024 * 1024\n\n/** Registration and reviewed exports carry SDL, canonical metadata, snapshots and migrations. */\nexport const ORM_REGISTRATION_MAX_BYTES = 64 * 1024 * 1024\n\n/** `/api/data/<ns>/actions/…` and `/api/data/<ns>/query` share the table path segment. */\nexport const RESERVED_TABLE_NAMES = new Set(['actions', 'query'])\n\n/**\n * The Data API's query-string grammar owns these parameter names — a column\n * with one of them could never be filtered over the wire, so definitions\n * refuse it up front (\"validate rejects only what can never work\").\n */\nexport const RESERVED_COLUMN_NAMES = new Set(['select', 'order', 'limit', 'offset'])\n\n/**\n * Per-cell metadata (`cellMetadata: true`, and every resolved-table source) is\n * stored as typed system columns beside each tracked column `c`:\n *\n * - `c__at` timestamptz — when the cell was last written (NULL: never / no opinion)\n * - `c__by` text — who wrote it\n * - `c__rev` uuid — a resolved table's manual source only: the edit's\n * identity, so an async writeback confirmation clears\n * only the exact edit it delivered\n *\n * A resolved view additionally exposes, per resolved column, the winner's\n * `c__src` (source name) and `c__lost` (newer candidates that lost, jsonb).\n * None of these are GraphQL columns: they surface through the typed `cells`\n * object and are never client-writable.\n */\nexport const CELL_PARTS = ['at', 'by', 'rev', 'source', 'conflicts'] as const\nexport type CellPart = (typeof CELL_PARTS)[number]\nexport const CELL_PART_SUFFIX: Readonly<Record<CellPart, string>> = {\n at: '__at', by: '__by', rev: '__rev', source: '__src', conflicts: '__lost',\n}\n/** Longest physical column name that can carry cell parts (63 minus the longest suffix). */\nexport const MAX_TRACKED_COLUMN_NAME = MAX_IDENTIFIER_LENGTH - 6\n/** GraphQL field carrying a row's per-cell metadata object. */\nexport const CELLS_FIELD = 'cells'\n\n/** Physical (and logical) name of one cell part of a column. */\nexport function cellColumnName(column: string, part: CellPart): string {\n return `${column}${CELL_PART_SUFFIX[part]}`\n}\n\n/**\n * Actor recorded when the data plane computes a materialized resolved table's\n * rows for every caller. Its claims are what the compute view's synced\n * sources see (materialized ETL sources must be readable by anyone).\n */\nexport const MATERIALIZE_ACTOR = 'orm:materialize'\nexport const MATERIALIZE_CLAIMS_JSON = JSON.stringify({ sub: MATERIALIZE_ACTOR, org: null, roles: [], capabilities: [] })\n\n/**\n * Apply-generated function that reconciles a materialized resolved table with\n * its compute view: `SELECT * FROM orm_<ns>.\"<table>__refresh\"(wait)` returns\n * `(upserted, deleted, locked)`; without `wait` it skips when another refresh\n * holds the table's lock. The one refresh implementation — the Atlas\n * reconcile, the post-ETL hook, and an operator in psql all call it.\n */\nexport function materializedRefreshFunctionName(table: string): string {\n return `${table}__refresh`\n}\n\n/**\n * Advisory-lock key serializing a materialized table's refreshes (hashed with\n * `hashtext`). A full refresh holds it exclusively and every ORM write's\n * per-row refresh holds it shared, both before reading the compute view — so\n * a full refresh never reads a snapshot older than a write it then overwrites.\n */\nexport function materializeLockKey(schema: string, table: string): string {\n return `orm:materialize:${schema}.${table}`\n}\n","export class OrmClientError extends Error {\n override readonly name: string = 'OrmClientError'\n\n constructor(message: string, readonly status: number | null = null) {\n super(message)\n }\n}\n\nexport interface OperationErrorEntry {\n readonly message: string\n readonly extensions?: { readonly code?: string }\n}\n\nexport class OrmOperationError extends OrmClientError {\n override readonly name = 'OrmOperationError'\n\n constructor(\n message: string,\n status: number | null,\n readonly code: string | null,\n readonly errors: readonly OperationErrorEntry[] = [],\n ) {\n super(message, status)\n }\n}\n","/**\n * Fetch-based transport for the Data API. Deliberately free of node builtins\n * so the client runs anywhere a `fetch` exists — browsers, artifact bridges,\n * Cloud Functions, `node:vm` sandboxes.\n */\nimport { ORM_DATA_TOKEN_HEADER } from '../constants.js'\n\nimport { OrmClientError } from './errors.js'\nexport { OrmClientError } from './errors.js'\n\nexport interface OrmTransport {\n get(path: string, params: URLSearchParams): Promise<unknown>\n post(path: string, body: unknown): Promise<unknown>\n}\n\nexport function createFetchTransport({\n baseUrl,\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: {\n baseUrl: string\n /** App-user / session bearer → `Authorization: Bearer`. */\n getToken?: () => Promise<string | null> | string | null\n /** Delegated, attenuated function token → the `ORM_DATA_TOKEN_HEADER`. */\n getDataToken?: () => Promise<string | null> | string | null\n fetchImpl?: typeof globalThis.fetch\n}): OrmTransport {\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n\n const request = async (path: string, init: Omit<RequestInit, 'headers'>): Promise<unknown> => {\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n // The delegated token rides its own header; the app-user bearer rides Authorization.\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n const response = await fetchImpl(`${root}${path}`, {\n ...init,\n headers: { ...auth, 'Content-Type': 'application/json' },\n })\n const payload: unknown = await response.json().catch(() => null)\n if (!response.ok) {\n const detail =\n payload && typeof payload === 'object' && 'detail' in payload\n ? String((payload as { detail: unknown }).detail)\n : `HTTP ${response.status}`\n throw new OrmClientError(detail, response.status)\n }\n return payload\n }\n\n return {\n get: (path, params) => {\n // Not params.size — that's Node 19.8+/2023-browser surface, newer than\n // the fetch this module documents as its only requirement.\n const serialized = params.toString()\n return request(serialized === '' ? path : `${path}?${serialized}`, {})\n },\n post: (path, body) => request(path, { method: 'POST', body: JSON.stringify(body ?? {}) }),\n }\n}\n","import { OrmClientError, type OrmTransport } from './transport.js'\n\n/**\n * Fluent read query over one table. Serializes to exactly the PostgREST\n * subset the Data API's query parser accepts — the round-trip contract is\n * asserted server-side (builder output → parseReadQuery) so the two ends\n * can't drift apart silently.\n *\n * IMMUTABLE: every method returns a new query, so narrowing `select()` can\n * never leave an alias holding a stale wider row type, and a base query can\n * be safely forked into variants.\n */\n\nexport type FilterValue = string | number | boolean\n\nexport interface ReadResponse<Row> {\n readonly rows: readonly Row[]\n readonly limit: number\n readonly offset: number\n}\n\n/** Characters the in-list grammar cannot carry — there is no escaping, so the builder hard-fails. */\nconst IN_LIST_UNREPRESENTABLE = /[,()]/\n\ninterface QueryState {\n readonly filters: ReadonlyArray<[column: string, expression: string]>\n readonly orderings: readonly string[]\n readonly selection: readonly string[] | null\n readonly limitValue: number | null\n readonly offsetValue: number | null\n}\n\nconst EMPTY_STATE: QueryState = {\n filters: [],\n orderings: [],\n selection: null,\n limitValue: null,\n offsetValue: null,\n}\n\n/**\n * `Row` is the TABLE's row (filters and order always accept every column);\n * `Result` is what rows() yields — narrowed by select(), re-widenable by a\n * later select() since keys always come from Row.\n */\nexport class TableQuery<Row extends Record<string, unknown>, Result = Row> {\n constructor(\n private readonly transport: OrmTransport,\n private readonly namespace: string,\n private readonly table: string,\n private readonly state: QueryState = EMPTY_STATE,\n ) {}\n\n private with(patch: Partial<QueryState>): TableQuery<Row, Result> {\n return new TableQuery(this.transport, this.namespace, this.table, { ...this.state, ...patch })\n }\n\n select<K extends keyof Row & string>(...columns: [K, ...K[]]): TableQuery<Row, Pick<Row, K>> {\n return new TableQuery<Row, Pick<Row, K>>(this.transport, this.namespace, this.table, {\n ...this.state,\n selection: columns,\n })\n }\n\n eq<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'eq', value)\n }\n\n ne<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'ne', value)\n }\n\n gt<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'gt', value)\n }\n\n gte<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'gte', value)\n }\n\n lt<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'lt', value)\n }\n\n lte<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'lte', value)\n }\n\n like<K extends keyof Row & string>(column: K, pattern: string): TableQuery<Row, Result> {\n return this.filter(column, 'like', pattern)\n }\n\n ilike<K extends keyof Row & string>(column: K, pattern: string): TableQuery<Row, Result> {\n return this.filter(column, 'ilike', pattern)\n }\n\n in<K extends keyof Row & string>(column: K, values: readonly FilterValue[]): TableQuery<Row, Result> {\n // An empty list is representable — `in.()` matches nothing, the same\n // semantics the server executes. Blank entries are legitimate values in\n // multi-entry lists (`in.(a,)` carries ['a','']), but a LONE '' renders\n // as `in.()` and silently becomes the empty list — unrepresentable.\n // Beyond that only characters the grammar can't escape, and whitespace\n // padding the server-side split would silently swallow, are refused.\n const rendered = values.map((value) => {\n const text = String(value)\n if (IN_LIST_UNREPRESENTABLE.test(text) || text !== text.trim()) {\n throw new OrmClientError(`in() value '${text}' cannot be represented — the list grammar has no escaping`)\n }\n return text\n })\n if (rendered.length === 1 && rendered[0] === '') {\n throw new OrmClientError(\"in() with a lone '' cannot be represented — it would read as the empty list\")\n }\n return this.with({ filters: [...this.state.filters, [column, `in.(${rendered.join(',')})`]] })\n }\n\n is<K extends keyof Row & string>(column: K, value: null | boolean): TableQuery<Row, Result> {\n return this.with({\n filters: [...this.state.filters, [column, `is.${value === null ? 'null' : value}`]],\n })\n }\n\n order<K extends keyof Row & string>(column: K, direction: 'asc' | 'desc' = 'asc'): TableQuery<Row, Result> {\n return this.with({ orderings: [...this.state.orderings, `${column}.${direction}`] })\n }\n\n limit(value: number): TableQuery<Row, Result> {\n return this.with({ limitValue: value })\n }\n\n offset(value: number): TableQuery<Row, Result> {\n return this.with({ offsetValue: value })\n }\n\n /** The exact query string sent to the Data API — exposed for debugging and the grammar contract test. */\n searchParams(): URLSearchParams {\n const params = new URLSearchParams()\n for (const [column, expression] of this.state.filters) params.append(column, expression)\n if (this.state.orderings.length > 0) params.set('order', this.state.orderings.join(','))\n if (this.state.selection) params.set('select', this.state.selection.join(','))\n if (this.state.limitValue !== null) params.set('limit', String(this.state.limitValue))\n if (this.state.offsetValue !== null) params.set('offset', String(this.state.offsetValue))\n return params\n }\n\n async rows(): Promise<Result[]> {\n const payload = await this.transport.get(\n `/api/data/${this.namespace}/${this.table}`,\n this.searchParams(),\n )\n if (!payload || typeof payload !== 'object' || !Array.isArray((payload as { rows?: unknown }).rows)) {\n throw new OrmClientError('unexpected Data API response shape — missing rows array')\n }\n return (payload as { rows: Result[] }).rows\n }\n\n private filter(column: string, op: string, value: FilterValue): TableQuery<Row, Result> {\n return this.with({ filters: [...this.state.filters, [column, `${op}.${String(value)}`]] })\n }\n}\n","import { OrmOperationError, type OperationErrorEntry } from './errors.js'\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isOperationError(value: unknown): value is OperationErrorEntry {\n if (!isRecord(value) || typeof value.message !== 'string') return false\n if (value.extensions === undefined) return true\n return isRecord(value.extensions) && (value.extensions.code === undefined || typeof value.extensions.code === 'string')\n}\n\nexport function readOperationResponse<TData>({\n ok, status, body,\n}: { ok: boolean; status: number; body: unknown }): TData {\n const payload = isRecord(body) ? body : null\n const rawErrors = payload?.errors\n if (rawErrors !== undefined && (!Array.isArray(rawErrors) || !rawErrors.every(isOperationError))) {\n throw new OrmOperationError('malformed response: invalid errors', status, null)\n }\n const errors: OperationErrorEntry[] = rawErrors ?? []\n if (!ok || errors.length > 0) {\n const first = errors[0]\n throw new OrmOperationError(first?.message ?? `HTTP ${status}`, status, first?.extensions?.code ?? null, errors)\n }\n if (!payload || payload.data === undefined || payload.data === null) {\n throw new OrmOperationError('malformed response: missing data', status, null)\n }\n if (!isRecord(payload.data)) {\n throw new OrmOperationError('malformed response: data must be an object', status, null)\n }\n // Generated consumer types describe operation data; envelope validation\n // cannot prove an application's selection-specific TData at runtime.\n return payload.data as TData\n}\n\n/** Only expose data together with a validated, opaque source receipt. */\nexport function readOperationResponseWithReceipt<TData>({\n ok, status, body, expectedSourceGeneration,\n}: { ok: boolean; status: number; body: unknown; expectedSourceGeneration?: string }): { data: TData; sourceGeneration: string } {\n const data = readOperationResponse<TData>({ ok, status, body })\n const extensions = isRecord(body) && isRecord(body.extensions) ? body.extensions : null\n const sourceGeneration = extensions?.sourceGeneration\n if (typeof sourceGeneration !== 'string' || !/^[a-f0-9]{64}$/.test(sourceGeneration)\n || (expectedSourceGeneration !== undefined && expectedSourceGeneration !== sourceGeneration)) {\n // Missing and changed receipts are indistinguishable; do not expose either token.\n throw new OrmOperationError('Source generation unavailable', status, 'OBJECT_UNAVAILABLE')\n }\n return { data, sourceGeneration }\n}\n","/** Runtime SQL inputs are values, never interpolated into the submitted SQL. */\n// SHA-256 of \"sequence-orm-builtin-sql-read-v1\". This identifies server-owned\n// behavior, independent of a namespace's authored operation manifest.\nexport const BUILTIN_SQL_READ_HASH = 'sha256:a50c477c952a5e0fe68ed158a4530e4aab573c09bcbb1a8ac454dc88a39a6258'\n\nexport type SqlQueryParameter =\n | { type: 'text' | 'uuid' | 'date' | 'timestamptz' | 'numeric' | 'bigint'; value: string | null }\n | { type: 'integer' | 'double'; value: number | null }\n | { type: 'boolean'; value: boolean | null }\n\nexport type SqlQueryVariables = {\n sql: string\n parameters?: Record<string, SqlQueryParameter>\n}\n\nexport interface SqlQueryResult {\n columns: Array<{ name: string; type: string; nullable: boolean }>\n rows: Array<Array<string | number | boolean | null>>\n truncated: boolean\n}\n","/**\n * Persisted-operation client for the v2 data plane. The wire carries only\n * `{ op: <hash>, variables, idempotencyKey?, expectedSourceGeneration? }`. Runtime SQL contracts accept SQL in variables;\n * GraphQL and fixed SQL operations keep their documents server-side. This runtime\n * is deliberately free of node builtins and third-\n * party deps (no @apollo/client import): Apollo integration happens through a\n * fetch-compatible shim (`createOrmFetch`) handed to `HttpLink({ fetch })`.\n */\nimport { OrmClientError } from './errors.js'\nimport { readOperationResponse, readOperationResponseWithReceipt } from './response.js'\nimport { ORM_DATA_TOKEN_HEADER } from '../constants.js'\nimport { BUILTIN_SQL_READ_HASH, type SqlQueryVariables, type SqlQueryResult } from './sql.js'\n\nexport { OrmOperationError, type OperationErrorEntry } from './errors.js'\n\n/** One entry of `operations.manifest.json` (generated by `orm generate`). */\nexport interface ManifestOperation {\n readonly hash: string\n readonly kind: 'query' | 'mutation'\n readonly requires: { readonly capability?: string; readonly role?: string } | null\n}\n\nexport interface OperationsManifest {\n readonly schemaHash: string\n readonly opsHash?: string\n readonly operations: Readonly<Record<string, ManifestOperation>>\n}\n\nexport interface OperationExecutorConfig {\n /** Deployment host root, e.g. `https://atlas.seqholdings.com`. */\n baseUrl: string\n namespace: string\n manifest?: OperationsManifest\n /** App-user / session bearer → `Authorization: Bearer`. */\n getToken?: () => Promise<string | null> | string | null\n /** Delegated, attenuated function token → the `ORM_DATA_TOKEN_HEADER`. */\n getDataToken?: () => Promise<string | null> | string | null\n fetchImpl?: typeof globalThis.fetch\n}\n\nexport interface OperationExecutionOptions {\n /** Reuse only when retrying the same logical mutation. */\n idempotencyKey?: string\n /** Require the same source publication as an earlier read receipt. */\n expectedSourceGeneration?: string\n}\n\nexport function validateIdempotencyKey(key: string | undefined): void {\n if (key !== undefined && !/^[A-Za-z0-9._:-]{1,128}$/.test(key)) {\n throw new OrmClientError('idempotencyKey must be 1–128 letters, digits, dots, underscores, colons or hyphens')\n }\n}\n\nexport function validateExpectedSourceGeneration(value: string | undefined): void {\n if (value !== undefined && (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value))) {\n throw new OrmClientError('expectedSourceGeneration must be a lowercase 64-character hexadecimal receipt')\n }\n}\n\nexport interface OperationExecutor {\n /** Execute a manifest operation by name (or a raw `sha256:` hash). */\n execute<TData = Record<string, unknown>>(\n op: string,\n variables?: Record<string, unknown>,\n options?: OperationExecutionOptions,\n ): Promise<TData>\n}\n\n/** Additive factory result; existing host wrappers implementing OperationExecutor remain valid. */\nexport interface SqlOperationExecutor extends OperationExecutor {\n /** Default read-only ontology SQL; no authored operation or manifest needed. */\n sql(variables: SqlQueryVariables): Promise<SqlQueryResult>\n}\n\nexport interface TypedOperationExecutor extends OperationExecutor {\n execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n}\n\n/** Factory result adds SQL without requiring it on existing typed host wrappers. */\nexport type TypedSqlOperationExecutor = TypedOperationExecutor & SqlOperationExecutor\n\nexport interface OperationReadReceipt<TData> {\n readonly data: TData\n /** Opaque source-publication identity; never an authorization credential. */\n readonly sourceGeneration: string\n}\n\nexport interface ReadReceiptOperationExecutor extends OperationExecutor {\n /** Execute a registered query or built-in SQL read; fail closed without a receipt. */\n executeWithReadReceipt<TData = Record<string, unknown>>(\n op: string,\n variables?: Record<string, unknown>,\n options?: OperationExecutionOptions,\n ): Promise<OperationReadReceipt<TData>>\n}\n\n/** Additive factories preserve existing host wrappers without receipt support. */\nexport type ReadReceiptSqlOperationExecutor = SqlOperationExecutor & ReadReceiptOperationExecutor\n\nexport interface TypedReadReceiptOperationExecutor extends TypedOperationExecutor {\n executeWithReadReceipt<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n executeWithReadReceipt<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n}\n\nexport type TypedReadReceiptSqlOperationExecutor = TypedReadReceiptOperationExecutor & ReadReceiptSqlOperationExecutor\n\nconst dataPlanePath = (namespace: string): string => `/_data/v2/${namespace}`\n\n/** Generated handle identifies the registered contract; optional types are phantom. */\nexport interface OperationReference<TVariables extends Record<string, unknown>, TData> {\n readonly namespace: string\n readonly hash: string\n readonly variables?: TVariables\n readonly result?: TData\n}\n\nfunction resolveOpHash(manifest: OperationsManifest, op: string): string {\n if (op.startsWith('sha256:')) return op\n const entry = manifest.operations[op]\n if (!entry) {\n const known = Object.keys(manifest.operations).sort()\n throw new OrmClientError(\n `unknown operation \"${op}\" — not in the manifest (${known.length} known). ` +\n 'Re-run `seq-studio orm generate` after editing graphql documents.',\n )\n }\n return entry.hash\n}\n\n/** Snapshot classification and name resolution before any receipt request can dispatch. */\nexport function createReadReceiptOperationResolver({ operations }: {\n operations: Iterable<readonly [string, Pick<ManifestOperation, 'hash' | 'kind'>]>\n}): (selection: { selector: string; hashOnly?: boolean }) => string {\n const hashesByName = new Map<string, string>()\n const readHashes = new Set([BUILTIN_SQL_READ_HASH])\n const mutationHashes = new Set<string>()\n for (const [name, entry] of operations) {\n hashesByName.set(name, entry.hash)\n if (entry.kind === 'query' && /^sha256:[a-f0-9]{64}$/.test(entry.hash)) readHashes.add(entry.hash)\n if (entry.kind === 'mutation') mutationHashes.add(entry.hash)\n }\n return ({ selector, hashOnly = false }) => {\n const hash = selector.startsWith('sha256:') ? selector : hashOnly ? undefined : hashesByName.get(selector)\n if (!hash || !readHashes.has(hash) || mutationHashes.has(hash)) {\n throw new OrmClientError('read receipts require a registered query or the built-in SQL read')\n }\n return hash\n }\n}\n\nexport function createOperationExecutor({\n baseUrl,\n namespace,\n manifest = { schemaHash: 'builtin', operations: {} },\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: OperationExecutorConfig): TypedReadReceiptSqlOperationExecutor {\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n const resolveReceiptOperation = createReadReceiptOperationResolver({ operations: Object.entries(manifest.operations) })\n\n async function request({ op, variables, options, requireReadReceipt = false }: {\n op: string | OperationReference<Record<string, unknown>, unknown>\n variables: Record<string, unknown>\n options: OperationExecutionOptions\n requireReadReceipt?: boolean\n }): Promise<{ ok: boolean; status: number; body: unknown }> {\n validateIdempotencyKey(options.idempotencyKey)\n validateExpectedSourceGeneration(options.expectedSourceGeneration)\n if (typeof op !== 'string' && op.namespace !== namespace) throw new OrmClientError('operation belongs to a different namespace')\n const hash = requireReadReceipt\n ? resolveReceiptOperation({ selector: typeof op === 'string' ? op : op.hash, hashOnly: typeof op !== 'string' })\n : typeof op === 'string' ? resolveOpHash(manifest, op) : op.hash\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n const response = await fetchImpl(`${root}${dataPlanePath(namespace)}`, {\n method: 'POST',\n headers: { ...auth, 'Content-Type': 'application/json' },\n body: JSON.stringify({ op: hash, variables, idempotencyKey: options.idempotencyKey,\n expectedSourceGeneration: options.expectedSourceGeneration }),\n })\n return {\n ok: response.ok,\n status: response.status,\n body: await response.json().catch(() => null),\n }\n }\n\n function execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n function execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n async function execute<TData = Record<string, unknown>>(op: string | OperationReference<Record<string, unknown>, TData>, variables: Record<string, unknown> = {}, options: OperationExecutionOptions = {}): Promise<TData> {\n const executionOptions = { ...options }\n const response = await request({ op, variables, options: executionOptions })\n return executionOptions.expectedSourceGeneration === undefined\n ? readOperationResponse<TData>(response)\n : readOperationResponseWithReceipt<TData>({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration }).data\n }\n\n function executeWithReadReceipt<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n function executeWithReadReceipt<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n async function executeWithReadReceipt<TData = Record<string, unknown>>(op: string | OperationReference<Record<string, unknown>, TData>, variables: Record<string, unknown> = {}, options: OperationExecutionOptions = {}): Promise<OperationReadReceipt<TData>> {\n const executionOptions = { ...options }\n const response = await request({ op, variables, options: executionOptions, requireReadReceipt: true })\n return readOperationResponseWithReceipt<TData>({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration })\n }\n return { execute, executeWithReadReceipt, sql: variables => execute<SqlQueryResult>(BUILTIN_SQL_READ_HASH, variables) }\n}\n\n// ---------------------------------------------------------------------------\n// Module-level convenience for generated server functions (`db<Name>`)\n// ---------------------------------------------------------------------------\n\nlet configured: OperationExecutor | null = null\n\n/**\n * Configure the process-wide executor the generated `db<Name>` server\n * functions call through. Call once at startup (server-side); browser apps\n * should prefer Apollo + `createOrmFetch` or an explicit executor.\n */\nexport function configureOrmOperations(config: OperationExecutorConfig): OperationExecutor {\n configured = createOperationExecutor(config)\n return configured\n}\n\n/** Used by generated code: `executeOperation({ op: 'getOpenDeals', variables })`. */\nexport async function executeOperation<TData = Record<string, unknown>>({\n op,\n variables,\n idempotencyKey,\n}: {\n op: string\n variables?: Record<string, unknown>\n idempotencyKey?: string\n}): Promise<TData> {\n if (!configured) {\n throw new OrmClientError(\n 'ORM operations client not configured — call configureOrmOperations({ baseUrl, namespace, manifest, getToken }) at startup',\n )\n }\n return configured.execute<TData>(op, variables, idempotencyKey === undefined ? {} : { idempotencyKey })\n}\n\n// ---------------------------------------------------------------------------\n// Apollo integration without an @apollo/client dependency\n// ---------------------------------------------------------------------------\n\n/**\n * A fetch-compatible function for `new HttpLink({ uri: '/unused', fetch: createOrmFetch(...) })`.\n * Intercepts Apollo's GraphQL POST, swaps the body for the persisted-op\n * envelope (`{ op: <hash>, variables }`) resolved via the manifest's\n * operationName, rewrites the URL to the data plane, and attaches auth.\n * The GraphQL-spec response body passes through untouched, so InMemoryCache\n * and error links behave exactly as they do against a GraphQL server.\n */\nexport function createOrmFetch({\n baseUrl,\n namespace,\n manifest,\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: OperationExecutorConfig): typeof globalThis.fetch {\n if (!manifest) throw new OrmClientError('createOrmFetch requires an operations manifest')\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n const url = `${root}${dataPlanePath(namespace)}`\n\n // Derived from `globalThis.fetch` rather than naming `RequestInfo` (a DOM-lib\n // global this module compiles without). The input is ignored — Apollo's\n // HttpLink calls the injected fetch with a string URI, and the real target\n // URL is fixed at `url` above.\n return async (_input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit): Promise<Response> => {\n const raw = typeof init?.body === 'string' ? init.body : null\n const parsed = raw\n ? (JSON.parse(raw) as { operationName?: string; variables?: Record<string, unknown> })\n : {}\n const name = parsed.operationName\n if (!name) {\n throw new OrmClientError(\n 'createOrmFetch requires named operations (Apollo sends operationName for named documents)',\n )\n }\n const hash = resolveOpHash(manifest, name)\n const idempotencyKey = new Headers(init?.headers).get('Idempotency-Key') ?? undefined\n validateIdempotencyKey(idempotencyKey)\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n return fetchImpl(url, {\n method: 'POST',\n headers: { ...auth, 'Content-Type': 'application/json' },\n body: JSON.stringify({ op: hash, variables: parsed.variables ?? {}, idempotencyKey }),\n ...(init?.signal ? { signal: init.signal } : {}),\n })\n }\n}\n","import { NAMESPACE_PATTERN } from '../constants.js'\nimport { OrmClientError, OrmOperationError } from './errors.js'\nimport {\n validateIdempotencyKey, validateExpectedSourceGeneration, createReadReceiptOperationResolver,\n type ManifestOperation,\n type TypedReadReceiptSqlOperationExecutor, type OperationReadReceipt, type OperationReference, type OperationExecutionOptions,\n} from './operations.js'\nimport { isRecord, readOperationResponse, readOperationResponseWithReceipt } from './response.js'\nimport { BUILTIN_SQL_READ_HASH, type SqlQueryResult } from './sql.js'\n\nexport interface OperationTransportRequest {\n namespace: string\n op: string\n variables: Record<string, unknown>\n idempotencyKey?: string\n expectedSourceGeneration?: string\n}\n\nexport interface OperationTransportResponse {\n ok: boolean\n status: number\n body: unknown\n}\n\nexport type OperationTransport = (request: OperationTransportRequest) => Promise<OperationTransportResponse>\n\nconst operationHash = /^sha256:[a-f0-9]{64}$/\n\nfunction readManifestHashes(manifest: unknown): ReadonlyMap<string, Pick<ManifestOperation, 'hash' | 'kind'>> {\n if (!isRecord(manifest) || typeof manifest.schemaHash !== 'string' || !manifest.schemaHash || !isRecord(manifest.operations)) {\n throw new OrmClientError('invalid operations manifest — use operations.manifest.json from seq-studio orm generate')\n }\n const hashes = new Map<string, Pick<ManifestOperation, 'hash' | 'kind'>>()\n for (const [name, entry] of Object.entries(manifest.operations)) {\n if (!/^[_A-Za-z][_0-9A-Za-z]*$/.test(name) || !isRecord(entry) || typeof entry.hash !== 'string' || !operationHash.test(entry.hash)\n || (entry.kind !== 'query' && entry.kind !== 'mutation')) {\n throw new OrmClientError(`invalid operations manifest entry \"${name}\" — regenerate the manifest`)\n }\n hashes.set(name, { hash: entry.hash, kind: entry.kind })\n }\n return hashes\n}\n\n/**\n * Execute generated operations through a host-owned authenticated transport.\n * No credential handling, retries, or global configuration. The manifest is\n * validated once and copied, so later caller mutation cannot alter the target.\n */\nexport function createOperationExecutorWithTransport({ namespace, manifest, transport }: {\n namespace: string\n /** Accept generated JSON imports directly; validate them at construction. */\n manifest?: unknown\n transport: OperationTransport\n}): TypedReadReceiptSqlOperationExecutor {\n if (typeof namespace !== 'string' || !NAMESPACE_PATTERN.test(namespace)) throw new OrmClientError('invalid ORM namespace — expected a lowercase identifier of at most 41 characters')\n const hashes = manifest === undefined ? new Map<string, Pick<ManifestOperation, 'hash' | 'kind'>>() : readManifestHashes(manifest)\n const knownHashes = new Set([...hashes.values()].map(entry => entry.hash))\n const resolveReceiptOperation = createReadReceiptOperationResolver({ operations: hashes })\n async function request({ op, variables, options, requireReadReceipt = false }: {\n op: string | OperationReference<Record<string, unknown>, unknown>\n variables: Record<string, unknown>\n options: OperationExecutionOptions\n requireReadReceipt?: boolean\n }): Promise<OperationTransportResponse> {\n validateIdempotencyKey(options.idempotencyKey)\n validateExpectedSourceGeneration(options.expectedSourceGeneration)\n if (typeof op !== 'string' && op.namespace !== namespace) throw new OrmClientError('operation belongs to a different namespace')\n const selector = typeof op === 'string' ? op : op.hash\n const hash = requireReadReceipt\n ? resolveReceiptOperation({ selector, hashOnly: typeof op !== 'string' })\n : selector === BUILTIN_SQL_READ_HASH ? selector : hashes.get(selector)?.hash ?? (knownHashes.has(selector) ? selector : undefined)\n if (!hash) throw new OrmClientError(`unknown operation \"${op}\" — not in the manifest (${hashes.size} known). Re-run seq-studio orm generate.`)\n if (!isRecord(variables)) throw new OrmClientError('operation variables must be an object')\n const response = await transport({ namespace, op: hash, variables,\n ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),\n ...(options.expectedSourceGeneration === undefined ? {} : { expectedSourceGeneration: options.expectedSourceGeneration }),\n })\n if (!response || typeof response.ok !== 'boolean' || !Number.isInteger(response.status) || response.status < 100 || response.status > 599\n || response.ok !== (response.status >= 200 && response.status < 300)) {\n throw new OrmOperationError('malformed transport response', null, null)\n }\n return response\n }\n\n function execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n function execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n async function execute<TData = Record<string, unknown>>(op: string | OperationReference<Record<string, unknown>, TData>, variables: Record<string, unknown> = {}, options: OperationExecutionOptions = {}): Promise<TData> {\n const executionOptions = { ...options }\n const response = await request({ op, variables, options: executionOptions })\n return executionOptions.expectedSourceGeneration === undefined\n ? readOperationResponse<TData>(response)\n : readOperationResponseWithReceipt<TData>({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration }).data\n }\n\n function executeWithReadReceipt<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n function executeWithReadReceipt<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n async function executeWithReadReceipt<TData = Record<string, unknown>>(op: string | OperationReference<Record<string, unknown>, TData>, variables: Record<string, unknown> = {}, options: OperationExecutionOptions = {}): Promise<OperationReadReceipt<TData>> {\n const executionOptions = { ...options }\n const response = await request({ op, variables, options: executionOptions, requireReadReceipt: true })\n return readOperationResponseWithReceipt<TData>({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration })\n }\n return { execute, executeWithReadReceipt, sql: variables => execute<SqlQueryResult>(BUILTIN_SQL_READ_HASH, variables) }\n}\n","import { OrmClientError, createFetchTransport, type OrmTransport } from './transport.js'\nimport { TableQuery } from './query-builder.js'\n\n/** Bindable scalar for `query()` placeholders ($1, $2, …). */\nexport type QueryParam = string | number | boolean | null\n\n/** Shape of one action in the generated `<Ns>Actions` map — params in, result out. */\nexport interface OrmActionShape {\n readonly params?: Record<string, unknown>\n readonly result: unknown\n}\n\n/** The generated `<Ns>Actions` map: action name → its param and result shapes. */\nexport type OrmActions = Record<string, OrmActionShape>\n\n/**\n * `action()`'s argument list: `params` is required when the action declares a\n * required field, optional otherwise. The empty-object type is assignable to\n * the params shape only when every field is optional, so that assignability is\n * the discriminant.\n */\ntype ActionArgs<Action extends OrmActionShape> =\n Record<string, never> extends NonNullable<Action['params']>\n ? [params?: NonNullable<Action['params']>]\n : [params: NonNullable<Action['params']>]\n\n/**\n * Typed read client for one namespace's Data API. `Tables` comes from\n * `types.gen.ts` (wire types the apply refreshes from the YAML definitions),\n * so column names and row shapes are checked at compile time; the server\n * re-validates everything and Postgres RLS decides row visibility.\n *\n * ```ts\n * const client = createOrmClient<LendingTables>({ namespace: 'lending', baseUrl, getToken })\n * const rows = await client.table('loans').select('id', 'balance').gte('balance', 1000).rows()\n * const top = await client.query<{ officer: string; total: string }>(\n * 'select officer, sum(balance) as total from loans group by officer order by total desc limit $1',\n * [5],\n * )\n * ```\n */\nexport interface OrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n> {\n table<Name extends keyof Tables & string>(name: Name): TableQuery<Tables[Name]>\n /**\n * Raw read-only SQL for everything the filter grammar can't say —\n * aggregates, joins, OR, expressions, CTEs. The same sandbox as every\n * read: the namespace consumer role (grants stop at the namespace schema),\n * Postgres RLS over the caller's claims, and a READ ONLY transaction —\n * Postgres itself rejects writes, which stay on declared actions. Values\n * bind as $1, $2, … placeholders; never interpolate them into the string.\n */\n query<Row = Record<string, unknown>>(sql: string, params?: readonly QueryParam[]): Promise<Row[]>\n /**\n * Invoke a declared action — the only write path the Data API exposes. The\n * params and result are typed from the namespace's `<Ns>Actions`: an action\n * with `returns:` resolves to `{ rows: Row[] }`, a count action to\n * `{ rowsAffected: number }`.\n */\n action<Name extends keyof Actions & string>(\n name: Name,\n ...args: ActionArgs<Actions[Name]>\n ): Promise<Actions[Name]['result']>\n}\n\nexport function createOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>({\n namespace,\n baseUrl,\n getToken,\n fetchImpl,\n transport,\n dataToken,\n}: {\n namespace: string\n baseUrl?: string\n /** App-user / session bearer (CLI, browser). Mutually exclusive with dataToken. */\n getToken?: () => Promise<string | null> | string | null\n /**\n * Delegated function data token — the inbound `ORM_DATA_TOKEN_HEADER` value a\n * managed function receives. Pass it and the client authenticates as the\n * invoking user, scoped to the function's declared refs; no manual transport.\n */\n dataToken?: string | (() => Promise<string | null> | string | null)\n fetchImpl?: typeof globalThis.fetch\n /** Injected transport (tests, bridges); overrides baseUrl/getToken/dataToken. */\n transport?: OrmTransport\n}): OrmClient<Tables, Actions> {\n const resolved =\n transport ??\n createFetchTransport({\n baseUrl: requireOption(baseUrl, 'baseUrl'),\n ...(dataToken !== undefined\n ? { getDataToken: typeof dataToken === 'function' ? dataToken : () => dataToken }\n : { getToken: requireOption(getToken, 'getToken') }),\n fetchImpl,\n })\n\n return buildOrmClient<Tables, Actions>(resolved, namespace)\n}\n\n/**\n * The ESCALATION path — use only deliberately. A managed function receives a\n * separate *service* data token on `ORM_SERVICE_DATA_TOKEN_HEADER`; pass that\n * value here and the client authenticates as the function's SERVICE IDENTITY,\n * not the invoking user. Reads run with the service identity's grants (clamped\n * to the function's declared refs), NOT the caller's — so the caller's own row\n * visibility does not apply. The invoking user is still recorded for audit.\n *\n * Default to `createOrmClient` (acts as the invoking user, full per-user RLS).\n * Reach for this only when the function must intentionally act beyond the\n * caller — e.g. enforcing per-user rules in code over a coarse upstream that\n * has no granular permissions of its own. The distinct name is the guardrail:\n * choosing the service identity is always explicit and greppable.\n *\n * ```ts\n * const client = createServiceOrmClient<LendingTables>({\n * namespace: 'lending',\n * baseUrl,\n * serviceDataToken: req.headers['x-sequence-data-token-service'],\n * })\n * ```\n */\nexport function createServiceOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>({\n namespace,\n baseUrl,\n serviceDataToken,\n fetchImpl,\n transport,\n}: {\n namespace: string\n baseUrl?: string\n /** The inbound `ORM_SERVICE_DATA_TOKEN_HEADER` value — the function's service token. */\n serviceDataToken?: string | (() => Promise<string | null> | string | null)\n fetchImpl?: typeof globalThis.fetch\n /** Injected transport (tests, bridges); overrides baseUrl/serviceDataToken. */\n transport?: OrmTransport\n}): OrmClient<Tables, Actions> {\n const resolved =\n transport ??\n createFetchTransport({\n baseUrl: requireOption(baseUrl, 'baseUrl'),\n getDataToken:\n typeof serviceDataToken === 'function'\n ? serviceDataToken\n : () => requireOption(serviceDataToken, 'serviceDataToken'),\n fetchImpl,\n })\n\n return buildOrmClient<Tables, Actions>(resolved, namespace)\n}\n\n/** Shared client surface over a resolved transport — the token/identity choice is made by the factory above. */\nfunction buildOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>(resolved: OrmTransport, namespace: string): OrmClient<Tables, Actions> {\n return {\n table(name) {\n return new TableQuery(resolved, namespace, name)\n },\n async query(sql, params) {\n const payload = await resolved.post(`/api/data/${namespace}/query`, {\n sql,\n ...(params ? { params: [...params] } : {}),\n })\n if (!payload || typeof payload !== 'object' || !Array.isArray((payload as { rows?: unknown }).rows)) {\n throw new OrmClientError('unexpected Data API response shape — missing rows array')\n }\n return (payload as { rows: never[] }).rows\n },\n async action(name, ...args) {\n const payload = await resolved.post(`/api/data/${namespace}/actions/${name}`, args[0] ?? {})\n if (payload && typeof payload === 'object') {\n // A returns action responds with `rows`; a count action with\n // `rows_affected` (mapped to `rowsAffected` for the client).\n if (Array.isArray((payload as { rows?: unknown }).rows)) {\n return { rows: (payload as { rows: unknown[] }).rows } as Awaited<ReturnType<OrmClient<Tables, Actions>['action']>>\n }\n if ('rows_affected' in payload) {\n const rowsAffected = Number((payload as { rows_affected: unknown }).rows_affected)\n if (!Number.isNaN(rowsAffected)) {\n return { rowsAffected } as Awaited<ReturnType<OrmClient<Tables, Actions>['action']>>\n }\n }\n }\n throw new OrmClientError('unexpected action response shape — expected rows or rows_affected')\n },\n }\n}\n\nfunction requireOption<T>(value: T | undefined, name: string): T {\n if (value === undefined) throw new Error(`createOrmClient requires ${name} when no transport is injected`)\n return value\n}\n\nexport { TableQuery, type FilterValue, type ReadResponse } from './query-builder.js'\nexport { createFetchTransport, OrmClientError, type OrmTransport } from './transport.js'\n\nexport {\n OrmOperationError,\n configureOrmOperations,\n createOperationExecutor,\n createOrmFetch,\n executeOperation,\n} from './operations.js'\nexport type {\n ManifestOperation,\n OperationErrorEntry,\n OperationExecutor,\n SqlOperationExecutor,\n OperationReference,\n TypedOperationExecutor,\n TypedSqlOperationExecutor,\n ReadReceiptOperationExecutor,\n ReadReceiptSqlOperationExecutor,\n TypedReadReceiptOperationExecutor,\n TypedReadReceiptSqlOperationExecutor,\n OperationReadReceipt,\n OperationExecutionOptions,\n OperationExecutorConfig,\n OperationsManifest,\n} from './operations.js'\n\nexport { NAMESPACE_PATTERN, ORM_DATA_TOKEN_HEADER, ORM_SERVICE_DATA_TOKEN_HEADER } from '../constants.js'\nexport type { SqlQueryParameter, SqlQueryVariables, SqlQueryResult } from './sql.js'\nexport { BUILTIN_SQL_READ_HASH } from './sql.js'\nexport {\n createOperationExecutorWithTransport,\n type OperationTransport, type OperationTransportRequest, type OperationTransportResponse,\n} from './transport-executor.js'\n"]}
|
package/dist/client.d.cts
CHANGED
|
@@ -140,6 +140,8 @@ interface OperationExecutorConfig {
|
|
|
140
140
|
interface OperationExecutionOptions {
|
|
141
141
|
/** Reuse only when retrying the same logical mutation. */
|
|
142
142
|
idempotencyKey?: string;
|
|
143
|
+
/** Require the same source publication as an earlier read receipt. */
|
|
144
|
+
expectedSourceGeneration?: string;
|
|
143
145
|
}
|
|
144
146
|
interface OperationExecutor {
|
|
145
147
|
/** Execute a manifest operation by name (or a raw `sha256:` hash). */
|
|
@@ -156,6 +158,22 @@ interface TypedOperationExecutor extends OperationExecutor {
|
|
|
156
158
|
}
|
|
157
159
|
/** Factory result adds SQL without requiring it on existing typed host wrappers. */
|
|
158
160
|
type TypedSqlOperationExecutor = TypedOperationExecutor & SqlOperationExecutor;
|
|
161
|
+
interface OperationReadReceipt<TData> {
|
|
162
|
+
readonly data: TData;
|
|
163
|
+
/** Opaque source-publication identity; never an authorization credential. */
|
|
164
|
+
readonly sourceGeneration: string;
|
|
165
|
+
}
|
|
166
|
+
interface ReadReceiptOperationExecutor extends OperationExecutor {
|
|
167
|
+
/** Execute a registered query or built-in SQL read; fail closed without a receipt. */
|
|
168
|
+
executeWithReadReceipt<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>;
|
|
169
|
+
}
|
|
170
|
+
/** Additive factories preserve existing host wrappers without receipt support. */
|
|
171
|
+
type ReadReceiptSqlOperationExecutor = SqlOperationExecutor & ReadReceiptOperationExecutor;
|
|
172
|
+
interface TypedReadReceiptOperationExecutor extends TypedOperationExecutor {
|
|
173
|
+
executeWithReadReceipt<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>;
|
|
174
|
+
executeWithReadReceipt<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>;
|
|
175
|
+
}
|
|
176
|
+
type TypedReadReceiptSqlOperationExecutor = TypedReadReceiptOperationExecutor & ReadReceiptSqlOperationExecutor;
|
|
159
177
|
/** Generated handle identifies the registered contract; optional types are phantom. */
|
|
160
178
|
interface OperationReference<TVariables extends Record<string, unknown>, TData> {
|
|
161
179
|
readonly namespace: string;
|
|
@@ -163,7 +181,7 @@ interface OperationReference<TVariables extends Record<string, unknown>, TData>
|
|
|
163
181
|
readonly variables?: TVariables;
|
|
164
182
|
readonly result?: TData;
|
|
165
183
|
}
|
|
166
|
-
declare function createOperationExecutor({ baseUrl, namespace, manifest, getToken, getDataToken, fetchImpl, }: OperationExecutorConfig):
|
|
184
|
+
declare function createOperationExecutor({ baseUrl, namespace, manifest, getToken, getDataToken, fetchImpl, }: OperationExecutorConfig): TypedReadReceiptSqlOperationExecutor;
|
|
167
185
|
/**
|
|
168
186
|
* Configure the process-wide executor the generated `db<Name>` server
|
|
169
187
|
* functions call through. Call once at startup (server-side); browser apps
|
|
@@ -191,6 +209,7 @@ interface OperationTransportRequest {
|
|
|
191
209
|
op: string;
|
|
192
210
|
variables: Record<string, unknown>;
|
|
193
211
|
idempotencyKey?: string;
|
|
212
|
+
expectedSourceGeneration?: string;
|
|
194
213
|
}
|
|
195
214
|
interface OperationTransportResponse {
|
|
196
215
|
ok: boolean;
|
|
@@ -208,7 +227,7 @@ declare function createOperationExecutorWithTransport({ namespace, manifest, tra
|
|
|
208
227
|
/** Accept generated JSON imports directly; validate them at construction. */
|
|
209
228
|
manifest?: unknown;
|
|
210
229
|
transport: OperationTransport;
|
|
211
|
-
}):
|
|
230
|
+
}): TypedReadReceiptSqlOperationExecutor;
|
|
212
231
|
|
|
213
232
|
/** Bindable scalar for `query()` placeholders ($1, $2, …). */
|
|
214
233
|
type QueryParam = string | number | boolean | null;
|
|
@@ -307,4 +326,4 @@ declare function createServiceOrmClient<Tables extends Record<string, Record<str
|
|
|
307
326
|
transport?: OrmTransport;
|
|
308
327
|
}): OrmClient<Tables, Actions>;
|
|
309
328
|
|
|
310
|
-
export { BUILTIN_SQL_READ_HASH, type FilterValue, type ManifestOperation, type OperationErrorEntry, type OperationExecutor, type OperationExecutorConfig, type OperationReference, type OperationTransport, type OperationTransportRequest, type OperationTransportResponse, type OperationsManifest, type OrmActionShape, type OrmActions, type OrmClient, OrmClientError, OrmOperationError, type OrmTransport, type QueryParam, type ReadResponse, type SqlOperationExecutor, type SqlQueryParameter, type SqlQueryResult, type SqlQueryVariables, TableQuery, type TypedOperationExecutor, type TypedSqlOperationExecutor, configureOrmOperations, createFetchTransport, createOperationExecutor, createOperationExecutorWithTransport, createOrmClient, createOrmFetch, createServiceOrmClient, executeOperation };
|
|
329
|
+
export { BUILTIN_SQL_READ_HASH, type FilterValue, type ManifestOperation, type OperationErrorEntry, type OperationExecutionOptions, type OperationExecutor, type OperationExecutorConfig, type OperationReadReceipt, type OperationReference, type OperationTransport, type OperationTransportRequest, type OperationTransportResponse, type OperationsManifest, type OrmActionShape, type OrmActions, type OrmClient, OrmClientError, OrmOperationError, type OrmTransport, type QueryParam, type ReadReceiptOperationExecutor, type ReadReceiptSqlOperationExecutor, type ReadResponse, type SqlOperationExecutor, type SqlQueryParameter, type SqlQueryResult, type SqlQueryVariables, TableQuery, type TypedOperationExecutor, type TypedReadReceiptOperationExecutor, type TypedReadReceiptSqlOperationExecutor, type TypedSqlOperationExecutor, configureOrmOperations, createFetchTransport, createOperationExecutor, createOperationExecutorWithTransport, createOrmClient, createOrmFetch, createServiceOrmClient, executeOperation };
|
package/dist/client.d.ts
CHANGED
|
@@ -140,6 +140,8 @@ interface OperationExecutorConfig {
|
|
|
140
140
|
interface OperationExecutionOptions {
|
|
141
141
|
/** Reuse only when retrying the same logical mutation. */
|
|
142
142
|
idempotencyKey?: string;
|
|
143
|
+
/** Require the same source publication as an earlier read receipt. */
|
|
144
|
+
expectedSourceGeneration?: string;
|
|
143
145
|
}
|
|
144
146
|
interface OperationExecutor {
|
|
145
147
|
/** Execute a manifest operation by name (or a raw `sha256:` hash). */
|
|
@@ -156,6 +158,22 @@ interface TypedOperationExecutor extends OperationExecutor {
|
|
|
156
158
|
}
|
|
157
159
|
/** Factory result adds SQL without requiring it on existing typed host wrappers. */
|
|
158
160
|
type TypedSqlOperationExecutor = TypedOperationExecutor & SqlOperationExecutor;
|
|
161
|
+
interface OperationReadReceipt<TData> {
|
|
162
|
+
readonly data: TData;
|
|
163
|
+
/** Opaque source-publication identity; never an authorization credential. */
|
|
164
|
+
readonly sourceGeneration: string;
|
|
165
|
+
}
|
|
166
|
+
interface ReadReceiptOperationExecutor extends OperationExecutor {
|
|
167
|
+
/** Execute a registered query or built-in SQL read; fail closed without a receipt. */
|
|
168
|
+
executeWithReadReceipt<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>;
|
|
169
|
+
}
|
|
170
|
+
/** Additive factories preserve existing host wrappers without receipt support. */
|
|
171
|
+
type ReadReceiptSqlOperationExecutor = SqlOperationExecutor & ReadReceiptOperationExecutor;
|
|
172
|
+
interface TypedReadReceiptOperationExecutor extends TypedOperationExecutor {
|
|
173
|
+
executeWithReadReceipt<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>;
|
|
174
|
+
executeWithReadReceipt<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>;
|
|
175
|
+
}
|
|
176
|
+
type TypedReadReceiptSqlOperationExecutor = TypedReadReceiptOperationExecutor & ReadReceiptSqlOperationExecutor;
|
|
159
177
|
/** Generated handle identifies the registered contract; optional types are phantom. */
|
|
160
178
|
interface OperationReference<TVariables extends Record<string, unknown>, TData> {
|
|
161
179
|
readonly namespace: string;
|
|
@@ -163,7 +181,7 @@ interface OperationReference<TVariables extends Record<string, unknown>, TData>
|
|
|
163
181
|
readonly variables?: TVariables;
|
|
164
182
|
readonly result?: TData;
|
|
165
183
|
}
|
|
166
|
-
declare function createOperationExecutor({ baseUrl, namespace, manifest, getToken, getDataToken, fetchImpl, }: OperationExecutorConfig):
|
|
184
|
+
declare function createOperationExecutor({ baseUrl, namespace, manifest, getToken, getDataToken, fetchImpl, }: OperationExecutorConfig): TypedReadReceiptSqlOperationExecutor;
|
|
167
185
|
/**
|
|
168
186
|
* Configure the process-wide executor the generated `db<Name>` server
|
|
169
187
|
* functions call through. Call once at startup (server-side); browser apps
|
|
@@ -191,6 +209,7 @@ interface OperationTransportRequest {
|
|
|
191
209
|
op: string;
|
|
192
210
|
variables: Record<string, unknown>;
|
|
193
211
|
idempotencyKey?: string;
|
|
212
|
+
expectedSourceGeneration?: string;
|
|
194
213
|
}
|
|
195
214
|
interface OperationTransportResponse {
|
|
196
215
|
ok: boolean;
|
|
@@ -208,7 +227,7 @@ declare function createOperationExecutorWithTransport({ namespace, manifest, tra
|
|
|
208
227
|
/** Accept generated JSON imports directly; validate them at construction. */
|
|
209
228
|
manifest?: unknown;
|
|
210
229
|
transport: OperationTransport;
|
|
211
|
-
}):
|
|
230
|
+
}): TypedReadReceiptSqlOperationExecutor;
|
|
212
231
|
|
|
213
232
|
/** Bindable scalar for `query()` placeholders ($1, $2, …). */
|
|
214
233
|
type QueryParam = string | number | boolean | null;
|
|
@@ -307,4 +326,4 @@ declare function createServiceOrmClient<Tables extends Record<string, Record<str
|
|
|
307
326
|
transport?: OrmTransport;
|
|
308
327
|
}): OrmClient<Tables, Actions>;
|
|
309
328
|
|
|
310
|
-
export { BUILTIN_SQL_READ_HASH, type FilterValue, type ManifestOperation, type OperationErrorEntry, type OperationExecutor, type OperationExecutorConfig, type OperationReference, type OperationTransport, type OperationTransportRequest, type OperationTransportResponse, type OperationsManifest, type OrmActionShape, type OrmActions, type OrmClient, OrmClientError, OrmOperationError, type OrmTransport, type QueryParam, type ReadResponse, type SqlOperationExecutor, type SqlQueryParameter, type SqlQueryResult, type SqlQueryVariables, TableQuery, type TypedOperationExecutor, type TypedSqlOperationExecutor, configureOrmOperations, createFetchTransport, createOperationExecutor, createOperationExecutorWithTransport, createOrmClient, createOrmFetch, createServiceOrmClient, executeOperation };
|
|
329
|
+
export { BUILTIN_SQL_READ_HASH, type FilterValue, type ManifestOperation, type OperationErrorEntry, type OperationExecutionOptions, type OperationExecutor, type OperationExecutorConfig, type OperationReadReceipt, type OperationReference, type OperationTransport, type OperationTransportRequest, type OperationTransportResponse, type OperationsManifest, type OrmActionShape, type OrmActions, type OrmClient, OrmClientError, OrmOperationError, type OrmTransport, type QueryParam, type ReadReceiptOperationExecutor, type ReadReceiptSqlOperationExecutor, type ReadResponse, type SqlOperationExecutor, type SqlQueryParameter, type SqlQueryResult, type SqlQueryVariables, TableQuery, type TypedOperationExecutor, type TypedReadReceiptOperationExecutor, type TypedReadReceiptSqlOperationExecutor, type TypedSqlOperationExecutor, configureOrmOperations, createFetchTransport, createOperationExecutor, createOperationExecutorWithTransport, createOrmClient, createOrmFetch, createServiceOrmClient, executeOperation };
|
package/dist/client.js
CHANGED
|
@@ -191,6 +191,20 @@ function readOperationResponse({
|
|
|
191
191
|
}
|
|
192
192
|
return payload.data;
|
|
193
193
|
}
|
|
194
|
+
function readOperationResponseWithReceipt({
|
|
195
|
+
ok,
|
|
196
|
+
status,
|
|
197
|
+
body,
|
|
198
|
+
expectedSourceGeneration
|
|
199
|
+
}) {
|
|
200
|
+
const data = readOperationResponse({ ok, status, body });
|
|
201
|
+
const extensions = isRecord(body) && isRecord(body.extensions) ? body.extensions : null;
|
|
202
|
+
const sourceGeneration = extensions?.sourceGeneration;
|
|
203
|
+
if (typeof sourceGeneration !== "string" || !/^[a-f0-9]{64}$/.test(sourceGeneration) || expectedSourceGeneration !== void 0 && expectedSourceGeneration !== sourceGeneration) {
|
|
204
|
+
throw new OrmOperationError("Source generation unavailable", status, "OBJECT_UNAVAILABLE");
|
|
205
|
+
}
|
|
206
|
+
return { data, sourceGeneration };
|
|
207
|
+
}
|
|
194
208
|
|
|
195
209
|
// src/client/sql.ts
|
|
196
210
|
var BUILTIN_SQL_READ_HASH = "sha256:a50c477c952a5e0fe68ed158a4530e4aab573c09bcbb1a8ac454dc88a39a6258";
|
|
@@ -201,6 +215,11 @@ function validateIdempotencyKey(key) {
|
|
|
201
215
|
throw new OrmClientError("idempotencyKey must be 1\u2013128 letters, digits, dots, underscores, colons or hyphens");
|
|
202
216
|
}
|
|
203
217
|
}
|
|
218
|
+
function validateExpectedSourceGeneration(value) {
|
|
219
|
+
if (value !== void 0 && (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value))) {
|
|
220
|
+
throw new OrmClientError("expectedSourceGeneration must be a lowercase 64-character hexadecimal receipt");
|
|
221
|
+
}
|
|
222
|
+
}
|
|
204
223
|
var dataPlanePath = (namespace) => `/_data/v2/${namespace}`;
|
|
205
224
|
function resolveOpHash(manifest, op) {
|
|
206
225
|
if (op.startsWith("sha256:")) return op;
|
|
@@ -213,6 +232,23 @@ function resolveOpHash(manifest, op) {
|
|
|
213
232
|
}
|
|
214
233
|
return entry.hash;
|
|
215
234
|
}
|
|
235
|
+
function createReadReceiptOperationResolver({ operations }) {
|
|
236
|
+
const hashesByName = /* @__PURE__ */ new Map();
|
|
237
|
+
const readHashes = /* @__PURE__ */ new Set([BUILTIN_SQL_READ_HASH]);
|
|
238
|
+
const mutationHashes = /* @__PURE__ */ new Set();
|
|
239
|
+
for (const [name, entry] of operations) {
|
|
240
|
+
hashesByName.set(name, entry.hash);
|
|
241
|
+
if (entry.kind === "query" && /^sha256:[a-f0-9]{64}$/.test(entry.hash)) readHashes.add(entry.hash);
|
|
242
|
+
if (entry.kind === "mutation") mutationHashes.add(entry.hash);
|
|
243
|
+
}
|
|
244
|
+
return ({ selector, hashOnly = false }) => {
|
|
245
|
+
const hash = selector.startsWith("sha256:") ? selector : hashOnly ? void 0 : hashesByName.get(selector);
|
|
246
|
+
if (!hash || !readHashes.has(hash) || mutationHashes.has(hash)) {
|
|
247
|
+
throw new OrmClientError("read receipts require a registered query or the built-in SQL read");
|
|
248
|
+
}
|
|
249
|
+
return hash;
|
|
250
|
+
};
|
|
251
|
+
}
|
|
216
252
|
function createOperationExecutor({
|
|
217
253
|
baseUrl,
|
|
218
254
|
namespace,
|
|
@@ -226,25 +262,42 @@ function createOperationExecutor({
|
|
|
226
262
|
throw new OrmClientError("provide exactly one of getToken (bearer) or getDataToken (delegated)");
|
|
227
263
|
}
|
|
228
264
|
const root = baseUrl.replace(/\/+$/, "");
|
|
229
|
-
|
|
265
|
+
const resolveReceiptOperation = createReadReceiptOperationResolver({ operations: Object.entries(manifest.operations) });
|
|
266
|
+
async function request({ op, variables, options, requireReadReceipt = false }) {
|
|
230
267
|
validateIdempotencyKey(options.idempotencyKey);
|
|
268
|
+
validateExpectedSourceGeneration(options.expectedSourceGeneration);
|
|
231
269
|
if (typeof op !== "string" && op.namespace !== namespace) throw new OrmClientError("operation belongs to a different namespace");
|
|
232
|
-
const hash = typeof op === "string" ? resolveOpHash(manifest, op) : op.hash;
|
|
270
|
+
const hash = requireReadReceipt ? resolveReceiptOperation({ selector: typeof op === "string" ? op : op.hash, hashOnly: typeof op !== "string" }) : typeof op === "string" ? resolveOpHash(manifest, op) : op.hash;
|
|
233
271
|
const token = await (getDataToken ?? getToken)();
|
|
234
272
|
if (!token) throw new OrmClientError("not authenticated \u2014 no token available");
|
|
235
273
|
const auth = getDataToken ? { [ORM_DATA_TOKEN_HEADER]: token } : { Authorization: `Bearer ${token}` };
|
|
236
274
|
const response = await fetchImpl(`${root}${dataPlanePath(namespace)}`, {
|
|
237
275
|
method: "POST",
|
|
238
276
|
headers: { ...auth, "Content-Type": "application/json" },
|
|
239
|
-
body: JSON.stringify({
|
|
277
|
+
body: JSON.stringify({
|
|
278
|
+
op: hash,
|
|
279
|
+
variables,
|
|
280
|
+
idempotencyKey: options.idempotencyKey,
|
|
281
|
+
expectedSourceGeneration: options.expectedSourceGeneration
|
|
282
|
+
})
|
|
240
283
|
});
|
|
241
|
-
return
|
|
284
|
+
return {
|
|
242
285
|
ok: response.ok,
|
|
243
286
|
status: response.status,
|
|
244
287
|
body: await response.json().catch(() => null)
|
|
245
|
-
}
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
async function execute(op, variables = {}, options = {}) {
|
|
291
|
+
const executionOptions = { ...options };
|
|
292
|
+
const response = await request({ op, variables, options: executionOptions });
|
|
293
|
+
return executionOptions.expectedSourceGeneration === void 0 ? readOperationResponse(response) : readOperationResponseWithReceipt({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration }).data;
|
|
294
|
+
}
|
|
295
|
+
async function executeWithReadReceipt(op, variables = {}, options = {}) {
|
|
296
|
+
const executionOptions = { ...options };
|
|
297
|
+
const response = await request({ op, variables, options: executionOptions, requireReadReceipt: true });
|
|
298
|
+
return readOperationResponseWithReceipt({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration });
|
|
246
299
|
}
|
|
247
|
-
return { execute, sql: (variables) => execute(BUILTIN_SQL_READ_HASH, variables) };
|
|
300
|
+
return { execute, executeWithReadReceipt, sql: (variables) => execute(BUILTIN_SQL_READ_HASH, variables) };
|
|
248
301
|
}
|
|
249
302
|
var configured = null;
|
|
250
303
|
function configureOrmOperations(config) {
|
|
@@ -313,33 +366,46 @@ function readManifestHashes(manifest) {
|
|
|
313
366
|
if (!/^[_A-Za-z][_0-9A-Za-z]*$/.test(name) || !isRecord(entry) || typeof entry.hash !== "string" || !operationHash.test(entry.hash) || entry.kind !== "query" && entry.kind !== "mutation") {
|
|
314
367
|
throw new OrmClientError(`invalid operations manifest entry "${name}" \u2014 regenerate the manifest`);
|
|
315
368
|
}
|
|
316
|
-
hashes.set(name, entry.hash);
|
|
369
|
+
hashes.set(name, { hash: entry.hash, kind: entry.kind });
|
|
317
370
|
}
|
|
318
371
|
return hashes;
|
|
319
372
|
}
|
|
320
373
|
function createOperationExecutorWithTransport({ namespace, manifest, transport }) {
|
|
321
374
|
if (typeof namespace !== "string" || !NAMESPACE_PATTERN.test(namespace)) throw new OrmClientError("invalid ORM namespace \u2014 expected a lowercase identifier of at most 41 characters");
|
|
322
375
|
const hashes = manifest === void 0 ? /* @__PURE__ */ new Map() : readManifestHashes(manifest);
|
|
323
|
-
const knownHashes = new Set(hashes.values());
|
|
324
|
-
|
|
376
|
+
const knownHashes = new Set([...hashes.values()].map((entry) => entry.hash));
|
|
377
|
+
const resolveReceiptOperation = createReadReceiptOperationResolver({ operations: hashes });
|
|
378
|
+
async function request({ op, variables, options, requireReadReceipt = false }) {
|
|
325
379
|
validateIdempotencyKey(options.idempotencyKey);
|
|
380
|
+
validateExpectedSourceGeneration(options.expectedSourceGeneration);
|
|
326
381
|
if (typeof op !== "string" && op.namespace !== namespace) throw new OrmClientError("operation belongs to a different namespace");
|
|
327
382
|
const selector = typeof op === "string" ? op : op.hash;
|
|
328
|
-
const hash = selector === BUILTIN_SQL_READ_HASH ? selector : hashes.get(selector) ?? (knownHashes.has(selector) ? selector : void 0);
|
|
383
|
+
const hash = requireReadReceipt ? resolveReceiptOperation({ selector, hashOnly: typeof op !== "string" }) : selector === BUILTIN_SQL_READ_HASH ? selector : hashes.get(selector)?.hash ?? (knownHashes.has(selector) ? selector : void 0);
|
|
329
384
|
if (!hash) throw new OrmClientError(`unknown operation "${op}" \u2014 not in the manifest (${hashes.size} known). Re-run seq-studio orm generate.`);
|
|
330
385
|
if (!isRecord(variables)) throw new OrmClientError("operation variables must be an object");
|
|
331
386
|
const response = await transport({
|
|
332
387
|
namespace,
|
|
333
388
|
op: hash,
|
|
334
389
|
variables,
|
|
335
|
-
...options.idempotencyKey === void 0 ? {} : { idempotencyKey: options.idempotencyKey }
|
|
390
|
+
...options.idempotencyKey === void 0 ? {} : { idempotencyKey: options.idempotencyKey },
|
|
391
|
+
...options.expectedSourceGeneration === void 0 ? {} : { expectedSourceGeneration: options.expectedSourceGeneration }
|
|
336
392
|
});
|
|
337
393
|
if (!response || typeof response.ok !== "boolean" || !Number.isInteger(response.status) || response.status < 100 || response.status > 599 || response.ok !== (response.status >= 200 && response.status < 300)) {
|
|
338
394
|
throw new OrmOperationError("malformed transport response", null, null);
|
|
339
395
|
}
|
|
340
|
-
return
|
|
396
|
+
return response;
|
|
397
|
+
}
|
|
398
|
+
async function execute(op, variables = {}, options = {}) {
|
|
399
|
+
const executionOptions = { ...options };
|
|
400
|
+
const response = await request({ op, variables, options: executionOptions });
|
|
401
|
+
return executionOptions.expectedSourceGeneration === void 0 ? readOperationResponse(response) : readOperationResponseWithReceipt({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration }).data;
|
|
402
|
+
}
|
|
403
|
+
async function executeWithReadReceipt(op, variables = {}, options = {}) {
|
|
404
|
+
const executionOptions = { ...options };
|
|
405
|
+
const response = await request({ op, variables, options: executionOptions, requireReadReceipt: true });
|
|
406
|
+
return readOperationResponseWithReceipt({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration });
|
|
341
407
|
}
|
|
342
|
-
return { execute, sql: (variables) => execute(BUILTIN_SQL_READ_HASH, variables) };
|
|
408
|
+
return { execute, executeWithReadReceipt, sql: (variables) => execute(BUILTIN_SQL_READ_HASH, variables) };
|
|
343
409
|
}
|
|
344
410
|
|
|
345
411
|
// src/client/index.ts
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/constants.ts","../src/client/errors.ts","../src/client/transport.ts","../src/client/query-builder.ts","../src/client/response.ts","../src/client/sql.ts","../src/client/operations.ts","../src/client/transport-executor.ts","../src/client/index.ts"],"names":[],"mappings":";AAIO,IAAM,iBAAA,GAAoB;AAG1B,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KAAA,CAAM,CAAA,yBAAA,EAA4B,IAAI,CAAA,8BAAA,CAAgC,CAAA;AACzG,EAAA,OAAO,KAAA;AACT","file":"client.js","sourcesContent":["/** Shared grammar for namespace identifiers; never interpolate arbitrary paths.\n * orm_events and orm_native_sources are migration-owned control-plane schemas,\n * not builder namespaces. Exclude their suffixes at every API/authoring entry.\n */\nexport const NAMESPACE_PATTERN = /^(?!(?:events|native_sources)$)[a-z][a-z0-9_]{0,40}$/\n\n/** Caller-scoped delegated data credential, supplied by an authenticated host. */\nexport const ORM_DATA_TOKEN_HEADER = 'x-sequence-data-token'\n\n/** Separate service-identity credential; never used as an implicit fallback. */\nexport const ORM_SERVICE_DATA_TOKEN_HEADER = 'x-sequence-data-token-service'\n\nexport const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/\n/** Native source columns may have one leading underscore; relation names may not. */\nexport const COLUMN_IDENTIFIER_PATTERN = /^_?[a-z][a-z0-9_]*$/\nexport const MAX_IDENTIFIER_LENGTH = 63\n\n/**\n * Custom Roles & Capabilities claim keys as policies reference them: a\n * host-scoped registry key, an org pin's `org/<key>`, or an Application\n * capability pin's `app/<application-id>/<key>`. Matches the registry\n * key grammar EXACTLY (`[a-z0-9-]`, 1–64 chars, no `_` — the FGA object-id\n * delimiter) so any capability that's declarable/attachable in namespace.yaml\n * can also be referenced here — a stricter pattern would let a valid key\n * register yet fail at apply (e.g. `org/2fa`, a one-char or digit-led key).\n */\nexport const CAPABILITY_KEY_PATTERN = /^(?:org\\/|app\\/[a-z][a-z0-9-]{0,63}\\/)?[a-z0-9-]{1,64}$/\n\n/** Hard ceiling for an explicitly authored flat persisted GraphQL read. */\nexport const MAX_PERSISTED_READ_ROWS = 50_001\n\nexport const CLAIM_KEY_PATTERN = /^[a-z][a-z0-9_]*$/\n\n/** Qualified reference to a table outside the defining file: `<schema>.<table>`. */\nexport const QUALIFIED_TABLE_PATTERN = /^[a-z][a-z0-9_]{0,62}\\.[a-z][a-z0-9_]{0,62}$/\n\n/** Qualified source syntax only; the serving installation controls authorized backing. */\nexport const SYNCED_SOURCE_PATTERN = QUALIFIED_TABLE_PATTERN\n\nexport const ORM_SCHEMA_PREFIX = 'orm_'\nexport const CONSUMER_ROLE_SUFFIX = '_consumer'\n\nexport const ormSchemaName = (namespace: string): string => {\n if (!NAMESPACE_PATTERN.test(namespace)) throw new Error(`invalid or reserved ORM namespace '${namespace}'`)\n return `${ORM_SCHEMA_PREFIX}${namespace}`\n}\nexport const consumerRoleName = (namespace: string): string =>\n `${ormSchemaName(namespace)}${CONSUMER_ROLE_SUFFIX}`\n\nexport const DEFINITION_FILE_EXTENSIONS = ['.yml', '.yaml'] as const\n\n/** Reserved basenames for the namespace-level config file (description, org capability pins). */\nexport const NAMESPACE_CONFIG_FILENAMES = new Set(['namespace.yaml', 'namespace.yml'])\n\nexport const HASH_DOMAIN = 'sequence-orm-definitions\\0'\n\n/**\n * A per-file byte cap where the loader reads untrusted YAML into memory — a real failure mode, not a product\n * limit. Counts of tables/indexes/params and policy/SQL lengths are\n * deliberately uncapped; Postgres enforces its own limits loudly at apply.\n */\nexport const MAX_DEFINITION_FILE_BYTES = 1024 * 1024\n\n/** Generated SDL aggregates every table/view; it is not an individual source file. */\nexport const MAX_GENERATED_SDL_BYTES = 16 * 1024 * 1024\n\n/** Registration and reviewed exports carry SDL, canonical metadata, snapshots and migrations. */\nexport const ORM_REGISTRATION_MAX_BYTES = 64 * 1024 * 1024\n\n/** `/api/data/<ns>/actions/…` and `/api/data/<ns>/query` share the table path segment. */\nexport const RESERVED_TABLE_NAMES = new Set(['actions', 'query'])\n\n/**\n * The Data API's query-string grammar owns these parameter names — a column\n * with one of them could never be filtered over the wire, so definitions\n * refuse it up front (\"validate rejects only what can never work\").\n */\nexport const RESERVED_COLUMN_NAMES = new Set(['select', 'order', 'limit', 'offset'])\n\n/**\n * Per-cell metadata (`cellMetadata: true`, and every resolved-table source) is\n * stored as typed system columns beside each tracked column `c`:\n *\n * - `c__at` timestamptz — when the cell was last written (NULL: never / no opinion)\n * - `c__by` text — who wrote it\n * - `c__rev` uuid — a resolved table's manual source only: the edit's\n * identity, so an async writeback confirmation clears\n * only the exact edit it delivered\n *\n * A resolved view additionally exposes, per resolved column, the winner's\n * `c__src` (source name) and `c__lost` (newer candidates that lost, jsonb).\n * None of these are GraphQL columns: they surface through the typed `cells`\n * object and are never client-writable.\n */\nexport const CELL_PARTS = ['at', 'by', 'rev', 'source', 'conflicts'] as const\nexport type CellPart = (typeof CELL_PARTS)[number]\nexport const CELL_PART_SUFFIX: Readonly<Record<CellPart, string>> = {\n at: '__at', by: '__by', rev: '__rev', source: '__src', conflicts: '__lost',\n}\n/** Longest physical column name that can carry cell parts (63 minus the longest suffix). */\nexport const MAX_TRACKED_COLUMN_NAME = MAX_IDENTIFIER_LENGTH - 6\n/** GraphQL field carrying a row's per-cell metadata object. */\nexport const CELLS_FIELD = 'cells'\n\n/** Physical (and logical) name of one cell part of a column. */\nexport function cellColumnName(column: string, part: CellPart): string {\n return `${column}${CELL_PART_SUFFIX[part]}`\n}\n\n/**\n * Actor recorded when the data plane computes a materialized resolved table's\n * rows for every caller. Its claims are what the compute view's synced\n * sources see (materialized ETL sources must be readable by anyone).\n */\nexport const MATERIALIZE_ACTOR = 'orm:materialize'\nexport const MATERIALIZE_CLAIMS_JSON = JSON.stringify({ sub: MATERIALIZE_ACTOR, org: null, roles: [], capabilities: [] })\n\n/**\n * Apply-generated function that reconciles a materialized resolved table with\n * its compute view: `SELECT * FROM orm_<ns>.\"<table>__refresh\"(wait)` returns\n * `(upserted, deleted, locked)`; without `wait` it skips when another refresh\n * holds the table's lock. The one refresh implementation — the Atlas\n * reconcile, the post-ETL hook, and an operator in psql all call it.\n */\nexport function materializedRefreshFunctionName(table: string): string {\n return `${table}__refresh`\n}\n\n/**\n * Advisory-lock key serializing a materialized table's refreshes (hashed with\n * `hashtext`). A full refresh holds it exclusively and every ORM write's\n * per-row refresh holds it shared, both before reading the compute view — so\n * a full refresh never reads a snapshot older than a write it then overwrites.\n */\nexport function materializeLockKey(schema: string, table: string): string {\n return `orm:materialize:${schema}.${table}`\n}\n","export class OrmClientError extends Error {\n override readonly name: string = 'OrmClientError'\n\n constructor(message: string, readonly status: number | null = null) {\n super(message)\n }\n}\n\nexport interface OperationErrorEntry {\n readonly message: string\n readonly extensions?: { readonly code?: string }\n}\n\nexport class OrmOperationError extends OrmClientError {\n override readonly name = 'OrmOperationError'\n\n constructor(\n message: string,\n status: number | null,\n readonly code: string | null,\n readonly errors: readonly OperationErrorEntry[] = [],\n ) {\n super(message, status)\n }\n}\n","/**\n * Fetch-based transport for the Data API. Deliberately free of node builtins\n * so the client runs anywhere a `fetch` exists — browsers, artifact bridges,\n * Cloud Functions, `node:vm` sandboxes.\n */\nimport { ORM_DATA_TOKEN_HEADER } from '../constants.js'\n\nimport { OrmClientError } from './errors.js'\nexport { OrmClientError } from './errors.js'\n\nexport interface OrmTransport {\n get(path: string, params: URLSearchParams): Promise<unknown>\n post(path: string, body: unknown): Promise<unknown>\n}\n\nexport function createFetchTransport({\n baseUrl,\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: {\n baseUrl: string\n /** App-user / session bearer → `Authorization: Bearer`. */\n getToken?: () => Promise<string | null> | string | null\n /** Delegated, attenuated function token → the `ORM_DATA_TOKEN_HEADER`. */\n getDataToken?: () => Promise<string | null> | string | null\n fetchImpl?: typeof globalThis.fetch\n}): OrmTransport {\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n\n const request = async (path: string, init: Omit<RequestInit, 'headers'>): Promise<unknown> => {\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n // The delegated token rides its own header; the app-user bearer rides Authorization.\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n const response = await fetchImpl(`${root}${path}`, {\n ...init,\n headers: { ...auth, 'Content-Type': 'application/json' },\n })\n const payload: unknown = await response.json().catch(() => null)\n if (!response.ok) {\n const detail =\n payload && typeof payload === 'object' && 'detail' in payload\n ? String((payload as { detail: unknown }).detail)\n : `HTTP ${response.status}`\n throw new OrmClientError(detail, response.status)\n }\n return payload\n }\n\n return {\n get: (path, params) => {\n // Not params.size — that's Node 19.8+/2023-browser surface, newer than\n // the fetch this module documents as its only requirement.\n const serialized = params.toString()\n return request(serialized === '' ? path : `${path}?${serialized}`, {})\n },\n post: (path, body) => request(path, { method: 'POST', body: JSON.stringify(body ?? {}) }),\n }\n}\n","import { OrmClientError, type OrmTransport } from './transport.js'\n\n/**\n * Fluent read query over one table. Serializes to exactly the PostgREST\n * subset the Data API's query parser accepts — the round-trip contract is\n * asserted server-side (builder output → parseReadQuery) so the two ends\n * can't drift apart silently.\n *\n * IMMUTABLE: every method returns a new query, so narrowing `select()` can\n * never leave an alias holding a stale wider row type, and a base query can\n * be safely forked into variants.\n */\n\nexport type FilterValue = string | number | boolean\n\nexport interface ReadResponse<Row> {\n readonly rows: readonly Row[]\n readonly limit: number\n readonly offset: number\n}\n\n/** Characters the in-list grammar cannot carry — there is no escaping, so the builder hard-fails. */\nconst IN_LIST_UNREPRESENTABLE = /[,()]/\n\ninterface QueryState {\n readonly filters: ReadonlyArray<[column: string, expression: string]>\n readonly orderings: readonly string[]\n readonly selection: readonly string[] | null\n readonly limitValue: number | null\n readonly offsetValue: number | null\n}\n\nconst EMPTY_STATE: QueryState = {\n filters: [],\n orderings: [],\n selection: null,\n limitValue: null,\n offsetValue: null,\n}\n\n/**\n * `Row` is the TABLE's row (filters and order always accept every column);\n * `Result` is what rows() yields — narrowed by select(), re-widenable by a\n * later select() since keys always come from Row.\n */\nexport class TableQuery<Row extends Record<string, unknown>, Result = Row> {\n constructor(\n private readonly transport: OrmTransport,\n private readonly namespace: string,\n private readonly table: string,\n private readonly state: QueryState = EMPTY_STATE,\n ) {}\n\n private with(patch: Partial<QueryState>): TableQuery<Row, Result> {\n return new TableQuery(this.transport, this.namespace, this.table, { ...this.state, ...patch })\n }\n\n select<K extends keyof Row & string>(...columns: [K, ...K[]]): TableQuery<Row, Pick<Row, K>> {\n return new TableQuery<Row, Pick<Row, K>>(this.transport, this.namespace, this.table, {\n ...this.state,\n selection: columns,\n })\n }\n\n eq<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'eq', value)\n }\n\n ne<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'ne', value)\n }\n\n gt<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'gt', value)\n }\n\n gte<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'gte', value)\n }\n\n lt<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'lt', value)\n }\n\n lte<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'lte', value)\n }\n\n like<K extends keyof Row & string>(column: K, pattern: string): TableQuery<Row, Result> {\n return this.filter(column, 'like', pattern)\n }\n\n ilike<K extends keyof Row & string>(column: K, pattern: string): TableQuery<Row, Result> {\n return this.filter(column, 'ilike', pattern)\n }\n\n in<K extends keyof Row & string>(column: K, values: readonly FilterValue[]): TableQuery<Row, Result> {\n // An empty list is representable — `in.()` matches nothing, the same\n // semantics the server executes. Blank entries are legitimate values in\n // multi-entry lists (`in.(a,)` carries ['a','']), but a LONE '' renders\n // as `in.()` and silently becomes the empty list — unrepresentable.\n // Beyond that only characters the grammar can't escape, and whitespace\n // padding the server-side split would silently swallow, are refused.\n const rendered = values.map((value) => {\n const text = String(value)\n if (IN_LIST_UNREPRESENTABLE.test(text) || text !== text.trim()) {\n throw new OrmClientError(`in() value '${text}' cannot be represented — the list grammar has no escaping`)\n }\n return text\n })\n if (rendered.length === 1 && rendered[0] === '') {\n throw new OrmClientError(\"in() with a lone '' cannot be represented — it would read as the empty list\")\n }\n return this.with({ filters: [...this.state.filters, [column, `in.(${rendered.join(',')})`]] })\n }\n\n is<K extends keyof Row & string>(column: K, value: null | boolean): TableQuery<Row, Result> {\n return this.with({\n filters: [...this.state.filters, [column, `is.${value === null ? 'null' : value}`]],\n })\n }\n\n order<K extends keyof Row & string>(column: K, direction: 'asc' | 'desc' = 'asc'): TableQuery<Row, Result> {\n return this.with({ orderings: [...this.state.orderings, `${column}.${direction}`] })\n }\n\n limit(value: number): TableQuery<Row, Result> {\n return this.with({ limitValue: value })\n }\n\n offset(value: number): TableQuery<Row, Result> {\n return this.with({ offsetValue: value })\n }\n\n /** The exact query string sent to the Data API — exposed for debugging and the grammar contract test. */\n searchParams(): URLSearchParams {\n const params = new URLSearchParams()\n for (const [column, expression] of this.state.filters) params.append(column, expression)\n if (this.state.orderings.length > 0) params.set('order', this.state.orderings.join(','))\n if (this.state.selection) params.set('select', this.state.selection.join(','))\n if (this.state.limitValue !== null) params.set('limit', String(this.state.limitValue))\n if (this.state.offsetValue !== null) params.set('offset', String(this.state.offsetValue))\n return params\n }\n\n async rows(): Promise<Result[]> {\n const payload = await this.transport.get(\n `/api/data/${this.namespace}/${this.table}`,\n this.searchParams(),\n )\n if (!payload || typeof payload !== 'object' || !Array.isArray((payload as { rows?: unknown }).rows)) {\n throw new OrmClientError('unexpected Data API response shape — missing rows array')\n }\n return (payload as { rows: Result[] }).rows\n }\n\n private filter(column: string, op: string, value: FilterValue): TableQuery<Row, Result> {\n return this.with({ filters: [...this.state.filters, [column, `${op}.${String(value)}`]] })\n }\n}\n","import { OrmOperationError, type OperationErrorEntry } from './errors.js'\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isOperationError(value: unknown): value is OperationErrorEntry {\n if (!isRecord(value) || typeof value.message !== 'string') return false\n if (value.extensions === undefined) return true\n return isRecord(value.extensions) && (value.extensions.code === undefined || typeof value.extensions.code === 'string')\n}\n\nexport function readOperationResponse<TData>({\n ok, status, body,\n}: { ok: boolean; status: number; body: unknown }): TData {\n const payload = isRecord(body) ? body : null\n const rawErrors = payload?.errors\n if (rawErrors !== undefined && (!Array.isArray(rawErrors) || !rawErrors.every(isOperationError))) {\n throw new OrmOperationError('malformed response: invalid errors', status, null)\n }\n const errors: OperationErrorEntry[] = rawErrors ?? []\n if (!ok || errors.length > 0) {\n const first = errors[0]\n throw new OrmOperationError(first?.message ?? `HTTP ${status}`, status, first?.extensions?.code ?? null, errors)\n }\n if (!payload || payload.data === undefined || payload.data === null) {\n throw new OrmOperationError('malformed response: missing data', status, null)\n }\n if (!isRecord(payload.data)) {\n throw new OrmOperationError('malformed response: data must be an object', status, null)\n }\n // Generated consumer types describe operation data; envelope validation\n // cannot prove an application's selection-specific TData at runtime.\n return payload.data as TData\n}\n","/** Runtime SQL inputs are values, never interpolated into the submitted SQL. */\n// SHA-256 of \"sequence-orm-builtin-sql-read-v1\". This identifies server-owned\n// behavior, independent of a namespace's authored operation manifest.\nexport const BUILTIN_SQL_READ_HASH = 'sha256:a50c477c952a5e0fe68ed158a4530e4aab573c09bcbb1a8ac454dc88a39a6258'\n\nexport type SqlQueryParameter =\n | { type: 'text' | 'uuid' | 'date' | 'timestamptz' | 'numeric' | 'bigint'; value: string | null }\n | { type: 'integer' | 'double'; value: number | null }\n | { type: 'boolean'; value: boolean | null }\n\nexport type SqlQueryVariables = {\n sql: string\n parameters?: Record<string, SqlQueryParameter>\n}\n\nexport interface SqlQueryResult {\n columns: Array<{ name: string; type: string; nullable: boolean }>\n rows: Array<Array<string | number | boolean | null>>\n truncated: boolean\n}\n","/**\n * Persisted-operation client for the v2 data plane. The wire carries only\n * `{ op: <hash>, variables, idempotencyKey? }`. Runtime SQL contracts accept SQL in variables;\n * GraphQL and fixed SQL operations keep their documents server-side. This runtime\n * is deliberately free of node builtins and third-\n * party deps (no @apollo/client import): Apollo integration happens through a\n * fetch-compatible shim (`createOrmFetch`) handed to `HttpLink({ fetch })`.\n */\nimport { OrmClientError } from './errors.js'\nimport { readOperationResponse } from './response.js'\nimport { ORM_DATA_TOKEN_HEADER } from '../constants.js'\nimport { BUILTIN_SQL_READ_HASH, type SqlQueryVariables, type SqlQueryResult } from './sql.js'\n\nexport { OrmOperationError, type OperationErrorEntry } from './errors.js'\n\n/** One entry of `operations.manifest.json` (generated by `orm generate`). */\nexport interface ManifestOperation {\n readonly hash: string\n readonly kind: 'query' | 'mutation'\n readonly requires: { readonly capability?: string; readonly role?: string } | null\n}\n\nexport interface OperationsManifest {\n readonly schemaHash: string\n readonly opsHash?: string\n readonly operations: Readonly<Record<string, ManifestOperation>>\n}\n\nexport interface OperationExecutorConfig {\n /** Deployment host root, e.g. `https://atlas.seqholdings.com`. */\n baseUrl: string\n namespace: string\n manifest?: OperationsManifest\n /** App-user / session bearer → `Authorization: Bearer`. */\n getToken?: () => Promise<string | null> | string | null\n /** Delegated, attenuated function token → the `ORM_DATA_TOKEN_HEADER`. */\n getDataToken?: () => Promise<string | null> | string | null\n fetchImpl?: typeof globalThis.fetch\n}\n\nexport interface OperationExecutionOptions {\n /** Reuse only when retrying the same logical mutation. */\n idempotencyKey?: string\n}\n\nexport function validateIdempotencyKey(key: string | undefined): void {\n if (key !== undefined && !/^[A-Za-z0-9._:-]{1,128}$/.test(key)) {\n throw new OrmClientError('idempotencyKey must be 1–128 letters, digits, dots, underscores, colons or hyphens')\n }\n}\n\nexport interface OperationExecutor {\n /** Execute a manifest operation by name (or a raw `sha256:` hash). */\n execute<TData = Record<string, unknown>>(\n op: string,\n variables?: Record<string, unknown>,\n options?: OperationExecutionOptions,\n ): Promise<TData>\n}\n\n/** Additive factory result; existing host wrappers implementing OperationExecutor remain valid. */\nexport interface SqlOperationExecutor extends OperationExecutor {\n /** Default read-only ontology SQL; no authored operation or manifest needed. */\n sql(variables: SqlQueryVariables): Promise<SqlQueryResult>\n}\n\nexport interface TypedOperationExecutor extends OperationExecutor {\n execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n}\n\n/** Factory result adds SQL without requiring it on existing typed host wrappers. */\nexport type TypedSqlOperationExecutor = TypedOperationExecutor & SqlOperationExecutor\n\nconst dataPlanePath = (namespace: string): string => `/_data/v2/${namespace}`\n\n/** Generated handle identifies the registered contract; optional types are phantom. */\nexport interface OperationReference<TVariables extends Record<string, unknown>, TData> {\n readonly namespace: string\n readonly hash: string\n readonly variables?: TVariables\n readonly result?: TData\n}\n\nfunction resolveOpHash(manifest: OperationsManifest, op: string): string {\n if (op.startsWith('sha256:')) return op\n const entry = manifest.operations[op]\n if (!entry) {\n const known = Object.keys(manifest.operations).sort()\n throw new OrmClientError(\n `unknown operation \"${op}\" — not in the manifest (${known.length} known). ` +\n 'Re-run `seq-studio orm generate` after editing graphql documents.',\n )\n }\n return entry.hash\n}\n\nexport function createOperationExecutor({\n baseUrl,\n namespace,\n manifest = { schemaHash: 'builtin', operations: {} },\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: OperationExecutorConfig): TypedSqlOperationExecutor {\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n\n function execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n function execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n async function execute<TData = Record<string, unknown>>(\n op: string | OperationReference<Record<string, unknown>, TData>,\n variables: Record<string, unknown> = {},\n options: OperationExecutionOptions = {},\n ): Promise<TData> {\n validateIdempotencyKey(options.idempotencyKey)\n if (typeof op !== 'string' && op.namespace !== namespace) throw new OrmClientError('operation belongs to a different namespace')\n const hash = typeof op === 'string' ? resolveOpHash(manifest, op) : op.hash\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n const response = await fetchImpl(`${root}${dataPlanePath(namespace)}`, {\n method: 'POST',\n headers: { ...auth, 'Content-Type': 'application/json' },\n body: JSON.stringify({ op: hash, variables, idempotencyKey: options.idempotencyKey }),\n })\n return readOperationResponse<TData>({\n ok: response.ok,\n status: response.status,\n body: await response.json().catch(() => null),\n })\n }\n return { execute, sql: variables => execute<SqlQueryResult>(BUILTIN_SQL_READ_HASH, variables) }\n}\n\n// ---------------------------------------------------------------------------\n// Module-level convenience for generated server functions (`db<Name>`)\n// ---------------------------------------------------------------------------\n\nlet configured: OperationExecutor | null = null\n\n/**\n * Configure the process-wide executor the generated `db<Name>` server\n * functions call through. Call once at startup (server-side); browser apps\n * should prefer Apollo + `createOrmFetch` or an explicit executor.\n */\nexport function configureOrmOperations(config: OperationExecutorConfig): OperationExecutor {\n configured = createOperationExecutor(config)\n return configured\n}\n\n/** Used by generated code: `executeOperation({ op: 'getOpenDeals', variables })`. */\nexport async function executeOperation<TData = Record<string, unknown>>({\n op,\n variables,\n idempotencyKey,\n}: {\n op: string\n variables?: Record<string, unknown>\n idempotencyKey?: string\n}): Promise<TData> {\n if (!configured) {\n throw new OrmClientError(\n 'ORM operations client not configured — call configureOrmOperations({ baseUrl, namespace, manifest, getToken }) at startup',\n )\n }\n return configured.execute<TData>(op, variables, idempotencyKey === undefined ? {} : { idempotencyKey })\n}\n\n// ---------------------------------------------------------------------------\n// Apollo integration without an @apollo/client dependency\n// ---------------------------------------------------------------------------\n\n/**\n * A fetch-compatible function for `new HttpLink({ uri: '/unused', fetch: createOrmFetch(...) })`.\n * Intercepts Apollo's GraphQL POST, swaps the body for the persisted-op\n * envelope (`{ op: <hash>, variables }`) resolved via the manifest's\n * operationName, rewrites the URL to the data plane, and attaches auth.\n * The GraphQL-spec response body passes through untouched, so InMemoryCache\n * and error links behave exactly as they do against a GraphQL server.\n */\nexport function createOrmFetch({\n baseUrl,\n namespace,\n manifest,\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: OperationExecutorConfig): typeof globalThis.fetch {\n if (!manifest) throw new OrmClientError('createOrmFetch requires an operations manifest')\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n const url = `${root}${dataPlanePath(namespace)}`\n\n // Derived from `globalThis.fetch` rather than naming `RequestInfo` (a DOM-lib\n // global this module compiles without). The input is ignored — Apollo's\n // HttpLink calls the injected fetch with a string URI, and the real target\n // URL is fixed at `url` above.\n return async (_input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit): Promise<Response> => {\n const raw = typeof init?.body === 'string' ? init.body : null\n const parsed = raw\n ? (JSON.parse(raw) as { operationName?: string; variables?: Record<string, unknown> })\n : {}\n const name = parsed.operationName\n if (!name) {\n throw new OrmClientError(\n 'createOrmFetch requires named operations (Apollo sends operationName for named documents)',\n )\n }\n const hash = resolveOpHash(manifest, name)\n const idempotencyKey = new Headers(init?.headers).get('Idempotency-Key') ?? undefined\n validateIdempotencyKey(idempotencyKey)\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n return fetchImpl(url, {\n method: 'POST',\n headers: { ...auth, 'Content-Type': 'application/json' },\n body: JSON.stringify({ op: hash, variables: parsed.variables ?? {}, idempotencyKey }),\n ...(init?.signal ? { signal: init.signal } : {}),\n })\n }\n}\n","import { NAMESPACE_PATTERN } from '../constants.js'\nimport { OrmClientError, OrmOperationError } from './errors.js'\nimport { validateIdempotencyKey, type TypedSqlOperationExecutor, type OperationReference, type OperationExecutionOptions } from './operations.js'\nimport { isRecord, readOperationResponse } from './response.js'\nimport { BUILTIN_SQL_READ_HASH, type SqlQueryResult } from './sql.js'\n\nexport interface OperationTransportRequest {\n namespace: string\n op: string\n variables: Record<string, unknown>\n idempotencyKey?: string\n}\n\nexport interface OperationTransportResponse {\n ok: boolean\n status: number\n body: unknown\n}\n\nexport type OperationTransport = (request: OperationTransportRequest) => Promise<OperationTransportResponse>\n\nconst operationHash = /^sha256:[a-f0-9]{64}$/\n\nfunction readManifestHashes(manifest: unknown): ReadonlyMap<string, string> {\n if (!isRecord(manifest) || typeof manifest.schemaHash !== 'string' || !manifest.schemaHash || !isRecord(manifest.operations)) {\n throw new OrmClientError('invalid operations manifest — use operations.manifest.json from seq-studio orm generate')\n }\n const hashes = new Map<string, string>()\n for (const [name, entry] of Object.entries(manifest.operations)) {\n if (!/^[_A-Za-z][_0-9A-Za-z]*$/.test(name) || !isRecord(entry) || typeof entry.hash !== 'string' || !operationHash.test(entry.hash)\n || (entry.kind !== 'query' && entry.kind !== 'mutation')) {\n throw new OrmClientError(`invalid operations manifest entry \"${name}\" — regenerate the manifest`)\n }\n hashes.set(name, entry.hash)\n }\n return hashes\n}\n\n/**\n * Execute generated operations through a host-owned authenticated transport.\n * No credential handling, retries, or global configuration. The manifest is\n * validated once and copied, so later caller mutation cannot alter the target.\n */\nexport function createOperationExecutorWithTransport({ namespace, manifest, transport }: {\n namespace: string\n /** Accept generated JSON imports directly; validate them at construction. */\n manifest?: unknown\n transport: OperationTransport\n}): TypedSqlOperationExecutor {\n if (typeof namespace !== 'string' || !NAMESPACE_PATTERN.test(namespace)) throw new OrmClientError('invalid ORM namespace — expected a lowercase identifier of at most 41 characters')\n const hashes = manifest === undefined ? new Map<string, string>() : readManifestHashes(manifest)\n const knownHashes = new Set(hashes.values())\n function execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n function execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n async function execute<TData = Record<string, unknown>>(op: string | OperationReference<Record<string, unknown>, TData>, variables: Record<string, unknown> = {}, options: OperationExecutionOptions = {}): Promise<TData> {\n validateIdempotencyKey(options.idempotencyKey)\n if (typeof op !== 'string' && op.namespace !== namespace) throw new OrmClientError('operation belongs to a different namespace')\n const selector = typeof op === 'string' ? op : op.hash\n const hash = selector === BUILTIN_SQL_READ_HASH ? selector : hashes.get(selector) ?? (knownHashes.has(selector) ? selector : undefined)\n if (!hash) throw new OrmClientError(`unknown operation \"${op}\" — not in the manifest (${hashes.size} known). Re-run seq-studio orm generate.`)\n if (!isRecord(variables)) throw new OrmClientError('operation variables must be an object')\n const response = await transport({ namespace, op: hash, variables,\n ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),\n })\n if (!response || typeof response.ok !== 'boolean' || !Number.isInteger(response.status) || response.status < 100 || response.status > 599\n || response.ok !== (response.status >= 200 && response.status < 300)) {\n throw new OrmOperationError('malformed transport response', null, null)\n }\n return readOperationResponse<TData>(response)\n }\n return { execute, sql: variables => execute<SqlQueryResult>(BUILTIN_SQL_READ_HASH, variables) }\n}\n","import { OrmClientError, createFetchTransport, type OrmTransport } from './transport.js'\nimport { TableQuery } from './query-builder.js'\n\n/** Bindable scalar for `query()` placeholders ($1, $2, …). */\nexport type QueryParam = string | number | boolean | null\n\n/** Shape of one action in the generated `<Ns>Actions` map — params in, result out. */\nexport interface OrmActionShape {\n readonly params?: Record<string, unknown>\n readonly result: unknown\n}\n\n/** The generated `<Ns>Actions` map: action name → its param and result shapes. */\nexport type OrmActions = Record<string, OrmActionShape>\n\n/**\n * `action()`'s argument list: `params` is required when the action declares a\n * required field, optional otherwise. The empty-object type is assignable to\n * the params shape only when every field is optional, so that assignability is\n * the discriminant.\n */\ntype ActionArgs<Action extends OrmActionShape> =\n Record<string, never> extends NonNullable<Action['params']>\n ? [params?: NonNullable<Action['params']>]\n : [params: NonNullable<Action['params']>]\n\n/**\n * Typed read client for one namespace's Data API. `Tables` comes from\n * `types.gen.ts` (wire types the apply refreshes from the YAML definitions),\n * so column names and row shapes are checked at compile time; the server\n * re-validates everything and Postgres RLS decides row visibility.\n *\n * ```ts\n * const client = createOrmClient<LendingTables>({ namespace: 'lending', baseUrl, getToken })\n * const rows = await client.table('loans').select('id', 'balance').gte('balance', 1000).rows()\n * const top = await client.query<{ officer: string; total: string }>(\n * 'select officer, sum(balance) as total from loans group by officer order by total desc limit $1',\n * [5],\n * )\n * ```\n */\nexport interface OrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n> {\n table<Name extends keyof Tables & string>(name: Name): TableQuery<Tables[Name]>\n /**\n * Raw read-only SQL for everything the filter grammar can't say —\n * aggregates, joins, OR, expressions, CTEs. The same sandbox as every\n * read: the namespace consumer role (grants stop at the namespace schema),\n * Postgres RLS over the caller's claims, and a READ ONLY transaction —\n * Postgres itself rejects writes, which stay on declared actions. Values\n * bind as $1, $2, … placeholders; never interpolate them into the string.\n */\n query<Row = Record<string, unknown>>(sql: string, params?: readonly QueryParam[]): Promise<Row[]>\n /**\n * Invoke a declared action — the only write path the Data API exposes. The\n * params and result are typed from the namespace's `<Ns>Actions`: an action\n * with `returns:` resolves to `{ rows: Row[] }`, a count action to\n * `{ rowsAffected: number }`.\n */\n action<Name extends keyof Actions & string>(\n name: Name,\n ...args: ActionArgs<Actions[Name]>\n ): Promise<Actions[Name]['result']>\n}\n\nexport function createOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>({\n namespace,\n baseUrl,\n getToken,\n fetchImpl,\n transport,\n dataToken,\n}: {\n namespace: string\n baseUrl?: string\n /** App-user / session bearer (CLI, browser). Mutually exclusive with dataToken. */\n getToken?: () => Promise<string | null> | string | null\n /**\n * Delegated function data token — the inbound `ORM_DATA_TOKEN_HEADER` value a\n * managed function receives. Pass it and the client authenticates as the\n * invoking user, scoped to the function's declared refs; no manual transport.\n */\n dataToken?: string | (() => Promise<string | null> | string | null)\n fetchImpl?: typeof globalThis.fetch\n /** Injected transport (tests, bridges); overrides baseUrl/getToken/dataToken. */\n transport?: OrmTransport\n}): OrmClient<Tables, Actions> {\n const resolved =\n transport ??\n createFetchTransport({\n baseUrl: requireOption(baseUrl, 'baseUrl'),\n ...(dataToken !== undefined\n ? { getDataToken: typeof dataToken === 'function' ? dataToken : () => dataToken }\n : { getToken: requireOption(getToken, 'getToken') }),\n fetchImpl,\n })\n\n return buildOrmClient<Tables, Actions>(resolved, namespace)\n}\n\n/**\n * The ESCALATION path — use only deliberately. A managed function receives a\n * separate *service* data token on `ORM_SERVICE_DATA_TOKEN_HEADER`; pass that\n * value here and the client authenticates as the function's SERVICE IDENTITY,\n * not the invoking user. Reads run with the service identity's grants (clamped\n * to the function's declared refs), NOT the caller's — so the caller's own row\n * visibility does not apply. The invoking user is still recorded for audit.\n *\n * Default to `createOrmClient` (acts as the invoking user, full per-user RLS).\n * Reach for this only when the function must intentionally act beyond the\n * caller — e.g. enforcing per-user rules in code over a coarse upstream that\n * has no granular permissions of its own. The distinct name is the guardrail:\n * choosing the service identity is always explicit and greppable.\n *\n * ```ts\n * const client = createServiceOrmClient<LendingTables>({\n * namespace: 'lending',\n * baseUrl,\n * serviceDataToken: req.headers['x-sequence-data-token-service'],\n * })\n * ```\n */\nexport function createServiceOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>({\n namespace,\n baseUrl,\n serviceDataToken,\n fetchImpl,\n transport,\n}: {\n namespace: string\n baseUrl?: string\n /** The inbound `ORM_SERVICE_DATA_TOKEN_HEADER` value — the function's service token. */\n serviceDataToken?: string | (() => Promise<string | null> | string | null)\n fetchImpl?: typeof globalThis.fetch\n /** Injected transport (tests, bridges); overrides baseUrl/serviceDataToken. */\n transport?: OrmTransport\n}): OrmClient<Tables, Actions> {\n const resolved =\n transport ??\n createFetchTransport({\n baseUrl: requireOption(baseUrl, 'baseUrl'),\n getDataToken:\n typeof serviceDataToken === 'function'\n ? serviceDataToken\n : () => requireOption(serviceDataToken, 'serviceDataToken'),\n fetchImpl,\n })\n\n return buildOrmClient<Tables, Actions>(resolved, namespace)\n}\n\n/** Shared client surface over a resolved transport — the token/identity choice is made by the factory above. */\nfunction buildOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>(resolved: OrmTransport, namespace: string): OrmClient<Tables, Actions> {\n return {\n table(name) {\n return new TableQuery(resolved, namespace, name)\n },\n async query(sql, params) {\n const payload = await resolved.post(`/api/data/${namespace}/query`, {\n sql,\n ...(params ? { params: [...params] } : {}),\n })\n if (!payload || typeof payload !== 'object' || !Array.isArray((payload as { rows?: unknown }).rows)) {\n throw new OrmClientError('unexpected Data API response shape — missing rows array')\n }\n return (payload as { rows: never[] }).rows\n },\n async action(name, ...args) {\n const payload = await resolved.post(`/api/data/${namespace}/actions/${name}`, args[0] ?? {})\n if (payload && typeof payload === 'object') {\n // A returns action responds with `rows`; a count action with\n // `rows_affected` (mapped to `rowsAffected` for the client).\n if (Array.isArray((payload as { rows?: unknown }).rows)) {\n return { rows: (payload as { rows: unknown[] }).rows } as Awaited<ReturnType<OrmClient<Tables, Actions>['action']>>\n }\n if ('rows_affected' in payload) {\n const rowsAffected = Number((payload as { rows_affected: unknown }).rows_affected)\n if (!Number.isNaN(rowsAffected)) {\n return { rowsAffected } as Awaited<ReturnType<OrmClient<Tables, Actions>['action']>>\n }\n }\n }\n throw new OrmClientError('unexpected action response shape — expected rows or rows_affected')\n },\n }\n}\n\nfunction requireOption<T>(value: T | undefined, name: string): T {\n if (value === undefined) throw new Error(`createOrmClient requires ${name} when no transport is injected`)\n return value\n}\n\nexport { TableQuery, type FilterValue, type ReadResponse } from './query-builder.js'\nexport { createFetchTransport, OrmClientError, type OrmTransport } from './transport.js'\n\nexport {\n OrmOperationError,\n configureOrmOperations,\n createOperationExecutor,\n createOrmFetch,\n executeOperation,\n} from './operations.js'\nexport type {\n ManifestOperation,\n OperationErrorEntry,\n OperationExecutor,\n SqlOperationExecutor,\n OperationReference,\n TypedOperationExecutor,\n TypedSqlOperationExecutor,\n OperationExecutorConfig,\n OperationsManifest,\n} from './operations.js'\n\nexport { NAMESPACE_PATTERN, ORM_DATA_TOKEN_HEADER, ORM_SERVICE_DATA_TOKEN_HEADER } from '../constants.js'\nexport type { SqlQueryParameter, SqlQueryVariables, SqlQueryResult } from './sql.js'\nexport { BUILTIN_SQL_READ_HASH } from './sql.js'\nexport {\n createOperationExecutorWithTransport,\n type OperationTransport, type OperationTransportRequest, type OperationTransportResponse,\n} from './transport-executor.js'\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/constants.ts","../src/client/errors.ts","../src/client/transport.ts","../src/client/query-builder.ts","../src/client/response.ts","../src/client/sql.ts","../src/client/operations.ts","../src/client/transport-executor.ts","../src/client/index.ts"],"names":[],"mappings":";AAIO,IAAM,iBAAA,GAAoB;AAG1B,IAAM,qBAAA,GAAwB;AAG9B,IAAM,6BAAA,GAAgC;AAwGtC,IAAM,iBAAA,GAAoB,iBAAA;AACM,IAAA,CAAK,SAAA,CAAU,EAAE,KAAK,iBAAA,EAAmB,GAAA,EAAK,IAAA,EAAM,KAAA,EAAO,EAAC,EAAG,YAAA,EAAc,IAAI;;;ACnHjH,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EAGxC,WAAA,CAAY,OAAA,EAA0B,MAAA,GAAwB,IAAA,EAAM;AAClE,IAAA,KAAA,CAAM,OAAO,CAAA;AADuB,IAAA,IAAA,CA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,UAAA,MAAM,YAAA,GAAe,MAAA,CAAQ,OAAA,CAAuC,aAAa,CAAA;AACjF,UAAA,IAAI,CAAC,MAAA,CAAO,KAAA,CAAM,YAAY,CAAA,EAAG;AAC/B,YAAA,OAAO,EAAE,YAAA,EAAa;AAAA,UACxB;AAAA,QACF;AAAA,MACF;AACA,MAAA,MAAM,IAAI,eAAe,wEAAmE,CAAA;AAAA,IAC9F;AAAA,GACF;AACF;AAEA,SAAS,aAAA,CAAiB,OAAsB,IAAA,EAAiB;AAC/D,EAAA,IAAI,UAAU,MAAA,EAAW,MAAM,IAAI,KAAA,CAAM,CAAA,yBAAA,EAA4B,IAAI,CAAA,8BAAA,CAAgC,CAAA;AACzG,EAAA,OAAO,KAAA;AACT","file":"client.js","sourcesContent":["/** Shared grammar for namespace identifiers; never interpolate arbitrary paths.\n * orm_events and orm_native_sources are migration-owned control-plane schemas,\n * not builder namespaces. Exclude their suffixes at every API/authoring entry.\n */\nexport const NAMESPACE_PATTERN = /^(?!(?:events|native_sources)$)[a-z][a-z0-9_]{0,40}$/\n\n/** Caller-scoped delegated data credential, supplied by an authenticated host. */\nexport const ORM_DATA_TOKEN_HEADER = 'x-sequence-data-token'\n\n/** Separate service-identity credential; never used as an implicit fallback. */\nexport const ORM_SERVICE_DATA_TOKEN_HEADER = 'x-sequence-data-token-service'\n\nexport const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/\n/** Native source columns may have one leading underscore; relation names may not. */\nexport const COLUMN_IDENTIFIER_PATTERN = /^_?[a-z][a-z0-9_]*$/\nexport const MAX_IDENTIFIER_LENGTH = 63\n\n/**\n * Custom Roles & Capabilities claim keys as policies reference them: a\n * host-scoped registry key, an org pin's `org/<key>`, or an Application\n * capability pin's `app/<application-id>/<key>`. Matches the registry\n * key grammar EXACTLY (`[a-z0-9-]`, 1–64 chars, no `_` — the FGA object-id\n * delimiter) so any capability that's declarable/attachable in namespace.yaml\n * can also be referenced here — a stricter pattern would let a valid key\n * register yet fail at apply (e.g. `org/2fa`, a one-char or digit-led key).\n */\nexport const CAPABILITY_KEY_PATTERN = /^(?:org\\/|app\\/[a-z][a-z0-9-]{0,63}\\/)?[a-z0-9-]{1,64}$/\n\n/** Hard ceiling for an explicitly authored flat persisted GraphQL read. */\nexport const MAX_PERSISTED_READ_ROWS = 50_001\n\nexport const CLAIM_KEY_PATTERN = /^[a-z][a-z0-9_]*$/\n\n/** Qualified reference to a table outside the defining file: `<schema>.<table>`. */\nexport const QUALIFIED_TABLE_PATTERN = /^[a-z][a-z0-9_]{0,62}\\.[a-z][a-z0-9_]{0,62}$/\n\n/** Qualified source syntax only; the serving installation controls authorized backing. */\nexport const SYNCED_SOURCE_PATTERN = QUALIFIED_TABLE_PATTERN\n\nexport const ORM_SCHEMA_PREFIX = 'orm_'\nexport const CONSUMER_ROLE_SUFFIX = '_consumer'\n\nexport const ormSchemaName = (namespace: string): string => {\n if (!NAMESPACE_PATTERN.test(namespace)) throw new Error(`invalid or reserved ORM namespace '${namespace}'`)\n return `${ORM_SCHEMA_PREFIX}${namespace}`\n}\nexport const consumerRoleName = (namespace: string): string =>\n `${ormSchemaName(namespace)}${CONSUMER_ROLE_SUFFIX}`\n\nexport const DEFINITION_FILE_EXTENSIONS = ['.yml', '.yaml'] as const\n\n/** Reserved basenames for the namespace-level config file (description, org capability pins). */\nexport const NAMESPACE_CONFIG_FILENAMES = new Set(['namespace.yaml', 'namespace.yml'])\n\nexport const HASH_DOMAIN = 'sequence-orm-definitions\\0'\n\n/**\n * A per-file byte cap where the loader reads untrusted YAML into memory — a real failure mode, not a product\n * limit. Counts of tables/indexes/params and policy/SQL lengths are\n * deliberately uncapped; Postgres enforces its own limits loudly at apply.\n */\nexport const MAX_DEFINITION_FILE_BYTES = 1024 * 1024\n\n/** Generated SDL aggregates every table/view; it is not an individual source file. */\nexport const MAX_GENERATED_SDL_BYTES = 16 * 1024 * 1024\n\n/** Registration and reviewed exports carry SDL, canonical metadata, snapshots and migrations. */\nexport const ORM_REGISTRATION_MAX_BYTES = 64 * 1024 * 1024\n\n/** `/api/data/<ns>/actions/…` and `/api/data/<ns>/query` share the table path segment. */\nexport const RESERVED_TABLE_NAMES = new Set(['actions', 'query'])\n\n/**\n * The Data API's query-string grammar owns these parameter names — a column\n * with one of them could never be filtered over the wire, so definitions\n * refuse it up front (\"validate rejects only what can never work\").\n */\nexport const RESERVED_COLUMN_NAMES = new Set(['select', 'order', 'limit', 'offset'])\n\n/**\n * Per-cell metadata (`cellMetadata: true`, and every resolved-table source) is\n * stored as typed system columns beside each tracked column `c`:\n *\n * - `c__at` timestamptz — when the cell was last written (NULL: never / no opinion)\n * - `c__by` text — who wrote it\n * - `c__rev` uuid — a resolved table's manual source only: the edit's\n * identity, so an async writeback confirmation clears\n * only the exact edit it delivered\n *\n * A resolved view additionally exposes, per resolved column, the winner's\n * `c__src` (source name) and `c__lost` (newer candidates that lost, jsonb).\n * None of these are GraphQL columns: they surface through the typed `cells`\n * object and are never client-writable.\n */\nexport const CELL_PARTS = ['at', 'by', 'rev', 'source', 'conflicts'] as const\nexport type CellPart = (typeof CELL_PARTS)[number]\nexport const CELL_PART_SUFFIX: Readonly<Record<CellPart, string>> = {\n at: '__at', by: '__by', rev: '__rev', source: '__src', conflicts: '__lost',\n}\n/** Longest physical column name that can carry cell parts (63 minus the longest suffix). */\nexport const MAX_TRACKED_COLUMN_NAME = MAX_IDENTIFIER_LENGTH - 6\n/** GraphQL field carrying a row's per-cell metadata object. */\nexport const CELLS_FIELD = 'cells'\n\n/** Physical (and logical) name of one cell part of a column. */\nexport function cellColumnName(column: string, part: CellPart): string {\n return `${column}${CELL_PART_SUFFIX[part]}`\n}\n\n/**\n * Actor recorded when the data plane computes a materialized resolved table's\n * rows for every caller. Its claims are what the compute view's synced\n * sources see (materialized ETL sources must be readable by anyone).\n */\nexport const MATERIALIZE_ACTOR = 'orm:materialize'\nexport const MATERIALIZE_CLAIMS_JSON = JSON.stringify({ sub: MATERIALIZE_ACTOR, org: null, roles: [], capabilities: [] })\n\n/**\n * Apply-generated function that reconciles a materialized resolved table with\n * its compute view: `SELECT * FROM orm_<ns>.\"<table>__refresh\"(wait)` returns\n * `(upserted, deleted, locked)`; without `wait` it skips when another refresh\n * holds the table's lock. The one refresh implementation — the Atlas\n * reconcile, the post-ETL hook, and an operator in psql all call it.\n */\nexport function materializedRefreshFunctionName(table: string): string {\n return `${table}__refresh`\n}\n\n/**\n * Advisory-lock key serializing a materialized table's refreshes (hashed with\n * `hashtext`). A full refresh holds it exclusively and every ORM write's\n * per-row refresh holds it shared, both before reading the compute view — so\n * a full refresh never reads a snapshot older than a write it then overwrites.\n */\nexport function materializeLockKey(schema: string, table: string): string {\n return `orm:materialize:${schema}.${table}`\n}\n","export class OrmClientError extends Error {\n override readonly name: string = 'OrmClientError'\n\n constructor(message: string, readonly status: number | null = null) {\n super(message)\n }\n}\n\nexport interface OperationErrorEntry {\n readonly message: string\n readonly extensions?: { readonly code?: string }\n}\n\nexport class OrmOperationError extends OrmClientError {\n override readonly name = 'OrmOperationError'\n\n constructor(\n message: string,\n status: number | null,\n readonly code: string | null,\n readonly errors: readonly OperationErrorEntry[] = [],\n ) {\n super(message, status)\n }\n}\n","/**\n * Fetch-based transport for the Data API. Deliberately free of node builtins\n * so the client runs anywhere a `fetch` exists — browsers, artifact bridges,\n * Cloud Functions, `node:vm` sandboxes.\n */\nimport { ORM_DATA_TOKEN_HEADER } from '../constants.js'\n\nimport { OrmClientError } from './errors.js'\nexport { OrmClientError } from './errors.js'\n\nexport interface OrmTransport {\n get(path: string, params: URLSearchParams): Promise<unknown>\n post(path: string, body: unknown): Promise<unknown>\n}\n\nexport function createFetchTransport({\n baseUrl,\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: {\n baseUrl: string\n /** App-user / session bearer → `Authorization: Bearer`. */\n getToken?: () => Promise<string | null> | string | null\n /** Delegated, attenuated function token → the `ORM_DATA_TOKEN_HEADER`. */\n getDataToken?: () => Promise<string | null> | string | null\n fetchImpl?: typeof globalThis.fetch\n}): OrmTransport {\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n\n const request = async (path: string, init: Omit<RequestInit, 'headers'>): Promise<unknown> => {\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n // The delegated token rides its own header; the app-user bearer rides Authorization.\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n const response = await fetchImpl(`${root}${path}`, {\n ...init,\n headers: { ...auth, 'Content-Type': 'application/json' },\n })\n const payload: unknown = await response.json().catch(() => null)\n if (!response.ok) {\n const detail =\n payload && typeof payload === 'object' && 'detail' in payload\n ? String((payload as { detail: unknown }).detail)\n : `HTTP ${response.status}`\n throw new OrmClientError(detail, response.status)\n }\n return payload\n }\n\n return {\n get: (path, params) => {\n // Not params.size — that's Node 19.8+/2023-browser surface, newer than\n // the fetch this module documents as its only requirement.\n const serialized = params.toString()\n return request(serialized === '' ? path : `${path}?${serialized}`, {})\n },\n post: (path, body) => request(path, { method: 'POST', body: JSON.stringify(body ?? {}) }),\n }\n}\n","import { OrmClientError, type OrmTransport } from './transport.js'\n\n/**\n * Fluent read query over one table. Serializes to exactly the PostgREST\n * subset the Data API's query parser accepts — the round-trip contract is\n * asserted server-side (builder output → parseReadQuery) so the two ends\n * can't drift apart silently.\n *\n * IMMUTABLE: every method returns a new query, so narrowing `select()` can\n * never leave an alias holding a stale wider row type, and a base query can\n * be safely forked into variants.\n */\n\nexport type FilterValue = string | number | boolean\n\nexport interface ReadResponse<Row> {\n readonly rows: readonly Row[]\n readonly limit: number\n readonly offset: number\n}\n\n/** Characters the in-list grammar cannot carry — there is no escaping, so the builder hard-fails. */\nconst IN_LIST_UNREPRESENTABLE = /[,()]/\n\ninterface QueryState {\n readonly filters: ReadonlyArray<[column: string, expression: string]>\n readonly orderings: readonly string[]\n readonly selection: readonly string[] | null\n readonly limitValue: number | null\n readonly offsetValue: number | null\n}\n\nconst EMPTY_STATE: QueryState = {\n filters: [],\n orderings: [],\n selection: null,\n limitValue: null,\n offsetValue: null,\n}\n\n/**\n * `Row` is the TABLE's row (filters and order always accept every column);\n * `Result` is what rows() yields — narrowed by select(), re-widenable by a\n * later select() since keys always come from Row.\n */\nexport class TableQuery<Row extends Record<string, unknown>, Result = Row> {\n constructor(\n private readonly transport: OrmTransport,\n private readonly namespace: string,\n private readonly table: string,\n private readonly state: QueryState = EMPTY_STATE,\n ) {}\n\n private with(patch: Partial<QueryState>): TableQuery<Row, Result> {\n return new TableQuery(this.transport, this.namespace, this.table, { ...this.state, ...patch })\n }\n\n select<K extends keyof Row & string>(...columns: [K, ...K[]]): TableQuery<Row, Pick<Row, K>> {\n return new TableQuery<Row, Pick<Row, K>>(this.transport, this.namespace, this.table, {\n ...this.state,\n selection: columns,\n })\n }\n\n eq<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'eq', value)\n }\n\n ne<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'ne', value)\n }\n\n gt<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'gt', value)\n }\n\n gte<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'gte', value)\n }\n\n lt<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'lt', value)\n }\n\n lte<K extends keyof Row & string>(column: K, value: FilterValue): TableQuery<Row, Result> {\n return this.filter(column, 'lte', value)\n }\n\n like<K extends keyof Row & string>(column: K, pattern: string): TableQuery<Row, Result> {\n return this.filter(column, 'like', pattern)\n }\n\n ilike<K extends keyof Row & string>(column: K, pattern: string): TableQuery<Row, Result> {\n return this.filter(column, 'ilike', pattern)\n }\n\n in<K extends keyof Row & string>(column: K, values: readonly FilterValue[]): TableQuery<Row, Result> {\n // An empty list is representable — `in.()` matches nothing, the same\n // semantics the server executes. Blank entries are legitimate values in\n // multi-entry lists (`in.(a,)` carries ['a','']), but a LONE '' renders\n // as `in.()` and silently becomes the empty list — unrepresentable.\n // Beyond that only characters the grammar can't escape, and whitespace\n // padding the server-side split would silently swallow, are refused.\n const rendered = values.map((value) => {\n const text = String(value)\n if (IN_LIST_UNREPRESENTABLE.test(text) || text !== text.trim()) {\n throw new OrmClientError(`in() value '${text}' cannot be represented — the list grammar has no escaping`)\n }\n return text\n })\n if (rendered.length === 1 && rendered[0] === '') {\n throw new OrmClientError(\"in() with a lone '' cannot be represented — it would read as the empty list\")\n }\n return this.with({ filters: [...this.state.filters, [column, `in.(${rendered.join(',')})`]] })\n }\n\n is<K extends keyof Row & string>(column: K, value: null | boolean): TableQuery<Row, Result> {\n return this.with({\n filters: [...this.state.filters, [column, `is.${value === null ? 'null' : value}`]],\n })\n }\n\n order<K extends keyof Row & string>(column: K, direction: 'asc' | 'desc' = 'asc'): TableQuery<Row, Result> {\n return this.with({ orderings: [...this.state.orderings, `${column}.${direction}`] })\n }\n\n limit(value: number): TableQuery<Row, Result> {\n return this.with({ limitValue: value })\n }\n\n offset(value: number): TableQuery<Row, Result> {\n return this.with({ offsetValue: value })\n }\n\n /** The exact query string sent to the Data API — exposed for debugging and the grammar contract test. */\n searchParams(): URLSearchParams {\n const params = new URLSearchParams()\n for (const [column, expression] of this.state.filters) params.append(column, expression)\n if (this.state.orderings.length > 0) params.set('order', this.state.orderings.join(','))\n if (this.state.selection) params.set('select', this.state.selection.join(','))\n if (this.state.limitValue !== null) params.set('limit', String(this.state.limitValue))\n if (this.state.offsetValue !== null) params.set('offset', String(this.state.offsetValue))\n return params\n }\n\n async rows(): Promise<Result[]> {\n const payload = await this.transport.get(\n `/api/data/${this.namespace}/${this.table}`,\n this.searchParams(),\n )\n if (!payload || typeof payload !== 'object' || !Array.isArray((payload as { rows?: unknown }).rows)) {\n throw new OrmClientError('unexpected Data API response shape — missing rows array')\n }\n return (payload as { rows: Result[] }).rows\n }\n\n private filter(column: string, op: string, value: FilterValue): TableQuery<Row, Result> {\n return this.with({ filters: [...this.state.filters, [column, `${op}.${String(value)}`]] })\n }\n}\n","import { OrmOperationError, type OperationErrorEntry } from './errors.js'\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isOperationError(value: unknown): value is OperationErrorEntry {\n if (!isRecord(value) || typeof value.message !== 'string') return false\n if (value.extensions === undefined) return true\n return isRecord(value.extensions) && (value.extensions.code === undefined || typeof value.extensions.code === 'string')\n}\n\nexport function readOperationResponse<TData>({\n ok, status, body,\n}: { ok: boolean; status: number; body: unknown }): TData {\n const payload = isRecord(body) ? body : null\n const rawErrors = payload?.errors\n if (rawErrors !== undefined && (!Array.isArray(rawErrors) || !rawErrors.every(isOperationError))) {\n throw new OrmOperationError('malformed response: invalid errors', status, null)\n }\n const errors: OperationErrorEntry[] = rawErrors ?? []\n if (!ok || errors.length > 0) {\n const first = errors[0]\n throw new OrmOperationError(first?.message ?? `HTTP ${status}`, status, first?.extensions?.code ?? null, errors)\n }\n if (!payload || payload.data === undefined || payload.data === null) {\n throw new OrmOperationError('malformed response: missing data', status, null)\n }\n if (!isRecord(payload.data)) {\n throw new OrmOperationError('malformed response: data must be an object', status, null)\n }\n // Generated consumer types describe operation data; envelope validation\n // cannot prove an application's selection-specific TData at runtime.\n return payload.data as TData\n}\n\n/** Only expose data together with a validated, opaque source receipt. */\nexport function readOperationResponseWithReceipt<TData>({\n ok, status, body, expectedSourceGeneration,\n}: { ok: boolean; status: number; body: unknown; expectedSourceGeneration?: string }): { data: TData; sourceGeneration: string } {\n const data = readOperationResponse<TData>({ ok, status, body })\n const extensions = isRecord(body) && isRecord(body.extensions) ? body.extensions : null\n const sourceGeneration = extensions?.sourceGeneration\n if (typeof sourceGeneration !== 'string' || !/^[a-f0-9]{64}$/.test(sourceGeneration)\n || (expectedSourceGeneration !== undefined && expectedSourceGeneration !== sourceGeneration)) {\n // Missing and changed receipts are indistinguishable; do not expose either token.\n throw new OrmOperationError('Source generation unavailable', status, 'OBJECT_UNAVAILABLE')\n }\n return { data, sourceGeneration }\n}\n","/** Runtime SQL inputs are values, never interpolated into the submitted SQL. */\n// SHA-256 of \"sequence-orm-builtin-sql-read-v1\". This identifies server-owned\n// behavior, independent of a namespace's authored operation manifest.\nexport const BUILTIN_SQL_READ_HASH = 'sha256:a50c477c952a5e0fe68ed158a4530e4aab573c09bcbb1a8ac454dc88a39a6258'\n\nexport type SqlQueryParameter =\n | { type: 'text' | 'uuid' | 'date' | 'timestamptz' | 'numeric' | 'bigint'; value: string | null }\n | { type: 'integer' | 'double'; value: number | null }\n | { type: 'boolean'; value: boolean | null }\n\nexport type SqlQueryVariables = {\n sql: string\n parameters?: Record<string, SqlQueryParameter>\n}\n\nexport interface SqlQueryResult {\n columns: Array<{ name: string; type: string; nullable: boolean }>\n rows: Array<Array<string | number | boolean | null>>\n truncated: boolean\n}\n","/**\n * Persisted-operation client for the v2 data plane. The wire carries only\n * `{ op: <hash>, variables, idempotencyKey?, expectedSourceGeneration? }`. Runtime SQL contracts accept SQL in variables;\n * GraphQL and fixed SQL operations keep their documents server-side. This runtime\n * is deliberately free of node builtins and third-\n * party deps (no @apollo/client import): Apollo integration happens through a\n * fetch-compatible shim (`createOrmFetch`) handed to `HttpLink({ fetch })`.\n */\nimport { OrmClientError } from './errors.js'\nimport { readOperationResponse, readOperationResponseWithReceipt } from './response.js'\nimport { ORM_DATA_TOKEN_HEADER } from '../constants.js'\nimport { BUILTIN_SQL_READ_HASH, type SqlQueryVariables, type SqlQueryResult } from './sql.js'\n\nexport { OrmOperationError, type OperationErrorEntry } from './errors.js'\n\n/** One entry of `operations.manifest.json` (generated by `orm generate`). */\nexport interface ManifestOperation {\n readonly hash: string\n readonly kind: 'query' | 'mutation'\n readonly requires: { readonly capability?: string; readonly role?: string } | null\n}\n\nexport interface OperationsManifest {\n readonly schemaHash: string\n readonly opsHash?: string\n readonly operations: Readonly<Record<string, ManifestOperation>>\n}\n\nexport interface OperationExecutorConfig {\n /** Deployment host root, e.g. `https://atlas.seqholdings.com`. */\n baseUrl: string\n namespace: string\n manifest?: OperationsManifest\n /** App-user / session bearer → `Authorization: Bearer`. */\n getToken?: () => Promise<string | null> | string | null\n /** Delegated, attenuated function token → the `ORM_DATA_TOKEN_HEADER`. */\n getDataToken?: () => Promise<string | null> | string | null\n fetchImpl?: typeof globalThis.fetch\n}\n\nexport interface OperationExecutionOptions {\n /** Reuse only when retrying the same logical mutation. */\n idempotencyKey?: string\n /** Require the same source publication as an earlier read receipt. */\n expectedSourceGeneration?: string\n}\n\nexport function validateIdempotencyKey(key: string | undefined): void {\n if (key !== undefined && !/^[A-Za-z0-9._:-]{1,128}$/.test(key)) {\n throw new OrmClientError('idempotencyKey must be 1–128 letters, digits, dots, underscores, colons or hyphens')\n }\n}\n\nexport function validateExpectedSourceGeneration(value: string | undefined): void {\n if (value !== undefined && (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value))) {\n throw new OrmClientError('expectedSourceGeneration must be a lowercase 64-character hexadecimal receipt')\n }\n}\n\nexport interface OperationExecutor {\n /** Execute a manifest operation by name (or a raw `sha256:` hash). */\n execute<TData = Record<string, unknown>>(\n op: string,\n variables?: Record<string, unknown>,\n options?: OperationExecutionOptions,\n ): Promise<TData>\n}\n\n/** Additive factory result; existing host wrappers implementing OperationExecutor remain valid. */\nexport interface SqlOperationExecutor extends OperationExecutor {\n /** Default read-only ontology SQL; no authored operation or manifest needed. */\n sql(variables: SqlQueryVariables): Promise<SqlQueryResult>\n}\n\nexport interface TypedOperationExecutor extends OperationExecutor {\n execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n}\n\n/** Factory result adds SQL without requiring it on existing typed host wrappers. */\nexport type TypedSqlOperationExecutor = TypedOperationExecutor & SqlOperationExecutor\n\nexport interface OperationReadReceipt<TData> {\n readonly data: TData\n /** Opaque source-publication identity; never an authorization credential. */\n readonly sourceGeneration: string\n}\n\nexport interface ReadReceiptOperationExecutor extends OperationExecutor {\n /** Execute a registered query or built-in SQL read; fail closed without a receipt. */\n executeWithReadReceipt<TData = Record<string, unknown>>(\n op: string,\n variables?: Record<string, unknown>,\n options?: OperationExecutionOptions,\n ): Promise<OperationReadReceipt<TData>>\n}\n\n/** Additive factories preserve existing host wrappers without receipt support. */\nexport type ReadReceiptSqlOperationExecutor = SqlOperationExecutor & ReadReceiptOperationExecutor\n\nexport interface TypedReadReceiptOperationExecutor extends TypedOperationExecutor {\n executeWithReadReceipt<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n executeWithReadReceipt<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n}\n\nexport type TypedReadReceiptSqlOperationExecutor = TypedReadReceiptOperationExecutor & ReadReceiptSqlOperationExecutor\n\nconst dataPlanePath = (namespace: string): string => `/_data/v2/${namespace}`\n\n/** Generated handle identifies the registered contract; optional types are phantom. */\nexport interface OperationReference<TVariables extends Record<string, unknown>, TData> {\n readonly namespace: string\n readonly hash: string\n readonly variables?: TVariables\n readonly result?: TData\n}\n\nfunction resolveOpHash(manifest: OperationsManifest, op: string): string {\n if (op.startsWith('sha256:')) return op\n const entry = manifest.operations[op]\n if (!entry) {\n const known = Object.keys(manifest.operations).sort()\n throw new OrmClientError(\n `unknown operation \"${op}\" — not in the manifest (${known.length} known). ` +\n 'Re-run `seq-studio orm generate` after editing graphql documents.',\n )\n }\n return entry.hash\n}\n\n/** Snapshot classification and name resolution before any receipt request can dispatch. */\nexport function createReadReceiptOperationResolver({ operations }: {\n operations: Iterable<readonly [string, Pick<ManifestOperation, 'hash' | 'kind'>]>\n}): (selection: { selector: string; hashOnly?: boolean }) => string {\n const hashesByName = new Map<string, string>()\n const readHashes = new Set([BUILTIN_SQL_READ_HASH])\n const mutationHashes = new Set<string>()\n for (const [name, entry] of operations) {\n hashesByName.set(name, entry.hash)\n if (entry.kind === 'query' && /^sha256:[a-f0-9]{64}$/.test(entry.hash)) readHashes.add(entry.hash)\n if (entry.kind === 'mutation') mutationHashes.add(entry.hash)\n }\n return ({ selector, hashOnly = false }) => {\n const hash = selector.startsWith('sha256:') ? selector : hashOnly ? undefined : hashesByName.get(selector)\n if (!hash || !readHashes.has(hash) || mutationHashes.has(hash)) {\n throw new OrmClientError('read receipts require a registered query or the built-in SQL read')\n }\n return hash\n }\n}\n\nexport function createOperationExecutor({\n baseUrl,\n namespace,\n manifest = { schemaHash: 'builtin', operations: {} },\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: OperationExecutorConfig): TypedReadReceiptSqlOperationExecutor {\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n const resolveReceiptOperation = createReadReceiptOperationResolver({ operations: Object.entries(manifest.operations) })\n\n async function request({ op, variables, options, requireReadReceipt = false }: {\n op: string | OperationReference<Record<string, unknown>, unknown>\n variables: Record<string, unknown>\n options: OperationExecutionOptions\n requireReadReceipt?: boolean\n }): Promise<{ ok: boolean; status: number; body: unknown }> {\n validateIdempotencyKey(options.idempotencyKey)\n validateExpectedSourceGeneration(options.expectedSourceGeneration)\n if (typeof op !== 'string' && op.namespace !== namespace) throw new OrmClientError('operation belongs to a different namespace')\n const hash = requireReadReceipt\n ? resolveReceiptOperation({ selector: typeof op === 'string' ? op : op.hash, hashOnly: typeof op !== 'string' })\n : typeof op === 'string' ? resolveOpHash(manifest, op) : op.hash\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n const response = await fetchImpl(`${root}${dataPlanePath(namespace)}`, {\n method: 'POST',\n headers: { ...auth, 'Content-Type': 'application/json' },\n body: JSON.stringify({ op: hash, variables, idempotencyKey: options.idempotencyKey,\n expectedSourceGeneration: options.expectedSourceGeneration }),\n })\n return {\n ok: response.ok,\n status: response.status,\n body: await response.json().catch(() => null),\n }\n }\n\n function execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n function execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n async function execute<TData = Record<string, unknown>>(op: string | OperationReference<Record<string, unknown>, TData>, variables: Record<string, unknown> = {}, options: OperationExecutionOptions = {}): Promise<TData> {\n const executionOptions = { ...options }\n const response = await request({ op, variables, options: executionOptions })\n return executionOptions.expectedSourceGeneration === undefined\n ? readOperationResponse<TData>(response)\n : readOperationResponseWithReceipt<TData>({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration }).data\n }\n\n function executeWithReadReceipt<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n function executeWithReadReceipt<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n async function executeWithReadReceipt<TData = Record<string, unknown>>(op: string | OperationReference<Record<string, unknown>, TData>, variables: Record<string, unknown> = {}, options: OperationExecutionOptions = {}): Promise<OperationReadReceipt<TData>> {\n const executionOptions = { ...options }\n const response = await request({ op, variables, options: executionOptions, requireReadReceipt: true })\n return readOperationResponseWithReceipt<TData>({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration })\n }\n return { execute, executeWithReadReceipt, sql: variables => execute<SqlQueryResult>(BUILTIN_SQL_READ_HASH, variables) }\n}\n\n// ---------------------------------------------------------------------------\n// Module-level convenience for generated server functions (`db<Name>`)\n// ---------------------------------------------------------------------------\n\nlet configured: OperationExecutor | null = null\n\n/**\n * Configure the process-wide executor the generated `db<Name>` server\n * functions call through. Call once at startup (server-side); browser apps\n * should prefer Apollo + `createOrmFetch` or an explicit executor.\n */\nexport function configureOrmOperations(config: OperationExecutorConfig): OperationExecutor {\n configured = createOperationExecutor(config)\n return configured\n}\n\n/** Used by generated code: `executeOperation({ op: 'getOpenDeals', variables })`. */\nexport async function executeOperation<TData = Record<string, unknown>>({\n op,\n variables,\n idempotencyKey,\n}: {\n op: string\n variables?: Record<string, unknown>\n idempotencyKey?: string\n}): Promise<TData> {\n if (!configured) {\n throw new OrmClientError(\n 'ORM operations client not configured — call configureOrmOperations({ baseUrl, namespace, manifest, getToken }) at startup',\n )\n }\n return configured.execute<TData>(op, variables, idempotencyKey === undefined ? {} : { idempotencyKey })\n}\n\n// ---------------------------------------------------------------------------\n// Apollo integration without an @apollo/client dependency\n// ---------------------------------------------------------------------------\n\n/**\n * A fetch-compatible function for `new HttpLink({ uri: '/unused', fetch: createOrmFetch(...) })`.\n * Intercepts Apollo's GraphQL POST, swaps the body for the persisted-op\n * envelope (`{ op: <hash>, variables }`) resolved via the manifest's\n * operationName, rewrites the URL to the data plane, and attaches auth.\n * The GraphQL-spec response body passes through untouched, so InMemoryCache\n * and error links behave exactly as they do against a GraphQL server.\n */\nexport function createOrmFetch({\n baseUrl,\n namespace,\n manifest,\n getToken,\n getDataToken,\n fetchImpl = globalThis.fetch,\n}: OperationExecutorConfig): typeof globalThis.fetch {\n if (!manifest) throw new OrmClientError('createOrmFetch requires an operations manifest')\n if (!fetchImpl) throw new OrmClientError('no fetch implementation available')\n if ((getToken ? 1 : 0) + (getDataToken ? 1 : 0) !== 1) {\n throw new OrmClientError('provide exactly one of getToken (bearer) or getDataToken (delegated)')\n }\n const root = baseUrl.replace(/\\/+$/, '')\n const url = `${root}${dataPlanePath(namespace)}`\n\n // Derived from `globalThis.fetch` rather than naming `RequestInfo` (a DOM-lib\n // global this module compiles without). The input is ignored — Apollo's\n // HttpLink calls the injected fetch with a string URI, and the real target\n // URL is fixed at `url` above.\n return async (_input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit): Promise<Response> => {\n const raw = typeof init?.body === 'string' ? init.body : null\n const parsed = raw\n ? (JSON.parse(raw) as { operationName?: string; variables?: Record<string, unknown> })\n : {}\n const name = parsed.operationName\n if (!name) {\n throw new OrmClientError(\n 'createOrmFetch requires named operations (Apollo sends operationName for named documents)',\n )\n }\n const hash = resolveOpHash(manifest, name)\n const idempotencyKey = new Headers(init?.headers).get('Idempotency-Key') ?? undefined\n validateIdempotencyKey(idempotencyKey)\n const token = await (getDataToken ?? getToken)!()\n if (!token) throw new OrmClientError('not authenticated — no token available')\n const auth: Record<string, string> = getDataToken\n ? { [ORM_DATA_TOKEN_HEADER]: token }\n : { Authorization: `Bearer ${token}` }\n\n return fetchImpl(url, {\n method: 'POST',\n headers: { ...auth, 'Content-Type': 'application/json' },\n body: JSON.stringify({ op: hash, variables: parsed.variables ?? {}, idempotencyKey }),\n ...(init?.signal ? { signal: init.signal } : {}),\n })\n }\n}\n","import { NAMESPACE_PATTERN } from '../constants.js'\nimport { OrmClientError, OrmOperationError } from './errors.js'\nimport {\n validateIdempotencyKey, validateExpectedSourceGeneration, createReadReceiptOperationResolver,\n type ManifestOperation,\n type TypedReadReceiptSqlOperationExecutor, type OperationReadReceipt, type OperationReference, type OperationExecutionOptions,\n} from './operations.js'\nimport { isRecord, readOperationResponse, readOperationResponseWithReceipt } from './response.js'\nimport { BUILTIN_SQL_READ_HASH, type SqlQueryResult } from './sql.js'\n\nexport interface OperationTransportRequest {\n namespace: string\n op: string\n variables: Record<string, unknown>\n idempotencyKey?: string\n expectedSourceGeneration?: string\n}\n\nexport interface OperationTransportResponse {\n ok: boolean\n status: number\n body: unknown\n}\n\nexport type OperationTransport = (request: OperationTransportRequest) => Promise<OperationTransportResponse>\n\nconst operationHash = /^sha256:[a-f0-9]{64}$/\n\nfunction readManifestHashes(manifest: unknown): ReadonlyMap<string, Pick<ManifestOperation, 'hash' | 'kind'>> {\n if (!isRecord(manifest) || typeof manifest.schemaHash !== 'string' || !manifest.schemaHash || !isRecord(manifest.operations)) {\n throw new OrmClientError('invalid operations manifest — use operations.manifest.json from seq-studio orm generate')\n }\n const hashes = new Map<string, Pick<ManifestOperation, 'hash' | 'kind'>>()\n for (const [name, entry] of Object.entries(manifest.operations)) {\n if (!/^[_A-Za-z][_0-9A-Za-z]*$/.test(name) || !isRecord(entry) || typeof entry.hash !== 'string' || !operationHash.test(entry.hash)\n || (entry.kind !== 'query' && entry.kind !== 'mutation')) {\n throw new OrmClientError(`invalid operations manifest entry \"${name}\" — regenerate the manifest`)\n }\n hashes.set(name, { hash: entry.hash, kind: entry.kind })\n }\n return hashes\n}\n\n/**\n * Execute generated operations through a host-owned authenticated transport.\n * No credential handling, retries, or global configuration. The manifest is\n * validated once and copied, so later caller mutation cannot alter the target.\n */\nexport function createOperationExecutorWithTransport({ namespace, manifest, transport }: {\n namespace: string\n /** Accept generated JSON imports directly; validate them at construction. */\n manifest?: unknown\n transport: OperationTransport\n}): TypedReadReceiptSqlOperationExecutor {\n if (typeof namespace !== 'string' || !NAMESPACE_PATTERN.test(namespace)) throw new OrmClientError('invalid ORM namespace — expected a lowercase identifier of at most 41 characters')\n const hashes = manifest === undefined ? new Map<string, Pick<ManifestOperation, 'hash' | 'kind'>>() : readManifestHashes(manifest)\n const knownHashes = new Set([...hashes.values()].map(entry => entry.hash))\n const resolveReceiptOperation = createReadReceiptOperationResolver({ operations: hashes })\n async function request({ op, variables, options, requireReadReceipt = false }: {\n op: string | OperationReference<Record<string, unknown>, unknown>\n variables: Record<string, unknown>\n options: OperationExecutionOptions\n requireReadReceipt?: boolean\n }): Promise<OperationTransportResponse> {\n validateIdempotencyKey(options.idempotencyKey)\n validateExpectedSourceGeneration(options.expectedSourceGeneration)\n if (typeof op !== 'string' && op.namespace !== namespace) throw new OrmClientError('operation belongs to a different namespace')\n const selector = typeof op === 'string' ? op : op.hash\n const hash = requireReadReceipt\n ? resolveReceiptOperation({ selector, hashOnly: typeof op !== 'string' })\n : selector === BUILTIN_SQL_READ_HASH ? selector : hashes.get(selector)?.hash ?? (knownHashes.has(selector) ? selector : undefined)\n if (!hash) throw new OrmClientError(`unknown operation \"${op}\" — not in the manifest (${hashes.size} known). Re-run seq-studio orm generate.`)\n if (!isRecord(variables)) throw new OrmClientError('operation variables must be an object')\n const response = await transport({ namespace, op: hash, variables,\n ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),\n ...(options.expectedSourceGeneration === undefined ? {} : { expectedSourceGeneration: options.expectedSourceGeneration }),\n })\n if (!response || typeof response.ok !== 'boolean' || !Number.isInteger(response.status) || response.status < 100 || response.status > 599\n || response.ok !== (response.status >= 200 && response.status < 300)) {\n throw new OrmOperationError('malformed transport response', null, null)\n }\n return response\n }\n\n function execute<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<TData>\n function execute<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<TData>\n async function execute<TData = Record<string, unknown>>(op: string | OperationReference<Record<string, unknown>, TData>, variables: Record<string, unknown> = {}, options: OperationExecutionOptions = {}): Promise<TData> {\n const executionOptions = { ...options }\n const response = await request({ op, variables, options: executionOptions })\n return executionOptions.expectedSourceGeneration === undefined\n ? readOperationResponse<TData>(response)\n : readOperationResponseWithReceipt<TData>({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration }).data\n }\n\n function executeWithReadReceipt<TVariables extends Record<string, unknown>, TData>(op: OperationReference<TVariables, TData>, variables: TVariables, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n function executeWithReadReceipt<TData = Record<string, unknown>>(op: string, variables?: Record<string, unknown>, options?: OperationExecutionOptions): Promise<OperationReadReceipt<TData>>\n async function executeWithReadReceipt<TData = Record<string, unknown>>(op: string | OperationReference<Record<string, unknown>, TData>, variables: Record<string, unknown> = {}, options: OperationExecutionOptions = {}): Promise<OperationReadReceipt<TData>> {\n const executionOptions = { ...options }\n const response = await request({ op, variables, options: executionOptions, requireReadReceipt: true })\n return readOperationResponseWithReceipt<TData>({ ...response, expectedSourceGeneration: executionOptions.expectedSourceGeneration })\n }\n return { execute, executeWithReadReceipt, sql: variables => execute<SqlQueryResult>(BUILTIN_SQL_READ_HASH, variables) }\n}\n","import { OrmClientError, createFetchTransport, type OrmTransport } from './transport.js'\nimport { TableQuery } from './query-builder.js'\n\n/** Bindable scalar for `query()` placeholders ($1, $2, …). */\nexport type QueryParam = string | number | boolean | null\n\n/** Shape of one action in the generated `<Ns>Actions` map — params in, result out. */\nexport interface OrmActionShape {\n readonly params?: Record<string, unknown>\n readonly result: unknown\n}\n\n/** The generated `<Ns>Actions` map: action name → its param and result shapes. */\nexport type OrmActions = Record<string, OrmActionShape>\n\n/**\n * `action()`'s argument list: `params` is required when the action declares a\n * required field, optional otherwise. The empty-object type is assignable to\n * the params shape only when every field is optional, so that assignability is\n * the discriminant.\n */\ntype ActionArgs<Action extends OrmActionShape> =\n Record<string, never> extends NonNullable<Action['params']>\n ? [params?: NonNullable<Action['params']>]\n : [params: NonNullable<Action['params']>]\n\n/**\n * Typed read client for one namespace's Data API. `Tables` comes from\n * `types.gen.ts` (wire types the apply refreshes from the YAML definitions),\n * so column names and row shapes are checked at compile time; the server\n * re-validates everything and Postgres RLS decides row visibility.\n *\n * ```ts\n * const client = createOrmClient<LendingTables>({ namespace: 'lending', baseUrl, getToken })\n * const rows = await client.table('loans').select('id', 'balance').gte('balance', 1000).rows()\n * const top = await client.query<{ officer: string; total: string }>(\n * 'select officer, sum(balance) as total from loans group by officer order by total desc limit $1',\n * [5],\n * )\n * ```\n */\nexport interface OrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n> {\n table<Name extends keyof Tables & string>(name: Name): TableQuery<Tables[Name]>\n /**\n * Raw read-only SQL for everything the filter grammar can't say —\n * aggregates, joins, OR, expressions, CTEs. The same sandbox as every\n * read: the namespace consumer role (grants stop at the namespace schema),\n * Postgres RLS over the caller's claims, and a READ ONLY transaction —\n * Postgres itself rejects writes, which stay on declared actions. Values\n * bind as $1, $2, … placeholders; never interpolate them into the string.\n */\n query<Row = Record<string, unknown>>(sql: string, params?: readonly QueryParam[]): Promise<Row[]>\n /**\n * Invoke a declared action — the only write path the Data API exposes. The\n * params and result are typed from the namespace's `<Ns>Actions`: an action\n * with `returns:` resolves to `{ rows: Row[] }`, a count action to\n * `{ rowsAffected: number }`.\n */\n action<Name extends keyof Actions & string>(\n name: Name,\n ...args: ActionArgs<Actions[Name]>\n ): Promise<Actions[Name]['result']>\n}\n\nexport function createOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>({\n namespace,\n baseUrl,\n getToken,\n fetchImpl,\n transport,\n dataToken,\n}: {\n namespace: string\n baseUrl?: string\n /** App-user / session bearer (CLI, browser). Mutually exclusive with dataToken. */\n getToken?: () => Promise<string | null> | string | null\n /**\n * Delegated function data token — the inbound `ORM_DATA_TOKEN_HEADER` value a\n * managed function receives. Pass it and the client authenticates as the\n * invoking user, scoped to the function's declared refs; no manual transport.\n */\n dataToken?: string | (() => Promise<string | null> | string | null)\n fetchImpl?: typeof globalThis.fetch\n /** Injected transport (tests, bridges); overrides baseUrl/getToken/dataToken. */\n transport?: OrmTransport\n}): OrmClient<Tables, Actions> {\n const resolved =\n transport ??\n createFetchTransport({\n baseUrl: requireOption(baseUrl, 'baseUrl'),\n ...(dataToken !== undefined\n ? { getDataToken: typeof dataToken === 'function' ? dataToken : () => dataToken }\n : { getToken: requireOption(getToken, 'getToken') }),\n fetchImpl,\n })\n\n return buildOrmClient<Tables, Actions>(resolved, namespace)\n}\n\n/**\n * The ESCALATION path — use only deliberately. A managed function receives a\n * separate *service* data token on `ORM_SERVICE_DATA_TOKEN_HEADER`; pass that\n * value here and the client authenticates as the function's SERVICE IDENTITY,\n * not the invoking user. Reads run with the service identity's grants (clamped\n * to the function's declared refs), NOT the caller's — so the caller's own row\n * visibility does not apply. The invoking user is still recorded for audit.\n *\n * Default to `createOrmClient` (acts as the invoking user, full per-user RLS).\n * Reach for this only when the function must intentionally act beyond the\n * caller — e.g. enforcing per-user rules in code over a coarse upstream that\n * has no granular permissions of its own. The distinct name is the guardrail:\n * choosing the service identity is always explicit and greppable.\n *\n * ```ts\n * const client = createServiceOrmClient<LendingTables>({\n * namespace: 'lending',\n * baseUrl,\n * serviceDataToken: req.headers['x-sequence-data-token-service'],\n * })\n * ```\n */\nexport function createServiceOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>({\n namespace,\n baseUrl,\n serviceDataToken,\n fetchImpl,\n transport,\n}: {\n namespace: string\n baseUrl?: string\n /** The inbound `ORM_SERVICE_DATA_TOKEN_HEADER` value — the function's service token. */\n serviceDataToken?: string | (() => Promise<string | null> | string | null)\n fetchImpl?: typeof globalThis.fetch\n /** Injected transport (tests, bridges); overrides baseUrl/serviceDataToken. */\n transport?: OrmTransport\n}): OrmClient<Tables, Actions> {\n const resolved =\n transport ??\n createFetchTransport({\n baseUrl: requireOption(baseUrl, 'baseUrl'),\n getDataToken:\n typeof serviceDataToken === 'function'\n ? serviceDataToken\n : () => requireOption(serviceDataToken, 'serviceDataToken'),\n fetchImpl,\n })\n\n return buildOrmClient<Tables, Actions>(resolved, namespace)\n}\n\n/** Shared client surface over a resolved transport — the token/identity choice is made by the factory above. */\nfunction buildOrmClient<\n Tables extends Record<string, Record<string, unknown>>,\n Actions extends OrmActions = OrmActions,\n>(resolved: OrmTransport, namespace: string): OrmClient<Tables, Actions> {\n return {\n table(name) {\n return new TableQuery(resolved, namespace, name)\n },\n async query(sql, params) {\n const payload = await resolved.post(`/api/data/${namespace}/query`, {\n sql,\n ...(params ? { params: [...params] } : {}),\n })\n if (!payload || typeof payload !== 'object' || !Array.isArray((payload as { rows?: unknown }).rows)) {\n throw new OrmClientError('unexpected Data API response shape — missing rows array')\n }\n return (payload as { rows: never[] }).rows\n },\n async action(name, ...args) {\n const payload = await resolved.post(`/api/data/${namespace}/actions/${name}`, args[0] ?? {})\n if (payload && typeof payload === 'object') {\n // A returns action responds with `rows`; a count action with\n // `rows_affected` (mapped to `rowsAffected` for the client).\n if (Array.isArray((payload as { rows?: unknown }).rows)) {\n return { rows: (payload as { rows: unknown[] }).rows } as Awaited<ReturnType<OrmClient<Tables, Actions>['action']>>\n }\n if ('rows_affected' in payload) {\n const rowsAffected = Number((payload as { rows_affected: unknown }).rows_affected)\n if (!Number.isNaN(rowsAffected)) {\n return { rowsAffected } as Awaited<ReturnType<OrmClient<Tables, Actions>['action']>>\n }\n }\n }\n throw new OrmClientError('unexpected action response shape — expected rows or rows_affected')\n },\n }\n}\n\nfunction requireOption<T>(value: T | undefined, name: string): T {\n if (value === undefined) throw new Error(`createOrmClient requires ${name} when no transport is injected`)\n return value\n}\n\nexport { TableQuery, type FilterValue, type ReadResponse } from './query-builder.js'\nexport { createFetchTransport, OrmClientError, type OrmTransport } from './transport.js'\n\nexport {\n OrmOperationError,\n configureOrmOperations,\n createOperationExecutor,\n createOrmFetch,\n executeOperation,\n} from './operations.js'\nexport type {\n ManifestOperation,\n OperationErrorEntry,\n OperationExecutor,\n SqlOperationExecutor,\n OperationReference,\n TypedOperationExecutor,\n TypedSqlOperationExecutor,\n ReadReceiptOperationExecutor,\n ReadReceiptSqlOperationExecutor,\n TypedReadReceiptOperationExecutor,\n TypedReadReceiptSqlOperationExecutor,\n OperationReadReceipt,\n OperationExecutionOptions,\n OperationExecutorConfig,\n OperationsManifest,\n} from './operations.js'\n\nexport { NAMESPACE_PATTERN, ORM_DATA_TOKEN_HEADER, ORM_SERVICE_DATA_TOKEN_HEADER } from '../constants.js'\nexport type { SqlQueryParameter, SqlQueryVariables, SqlQueryResult } from './sql.js'\nexport { BUILTIN_SQL_READ_HASH } from './sql.js'\nexport {\n createOperationExecutorWithTransport,\n type OperationTransport, type OperationTransportRequest, type OperationTransportResponse,\n} from './transport-executor.js'\n"]}
|
package/package.json
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"validate": "seq-studio orm validate",
|
|
7
|
+
"lint": "seq-studio orm validate",
|
|
7
8
|
"generate": "seq-studio orm generate",
|
|
8
9
|
"diff": "seq-studio orm diff",
|
|
9
10
|
"apply": "seq-studio orm apply",
|
|
@@ -20,6 +21,7 @@
|
|
|
20
21
|
"@graphql-codegen/typed-document-node": "^5.1.1",
|
|
21
22
|
"@graphql-codegen/typescript": "^4.1.6",
|
|
22
23
|
"@graphql-codegen/typescript-operations": "^4.6.1",
|
|
24
|
+
"@sequenceholdings/studio-cli": "^0.5.1",
|
|
23
25
|
"typescript": "^5.6.0"
|
|
24
26
|
},
|
|
25
27
|
"engines": {
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
defineEnum, defineTable, t, toMany, toOne, toPlatformUser, type SeqTable,
|
|
3
|
+
} from '@sequenceholdings/orm/authoring'
|
|
2
4
|
|
|
3
5
|
/**
|
|
4
6
|
* Tables are TypeScript, but they SERIALIZE to data — the server never runs
|
|
@@ -17,7 +19,9 @@ import { defineEnum, defineTable, t, toMany, toOne, toPlatformUser } from '@sequ
|
|
|
17
19
|
*/
|
|
18
20
|
export const dealStatus = defineEnum('deal_status', ['open', 'won', 'lost'])
|
|
19
21
|
|
|
20
|
-
|
|
22
|
+
// Tables that link to each other need an explicit `SeqTable` annotation:
|
|
23
|
+
// TypeScript cannot infer a type through a mutually recursive `() => table`.
|
|
24
|
+
export const deals: SeqTable = defineTable(
|
|
21
25
|
'deals',
|
|
22
26
|
{
|
|
23
27
|
id: t.uuid().primaryKey().default('gen_random_uuid()'),
|
|
@@ -48,7 +52,7 @@ export const deals = defineTable(
|
|
|
48
52
|
},
|
|
49
53
|
)
|
|
50
54
|
|
|
51
|
-
export const comments = defineTable(
|
|
55
|
+
export const comments: SeqTable = defineTable(
|
|
52
56
|
'comments',
|
|
53
57
|
{
|
|
54
58
|
id: t.uuid().primaryKey().default('gen_random_uuid()'),
|