@xylex-group/athena 2.0.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +287 -95
  2. package/dist/browser.cjs +4791 -0
  3. package/dist/browser.cjs.map +1 -0
  4. package/dist/browser.d.cts +25 -0
  5. package/dist/browser.d.ts +25 -0
  6. package/dist/browser.js +4745 -0
  7. package/dist/browser.js.map +1 -0
  8. package/dist/cli/index.cjs +2087 -220
  9. package/dist/cli/index.cjs.map +1 -1
  10. package/dist/cli/index.d.cts +3 -2
  11. package/dist/cli/index.d.ts +3 -2
  12. package/dist/cli/index.js +2089 -222
  13. package/dist/cli/index.js.map +1 -1
  14. package/dist/cookies.cjs +890 -0
  15. package/dist/cookies.cjs.map +1 -0
  16. package/dist/cookies.d.cts +174 -0
  17. package/dist/cookies.d.ts +174 -0
  18. package/dist/cookies.js +869 -0
  19. package/dist/cookies.js.map +1 -0
  20. package/dist/index.cjs +3046 -1200
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +8 -408
  23. package/dist/index.d.ts +8 -408
  24. package/dist/index.js +3045 -1202
  25. package/dist/index.js.map +1 -1
  26. package/dist/{model-form-CVOtC8jq.d.ts → model-form-BpDXlbxb.d.ts} +97 -2
  27. package/dist/{model-form-hXkvHS_3.d.cts → model-form-hoE2jHIi.d.cts} +97 -2
  28. package/dist/pipeline-BNIw8pDQ.d.ts +8 -0
  29. package/dist/pipeline-DNIpEsN8.d.cts +8 -0
  30. package/dist/react-email-BvyCZnfW.d.cts +610 -0
  31. package/dist/react-email-qPA1wjFV.d.ts +610 -0
  32. package/dist/react.cjs +30 -9
  33. package/dist/react.cjs.map +1 -1
  34. package/dist/react.d.cts +4 -4
  35. package/dist/react.d.ts +4 -4
  36. package/dist/react.js +30 -9
  37. package/dist/react.js.map +1 -1
  38. package/dist/{types-BnzoaNRC.d.cts → types-A5e97acl.d.cts} +2 -1
  39. package/dist/{types-BnzoaNRC.d.ts → types-A5e97acl.d.ts} +2 -1
  40. package/dist/{pipeline-CQgV-Yfo.d.ts → types-BnD22-vb.d.ts} +2 -7
  41. package/dist/{pipeline-C-cN0ACi.d.cts → types-bDlr4u7p.d.cts} +2 -7
  42. package/dist/utils.cjs +153 -0
  43. package/dist/utils.cjs.map +1 -0
  44. package/dist/utils.d.cts +23 -0
  45. package/dist/utils.d.ts +23 -0
  46. package/dist/utils.js +146 -0
  47. package/dist/utils.js.map +1 -0
  48. package/package.json +87 -9
@@ -0,0 +1,4745 @@
1
+ // src/gateway/errors.ts
2
+ var AthenaGatewayError = class _AthenaGatewayError extends Error {
3
+ code;
4
+ status;
5
+ endpoint;
6
+ method;
7
+ requestId;
8
+ hint;
9
+ causeDetail;
10
+ constructor(input) {
11
+ super(input.message);
12
+ this.name = "AthenaGatewayError";
13
+ this.code = input.code;
14
+ this.status = input.status ?? 0;
15
+ this.endpoint = input.endpoint;
16
+ this.method = input.method;
17
+ this.requestId = input.requestId;
18
+ this.hint = input.hint;
19
+ this.causeDetail = input.cause;
20
+ }
21
+ toDetails() {
22
+ return {
23
+ code: this.code,
24
+ message: this.message,
25
+ status: this.status,
26
+ endpoint: this.endpoint,
27
+ method: this.method,
28
+ requestId: this.requestId,
29
+ hint: this.hint,
30
+ cause: this.causeDetail
31
+ };
32
+ }
33
+ static fromResponse(response, fallback) {
34
+ const details = response.errorDetails;
35
+ if (details) {
36
+ return new _AthenaGatewayError({
37
+ code: details.code,
38
+ message: details.message,
39
+ status: details.status,
40
+ endpoint: details.endpoint ?? fallback.endpoint,
41
+ method: details.method ?? fallback.method,
42
+ requestId: details.requestId ?? fallback.requestId,
43
+ hint: details.hint,
44
+ cause: details.cause
45
+ });
46
+ }
47
+ return new _AthenaGatewayError({
48
+ code: "HTTP_ERROR",
49
+ message: response.error ?? "Gateway request failed",
50
+ status: response.status,
51
+ endpoint: fallback.endpoint,
52
+ method: fallback.method,
53
+ requestId: fallback.requestId
54
+ });
55
+ }
56
+ };
57
+ function isAthenaGatewayError(error) {
58
+ return error instanceof AthenaGatewayError;
59
+ }
60
+
61
+ // src/gateway/client.ts
62
+ var DEFAULT_BASE_URL = "https://athena-db.com";
63
+ var DEFAULT_CLIENT = "railway_direct";
64
+ var FALLBACK_SDK_VERSION = "1.3.0";
65
+ var SDK_NAME = "xylex-group/athena";
66
+ var SDK_VERSION = typeof process !== "undefined" && process?.env?.npm_package_version ? process.env.npm_package_version : FALLBACK_SDK_VERSION;
67
+ var SDK_HEADER_VALUE = `${SDK_NAME} ${SDK_VERSION}`;
68
+ function parseResponseBody(rawText, contentType) {
69
+ if (!rawText) {
70
+ return { parsed: null, parseFailed: false };
71
+ }
72
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
73
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
74
+ if (!looksJson) {
75
+ return { parsed: rawText, parseFailed: false };
76
+ }
77
+ try {
78
+ return { parsed: JSON.parse(rawText), parseFailed: false };
79
+ } catch {
80
+ return { parsed: rawText, parseFailed: true };
81
+ }
82
+ }
83
+ function normalizeHeaderValue(value) {
84
+ return value ? value : void 0;
85
+ }
86
+ function isRecord(value) {
87
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
88
+ }
89
+ function nonEmptyString(value) {
90
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
91
+ }
92
+ function resolveStructuredErrorPayload(payload) {
93
+ if (!isRecord(payload)) return null;
94
+ return isRecord(payload.error) ? payload.error : payload;
95
+ }
96
+ function resolveRequestId(headers) {
97
+ return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
98
+ }
99
+ function resolveErrorMessage(payload, fallback) {
100
+ const structuredPayload = resolveStructuredErrorPayload(payload);
101
+ if (structuredPayload) {
102
+ const messageCandidates = [structuredPayload.message, structuredPayload.error, structuredPayload.details];
103
+ for (const candidate of messageCandidates) {
104
+ const resolved = nonEmptyString(candidate);
105
+ if (resolved) return resolved;
106
+ }
107
+ }
108
+ const rawMessage = nonEmptyString(payload);
109
+ if (rawMessage) return rawMessage;
110
+ return fallback;
111
+ }
112
+ function resolveErrorHint(payload) {
113
+ const structuredPayload = resolveStructuredErrorPayload(payload);
114
+ return structuredPayload ? nonEmptyString(structuredPayload.hint) : void 0;
115
+ }
116
+ function resolveStatusText(response, payload) {
117
+ const rawStatusText = nonEmptyString(response.statusText);
118
+ if (rawStatusText) return rawStatusText;
119
+ const payloadRecord = isRecord(payload) ? payload : null;
120
+ return payloadRecord ? nonEmptyString(payloadRecord.statusText) ?? null : null;
121
+ }
122
+ function detailsFromError(error) {
123
+ return error.toDetails();
124
+ }
125
+ function toQueryScalar(value) {
126
+ if (value === null || value === void 0) return "null";
127
+ if (typeof value === "boolean") return value ? "true" : "false";
128
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : "null";
129
+ return String(value);
130
+ }
131
+ function toQueryArray(values) {
132
+ return `{${values.map(toQueryScalar).join(",")}}`;
133
+ }
134
+ function toRpcArgumentQueryValue(value) {
135
+ if (Array.isArray(value)) return toQueryArray(value);
136
+ if (value && typeof value === "object") return JSON.stringify(value);
137
+ return toQueryScalar(value);
138
+ }
139
+ function toRpcFilterQueryValue(filter) {
140
+ const value = filter.value;
141
+ switch (filter.operator) {
142
+ case "in": {
143
+ if (!Array.isArray(value)) {
144
+ throw new AthenaGatewayError({
145
+ code: "UNKNOWN_ERROR",
146
+ message: `RPC filter "${filter.column}" with operator "in" requires an array value`,
147
+ status: 0
148
+ });
149
+ }
150
+ return `in.${toQueryArray(value)}`;
151
+ }
152
+ case "is":
153
+ return `is.${toQueryScalar(value)}`;
154
+ case "eq":
155
+ case "neq":
156
+ case "gt":
157
+ case "gte":
158
+ case "lt":
159
+ case "lte":
160
+ case "like":
161
+ case "ilike":
162
+ return `${filter.operator}.${toQueryScalar(value)}`;
163
+ }
164
+ }
165
+ function buildRpcGetEndpoint(payload) {
166
+ const functionName = (payload.function_name ?? payload.function).trim();
167
+ if (!functionName) {
168
+ throw new AthenaGatewayError({
169
+ code: "UNKNOWN_ERROR",
170
+ message: "rpc requires a function name",
171
+ status: 0,
172
+ endpoint: "/gateway/rpc",
173
+ method: "GET"
174
+ });
175
+ }
176
+ const query = new URLSearchParams();
177
+ if (payload.schema) query.set("schema", payload.schema);
178
+ if (payload.select) query.set("select", payload.select);
179
+ if (payload.count) query.set("count", payload.count);
180
+ if (payload.head) query.set("head", "true");
181
+ if (typeof payload.limit === "number") query.set("limit", String(payload.limit));
182
+ if (typeof payload.offset === "number") query.set("offset", String(payload.offset));
183
+ if (payload.order?.column) {
184
+ query.set(
185
+ "order",
186
+ payload.order.ascending === false ? `${payload.order.column}.desc` : payload.order.column
187
+ );
188
+ }
189
+ if (payload.args) {
190
+ for (const [key, value] of Object.entries(payload.args)) {
191
+ query.set(key, toRpcArgumentQueryValue(value));
192
+ }
193
+ }
194
+ if (payload.filters?.length) {
195
+ for (const filter of payload.filters) {
196
+ if (payload.args && Object.prototype.hasOwnProperty.call(payload.args, filter.column)) {
197
+ throw new AthenaGatewayError({
198
+ code: "UNKNOWN_ERROR",
199
+ message: `RPC filter "${filter.column}" conflicts with RPC argument "${filter.column}" in GET mode`,
200
+ status: 0
201
+ });
202
+ }
203
+ query.set(filter.column, toRpcFilterQueryValue(filter));
204
+ }
205
+ }
206
+ const endpoint = `/rpc/${encodeURIComponent(functionName)}`;
207
+ const queryText = query.toString();
208
+ const withQuery = queryText ? `${endpoint}?${queryText}` : endpoint;
209
+ return withQuery;
210
+ }
211
+ function buildHeaders(config, options) {
212
+ const mergedStripNulls = options?.stripNulls ?? true;
213
+ const extraHeaders = {
214
+ ...config.headers ?? {},
215
+ ...options?.headers ?? {}
216
+ };
217
+ const headerClient = extraHeaders["x-athena-client"] ?? extraHeaders["X-Athena-Client"];
218
+ const finalClient = options?.client ?? config.client ?? (typeof headerClient === "string" ? headerClient : void 0) ?? DEFAULT_CLIENT;
219
+ const finalApiKey = options?.apiKey ?? config.apiKey;
220
+ const finalPublishEvent = options?.publishEvent ?? config.publishEvent;
221
+ const headers = {
222
+ "Content-Type": "application/json",
223
+ "X-Athena-Sdk": SDK_HEADER_VALUE
224
+ };
225
+ if (options?.userId ?? config.userId) {
226
+ headers["X-User-Id"] = options?.userId ?? config.userId ?? "";
227
+ }
228
+ if (options?.organizationId ?? config.organizationId) {
229
+ headers["X-Organization-Id"] = options?.organizationId ?? config.organizationId ?? "";
230
+ }
231
+ if (finalClient) {
232
+ headers["X-Athena-Client"] = finalClient;
233
+ }
234
+ const finalBackend = options?.backend ?? config.backend;
235
+ if (finalBackend) {
236
+ const type = typeof finalBackend === "string" ? finalBackend : finalBackend.type;
237
+ if (type) headers["X-Backend-Type"] = type;
238
+ }
239
+ if (typeof mergedStripNulls === "boolean") {
240
+ headers["X-Strip-Nulls"] = mergedStripNulls ? "true" : "false";
241
+ }
242
+ if (finalPublishEvent) {
243
+ headers["X-Publish-Event"] = finalPublishEvent;
244
+ }
245
+ if (finalApiKey) {
246
+ headers["apikey"] = finalApiKey;
247
+ headers["x-api-key"] = headers["x-api-key"] ?? finalApiKey;
248
+ }
249
+ const athenaClientKeys = ["x-athena-client", "X-Athena-Client"];
250
+ Object.entries(extraHeaders).forEach(([key, value]) => {
251
+ if (athenaClientKeys.includes(key)) return;
252
+ const normalized = normalizeHeaderValue(value);
253
+ if (normalized) {
254
+ headers[key] = normalized;
255
+ }
256
+ });
257
+ return headers;
258
+ }
259
+ async function callAthena(config, endpoint, method, payload, options) {
260
+ const baseUrl = (options?.baseUrl ?? config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
261
+ const url = `${baseUrl}${endpoint}`;
262
+ const headers = buildHeaders(config, options);
263
+ try {
264
+ const requestInit = {
265
+ method,
266
+ headers
267
+ };
268
+ if (method !== "GET") {
269
+ requestInit.body = JSON.stringify(payload);
270
+ }
271
+ const response = await fetch(url, requestInit);
272
+ const rawText = await response.text();
273
+ const requestId = resolveRequestId(response.headers);
274
+ const parsedBody = parseResponseBody(
275
+ rawText ?? "",
276
+ response.headers.get("content-type")
277
+ );
278
+ if (parsedBody.parseFailed) {
279
+ const invalidJsonError = new AthenaGatewayError({
280
+ code: "INVALID_JSON",
281
+ message: "Gateway returned malformed JSON",
282
+ status: response.status,
283
+ endpoint,
284
+ method,
285
+ requestId,
286
+ hint: "Verify the gateway response body is valid JSON.",
287
+ cause: rawText.slice(0, 300)
288
+ });
289
+ return {
290
+ ok: false,
291
+ status: response.status,
292
+ statusText: resolveStatusText(response, parsedBody.parsed),
293
+ data: null,
294
+ error: invalidJsonError.message,
295
+ errorDetails: detailsFromError(invalidJsonError),
296
+ raw: parsedBody.parsed
297
+ };
298
+ }
299
+ const parsed = parsedBody.parsed;
300
+ const parsedPayload = isRecord(parsed) ? parsed : null;
301
+ if (!response.ok) {
302
+ const httpError = new AthenaGatewayError({
303
+ code: "HTTP_ERROR",
304
+ message: resolveErrorMessage(
305
+ parsed,
306
+ `Athena gateway ${method} ${endpoint} failed with status ${response.status}`
307
+ ),
308
+ status: response.status,
309
+ endpoint,
310
+ method,
311
+ requestId,
312
+ hint: resolveErrorHint(parsed)
313
+ });
314
+ return {
315
+ ok: false,
316
+ status: response.status,
317
+ statusText: resolveStatusText(response, parsed),
318
+ data: null,
319
+ error: httpError.message,
320
+ errorDetails: detailsFromError(httpError),
321
+ raw: parsed
322
+ };
323
+ }
324
+ const payloadData = parsedPayload && "data" in parsedPayload ? parsedPayload.data : parsed;
325
+ const payloadCount = parsedPayload && "count" in parsedPayload ? typeof parsedPayload.count === "number" || parsedPayload.count === null ? parsedPayload.count : void 0 : void 0;
326
+ return {
327
+ ok: true,
328
+ status: response.status,
329
+ statusText: resolveStatusText(response, parsed),
330
+ data: payloadData ?? null,
331
+ count: payloadCount,
332
+ error: void 0,
333
+ errorDetails: null,
334
+ raw: parsed
335
+ };
336
+ } catch (callError) {
337
+ const message = callError instanceof Error ? callError.message : String(callError);
338
+ const networkError = new AthenaGatewayError({
339
+ code: "NETWORK_ERROR",
340
+ message: `Network error while calling ${method} ${endpoint}: ${message}`,
341
+ endpoint,
342
+ method,
343
+ cause: message,
344
+ hint: "Check gateway URL, DNS, and network reachability."
345
+ });
346
+ return {
347
+ ok: false,
348
+ status: 0,
349
+ statusText: null,
350
+ data: null,
351
+ error: networkError.message,
352
+ errorDetails: detailsFromError(networkError),
353
+ raw: null
354
+ };
355
+ }
356
+ }
357
+ function createAthenaGatewayClient(config = {}) {
358
+ return {
359
+ baseUrl: (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
360
+ buildHeaders(options) {
361
+ return buildHeaders(config, options);
362
+ },
363
+ fetchGateway(payload, options) {
364
+ return callAthena(config, "/gateway/fetch", "POST", payload, options);
365
+ },
366
+ insertGateway(payload, options) {
367
+ return callAthena(config, "/gateway/insert", "PUT", payload, options);
368
+ },
369
+ updateGateway(payload, options) {
370
+ return callAthena(config, "/gateway/update", "POST", payload, options);
371
+ },
372
+ deleteGateway(payload, options) {
373
+ return callAthena(config, "/gateway/delete", "DELETE", payload, options);
374
+ },
375
+ rpcGateway(payload, options) {
376
+ if (options?.get) {
377
+ const endpoint = buildRpcGetEndpoint(payload);
378
+ return callAthena(config, endpoint, "GET", null, options);
379
+ }
380
+ return callAthena(config, "/gateway/rpc", "POST", payload, options);
381
+ },
382
+ queryGateway(payload, options) {
383
+ return callAthena(config, "/gateway/query", "POST", payload, options);
384
+ }
385
+ };
386
+ }
387
+
388
+ // src/sql-identifiers.ts
389
+ var SIMPLE_IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
390
+ var COMPOSITE_IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;
391
+ var SQL_ALIAS_PATTERN = /^([A-Za-z_][A-Za-z0-9_.]*)\s+(?:as\s+)?([A-Za-z_][A-Za-z0-9_]*)$/i;
392
+ var RESPONSE_ALIAS_PATTERN = /^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*([A-Za-z_][A-Za-z0-9_.]*)$/i;
393
+ function quoteIdentifierSegment(identifier2) {
394
+ return `"${identifier2.replace(/"/g, '""')}"`;
395
+ }
396
+ function parseAliasedIdentifierToken(token) {
397
+ const responseAliasMatch = RESPONSE_ALIAS_PATTERN.exec(token);
398
+ if (responseAliasMatch) {
399
+ const [, aliasIdentifier2, baseIdentifier2] = responseAliasMatch;
400
+ if (COMPOSITE_IDENTIFIER_PATTERN.test(baseIdentifier2) && SIMPLE_IDENTIFIER_PATTERN.test(aliasIdentifier2)) {
401
+ return { baseIdentifier: baseIdentifier2, aliasIdentifier: aliasIdentifier2 };
402
+ }
403
+ }
404
+ const sqlAliasMatch = SQL_ALIAS_PATTERN.exec(token);
405
+ if (!sqlAliasMatch) {
406
+ return null;
407
+ }
408
+ const [, baseIdentifier, aliasIdentifier] = sqlAliasMatch;
409
+ if (!COMPOSITE_IDENTIFIER_PATTERN.test(baseIdentifier) || !SIMPLE_IDENTIFIER_PATTERN.test(aliasIdentifier)) {
410
+ return null;
411
+ }
412
+ return { baseIdentifier, aliasIdentifier };
413
+ }
414
+ function quoteQualifiedIdentifier(identifier2) {
415
+ return identifier2.split(".").map((segment) => quoteIdentifierSegment(segment)).join(".");
416
+ }
417
+ function quoteSelectToken(token) {
418
+ if (token === "*") return token;
419
+ if (COMPOSITE_IDENTIFIER_PATTERN.test(token)) {
420
+ return quoteQualifiedIdentifier(token);
421
+ }
422
+ const aliasedIdentifier = parseAliasedIdentifierToken(token);
423
+ if (!aliasedIdentifier) {
424
+ return token;
425
+ }
426
+ const { baseIdentifier, aliasIdentifier } = aliasedIdentifier;
427
+ return `${quoteQualifiedIdentifier(baseIdentifier)} AS ${quoteIdentifierSegment(aliasIdentifier)}`;
428
+ }
429
+ function quoteSelectColumnToken(token) {
430
+ const trimmed = token.trim();
431
+ if (!trimmed || trimmed === "*") return trimmed || "*";
432
+ const responseAliasMatch = RESPONSE_ALIAS_PATTERN.exec(trimmed);
433
+ if (responseAliasMatch) {
434
+ const [, aliasIdentifier, baseIdentifier] = responseAliasMatch;
435
+ return `${quoteQualifiedIdentifier(baseIdentifier)} AS ${quoteIdentifierSegment(aliasIdentifier)}`;
436
+ }
437
+ return quoteQualifiedIdentifier(trimmed);
438
+ }
439
+ function canAutoQuoteToken(token) {
440
+ if (token === "*") return true;
441
+ if (COMPOSITE_IDENTIFIER_PATTERN.test(token)) return true;
442
+ return parseAliasedIdentifierToken(token) != null;
443
+ }
444
+ function splitTopLevelCommaSeparated(input) {
445
+ const parts = [];
446
+ let buffer = "";
447
+ let singleQuoted = false;
448
+ let doubleQuoted = false;
449
+ let depth = 0;
450
+ for (let index = 0; index < input.length; index += 1) {
451
+ const char = input[index];
452
+ const next = index + 1 < input.length ? input[index + 1] : "";
453
+ if (singleQuoted) {
454
+ buffer += char;
455
+ if (char === "'" && next === "'") {
456
+ buffer += next;
457
+ index += 1;
458
+ continue;
459
+ }
460
+ if (char === "'") {
461
+ singleQuoted = false;
462
+ }
463
+ continue;
464
+ }
465
+ if (doubleQuoted) {
466
+ buffer += char;
467
+ if (char === '"' && next === '"') {
468
+ buffer += next;
469
+ index += 1;
470
+ continue;
471
+ }
472
+ if (char === '"') {
473
+ doubleQuoted = false;
474
+ }
475
+ continue;
476
+ }
477
+ if (char === "'") {
478
+ singleQuoted = true;
479
+ buffer += char;
480
+ continue;
481
+ }
482
+ if (char === '"') {
483
+ doubleQuoted = true;
484
+ buffer += char;
485
+ continue;
486
+ }
487
+ if (char === "(") {
488
+ depth += 1;
489
+ buffer += char;
490
+ continue;
491
+ }
492
+ if (char === ")") {
493
+ depth -= 1;
494
+ if (depth < 0) return null;
495
+ buffer += char;
496
+ continue;
497
+ }
498
+ if (char === "," && depth === 0) {
499
+ parts.push(buffer.trim());
500
+ buffer = "";
501
+ continue;
502
+ }
503
+ buffer += char;
504
+ }
505
+ if (singleQuoted || doubleQuoted || depth !== 0) {
506
+ return null;
507
+ }
508
+ if (buffer.trim().length > 0) {
509
+ parts.push(buffer.trim());
510
+ }
511
+ return parts;
512
+ }
513
+ function quoteSelectColumnsExpression(columns) {
514
+ const trimmed = columns.trim();
515
+ if (!trimmed || trimmed === "*") return trimmed || "*";
516
+ const tokens = splitTopLevelCommaSeparated(trimmed);
517
+ if (!tokens || tokens.length === 0) {
518
+ return trimmed;
519
+ }
520
+ if (!tokens.every(canAutoQuoteToken)) {
521
+ return trimmed;
522
+ }
523
+ return tokens.map(quoteSelectToken).join(", ");
524
+ }
525
+ var SqlIdentifierPath = class {
526
+ segments;
527
+ constructor(segments) {
528
+ this.segments = segments;
529
+ }
530
+ toSql() {
531
+ return this.segments.map(quoteIdentifierSegment).join(".");
532
+ }
533
+ toString() {
534
+ return this.toSql();
535
+ }
536
+ };
537
+ function identifier(...segments) {
538
+ const expandedSegments = segments.flatMap((segment) => segment.split(".")).map((segment) => segment.trim()).filter((segment) => segment.length > 0);
539
+ return new SqlIdentifierPath(expandedSegments);
540
+ }
541
+
542
+ // src/auth/react-email.ts
543
+ var reactEmailRenderModulePromise;
544
+ function isRecord2(value) {
545
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
546
+ }
547
+ function isFunction(value) {
548
+ return typeof value === "function";
549
+ }
550
+ function toStringOrUndefined(value) {
551
+ if (typeof value !== "string") return void 0;
552
+ return value;
553
+ }
554
+ function nowIsoString() {
555
+ return (/* @__PURE__ */ new Date()).toISOString();
556
+ }
557
+ function emitReactEmailEvent(observe, phase, input = {}) {
558
+ if (!observe) return;
559
+ try {
560
+ observe({
561
+ phase,
562
+ timestamp: nowIsoString(),
563
+ ...input
564
+ });
565
+ } catch {
566
+ }
567
+ }
568
+ function mergeRenderDefaults(input, defaults) {
569
+ return {
570
+ ...input,
571
+ pretty: input.pretty ?? defaults?.pretty,
572
+ includePlainText: input.includePlainText ?? defaults?.includePlainText
573
+ };
574
+ }
575
+ function mergeRuntimeOptions(options) {
576
+ if (!options) return void 0;
577
+ return {
578
+ defaults: options.defaults,
579
+ observe: options.observe,
580
+ route: "route" in options ? options.route : void 0
581
+ };
582
+ }
583
+ async function resolveReactEmailRenderModule() {
584
+ if (!reactEmailRenderModulePromise) {
585
+ reactEmailRenderModulePromise = (async () => {
586
+ try {
587
+ const loaded = await import('@react-email/render');
588
+ if (!isFunction(loaded.render)) {
589
+ throw new Error("missing render(...) export");
590
+ }
591
+ return {
592
+ render: loaded.render,
593
+ toPlainText: isFunction(loaded.toPlainText) ? loaded.toPlainText : void 0,
594
+ pretty: isFunction(loaded.pretty) ? loaded.pretty : void 0
595
+ };
596
+ } catch (error) {
597
+ const message = error instanceof Error ? error.message : String(error);
598
+ throw new Error(
599
+ `React Email rendering requires @react-email/render. Install it in your project (for example: pnpm add @react-email/render). Loader error: ${message}`
600
+ );
601
+ }
602
+ })();
603
+ }
604
+ if (!reactEmailRenderModulePromise) {
605
+ throw new Error("React Email renderer module failed to initialize");
606
+ }
607
+ return reactEmailRenderModulePromise;
608
+ }
609
+ async function resolveReactEmailElement(input) {
610
+ if (input.element != null) {
611
+ return input.element;
612
+ }
613
+ if (!input.component) {
614
+ throw new Error("react email payload requires either `element` or `component`");
615
+ }
616
+ try {
617
+ const reactModule = await import('react');
618
+ if (typeof reactModule.createElement !== "function") {
619
+ throw new Error("react createElement(...) export is unavailable");
620
+ }
621
+ return reactModule.createElement(
622
+ input.component,
623
+ input.props ?? {}
624
+ );
625
+ } catch (error) {
626
+ const message = error instanceof Error ? error.message : String(error);
627
+ throw new Error(
628
+ `React Email component rendering requires react runtime support. Install react in your project. Loader error: ${message}`
629
+ );
630
+ }
631
+ }
632
+ function createAuthReactEmailInput(component, props, overrides = {}) {
633
+ return {
634
+ ...overrides,
635
+ component,
636
+ props
637
+ };
638
+ }
639
+ function defineAuthEmailTemplate(definition) {
640
+ const react = (props, overrides) => createAuthReactEmailInput(definition.component, props, {
641
+ ...definition.defaults,
642
+ ...overrides
643
+ });
644
+ return {
645
+ component: definition.component,
646
+ react,
647
+ toTemplateCreate: (input) => {
648
+ const templateKey = input.templateKey ?? definition.templateKey;
649
+ const subjectTemplate = input.subjectTemplate ?? definition.subjectTemplate;
650
+ if (!templateKey) {
651
+ throw new Error("defineAuthEmailTemplate.toTemplateCreate requires templateKey");
652
+ }
653
+ if (!subjectTemplate) {
654
+ throw new Error("defineAuthEmailTemplate.toTemplateCreate requires subjectTemplate");
655
+ }
656
+ const { props, react: reactOverrides, ...rest } = input;
657
+ return {
658
+ ...rest,
659
+ templateKey,
660
+ subjectTemplate,
661
+ react: react(props, reactOverrides)
662
+ };
663
+ },
664
+ toTemplateUpdate: (input) => {
665
+ const { props, react: reactOverrides, ...rest } = input;
666
+ return {
667
+ ...rest,
668
+ react: react(props, reactOverrides)
669
+ };
670
+ }
671
+ };
672
+ }
673
+ async function renderAthenaReactEmail(input, options) {
674
+ if (!isRecord2(input)) {
675
+ throw new Error("react email payload must be an object");
676
+ }
677
+ const runtimeOptions = mergeRuntimeOptions(options);
678
+ const start = Date.now();
679
+ emitReactEmailEvent(runtimeOptions?.observe, "render:start", {
680
+ route: runtimeOptions?.route,
681
+ message: "Rendering react email payload"
682
+ });
683
+ try {
684
+ const normalizedInput = mergeRenderDefaults(input, runtimeOptions?.defaults);
685
+ const element = await resolveReactEmailElement(normalizedInput);
686
+ const renderModule = await resolveReactEmailRenderModule();
687
+ const htmlValue = await renderModule.render(element);
688
+ const renderedHtml = typeof htmlValue === "string" ? htmlValue : String(htmlValue ?? "");
689
+ if (!renderedHtml.trim()) {
690
+ throw new Error("react email renderer returned an empty HTML string");
691
+ }
692
+ let html = renderedHtml;
693
+ if (normalizedInput.pretty && renderModule.pretty) {
694
+ const prettyValue = await renderModule.pretty(renderedHtml);
695
+ if (typeof prettyValue === "string" && prettyValue.trim().length > 0) {
696
+ html = prettyValue;
697
+ }
698
+ }
699
+ const explicitText = toStringOrUndefined(normalizedInput.text);
700
+ if (explicitText !== void 0) {
701
+ emitReactEmailEvent(runtimeOptions?.observe, "render:success", {
702
+ route: runtimeOptions?.route,
703
+ durationMs: Date.now() - start,
704
+ message: "Rendered react email with explicit text"
705
+ });
706
+ return {
707
+ html,
708
+ text: explicitText
709
+ };
710
+ }
711
+ if (normalizedInput.includePlainText === false || !renderModule.toPlainText) {
712
+ emitReactEmailEvent(runtimeOptions?.observe, "render:success", {
713
+ route: runtimeOptions?.route,
714
+ durationMs: Date.now() - start,
715
+ message: "Rendered react email without plain-text derivation"
716
+ });
717
+ return { html };
718
+ }
719
+ const plainTextValue = await renderModule.toPlainText(html);
720
+ const plainText = toStringOrUndefined(plainTextValue);
721
+ emitReactEmailEvent(runtimeOptions?.observe, "render:success", {
722
+ route: runtimeOptions?.route,
723
+ durationMs: Date.now() - start,
724
+ message: plainText ? "Rendered react email with derived plain text" : "Rendered react email HTML only"
725
+ });
726
+ if (plainText === void 0) {
727
+ return { html };
728
+ }
729
+ return {
730
+ html,
731
+ text: plainText
732
+ };
733
+ } catch (error) {
734
+ const message = error instanceof Error ? error.message : String(error);
735
+ emitReactEmailEvent(runtimeOptions?.observe, "render:error", {
736
+ route: runtimeOptions?.route,
737
+ durationMs: Date.now() - start,
738
+ error: message,
739
+ message: "Failed to render react email payload"
740
+ });
741
+ throw error;
742
+ }
743
+ }
744
+ async function resolveReactEmailPayloadFields(input, fields, options) {
745
+ const { react, ...payloadWithoutReact } = input;
746
+ if (!react) {
747
+ return payloadWithoutReact;
748
+ }
749
+ const rendered = await renderAthenaReactEmail(react, options);
750
+ const payload = {
751
+ ...payloadWithoutReact
752
+ };
753
+ payload[fields.htmlField] = rendered.html;
754
+ const currentTextValue = payload[fields.textField];
755
+ if (rendered.text !== void 0 && (currentTextValue === void 0 || currentTextValue === null || currentTextValue === "")) {
756
+ payload[fields.textField] = rendered.text;
757
+ }
758
+ if (fields.variablesField && (payload[fields.variablesField] === void 0 || payload[fields.variablesField] === null) && isRecord2(react.props)) {
759
+ const derivedVariables = Object.keys(react.props);
760
+ if (derivedVariables.length > 0) {
761
+ payload[fields.variablesField] = derivedVariables;
762
+ }
763
+ }
764
+ return payload;
765
+ }
766
+
767
+ // src/auth/client.ts
768
+ var DEFAULT_AUTH_BASE_URL = "http://localhost:3001/api/auth";
769
+ var FALLBACK_SDK_VERSION2 = "1.0.0";
770
+ var SDK_NAME2 = "xylex-group/athena-auth";
771
+ var SDK_VERSION2 = typeof process !== "undefined" && process?.env?.npm_package_version ? process.env.npm_package_version : FALLBACK_SDK_VERSION2;
772
+ var SDK_HEADER_VALUE2 = `${SDK_NAME2} ${SDK_VERSION2}`;
773
+ function normalizeBaseUrl(baseUrl) {
774
+ return (baseUrl ?? DEFAULT_AUTH_BASE_URL).replace(/\/$/, "");
775
+ }
776
+ function isRecord3(value) {
777
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
778
+ }
779
+ function normalizeHeaderValue2(value) {
780
+ return value ? value : void 0;
781
+ }
782
+ function parseResponseBody2(rawText, contentType) {
783
+ if (!rawText) {
784
+ return { parsed: null, parseFailed: false };
785
+ }
786
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
787
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
788
+ if (!looksJson) {
789
+ return { parsed: rawText, parseFailed: false };
790
+ }
791
+ try {
792
+ return { parsed: JSON.parse(rawText), parseFailed: false };
793
+ } catch {
794
+ return { parsed: rawText, parseFailed: true };
795
+ }
796
+ }
797
+ function resolveRequestId2(headers) {
798
+ return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
799
+ }
800
+ function resolveErrorMessage2(payload, fallback) {
801
+ if (isRecord3(payload)) {
802
+ const messageCandidates = [payload.error, payload.message, payload.details];
803
+ for (const candidate of messageCandidates) {
804
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
805
+ return candidate.trim();
806
+ }
807
+ }
808
+ }
809
+ if (typeof payload === "string" && payload.trim().length > 0) {
810
+ return payload.trim();
811
+ }
812
+ return fallback;
813
+ }
814
+ function toErrorDetails(input) {
815
+ return {
816
+ code: input.code,
817
+ message: input.message,
818
+ status: input.status,
819
+ endpoint: input.endpoint,
820
+ method: input.method,
821
+ requestId: input.requestId,
822
+ hint: input.hint,
823
+ cause: input.cause
824
+ };
825
+ }
826
+ function mergeCallOptions(base, override) {
827
+ if (!base && !override) return void 0;
828
+ return {
829
+ ...base,
830
+ ...override,
831
+ headers: {
832
+ ...base?.headers ?? {},
833
+ ...override?.headers ?? {}
834
+ }
835
+ };
836
+ }
837
+ function extractFetchOptions(input) {
838
+ if (!input) {
839
+ return {
840
+ payload: void 0,
841
+ fetchOptions: void 0
842
+ };
843
+ }
844
+ const { fetchOptions, ...rest } = input;
845
+ const hasPayloadKeys = Object.keys(rest).length > 0;
846
+ return {
847
+ payload: hasPayloadKeys ? rest : void 0,
848
+ fetchOptions
849
+ };
850
+ }
851
+ function buildHeaders2(config, options) {
852
+ const headers = {
853
+ "Content-Type": "application/json",
854
+ "X-Athena-Sdk": SDK_HEADER_VALUE2
855
+ };
856
+ const apiKey = options?.apiKey ?? config.apiKey;
857
+ if (apiKey) {
858
+ headers.apikey = apiKey;
859
+ headers["x-api-key"] = apiKey;
860
+ }
861
+ const bearerToken = options?.bearerToken ?? config.bearerToken;
862
+ if (bearerToken) {
863
+ headers.Authorization = `Bearer ${bearerToken}`;
864
+ }
865
+ const mergedExtraHeaders = {
866
+ ...config.headers ?? {},
867
+ ...options?.headers ?? {}
868
+ };
869
+ Object.entries(mergedExtraHeaders).forEach(([key, value]) => {
870
+ const normalized = normalizeHeaderValue2(value);
871
+ if (normalized) {
872
+ headers[key] = normalized;
873
+ }
874
+ });
875
+ return headers;
876
+ }
877
+ function appendQueryParam(searchParams, key, value) {
878
+ if (value === void 0 || value === null) return;
879
+ if (Array.isArray(value)) {
880
+ value.forEach((item) => {
881
+ searchParams.append(key, String(item));
882
+ });
883
+ return;
884
+ }
885
+ searchParams.append(key, String(value));
886
+ }
887
+ function buildRequestUrl(baseUrl, endpoint, query) {
888
+ const url = `${baseUrl}${endpoint}`;
889
+ if (!query || Object.keys(query).length === 0) return url;
890
+ const searchParams = new URLSearchParams();
891
+ Object.entries(query).forEach(([key, value]) => appendQueryParam(searchParams, key, value));
892
+ const queryText = searchParams.toString();
893
+ return queryText ? `${url}?${queryText}` : url;
894
+ }
895
+ function inferDefaultMethod(endpoint) {
896
+ if (endpoint.startsWith("/reset-password/")) {
897
+ return "GET";
898
+ }
899
+ switch (endpoint) {
900
+ case "/get-session":
901
+ case "/list-sessions":
902
+ case "/verify-email":
903
+ case "/change-email/verify":
904
+ case "/delete-user/verify":
905
+ case "/email-list":
906
+ case "/email/list":
907
+ case "/delete-user/callback":
908
+ case "/list-accounts":
909
+ case "/passkey/generate-register-options":
910
+ case "/passkey/list-user-passkeys":
911
+ case "/.well-known/webauthn":
912
+ case "/admin/list-users":
913
+ case "/admin/athena-client/list":
914
+ case "/admin/audit-log/list":
915
+ case "/admin/email/get":
916
+ case "/admin/email-failure/list":
917
+ case "/admin/email-failure/get":
918
+ case "/admin/email-template/get":
919
+ case "/admin/email-template/list":
920
+ case "/admin/email/list":
921
+ case "/api-key/get":
922
+ case "/api-key/list":
923
+ case "/organization/get-full-organization":
924
+ case "/organization/list":
925
+ case "/organization/get-invitation":
926
+ case "/organization/list-invitations":
927
+ case "/organization/list-user-invitations":
928
+ case "/organization/list-members":
929
+ case "/organization/get-active-member":
930
+ case "/health":
931
+ case "/ok":
932
+ case "/error":
933
+ return "GET";
934
+ default:
935
+ return "POST";
936
+ }
937
+ }
938
+ async function callAuthEndpoint(config, context, body, query, options) {
939
+ const baseUrl = normalizeBaseUrl(options?.baseUrl ?? config.baseUrl);
940
+ const url = buildRequestUrl(baseUrl, context.endpoint, query);
941
+ const headers = buildHeaders2(config, options);
942
+ const credentials = options?.credentials ?? config.credentials ?? "include";
943
+ const requestInit = {
944
+ method: context.method,
945
+ headers,
946
+ credentials,
947
+ signal: options?.signal
948
+ };
949
+ if (context.method !== "GET") {
950
+ requestInit.body = JSON.stringify(body ?? {});
951
+ }
952
+ const fetcher = config.fetch ?? globalThis.fetch;
953
+ if (!fetcher) {
954
+ const details = toErrorDetails({
955
+ code: "UNKNOWN_ERROR",
956
+ message: "No fetch implementation available for auth client",
957
+ status: 0,
958
+ endpoint: context.endpoint,
959
+ method: context.method,
960
+ hint: "Use Node 18+ or provide `fetch` via createClient(..., { auth: { fetch } }) or createAuthClient({ fetch })"
961
+ });
962
+ return {
963
+ ok: false,
964
+ status: 0,
965
+ data: null,
966
+ error: details.message,
967
+ errorDetails: details,
968
+ raw: null
969
+ };
970
+ }
971
+ try {
972
+ const response = await fetcher(url, requestInit);
973
+ const rawText = await response.text();
974
+ const requestId = resolveRequestId2(response.headers);
975
+ const parsedBody = parseResponseBody2(rawText ?? "", response.headers.get("content-type"));
976
+ if (parsedBody.parseFailed) {
977
+ const details = toErrorDetails({
978
+ code: "INVALID_JSON",
979
+ message: "Auth server returned malformed JSON",
980
+ status: response.status,
981
+ endpoint: context.endpoint,
982
+ method: context.method,
983
+ requestId,
984
+ hint: "Verify the auth endpoint response body is valid JSON.",
985
+ cause: rawText.slice(0, 300)
986
+ });
987
+ return {
988
+ ok: false,
989
+ status: response.status,
990
+ data: null,
991
+ error: details.message,
992
+ errorDetails: details,
993
+ raw: parsedBody.parsed
994
+ };
995
+ }
996
+ const parsed = parsedBody.parsed;
997
+ if (!response.ok) {
998
+ const details = toErrorDetails({
999
+ code: "HTTP_ERROR",
1000
+ message: resolveErrorMessage2(
1001
+ parsed,
1002
+ `Auth endpoint ${context.method} ${context.endpoint} failed with status ${response.status}`
1003
+ ),
1004
+ status: response.status,
1005
+ endpoint: context.endpoint,
1006
+ method: context.method,
1007
+ requestId
1008
+ });
1009
+ return {
1010
+ ok: false,
1011
+ status: response.status,
1012
+ data: null,
1013
+ error: details.message,
1014
+ errorDetails: details,
1015
+ raw: parsed
1016
+ };
1017
+ }
1018
+ return {
1019
+ ok: true,
1020
+ status: response.status,
1021
+ data: parsed ?? null,
1022
+ error: null,
1023
+ errorDetails: null,
1024
+ raw: parsed
1025
+ };
1026
+ } catch (callError) {
1027
+ const message = callError instanceof Error ? callError.message : String(callError);
1028
+ const details = toErrorDetails({
1029
+ code: "NETWORK_ERROR",
1030
+ message: `Network error while calling ${context.method} ${context.endpoint}: ${message}`,
1031
+ status: 0,
1032
+ endpoint: context.endpoint,
1033
+ method: context.method,
1034
+ cause: message,
1035
+ hint: "Check auth server URL, DNS, and network reachability."
1036
+ });
1037
+ return {
1038
+ ok: false,
1039
+ status: 0,
1040
+ data: null,
1041
+ error: details.message,
1042
+ errorDetails: details,
1043
+ raw: null
1044
+ };
1045
+ }
1046
+ }
1047
+ function executePostWithCompatibleInput(config, context, input, options) {
1048
+ const { payload, fetchOptions } = extractFetchOptions(input);
1049
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
1050
+ return callAuthEndpoint(config, context, payload ?? {}, void 0, mergedOptions);
1051
+ }
1052
+ function executePostWithOptionalInput(config, context, input, options) {
1053
+ const { fetchOptions } = extractFetchOptions(input);
1054
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
1055
+ return callAuthEndpoint(config, context, {}, void 0, mergedOptions);
1056
+ }
1057
+ function executeGetWithCompatibleInput(config, context, input, options) {
1058
+ const { fetchOptions } = extractFetchOptions(input);
1059
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
1060
+ return callAuthEndpoint(config, context, void 0, void 0, mergedOptions);
1061
+ }
1062
+ function executeGetWithQueryCompatibleInput(config, context, input, options) {
1063
+ const { payload, fetchOptions } = extractFetchOptions(input);
1064
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
1065
+ const query = payload?.query;
1066
+ return callAuthEndpoint(
1067
+ config,
1068
+ context,
1069
+ void 0,
1070
+ query,
1071
+ mergedOptions
1072
+ );
1073
+ }
1074
+ function createAuthClient(config = {}) {
1075
+ const normalizedBaseUrl = normalizeBaseUrl(config.baseUrl);
1076
+ const resolvedConfig = {
1077
+ ...config,
1078
+ baseUrl: normalizedBaseUrl
1079
+ };
1080
+ const request = (input, options) => {
1081
+ const method = input.method ?? (input.body !== void 0 ? "POST" : inferDefaultMethod(input.endpoint));
1082
+ const mergedOptions = mergeCallOptions(input.fetchOptions, options);
1083
+ return callAuthEndpoint(
1084
+ resolvedConfig,
1085
+ { endpoint: input.endpoint, method },
1086
+ input.body,
1087
+ input.query,
1088
+ mergedOptions
1089
+ );
1090
+ };
1091
+ const postGeneric = (endpoint, input, options) => {
1092
+ const { payload, fetchOptions } = extractFetchOptions(input);
1093
+ return request(
1094
+ {
1095
+ endpoint,
1096
+ method: "POST",
1097
+ body: payload ?? {},
1098
+ fetchOptions
1099
+ },
1100
+ options
1101
+ );
1102
+ };
1103
+ const getGeneric = (endpoint, input, options) => {
1104
+ const { fetchOptions } = extractFetchOptions(input);
1105
+ return request(
1106
+ {
1107
+ endpoint,
1108
+ method: "GET",
1109
+ fetchOptions
1110
+ },
1111
+ options
1112
+ );
1113
+ };
1114
+ const getWithQuery = (endpoint, input, options) => {
1115
+ const { payload, fetchOptions } = extractFetchOptions(input);
1116
+ const query = payload?.query;
1117
+ return request(
1118
+ {
1119
+ endpoint,
1120
+ method: "GET",
1121
+ query,
1122
+ fetchOptions
1123
+ },
1124
+ options
1125
+ );
1126
+ };
1127
+ const withReactEmailRoute = (route) => ({
1128
+ ...resolvedConfig.reactEmail,
1129
+ route
1130
+ });
1131
+ const resolveAdminEmailPayload = (route, input) => resolveReactEmailPayloadFields(input, {
1132
+ htmlField: "htmlBody",
1133
+ textField: "textBody"
1134
+ }, withReactEmailRoute(route));
1135
+ const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(input, {
1136
+ htmlField: "htmlTemplate",
1137
+ textField: "textTemplate",
1138
+ variablesField: "variables"
1139
+ }, withReactEmailRoute(route));
1140
+ const listUserEmailsWithFallback = async (input, options) => {
1141
+ const primary = await getWithQuery(
1142
+ "/email/list",
1143
+ input,
1144
+ options
1145
+ );
1146
+ if (primary.ok || primary.status !== 404 || primary.errorDetails?.code !== "HTTP_ERROR") {
1147
+ return primary;
1148
+ }
1149
+ return getWithQuery(
1150
+ "/email-list",
1151
+ input,
1152
+ options
1153
+ );
1154
+ };
1155
+ const healthWithFallback = async (input, options) => {
1156
+ const primary = await getGeneric("/health", input, options);
1157
+ if (primary.ok || primary.status !== 404 || primary.errorDetails?.code !== "HTTP_ERROR") {
1158
+ return primary;
1159
+ }
1160
+ const fallback = await getGeneric("/ok", input, options);
1161
+ if (!fallback.ok) {
1162
+ return {
1163
+ ...fallback,
1164
+ data: null
1165
+ };
1166
+ }
1167
+ const fallbackStatus = isRecord3(fallback.data) && typeof fallback.data.ok === "boolean" ? fallback.data.ok ? "ok" : "error" : "ok";
1168
+ return {
1169
+ ...fallback,
1170
+ data: {
1171
+ status: fallbackStatus
1172
+ }
1173
+ };
1174
+ };
1175
+ const signOut = (input, options) => executePostWithOptionalInput(
1176
+ resolvedConfig,
1177
+ { endpoint: "/sign-out", method: "POST" },
1178
+ input,
1179
+ options
1180
+ );
1181
+ const revokeSessions = (input, options) => executePostWithOptionalInput(
1182
+ resolvedConfig,
1183
+ { endpoint: "/revoke-sessions", method: "POST" },
1184
+ input,
1185
+ options
1186
+ );
1187
+ const revokeOtherSessions = (input, options) => executePostWithOptionalInput(
1188
+ resolvedConfig,
1189
+ { endpoint: "/revoke-other-sessions", method: "POST" },
1190
+ input,
1191
+ options
1192
+ );
1193
+ const revokeSession = (input, options) => executePostWithCompatibleInput(
1194
+ resolvedConfig,
1195
+ { endpoint: "/revoke-session", method: "POST" },
1196
+ input,
1197
+ options
1198
+ );
1199
+ const deleteUser = (input, options) => {
1200
+ const { payload, fetchOptions } = extractFetchOptions(input);
1201
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
1202
+ return callAuthEndpoint(
1203
+ resolvedConfig,
1204
+ { endpoint: "/delete-user", method: "POST" },
1205
+ payload ?? {},
1206
+ void 0,
1207
+ mergedOptions
1208
+ );
1209
+ };
1210
+ const deleteUserCallback = (input, options) => {
1211
+ const { payload, fetchOptions } = extractFetchOptions(input);
1212
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
1213
+ const query = payload ?? {};
1214
+ return callAuthEndpoint(
1215
+ resolvedConfig,
1216
+ { endpoint: "/delete-user/callback", method: "GET" },
1217
+ void 0,
1218
+ {
1219
+ token: query.token,
1220
+ callbackURL: query.callbackURL
1221
+ },
1222
+ mergedOptions
1223
+ );
1224
+ };
1225
+ const resolveResetPasswordToken = (input, options) => {
1226
+ const { payload, fetchOptions } = extractFetchOptions(input);
1227
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
1228
+ const query = payload;
1229
+ const token = query?.token?.trim();
1230
+ if (!token) {
1231
+ throw new Error("resolveResetPasswordToken requires a non-empty token");
1232
+ }
1233
+ const endpoint = `/reset-password/${encodeURIComponent(token)}`;
1234
+ return callAuthEndpoint(
1235
+ resolvedConfig,
1236
+ { endpoint, method: "GET" },
1237
+ void 0,
1238
+ query?.callbackURL ? { callbackURL: query.callbackURL } : void 0,
1239
+ mergedOptions
1240
+ );
1241
+ };
1242
+ const organization = {
1243
+ create: (input, options) => executePostWithCompatibleInput(
1244
+ resolvedConfig,
1245
+ { endpoint: "/organization/create", method: "POST" },
1246
+ input,
1247
+ options
1248
+ ),
1249
+ update: (input, options) => executePostWithCompatibleInput(
1250
+ resolvedConfig,
1251
+ { endpoint: "/organization/update", method: "POST" },
1252
+ input,
1253
+ options
1254
+ ),
1255
+ delete: (input, options) => executePostWithCompatibleInput(
1256
+ resolvedConfig,
1257
+ { endpoint: "/organization/delete", method: "POST" },
1258
+ input,
1259
+ options
1260
+ ),
1261
+ setActive: (input, options) => executePostWithCompatibleInput(
1262
+ resolvedConfig,
1263
+ { endpoint: "/organization/set-active", method: "POST" },
1264
+ input,
1265
+ options
1266
+ ),
1267
+ list: (input, options) => getGeneric(
1268
+ "/organization/list",
1269
+ input,
1270
+ options
1271
+ ),
1272
+ getFull: (input, options) => executeGetWithQueryCompatibleInput(
1273
+ resolvedConfig,
1274
+ { endpoint: "/organization/get-full-organization", method: "GET" },
1275
+ input,
1276
+ options
1277
+ ),
1278
+ checkSlug: (input, options) => executePostWithCompatibleInput(
1279
+ resolvedConfig,
1280
+ { endpoint: "/organization/check-slug", method: "POST" },
1281
+ input,
1282
+ options
1283
+ ),
1284
+ leave: (input, options) => executePostWithCompatibleInput(
1285
+ resolvedConfig,
1286
+ { endpoint: "/organization/leave", method: "POST" },
1287
+ input,
1288
+ options
1289
+ ),
1290
+ listUserInvitations: (input, options) => executeGetWithQueryCompatibleInput(
1291
+ resolvedConfig,
1292
+ { endpoint: "/organization/list-user-invitations", method: "GET" },
1293
+ input,
1294
+ options
1295
+ ),
1296
+ hasPermission: (input, options) => postGeneric(
1297
+ "/organization/has-permission",
1298
+ input,
1299
+ options
1300
+ ),
1301
+ invitation: {
1302
+ cancel: (input, options) => executePostWithCompatibleInput(
1303
+ resolvedConfig,
1304
+ { endpoint: "/organization/cancel-invitation", method: "POST" },
1305
+ input,
1306
+ options
1307
+ ),
1308
+ accept: (input, options) => executePostWithCompatibleInput(
1309
+ resolvedConfig,
1310
+ { endpoint: "/organization/accept-invitation", method: "POST" },
1311
+ input,
1312
+ options
1313
+ ),
1314
+ get: (input, options) => executeGetWithQueryCompatibleInput(
1315
+ resolvedConfig,
1316
+ { endpoint: "/organization/get-invitation", method: "GET" },
1317
+ input,
1318
+ options
1319
+ ),
1320
+ reject: (input, options) => executePostWithCompatibleInput(
1321
+ resolvedConfig,
1322
+ { endpoint: "/organization/reject-invitation", method: "POST" },
1323
+ input,
1324
+ options
1325
+ ),
1326
+ list: (input, options) => executeGetWithQueryCompatibleInput(
1327
+ resolvedConfig,
1328
+ { endpoint: "/organization/list-invitations", method: "GET" },
1329
+ input,
1330
+ options
1331
+ )
1332
+ },
1333
+ member: {
1334
+ remove: (input, options) => executePostWithCompatibleInput(
1335
+ resolvedConfig,
1336
+ { endpoint: "/organization/remove-member", method: "POST" },
1337
+ input,
1338
+ options
1339
+ ),
1340
+ updateRole: (input, options) => executePostWithCompatibleInput(
1341
+ resolvedConfig,
1342
+ { endpoint: "/organization/update-member-role", method: "POST" },
1343
+ input,
1344
+ options
1345
+ ),
1346
+ invite: (input, options) => executePostWithCompatibleInput(
1347
+ resolvedConfig,
1348
+ { endpoint: "/organization/invite-member", method: "POST" },
1349
+ input,
1350
+ options
1351
+ ),
1352
+ getActive: (input, options) => executeGetWithCompatibleInput(
1353
+ resolvedConfig,
1354
+ { endpoint: "/organization/get-active-member", method: "GET" },
1355
+ input,
1356
+ options
1357
+ ),
1358
+ list: (input, options) => executeGetWithQueryCompatibleInput(
1359
+ resolvedConfig,
1360
+ { endpoint: "/organization/list-members", method: "GET" },
1361
+ input,
1362
+ options
1363
+ )
1364
+ }
1365
+ };
1366
+ const authResetPassword = Object.assign(
1367
+ (input, options) => executePostWithCompatibleInput(
1368
+ resolvedConfig,
1369
+ { endpoint: "/reset-password", method: "POST" },
1370
+ input,
1371
+ options
1372
+ ),
1373
+ {
1374
+ token: resolveResetPasswordToken
1375
+ }
1376
+ );
1377
+ const sessionRevokeBinding = (input, options) => {
1378
+ if (Array.isArray(input)) {
1379
+ if (input.length === 0) {
1380
+ throw new Error("session.revoke requires at least one session token");
1381
+ }
1382
+ if (input.length === 1) {
1383
+ return revokeSession(input[0], options);
1384
+ }
1385
+ return revokeSessions(void 0, options);
1386
+ }
1387
+ const parsed = input;
1388
+ const tokens = Array.isArray(parsed.tokens) ? parsed.tokens.filter((token2) => token2.trim().length > 0) : void 0;
1389
+ if (tokens && tokens.length > 1) {
1390
+ return revokeSessions(
1391
+ parsed.fetchOptions ? { fetchOptions: parsed.fetchOptions } : void 0,
1392
+ options
1393
+ );
1394
+ }
1395
+ if (tokens && tokens.length === 1) {
1396
+ return revokeSession(
1397
+ { token: tokens[0], fetchOptions: parsed.fetchOptions },
1398
+ options
1399
+ );
1400
+ }
1401
+ const token = parsed.token?.trim();
1402
+ if (!token) {
1403
+ throw new Error("session.revoke requires a non-empty token or a non-empty token list");
1404
+ }
1405
+ return revokeSession(
1406
+ {
1407
+ token,
1408
+ fetchOptions: parsed.fetchOptions
1409
+ },
1410
+ options
1411
+ );
1412
+ };
1413
+ const adminUserSessionRevokeBinding = (input, options) => {
1414
+ const requireUserId = (userId) => {
1415
+ const trimmed = String(userId ?? "").trim();
1416
+ if (!trimmed) {
1417
+ throw new Error("admin.user.session.revoke requires a non-empty userId");
1418
+ }
1419
+ return trimmed;
1420
+ };
1421
+ const requireSinglePluralUserId = (sessions2) => {
1422
+ const uniqueUserIds = [...new Set(sessions2.map((session) => requireUserId(session.userId)))];
1423
+ if (uniqueUserIds.length !== 1) {
1424
+ throw new Error("admin.user.session.revoke requires the same userId across plural payloads");
1425
+ }
1426
+ return { userId: uniqueUserIds[0] };
1427
+ };
1428
+ if (Array.isArray(input)) {
1429
+ if (input.length === 0) {
1430
+ throw new Error("admin.user.session.revoke requires at least one payload item");
1431
+ }
1432
+ if (input.length === 1) {
1433
+ return postGeneric(
1434
+ "/admin/revoke-user-session",
1435
+ {
1436
+ ...input[0],
1437
+ userId: requireUserId(input[0].userId)
1438
+ },
1439
+ options
1440
+ );
1441
+ }
1442
+ return postGeneric(
1443
+ "/admin/revoke-user-sessions",
1444
+ requireSinglePluralUserId(input),
1445
+ options
1446
+ );
1447
+ }
1448
+ const parsed = input;
1449
+ const sessions = parsed.sessions;
1450
+ if (sessions && sessions.length === 0) {
1451
+ throw new Error("admin.user.session.revoke requires at least one payload item");
1452
+ }
1453
+ if (sessions && sessions.length === 1) {
1454
+ return postGeneric(
1455
+ "/admin/revoke-user-session",
1456
+ {
1457
+ ...sessions[0],
1458
+ userId: requireUserId(sessions[0].userId),
1459
+ fetchOptions: parsed.fetchOptions
1460
+ },
1461
+ options
1462
+ );
1463
+ }
1464
+ if (sessions && sessions.length > 1) {
1465
+ return postGeneric(
1466
+ "/admin/revoke-user-sessions",
1467
+ {
1468
+ ...requireSinglePluralUserId(sessions),
1469
+ fetchOptions: parsed.fetchOptions
1470
+ },
1471
+ options
1472
+ );
1473
+ }
1474
+ const normalizedUserId = requireUserId(parsed.userId);
1475
+ if (!parsed.sessionToken) {
1476
+ return postGeneric(
1477
+ "/admin/revoke-user-sessions",
1478
+ {
1479
+ userId: normalizedUserId,
1480
+ fetchOptions: parsed.fetchOptions
1481
+ },
1482
+ options
1483
+ );
1484
+ }
1485
+ return postGeneric(
1486
+ "/admin/revoke-user-session",
1487
+ {
1488
+ ...parsed,
1489
+ userId: normalizedUserId
1490
+ },
1491
+ options
1492
+ );
1493
+ };
1494
+ const auth = {
1495
+ getSession: (input, options) => getGeneric("/get-session", input, options),
1496
+ signOut,
1497
+ forgetPassword: (input, options) => postGeneric("/forget-password", input, options),
1498
+ resetPassword: authResetPassword,
1499
+ setPassword: (input, options) => postGeneric("/set-password", input, options),
1500
+ verifyEmail: (input, options) => {
1501
+ const queryInput = {
1502
+ query: {
1503
+ token: input.token,
1504
+ callbackURL: input.callbackURL
1505
+ },
1506
+ fetchOptions: input.fetchOptions
1507
+ };
1508
+ return getWithQuery(
1509
+ "/verify-email",
1510
+ queryInput,
1511
+ options
1512
+ );
1513
+ },
1514
+ sendVerificationEmail: (input, options) => postGeneric("/send-verification-email", input, options),
1515
+ changeEmail: (input, options) => postGeneric("/change-email", input, options),
1516
+ changeEmailVerify: (input, options) => getWithQuery("/change-email/verify", input, options),
1517
+ deleteUserVerify: (input, options) => getWithQuery("/delete-user/verify", input, options),
1518
+ changePassword: (input, options) => postGeneric("/change-password", input, options),
1519
+ user: {
1520
+ update: (input, options) => postGeneric("/update-user", input, options),
1521
+ delete: (input, options) => postGeneric("/delete-user", input, options),
1522
+ email: {
1523
+ list: listUserEmailsWithFallback
1524
+ }
1525
+ },
1526
+ session: {
1527
+ list: (input, options) => getGeneric("/list-sessions", input, options),
1528
+ revoke: sessionRevokeBinding,
1529
+ revokeOther: revokeOtherSessions
1530
+ },
1531
+ social: {
1532
+ link: (input, options) => postGeneric("/link-social", input, options)
1533
+ },
1534
+ account: {
1535
+ list: (input, options) => getGeneric("/list-accounts", input, options),
1536
+ unlink: (input, options) => postGeneric("/unlink-account", input, options)
1537
+ },
1538
+ deleteUser: {
1539
+ callback: deleteUserCallback
1540
+ },
1541
+ refreshToken: (input, options) => postGeneric("/refresh-token", input, options),
1542
+ getAccessToken: (input, options) => postGeneric("/get-access-token", input, options),
1543
+ health: healthWithFallback,
1544
+ ok: (input, options) => getGeneric("/ok", input, options),
1545
+ error: (input, options) => getGeneric("/error", input, options),
1546
+ twoFactor: {
1547
+ getTotpUri: (input, options) => postGeneric("/two-factor/get-totp-uri", input, options),
1548
+ verifyTotp: (input, options) => postGeneric("/two-factor/verify-totp", input, options),
1549
+ sendOtp: (input, options) => postGeneric("/two-factor/send-otp", input, options),
1550
+ verifyOtp: (input, options) => postGeneric("/two-factor/verify-otp", input, options),
1551
+ verifyBackupCode: (input, options) => postGeneric("/two-factor/verify-backup-code", input, options),
1552
+ generateBackupCodes: (input, options) => executePostWithCompatibleInput(
1553
+ resolvedConfig,
1554
+ { endpoint: "/two-factor/generate-backup-codes", method: "POST" },
1555
+ input,
1556
+ options
1557
+ ),
1558
+ enable: (input, options) => postGeneric("/two-factor/enable", input, options),
1559
+ disable: (input, options) => postGeneric("/two-factor/disable", input, options)
1560
+ },
1561
+ passkey: {
1562
+ generateRegisterOptions: (input, options) => getGeneric("/passkey/generate-register-options", input, options),
1563
+ generateAuthenticateOptions: (input, options) => postGeneric("/passkey/generate-authenticate-options", input, options),
1564
+ verifyRegistration: (input, options) => postGeneric("/passkey/verify-registration", input, options),
1565
+ verifyAuthentication: (input, options) => postGeneric("/passkey/verify-authentication", input, options),
1566
+ listUserPasskeys: (input, options) => getGeneric("/passkey/list-user-passkeys", input, options),
1567
+ deletePasskey: (input, options) => postGeneric("/passkey/delete-passkey", input, options),
1568
+ updatePasskey: (input, options) => postGeneric("/passkey/update-passkey", input, options),
1569
+ getRelatedOrigins: (input, options) => getGeneric("/.well-known/webauthn", input, options)
1570
+ },
1571
+ admin: {
1572
+ role: {
1573
+ set: (input, options) => postGeneric("/admin/set-role", input, options)
1574
+ },
1575
+ user: {
1576
+ list: (input, options) => getWithQuery("/admin/list-users", input, options),
1577
+ create: (input, options) => postGeneric("/admin/create-user", input, options),
1578
+ unban: (input, options) => postGeneric("/admin/unban-user", input, options),
1579
+ ban: (input, options) => postGeneric("/admin/ban-user", input, options),
1580
+ impersonate: (input, options) => postGeneric("/admin/impersonate-user", input, options),
1581
+ stopImpersonating: (input, options) => postGeneric("/admin/stop-impersonating", input, options),
1582
+ remove: (input, options) => postGeneric("/admin/remove-user", input, options),
1583
+ setPassword: (input, options) => postGeneric("/admin/set-user-password", input, options),
1584
+ session: {
1585
+ list: (input, options) => postGeneric("/admin/list-user-sessions", input, options),
1586
+ revoke: adminUserSessionRevokeBinding
1587
+ }
1588
+ },
1589
+ hasPermission: (input, options) => postGeneric("/admin/has-permission", input, options),
1590
+ apiKey: {
1591
+ create: (input, options) => postGeneric("/admin/api-key/create", input, options)
1592
+ },
1593
+ athenaClient: {
1594
+ create: (input, options) => postGeneric("/admin/athena-client/create", input, options),
1595
+ list: (input, options) => getWithQuery("/admin/athena-client/list", input, options)
1596
+ },
1597
+ auditLog: {
1598
+ list: (input, options) => getWithQuery("/admin/audit-log/list", input, options)
1599
+ },
1600
+ email: {
1601
+ list: (input, options) => getWithQuery("/admin/email/list", input, options),
1602
+ get: (input, options) => getWithQuery("/admin/email/get", input, options),
1603
+ create: async (input, options) => postGeneric(
1604
+ "/admin/email/create",
1605
+ await resolveAdminEmailPayload("/admin/email/create", input),
1606
+ options
1607
+ ),
1608
+ update: async (input, options) => postGeneric(
1609
+ "/admin/email/update",
1610
+ await resolveAdminEmailPayload("/admin/email/update", input),
1611
+ options
1612
+ ),
1613
+ delete: (input, options) => postGeneric("/admin/email/delete", input, options),
1614
+ failure: {
1615
+ list: (input, options) => getWithQuery("/admin/email-failure/list", input, options),
1616
+ get: (input, options) => getWithQuery("/admin/email-failure/get", input, options),
1617
+ create: (input, options) => postGeneric("/admin/email-failure/create", input, options),
1618
+ update: (input, options) => postGeneric("/admin/email-failure/update", input, options),
1619
+ delete: (input, options) => postGeneric("/admin/email-failure/delete", input, options)
1620
+ },
1621
+ template: {
1622
+ list: (input, options) => getWithQuery("/admin/email-template/list", input, options),
1623
+ get: (input, options) => getWithQuery("/admin/email-template/get", input, options),
1624
+ create: async (input, options) => postGeneric(
1625
+ "/admin/email-template/create",
1626
+ await resolveAdminEmailTemplatePayload("/admin/email-template/create", input),
1627
+ options
1628
+ ),
1629
+ update: async (input, options) => postGeneric(
1630
+ "/admin/email-template/update",
1631
+ await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
1632
+ options
1633
+ ),
1634
+ delete: (input, options) => postGeneric("/admin/email-template/delete", input, options)
1635
+ }
1636
+ },
1637
+ emailTemplate: {
1638
+ get: (input, options) => getWithQuery("/admin/email-template/get", input, options),
1639
+ create: async (input, options) => postGeneric(
1640
+ "/admin/email-template/create",
1641
+ await resolveAdminEmailTemplatePayload("/admin/email-template/create", input),
1642
+ options
1643
+ ),
1644
+ delete: (input, options) => postGeneric("/admin/email-template/delete", input, options),
1645
+ list: (input, options) => getWithQuery("/admin/email-template/list", input, options),
1646
+ update: async (input, options) => postGeneric(
1647
+ "/admin/email-template/update",
1648
+ await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
1649
+ options
1650
+ )
1651
+ }
1652
+ },
1653
+ apiKey: {
1654
+ create: (input, options) => postGeneric("/api-key/create", input, options),
1655
+ get: (input, options) => getWithQuery("/api-key/get", input, options),
1656
+ update: (input, options) => postGeneric("/api-key/update", input, options),
1657
+ delete: (input, options) => postGeneric("/api-key/delete", input, options),
1658
+ list: (input, options) => getWithQuery("/api-key/list", input, options),
1659
+ verify: (input, options) => postGeneric("/api-key/verify", input, options),
1660
+ deleteAllExpired: (input, options) => executePostWithOptionalInput(
1661
+ resolvedConfig,
1662
+ { endpoint: "/api-key/delete-all-expired-api-keys", method: "POST" },
1663
+ input,
1664
+ options
1665
+ )
1666
+ },
1667
+ signIn: {
1668
+ email: (input, options) => postGeneric("/sign-in/email", input, options),
1669
+ username: (input, options) => postGeneric("/sign-in/username", input, options),
1670
+ social: (input, options) => postGeneric("/sign-in/social", input, options)
1671
+ },
1672
+ signUp: {
1673
+ email: (input, options) => postGeneric("/sign-up/email", input, options)
1674
+ },
1675
+ organization,
1676
+ callback: {
1677
+ provider: (input, options) => {
1678
+ const { payload, fetchOptions } = extractFetchOptions(input);
1679
+ const parsed = payload;
1680
+ const provider = String(parsed?.provider ?? "").trim();
1681
+ if (!provider) {
1682
+ throw new Error("callback.provider requires a non-empty provider value");
1683
+ }
1684
+ const code = String(parsed?.code ?? "").trim();
1685
+ const state = String(parsed?.state ?? "").trim();
1686
+ if (!code || !state) {
1687
+ throw new Error("callback.provider requires non-empty code and state values");
1688
+ }
1689
+ const endpoint = `/callback/${encodeURIComponent(provider)}`;
1690
+ return request({
1691
+ endpoint,
1692
+ method: "GET",
1693
+ query: {
1694
+ code,
1695
+ state
1696
+ },
1697
+ fetchOptions
1698
+ }, options);
1699
+ }
1700
+ }
1701
+ };
1702
+ return {
1703
+ baseUrl: normalizedBaseUrl,
1704
+ request,
1705
+ signIn: {
1706
+ email: (input, options) => executePostWithCompatibleInput(
1707
+ resolvedConfig,
1708
+ { endpoint: "/sign-in/email", method: "POST" },
1709
+ input,
1710
+ options
1711
+ ),
1712
+ username: (input, options) => executePostWithCompatibleInput(
1713
+ resolvedConfig,
1714
+ { endpoint: "/sign-in/username", method: "POST" },
1715
+ input,
1716
+ options
1717
+ ),
1718
+ social: (input, options) => executePostWithCompatibleInput(
1719
+ resolvedConfig,
1720
+ { endpoint: "/sign-in/social", method: "POST" },
1721
+ input,
1722
+ options
1723
+ )
1724
+ },
1725
+ signUp: {
1726
+ email: (input, options) => executePostWithCompatibleInput(
1727
+ resolvedConfig,
1728
+ { endpoint: "/sign-up/email", method: "POST" },
1729
+ input,
1730
+ options
1731
+ )
1732
+ },
1733
+ signOut,
1734
+ logout: signOut,
1735
+ getSession: (input, options) => executeGetWithCompatibleInput(
1736
+ resolvedConfig,
1737
+ { endpoint: "/get-session", method: "GET" },
1738
+ input,
1739
+ options
1740
+ ),
1741
+ listSessions: (input, options) => executeGetWithCompatibleInput(
1742
+ resolvedConfig,
1743
+ { endpoint: "/list-sessions", method: "GET" },
1744
+ input,
1745
+ options
1746
+ ),
1747
+ revokeSession,
1748
+ clearSession: revokeSession,
1749
+ revokeSessions,
1750
+ clearSessions: revokeSessions,
1751
+ revokeOtherSessions,
1752
+ clearOtherSessions: revokeOtherSessions,
1753
+ forgetPassword: (input, options) => executePostWithCompatibleInput(
1754
+ resolvedConfig,
1755
+ { endpoint: "/forget-password", method: "POST" },
1756
+ input,
1757
+ options
1758
+ ),
1759
+ resetPassword: (input, options) => executePostWithCompatibleInput(
1760
+ resolvedConfig,
1761
+ { endpoint: "/reset-password", method: "POST" },
1762
+ input,
1763
+ options
1764
+ ),
1765
+ resolveResetPasswordToken,
1766
+ verifyEmail: (input, options) => {
1767
+ const { payload, fetchOptions } = extractFetchOptions(input);
1768
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
1769
+ const query = payload;
1770
+ return callAuthEndpoint(
1771
+ resolvedConfig,
1772
+ { endpoint: "/verify-email", method: "GET" },
1773
+ void 0,
1774
+ query ? {
1775
+ token: query.token,
1776
+ callbackURL: query.callbackURL
1777
+ } : void 0,
1778
+ mergedOptions
1779
+ );
1780
+ },
1781
+ sendVerificationEmail: (input, options) => executePostWithCompatibleInput(
1782
+ resolvedConfig,
1783
+ { endpoint: "/send-verification-email", method: "POST" },
1784
+ input,
1785
+ options
1786
+ ),
1787
+ changeEmail: (input, options) => executePostWithCompatibleInput(
1788
+ resolvedConfig,
1789
+ { endpoint: "/change-email", method: "POST" },
1790
+ input,
1791
+ options
1792
+ ),
1793
+ changePassword: (input, options) => executePostWithCompatibleInput(
1794
+ resolvedConfig,
1795
+ { endpoint: "/change-password", method: "POST" },
1796
+ input,
1797
+ options
1798
+ ),
1799
+ updateUser: (input, options) => executePostWithCompatibleInput(
1800
+ resolvedConfig,
1801
+ { endpoint: "/update-user", method: "POST" },
1802
+ input,
1803
+ options
1804
+ ),
1805
+ deleteUser,
1806
+ deleteUserCallback,
1807
+ linkSocial: (input, options) => executePostWithCompatibleInput(
1808
+ resolvedConfig,
1809
+ { endpoint: "/link-social", method: "POST" },
1810
+ input,
1811
+ options
1812
+ ),
1813
+ listAccounts: (input, options) => executeGetWithCompatibleInput(
1814
+ resolvedConfig,
1815
+ { endpoint: "/list-accounts", method: "GET" },
1816
+ input,
1817
+ options
1818
+ ),
1819
+ unlinkAccount: (input, options) => executePostWithCompatibleInput(
1820
+ resolvedConfig,
1821
+ { endpoint: "/unlink-account", method: "POST" },
1822
+ input,
1823
+ options
1824
+ ),
1825
+ refreshToken: (input, options) => executePostWithCompatibleInput(
1826
+ resolvedConfig,
1827
+ { endpoint: "/refresh-token", method: "POST" },
1828
+ input,
1829
+ options
1830
+ ),
1831
+ getAccessToken: (input, options) => executePostWithCompatibleInput(
1832
+ resolvedConfig,
1833
+ { endpoint: "/get-access-token", method: "POST" },
1834
+ input,
1835
+ options
1836
+ ),
1837
+ organization,
1838
+ auth
1839
+ };
1840
+ }
1841
+
1842
+ // src/utils/parse-boolean-flag.ts
1843
+ function parseBooleanFlag(rawValue, fallback) {
1844
+ if (!rawValue) return fallback;
1845
+ const normalized = rawValue.trim().toLowerCase();
1846
+ if (normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on") {
1847
+ return true;
1848
+ }
1849
+ if (normalized === "0" || normalized === "false" || normalized === "no" || normalized === "off") {
1850
+ return false;
1851
+ }
1852
+ return fallback;
1853
+ }
1854
+
1855
+ // src/auxiliaries.ts
1856
+ var AthenaErrorKind = {
1857
+ UniqueViolation: "unique_violation",
1858
+ NotFound: "not_found",
1859
+ Validation: "validation",
1860
+ Auth: "auth",
1861
+ RateLimit: "rate_limit",
1862
+ Transient: "transient",
1863
+ Unknown: "unknown"
1864
+ };
1865
+ var AthenaErrorCode = {
1866
+ UniqueViolation: "UNIQUE_VIOLATION",
1867
+ NotFound: "NOT_FOUND",
1868
+ ValidationFailed: "VALIDATION_FAILED",
1869
+ AuthUnauthorized: "AUTH_UNAUTHORIZED",
1870
+ AuthForbidden: "AUTH_FORBIDDEN",
1871
+ RateLimited: "RATE_LIMITED",
1872
+ NetworkUnavailable: "NETWORK_UNAVAILABLE",
1873
+ TransientFailure: "TRANSIENT_FAILURE",
1874
+ HttpFailure: "HTTP_FAILURE",
1875
+ Unknown: "UNKNOWN"
1876
+ };
1877
+ var AthenaErrorCategory = {
1878
+ Transport: "transport",
1879
+ Client: "client",
1880
+ Server: "server",
1881
+ Database: "database",
1882
+ Unknown: "unknown"
1883
+ };
1884
+ function parseBooleanFlag2(rawValue, fallback) {
1885
+ return parseBooleanFlag(rawValue, fallback);
1886
+ }
1887
+ var AthenaError = class extends Error {
1888
+ code;
1889
+ kind;
1890
+ category;
1891
+ status;
1892
+ retryable;
1893
+ requestId;
1894
+ context;
1895
+ raw;
1896
+ constructor(input) {
1897
+ super(input.message);
1898
+ this.name = "AthenaError";
1899
+ this.code = input.code;
1900
+ this.kind = input.kind;
1901
+ this.category = input.category;
1902
+ this.status = input.status;
1903
+ this.retryable = input.retryable ?? false;
1904
+ this.requestId = input.requestId;
1905
+ this.context = input.context;
1906
+ this.raw = input.raw;
1907
+ }
1908
+ };
1909
+ function isRecord4(value) {
1910
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1911
+ }
1912
+ function firstNonEmptyString(...values) {
1913
+ for (const value of values) {
1914
+ if (typeof value === "string" && value.trim().length > 0) {
1915
+ return value.trim();
1916
+ }
1917
+ }
1918
+ return void 0;
1919
+ }
1920
+ function messageFromUnknownError(error) {
1921
+ if (typeof error === "string" && error.trim().length > 0) {
1922
+ return error.trim();
1923
+ }
1924
+ if (error instanceof Error && error.message.trim().length > 0) {
1925
+ return error.message.trim();
1926
+ }
1927
+ if (!isRecord4(error)) {
1928
+ return void 0;
1929
+ }
1930
+ return firstNonEmptyString(error.message, error.error, error.details);
1931
+ }
1932
+ function gatewayCodeFromUnknownError(error) {
1933
+ if (!isRecord4(error) || typeof error.gatewayCode !== "string") {
1934
+ return void 0;
1935
+ }
1936
+ return error.gatewayCode;
1937
+ }
1938
+ function isAthenaResultErrorLike(value) {
1939
+ return isRecord4(value) && typeof value.message === "string" && (value.athenaCode === void 0 || isAthenaErrorCode(value.athenaCode)) && (value.kind === void 0 || isAthenaErrorKind(value.kind)) && (value.category === void 0 || isAthenaErrorCategory(value.category)) && (value.retryable === void 0 || typeof value.retryable === "boolean") && (value.status === void 0 || typeof value.status === "number");
1940
+ }
1941
+ function isAthenaErrorKind(value) {
1942
+ return value === "unique_violation" || value === "not_found" || value === "validation" || value === "auth" || value === "rate_limit" || value === "transient" || value === "unknown";
1943
+ }
1944
+ function isAthenaErrorCode(value) {
1945
+ return value === "UNIQUE_VIOLATION" || value === "NOT_FOUND" || value === "VALIDATION_FAILED" || value === "AUTH_UNAUTHORIZED" || value === "AUTH_FORBIDDEN" || value === "RATE_LIMITED" || value === "NETWORK_UNAVAILABLE" || value === "TRANSIENT_FAILURE" || value === "HTTP_FAILURE" || value === "UNKNOWN";
1946
+ }
1947
+ function isAthenaErrorCategory(value) {
1948
+ return value === "transport" || value === "client" || value === "server" || value === "database" || value === "unknown";
1949
+ }
1950
+ function isNormalizedAthenaError(value) {
1951
+ return isRecord4(value) && isAthenaErrorKind(value.kind) && isAthenaErrorCode(value.code) && isAthenaErrorCategory(value.category) && typeof value.retryable === "boolean" && typeof value.message === "string" && "raw" in value;
1952
+ }
1953
+ function withContextOverrides(normalized, context) {
1954
+ if (!context?.table && !context?.operation) {
1955
+ return normalized;
1956
+ }
1957
+ return {
1958
+ ...normalized,
1959
+ table: context.table ?? normalized.table,
1960
+ operation: context.operation ?? normalized.operation
1961
+ };
1962
+ }
1963
+ function resolveAttachedNormalizedError(resultOrError) {
1964
+ if (!isRecord4(resultOrError)) return void 0;
1965
+ if (!("__athenaNormalizedError" in resultOrError)) return void 0;
1966
+ const candidate = resultOrError.__athenaNormalizedError;
1967
+ return isNormalizedAthenaError(candidate) ? candidate : void 0;
1968
+ }
1969
+ function safeStringify(value) {
1970
+ try {
1971
+ const serialized = JSON.stringify(value);
1972
+ return serialized ?? String(value);
1973
+ } catch {
1974
+ return "[unserializable]";
1975
+ }
1976
+ }
1977
+ function contextHint(context) {
1978
+ if (!context?.identity) return void 0;
1979
+ const identity = typeof context.identity === "string" ? context.identity : safeStringify(context.identity);
1980
+ return `Identity: ${identity}`;
1981
+ }
1982
+ function isAthenaResultLike(value) {
1983
+ return isRecord4(value) && "status" in value && "error" in value && "data" in value && typeof value.status === "number";
1984
+ }
1985
+ function operationFromDetails(details) {
1986
+ if (!details?.endpoint) return void 0;
1987
+ if (details.endpoint === "/gateway/fetch" || details.endpoint === "/gateway/query") return "select";
1988
+ if (details.endpoint === "/gateway/insert") return "insert";
1989
+ if (details.endpoint === "/gateway/update") return "update";
1990
+ if (details.endpoint === "/gateway/delete") return "delete";
1991
+ if (details.endpoint === "/gateway/rpc" || details.endpoint.startsWith("/rpc/")) return "rpc";
1992
+ return void 0;
1993
+ }
1994
+ function matchRegex(input, patterns) {
1995
+ for (const pattern of patterns) {
1996
+ const match = pattern.exec(input);
1997
+ if (match?.[1]) return match[1];
1998
+ }
1999
+ return void 0;
2000
+ }
2001
+ function extractConstraint(message) {
2002
+ return matchRegex(message, [
2003
+ /unique constraint\s+["'`]([^"'`]+)["'`]/i,
2004
+ /constraint\s+["'`]([^"'`]+)["'`]/i
2005
+ ]);
2006
+ }
2007
+ function extractTable(message) {
2008
+ return matchRegex(message, [
2009
+ /(?:table|relation)\s+["'`]([^"'`]+)["'`]/i,
2010
+ /on\s+table\s+([a-zA-Z0-9_.]+)/i
2011
+ ]);
2012
+ }
2013
+ function classifyKind(status, code, message) {
2014
+ const lower = message.toLowerCase();
2015
+ const hasUniquePattern = lower.includes("unique constraint") || lower.includes("duplicate key") || lower.includes("already exists") || lower.includes("duplicate");
2016
+ const hasNotFoundPattern = lower.includes("not found") || lower.includes("no rows");
2017
+ const hasValidationPattern = lower.includes("validation") || lower.includes("invalid") || lower.includes("malformed");
2018
+ const hasAuthPattern = lower.includes("unauthorized") || lower.includes("forbidden") || lower.includes("auth");
2019
+ const hasRateLimitPattern = lower.includes("rate limit") || lower.includes("too many requests");
2020
+ const hasTransientPattern = lower.includes("timeout") || lower.includes("temporar") || lower.includes("connection reset") || lower.includes("socket") || lower.includes("deadlock");
2021
+ if (status === 409 || hasUniquePattern) return "unique_violation";
2022
+ if (status === 404 || hasNotFoundPattern) return "not_found";
2023
+ if (status === 401 || status === 403 || hasAuthPattern) return "auth";
2024
+ if (status === 429 || hasRateLimitPattern) return "rate_limit";
2025
+ if (status === 400 || status === 422 || hasValidationPattern) return "validation";
2026
+ if (code === "NETWORK_ERROR" || status === 0 || status !== void 0 && status >= 500 || hasTransientPattern) {
2027
+ return "transient";
2028
+ }
2029
+ return "unknown";
2030
+ }
2031
+ function toAthenaErrorCode(kind, status, gatewayCode) {
2032
+ if (gatewayCode === "NETWORK_ERROR" || kind === "transient" && status === 0) {
2033
+ return AthenaErrorCode.NetworkUnavailable;
2034
+ }
2035
+ switch (kind) {
2036
+ case "unique_violation":
2037
+ return AthenaErrorCode.UniqueViolation;
2038
+ case "not_found":
2039
+ return AthenaErrorCode.NotFound;
2040
+ case "validation":
2041
+ return AthenaErrorCode.ValidationFailed;
2042
+ case "rate_limit":
2043
+ return AthenaErrorCode.RateLimited;
2044
+ case "auth":
2045
+ if (status === 403) {
2046
+ return AthenaErrorCode.AuthForbidden;
2047
+ }
2048
+ return AthenaErrorCode.AuthUnauthorized;
2049
+ case "transient":
2050
+ return status !== void 0 && status >= 500 ? AthenaErrorCode.HttpFailure : AthenaErrorCode.TransientFailure;
2051
+ case "unknown":
2052
+ default:
2053
+ return status !== void 0 && status >= 400 ? AthenaErrorCode.HttpFailure : AthenaErrorCode.Unknown;
2054
+ }
2055
+ }
2056
+ function toAthenaErrorCategory(kind, status) {
2057
+ if (kind === "transient" && (status === 0 || status === void 0)) {
2058
+ return AthenaErrorCategory.Transport;
2059
+ }
2060
+ if (kind === "unique_violation") return AthenaErrorCategory.Database;
2061
+ if (kind === "validation" || kind === "auth" || kind === "not_found") return AthenaErrorCategory.Client;
2062
+ if (kind === "rate_limit" || kind === "transient") return AthenaErrorCategory.Server;
2063
+ return AthenaErrorCategory.Unknown;
2064
+ }
2065
+ function isRetryable(kind, status) {
2066
+ if (kind === "rate_limit" || kind === "transient") return true;
2067
+ return status !== void 0 && status >= 500;
2068
+ }
2069
+ function toGatewayCode(kind, status) {
2070
+ if (kind === "transient" && (status === 0 || status === void 0)) return "NETWORK_ERROR";
2071
+ if (kind === "validation") return "INVALID_JSON";
2072
+ if (status !== void 0 && status >= 400) return "HTTP_ERROR";
2073
+ return "UNKNOWN_ERROR";
2074
+ }
2075
+ function toAthenaGatewayError(source, fallbackMessage, context) {
2076
+ if (isAthenaGatewayError(source)) {
2077
+ return source;
2078
+ }
2079
+ if (isAthenaResultLike(source) && source.errorDetails) {
2080
+ const message2 = messageFromUnknownError(source.error) ?? source.errorDetails.message ?? fallbackMessage;
2081
+ return new AthenaGatewayError({
2082
+ code: source.errorDetails.code,
2083
+ message: message2,
2084
+ status: source.status,
2085
+ endpoint: source.errorDetails.endpoint,
2086
+ method: source.errorDetails.method,
2087
+ requestId: source.errorDetails.requestId,
2088
+ hint: (isRecord4(source.error) ? firstNonEmptyString(source.error.hint) : void 0) ?? source.errorDetails.hint,
2089
+ cause: (isRecord4(source.error) ? firstNonEmptyString(source.error.cause) : void 0) ?? source.errorDetails.cause
2090
+ });
2091
+ }
2092
+ const normalized = normalizeAthenaError(source, context);
2093
+ const message = isAthenaResultLike(source) && source.error == null && source.errorDetails == null ? fallbackMessage : normalized.message || fallbackMessage;
2094
+ return new AthenaGatewayError({
2095
+ code: toGatewayCode(normalized.kind, normalized.status),
2096
+ message,
2097
+ status: normalized.status ?? 0,
2098
+ hint: normalized.constraint != null ? `Constraint: ${normalized.constraint}` : contextHint(context),
2099
+ cause: typeof normalized.raw === "string" ? normalized.raw : safeStringify(normalized.raw)
2100
+ });
2101
+ }
2102
+ function isOk(result) {
2103
+ return result.error == null && result.status >= 200 && result.status < 300;
2104
+ }
2105
+ function normalizeAthenaError(resultOrError, context) {
2106
+ const attached = resolveAttachedNormalizedError(resultOrError);
2107
+ if (attached) {
2108
+ return withContextOverrides(attached, context);
2109
+ }
2110
+ if (isAthenaResultLike(resultOrError)) {
2111
+ if (isAthenaResultErrorLike(resultOrError.error)) {
2112
+ return {
2113
+ kind: resultOrError.error.kind ?? classifyKind(resultOrError.status, gatewayCodeFromUnknownError(resultOrError.error), resultOrError.error.message),
2114
+ code: resultOrError.error.athenaCode ?? toAthenaErrorCode(
2115
+ resultOrError.error.kind ?? classifyKind(
2116
+ resultOrError.status,
2117
+ gatewayCodeFromUnknownError(resultOrError.error),
2118
+ resultOrError.error.message
2119
+ ),
2120
+ resultOrError.error.status ?? resultOrError.status,
2121
+ gatewayCodeFromUnknownError(resultOrError.error)
2122
+ ),
2123
+ category: resultOrError.error.category ?? toAthenaErrorCategory(
2124
+ resultOrError.error.kind ?? classifyKind(
2125
+ resultOrError.status,
2126
+ gatewayCodeFromUnknownError(resultOrError.error),
2127
+ resultOrError.error.message
2128
+ ),
2129
+ resultOrError.error.status ?? resultOrError.status
2130
+ ),
2131
+ retryable: resultOrError.error.retryable ?? isRetryable(
2132
+ resultOrError.error.kind ?? classifyKind(
2133
+ resultOrError.status,
2134
+ gatewayCodeFromUnknownError(resultOrError.error),
2135
+ resultOrError.error.message
2136
+ ),
2137
+ resultOrError.error.status ?? resultOrError.status
2138
+ ),
2139
+ status: resultOrError.error.status ?? resultOrError.status,
2140
+ constraint: resultOrError.error.constraint,
2141
+ table: context?.table ?? resultOrError.error.table,
2142
+ operation: context?.operation ?? resultOrError.error.operation,
2143
+ message: resultOrError.error.message,
2144
+ raw: resultOrError.error.raw ?? resultOrError.raw
2145
+ };
2146
+ }
2147
+ const details = resultOrError.errorDetails;
2148
+ const message2 = messageFromUnknownError(resultOrError.error) ?? details?.message ?? `Athena ${context?.operation ?? operationFromDetails(details) ?? "request"} failed`;
2149
+ const operation = context?.operation ?? operationFromDetails(details);
2150
+ const table = context?.table ?? extractTable(message2);
2151
+ const constraint = extractConstraint(message2);
2152
+ const gatewayCode = details?.code ?? gatewayCodeFromUnknownError(resultOrError.error);
2153
+ const kind2 = classifyKind(resultOrError.status, gatewayCode, message2);
2154
+ const code = toAthenaErrorCode(kind2, resultOrError.status, gatewayCode);
2155
+ const category = toAthenaErrorCategory(kind2, resultOrError.status);
2156
+ return {
2157
+ kind: kind2,
2158
+ code,
2159
+ category,
2160
+ retryable: isRetryable(kind2, resultOrError.status),
2161
+ status: resultOrError.status,
2162
+ constraint,
2163
+ table,
2164
+ operation,
2165
+ message: message2,
2166
+ raw: resultOrError.raw
2167
+ };
2168
+ }
2169
+ if (isAthenaGatewayError(resultOrError)) {
2170
+ const details = resultOrError.toDetails();
2171
+ const operation = context?.operation ?? operationFromDetails(details);
2172
+ const table = context?.table ?? extractTable(resultOrError.message);
2173
+ const constraint = extractConstraint(resultOrError.message);
2174
+ const kind2 = classifyKind(resultOrError.status, resultOrError.code, resultOrError.message);
2175
+ const code = toAthenaErrorCode(kind2, resultOrError.status, resultOrError.code);
2176
+ const category = toAthenaErrorCategory(kind2, resultOrError.status);
2177
+ return {
2178
+ kind: kind2,
2179
+ code,
2180
+ category,
2181
+ retryable: isRetryable(kind2, resultOrError.status),
2182
+ status: resultOrError.status,
2183
+ constraint,
2184
+ table,
2185
+ operation,
2186
+ message: resultOrError.message,
2187
+ raw: resultOrError
2188
+ };
2189
+ }
2190
+ if (resultOrError instanceof Error) {
2191
+ const maybeStatus = isRecord4(resultOrError) && typeof resultOrError.status === "number" ? resultOrError.status : void 0;
2192
+ const kind2 = classifyKind(maybeStatus, void 0, resultOrError.message);
2193
+ return {
2194
+ kind: kind2,
2195
+ code: toAthenaErrorCode(kind2, maybeStatus),
2196
+ category: toAthenaErrorCategory(kind2, maybeStatus),
2197
+ retryable: isRetryable(kind2, maybeStatus),
2198
+ status: maybeStatus,
2199
+ constraint: extractConstraint(resultOrError.message),
2200
+ table: context?.table ?? extractTable(resultOrError.message),
2201
+ operation: context?.operation,
2202
+ message: resultOrError.message,
2203
+ raw: resultOrError
2204
+ };
2205
+ }
2206
+ const message = typeof resultOrError === "string" ? resultOrError : "Unknown Athena error";
2207
+ const kind = classifyKind(void 0, void 0, message);
2208
+ return {
2209
+ kind,
2210
+ code: toAthenaErrorCode(kind, void 0),
2211
+ category: toAthenaErrorCategory(kind, void 0),
2212
+ retryable: isRetryable(kind, void 0),
2213
+ status: void 0,
2214
+ constraint: extractConstraint(message),
2215
+ table: context?.table ?? extractTable(message),
2216
+ operation: context?.operation,
2217
+ message,
2218
+ raw: resultOrError
2219
+ };
2220
+ }
2221
+ function unwrapRows(result, options) {
2222
+ if (!isOk(result)) {
2223
+ throw toAthenaGatewayError(result, "Athena request failed", options?.context);
2224
+ }
2225
+ if (result.data == null) return [];
2226
+ return Array.isArray(result.data) ? result.data : [result.data];
2227
+ }
2228
+ function unwrap(result, options) {
2229
+ if (!isOk(result)) {
2230
+ throw toAthenaGatewayError(result, "Athena request failed", options?.context);
2231
+ }
2232
+ if (result.data == null && !options?.allowNull) {
2233
+ throw toAthenaGatewayError(result, "Expected data but received null", options?.context);
2234
+ }
2235
+ return result.data;
2236
+ }
2237
+ function unwrapOne(result, options) {
2238
+ const rows = unwrapRows(result, options);
2239
+ if (!rows.length) {
2240
+ if (options?.allowNull) return null;
2241
+ throw toAthenaGatewayError(result, "Expected one row but received none", options?.context);
2242
+ }
2243
+ if (options?.requireExactlyOne && rows.length !== 1) {
2244
+ throw toAthenaGatewayError(
2245
+ result,
2246
+ `Expected exactly one row but received ${rows.length}`,
2247
+ options.context
2248
+ );
2249
+ }
2250
+ return rows[0];
2251
+ }
2252
+ function requireSuccess(result, context) {
2253
+ if (!isOk(result)) {
2254
+ throw toAthenaGatewayError(
2255
+ result,
2256
+ `Athena ${context?.operation ?? "request"} failed`,
2257
+ context
2258
+ );
2259
+ }
2260
+ return result;
2261
+ }
2262
+ function requireAffected(result, options, context) {
2263
+ requireSuccess(result, context);
2264
+ const minimum = options?.min ?? 1;
2265
+ const count = result.count;
2266
+ if (count == null) {
2267
+ throw new AthenaGatewayError({
2268
+ code: "UNKNOWN_ERROR",
2269
+ status: result.status,
2270
+ message: "Expected affected row count but response.count is missing",
2271
+ hint: 'Set call option { count: "exact" } for mutation postcondition checks.',
2272
+ cause: safeStringify(result.raw)
2273
+ });
2274
+ }
2275
+ if (count < minimum) {
2276
+ throw new AthenaGatewayError({
2277
+ code: "UNKNOWN_ERROR",
2278
+ status: result.status,
2279
+ message: `Expected at least ${minimum} affected rows but received ${count}`,
2280
+ hint: contextHint(context),
2281
+ cause: safeStringify(result.raw)
2282
+ });
2283
+ }
2284
+ return count;
2285
+ }
2286
+ function applyBounds(value, options) {
2287
+ if (options?.min !== void 0 && value < options.min) return null;
2288
+ if (options?.max !== void 0 && value > options.max) return null;
2289
+ return value;
2290
+ }
2291
+ function parseIntegerString(value) {
2292
+ const normalized = value.trim();
2293
+ if (!/^[-+]?\d+$/.test(normalized)) return null;
2294
+ const parsed = Number(normalized);
2295
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) return null;
2296
+ return parsed;
2297
+ }
2298
+ function coerceInt(value, options) {
2299
+ if (value == null) return null;
2300
+ if (typeof value === "number") {
2301
+ if (!Number.isFinite(value) || !Number.isInteger(value)) return null;
2302
+ return applyBounds(value, options);
2303
+ }
2304
+ if (typeof value === "string") {
2305
+ const parsed = parseIntegerString(value);
2306
+ if (parsed == null) return null;
2307
+ return applyBounds(parsed, options);
2308
+ }
2309
+ if (typeof value === "bigint") {
2310
+ if (options?.strictBigInt) {
2311
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
2312
+ return null;
2313
+ }
2314
+ }
2315
+ const parsed = Number(value);
2316
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) return null;
2317
+ return applyBounds(parsed, options);
2318
+ }
2319
+ return null;
2320
+ }
2321
+ function assertInt(value, label = "value", options) {
2322
+ const parsed = coerceInt(value, options);
2323
+ if (parsed == null) {
2324
+ throw new TypeError(`${label} must be a finite integer`);
2325
+ }
2326
+ return parsed;
2327
+ }
2328
+ function defaultShouldRetry(error) {
2329
+ const normalized = normalizeAthenaError(error);
2330
+ return normalized.kind === "transient" || normalized.kind === "rate_limit";
2331
+ }
2332
+ function computeDelayMs(attempt, error, config) {
2333
+ const baseDelay = config.baseDelayMs;
2334
+ const rawDelay = typeof config.backoff === "function" ? config.backoff(attempt, error) : config.backoff === "linear" ? baseDelay * attempt : baseDelay * Math.pow(2, attempt - 1);
2335
+ const safeDelay = Number.isFinite(rawDelay) ? Math.max(0, rawDelay) : 0;
2336
+ const clamped = Math.min(config.maxDelayMs, safeDelay);
2337
+ const jitterFactor = typeof config.jitter === "number" ? Math.max(0, Math.min(1, config.jitter)) : config.jitter ? 0.2 : 0;
2338
+ if (!jitterFactor) return clamped;
2339
+ const deviation = clamped * jitterFactor;
2340
+ const offset = (Math.random() * 2 - 1) * deviation;
2341
+ return Math.max(0, clamped + offset);
2342
+ }
2343
+ function sleep(ms) {
2344
+ if (ms <= 0) return Promise.resolve();
2345
+ return new Promise((resolve) => {
2346
+ setTimeout(resolve, ms);
2347
+ });
2348
+ }
2349
+ async function withRetry(config, fn) {
2350
+ const retries = Math.max(0, Math.trunc(config.retries));
2351
+ const shouldRetry = config.shouldRetry ?? defaultShouldRetry;
2352
+ const resolvedConfig = {
2353
+ baseDelayMs: config.baseDelayMs ?? 100,
2354
+ maxDelayMs: config.maxDelayMs ?? 1e4,
2355
+ backoff: config.backoff ?? "exponential",
2356
+ jitter: config.jitter ?? false
2357
+ };
2358
+ for (let attempts = 0; attempts <= retries; attempts += 1) {
2359
+ try {
2360
+ return await fn();
2361
+ } catch (error) {
2362
+ if (attempts >= retries) {
2363
+ throw error;
2364
+ }
2365
+ const currentAttempt = attempts + 1;
2366
+ const retry = await shouldRetry(error, currentAttempt);
2367
+ if (!retry) {
2368
+ throw error;
2369
+ }
2370
+ const delay = computeDelayMs(currentAttempt, error, resolvedConfig);
2371
+ await sleep(delay);
2372
+ }
2373
+ }
2374
+ throw new Error("withRetry reached an unexpected state");
2375
+ }
2376
+
2377
+ // src/db/module.ts
2378
+ function createDbModule(input) {
2379
+ const db = {
2380
+ from(table) {
2381
+ return input.from(table);
2382
+ },
2383
+ select(table, columns, options) {
2384
+ return input.from(table).select(columns, options);
2385
+ },
2386
+ insert(table, values, options) {
2387
+ return Array.isArray(values) ? input.from(table).insert(values, options) : input.from(table).insert(values, options);
2388
+ },
2389
+ upsert(table, values, options) {
2390
+ return Array.isArray(values) ? input.from(table).upsert(values, options) : input.from(table).upsert(values, options);
2391
+ },
2392
+ update(table, values, options) {
2393
+ return input.from(table).update(values, options);
2394
+ },
2395
+ delete(table, options) {
2396
+ return input.from(table).delete(options);
2397
+ },
2398
+ rpc(fn, args, options) {
2399
+ return input.rpc(fn, args, options);
2400
+ },
2401
+ query(query, options) {
2402
+ return input.query(query, options);
2403
+ }
2404
+ };
2405
+ return db;
2406
+ }
2407
+
2408
+ // src/query-ast.ts
2409
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
2410
+ var FILTER_OPERATORS = /* @__PURE__ */ new Set([
2411
+ "eq",
2412
+ "neq",
2413
+ "gt",
2414
+ "gte",
2415
+ "lt",
2416
+ "lte",
2417
+ "like",
2418
+ "ilike",
2419
+ "is",
2420
+ "in",
2421
+ "contains",
2422
+ "containedBy"
2423
+ ]);
2424
+ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
2425
+ "eq",
2426
+ "neq",
2427
+ "gt",
2428
+ "gte",
2429
+ "lt",
2430
+ "lte",
2431
+ "like",
2432
+ "ilike",
2433
+ "is"
2434
+ ]);
2435
+ function isRecord5(value) {
2436
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
2437
+ }
2438
+ function isUuidString(value) {
2439
+ return UUID_PATTERN.test(value.trim());
2440
+ }
2441
+ function isUuidIdentifierColumn(column) {
2442
+ return column === "id" || /(?:^|_)uuid(?:_|$)/i.test(column) || /_id$/i.test(column);
2443
+ }
2444
+ function shouldUseUuidTextComparison(column, value) {
2445
+ return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
2446
+ }
2447
+ function isRelationSelectNode(value) {
2448
+ return isRecord5(value) && isRecord5(value.select);
2449
+ }
2450
+ function normalizeIdentifier(value, label) {
2451
+ const normalized = value.trim();
2452
+ if (!normalized) {
2453
+ throw new Error(`${label} must be a non-empty string`);
2454
+ }
2455
+ return normalized;
2456
+ }
2457
+ function stringifyFilterValue(value) {
2458
+ if (Array.isArray(value)) {
2459
+ return value.join(",");
2460
+ }
2461
+ return String(value);
2462
+ }
2463
+ function buildGatewayCondition(operator, column, value) {
2464
+ const condition = { operator };
2465
+ if (column) {
2466
+ condition.column = column;
2467
+ if (operator === "eq") {
2468
+ condition.eq_column = column;
2469
+ }
2470
+ }
2471
+ if (value !== void 0) {
2472
+ condition.value = value;
2473
+ if (operator === "eq") {
2474
+ condition.eq_value = value;
2475
+ }
2476
+ }
2477
+ if (operator === "eq" && column && value !== void 0 && shouldUseUuidTextComparison(column, value)) {
2478
+ condition.column_cast = "text";
2479
+ condition.eq_column_cast = "text";
2480
+ }
2481
+ return condition;
2482
+ }
2483
+ function compileRelationToken(key, node) {
2484
+ const nested = compileSelectShape(node.select);
2485
+ const propertyKey = normalizeIdentifier(key, "select relation key");
2486
+ const relationToken = normalizeIdentifier(node.via ?? propertyKey, "select relation token");
2487
+ const alias = node.as?.trim() || (relationToken !== propertyKey ? propertyKey : "");
2488
+ const prefix = alias ? `${alias}:` : "";
2489
+ return `${prefix}${relationToken}(${nested})`;
2490
+ }
2491
+ function compileSelectShape(select) {
2492
+ if (!isRecord5(select)) {
2493
+ throw new Error("findMany select must be an object");
2494
+ }
2495
+ const tokens = [];
2496
+ for (const [rawKey, rawValue] of Object.entries(select)) {
2497
+ if (rawValue === void 0) {
2498
+ continue;
2499
+ }
2500
+ if (rawValue === true) {
2501
+ tokens.push(normalizeIdentifier(rawKey, "select column"));
2502
+ continue;
2503
+ }
2504
+ if (isRelationSelectNode(rawValue)) {
2505
+ tokens.push(compileRelationToken(rawKey, rawValue));
2506
+ continue;
2507
+ }
2508
+ throw new Error(`Unsupported select node for "${rawKey}"`);
2509
+ }
2510
+ if (tokens.length === 0) {
2511
+ throw new Error("findMany select requires at least one field");
2512
+ }
2513
+ return tokens.join(",");
2514
+ }
2515
+ function compileColumnWhere(column, input) {
2516
+ const normalizedColumn = normalizeIdentifier(column, "where column");
2517
+ if (!isRecord5(input)) {
2518
+ return [buildGatewayCondition("eq", normalizedColumn, input)];
2519
+ }
2520
+ const conditions = [];
2521
+ for (const [rawOperator, rawValue] of Object.entries(input)) {
2522
+ if (rawValue === void 0) {
2523
+ continue;
2524
+ }
2525
+ if (!FILTER_OPERATORS.has(rawOperator)) {
2526
+ throw new Error(`Unsupported where operator "${rawOperator}" on "${normalizedColumn}"`);
2527
+ }
2528
+ if ((rawOperator === "in" || rawOperator === "contains" || rawOperator === "containedBy") && !Array.isArray(rawValue)) {
2529
+ throw new Error(`where.${normalizedColumn}.${rawOperator} requires an array value`);
2530
+ }
2531
+ conditions.push(
2532
+ buildGatewayCondition(
2533
+ rawOperator,
2534
+ normalizedColumn,
2535
+ rawValue
2536
+ )
2537
+ );
2538
+ }
2539
+ if (conditions.length === 0) {
2540
+ throw new Error(`where.${normalizedColumn} requires at least one operator`);
2541
+ }
2542
+ return conditions;
2543
+ }
2544
+ function compileBooleanExpressionTerms(clause, label) {
2545
+ if (!isRecord5(clause)) {
2546
+ throw new Error(`findMany where.${label} clauses must be objects`);
2547
+ }
2548
+ const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
2549
+ if (entries.length !== 1) {
2550
+ throw new Error(`findMany where.${label} clauses must target exactly one column`);
2551
+ }
2552
+ const [rawColumn, rawValue] = entries[0];
2553
+ const column = normalizeIdentifier(rawColumn, `where.${label} column`);
2554
+ if (!isRecord5(rawValue)) {
2555
+ return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
2556
+ }
2557
+ const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
2558
+ if (operatorEntries.length === 0) {
2559
+ throw new Error(`findMany where.${label}.${column} requires at least one operator`);
2560
+ }
2561
+ if (label === "not" && operatorEntries.length > 1) {
2562
+ throw new Error("findMany where.not only supports a single lossless operator expression");
2563
+ }
2564
+ return operatorEntries.map(([rawOperator, rawOperand]) => {
2565
+ if (!BOOLEAN_SAFE_OPERATORS.has(rawOperator)) {
2566
+ throw new Error(`findMany where.${label} only supports lossless scalar operators`);
2567
+ }
2568
+ if (Array.isArray(rawOperand)) {
2569
+ throw new Error(`findMany where.${label} does not support array-valued operators`);
2570
+ }
2571
+ return `${column}.${rawOperator}.${stringifyFilterValue(rawOperand)}`;
2572
+ });
2573
+ }
2574
+ function compileWhere(where) {
2575
+ if (where === void 0) {
2576
+ return void 0;
2577
+ }
2578
+ if (!isRecord5(where)) {
2579
+ throw new Error("findMany where must be an object");
2580
+ }
2581
+ const conditions = [];
2582
+ for (const [rawKey, rawValue] of Object.entries(where)) {
2583
+ if (rawValue === void 0) {
2584
+ continue;
2585
+ }
2586
+ if (rawKey === "or") {
2587
+ if (!Array.isArray(rawValue) || rawValue.length === 0) {
2588
+ throw new Error("findMany where.or must be a non-empty array");
2589
+ }
2590
+ const expressions = rawValue.flatMap(
2591
+ (value) => compileBooleanExpressionTerms(value, "or")
2592
+ );
2593
+ conditions.push(buildGatewayCondition("or", void 0, expressions.join(",")));
2594
+ continue;
2595
+ }
2596
+ if (rawKey === "not") {
2597
+ const expressions = compileBooleanExpressionTerms(rawValue, "not");
2598
+ if (expressions.length !== 1) {
2599
+ throw new Error("findMany where.not must compile to exactly one lossless expression");
2600
+ }
2601
+ conditions.push(buildGatewayCondition("not", void 0, expressions[0]));
2602
+ continue;
2603
+ }
2604
+ conditions.push(...compileColumnWhere(rawKey, rawValue));
2605
+ }
2606
+ return conditions.length > 0 ? conditions : void 0;
2607
+ }
2608
+ function resolveOrderDirection(input) {
2609
+ if (typeof input === "boolean") {
2610
+ return input === false ? "descending" : "ascending";
2611
+ }
2612
+ if (typeof input === "string") {
2613
+ const normalized = input.trim().toLowerCase();
2614
+ if (normalized === "asc" || normalized === "ascending") {
2615
+ return "ascending";
2616
+ }
2617
+ if (normalized === "desc" || normalized === "descending") {
2618
+ return "descending";
2619
+ }
2620
+ throw new Error(`Unsupported orderBy direction "${input}"`);
2621
+ }
2622
+ return input.ascending === false ? "descending" : "ascending";
2623
+ }
2624
+ function compileOrderBy(orderBy) {
2625
+ if (orderBy === void 0) {
2626
+ return void 0;
2627
+ }
2628
+ if (!isRecord5(orderBy)) {
2629
+ throw new Error("findMany orderBy must be an object");
2630
+ }
2631
+ if ("column" in orderBy) {
2632
+ return {
2633
+ field: normalizeIdentifier(String(orderBy.column), "orderBy column"),
2634
+ direction: orderBy.ascending === false ? "descending" : "ascending"
2635
+ };
2636
+ }
2637
+ const entries = Object.entries(orderBy).filter(([, value]) => value !== void 0);
2638
+ if (entries.length === 0) {
2639
+ return void 0;
2640
+ }
2641
+ if (entries.length > 1) {
2642
+ throw new Error("findMany orderBy only supports a single column in v1");
2643
+ }
2644
+ const [column, input] = entries[0];
2645
+ return {
2646
+ field: normalizeIdentifier(column, "orderBy column"),
2647
+ direction: resolveOrderDirection(input)
2648
+ };
2649
+ }
2650
+
2651
+ // src/client.ts
2652
+ var DEFAULT_COLUMNS = "*";
2653
+ var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
2654
+ var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
2655
+ var QUERY_TRACE_STACK_SKIP_PATTERNS = [
2656
+ "src\\client.ts",
2657
+ "src/client.ts",
2658
+ "dist\\client.",
2659
+ "dist/client.",
2660
+ "node_modules\\@xylex-group\\athena",
2661
+ "node_modules/@xylex-group/athena",
2662
+ "node:internal",
2663
+ "internal/process"
2664
+ ];
2665
+ function canUseFindManyAstTransport(state) {
2666
+ return state.conditions.length === 0 && state.offset === void 0 && state.currentPage === void 0 && state.pageSize === void 0 && state.totalPages === void 0;
2667
+ }
2668
+ function toFindManyAstOrder(order) {
2669
+ if (!order) {
2670
+ return void 0;
2671
+ }
2672
+ return {
2673
+ column: order.field,
2674
+ ascending: order.direction !== "descending"
2675
+ };
2676
+ }
2677
+ function formatResult(response) {
2678
+ const result = {
2679
+ data: response.data ?? null,
2680
+ error: null,
2681
+ errorDetails: response.errorDetails ?? null,
2682
+ status: response.status,
2683
+ statusText: response.statusText ?? null,
2684
+ raw: response.raw
2685
+ };
2686
+ if (response.count !== void 0) {
2687
+ result.count = response.count;
2688
+ }
2689
+ return result;
2690
+ }
2691
+ function attachNormalizedError(result, normalizedError) {
2692
+ Object.defineProperty(result, ATHENA_NORMALIZED_ERROR_KEY, {
2693
+ value: normalizedError,
2694
+ enumerable: false,
2695
+ configurable: true,
2696
+ writable: false
2697
+ });
2698
+ }
2699
+ function createResultFormatter(experimental) {
2700
+ return (response, context) => {
2701
+ const result = formatResult(response);
2702
+ if (response.error == null && response.errorDetails == null) {
2703
+ return result;
2704
+ }
2705
+ const normalizedError = normalizeAthenaError(
2706
+ {
2707
+ ...result,
2708
+ error: response.error ?? response.errorDetails?.message ?? null
2709
+ },
2710
+ context
2711
+ );
2712
+ result.error = createResultError(response, result, normalizedError);
2713
+ attachNormalizedError(result, normalizedError);
2714
+ return result;
2715
+ };
2716
+ }
2717
+ function isRecord6(value) {
2718
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
2719
+ }
2720
+ function firstNonEmptyString2(...values) {
2721
+ for (const value of values) {
2722
+ if (typeof value === "string" && value.trim().length > 0) {
2723
+ return value.trim();
2724
+ }
2725
+ }
2726
+ return void 0;
2727
+ }
2728
+ function resolveStructuredErrorPayload2(raw) {
2729
+ if (!isRecord6(raw)) return null;
2730
+ return isRecord6(raw.error) ? raw.error : raw;
2731
+ }
2732
+ function resolveStructuredErrorDetails(payload, message) {
2733
+ if (!payload || !("details" in payload)) {
2734
+ return null;
2735
+ }
2736
+ const details = payload.details;
2737
+ if (details == null) {
2738
+ return null;
2739
+ }
2740
+ if (typeof details === "string" && details.trim() === message.trim()) {
2741
+ return null;
2742
+ }
2743
+ return details;
2744
+ }
2745
+ function createResultError(response, result, normalized) {
2746
+ const rawRecord = isRecord6(response.raw) ? response.raw : null;
2747
+ const payload = resolveStructuredErrorPayload2(response.raw);
2748
+ const message = firstNonEmptyString2(
2749
+ response.error,
2750
+ payload?.message,
2751
+ payload?.error,
2752
+ payload?.details,
2753
+ response.errorDetails?.message,
2754
+ normalized.message
2755
+ ) ?? normalized.message;
2756
+ const statusText = firstNonEmptyString2(response.statusText, rawRecord?.statusText) ?? null;
2757
+ const hint = firstNonEmptyString2(payload?.hint, response.errorDetails?.hint) ?? null;
2758
+ const code = firstNonEmptyString2(payload?.code) ?? normalized.code;
2759
+ const details = resolveStructuredErrorDetails(payload, message) ?? response.errorDetails?.cause ?? null;
2760
+ return {
2761
+ message,
2762
+ code,
2763
+ athenaCode: normalized.code,
2764
+ gatewayCode: response.errorDetails?.code ?? null,
2765
+ kind: normalized.kind,
2766
+ category: normalized.category,
2767
+ retryable: normalized.retryable,
2768
+ details,
2769
+ hint,
2770
+ status: result.status,
2771
+ statusText,
2772
+ constraint: normalized.constraint,
2773
+ table: normalized.table,
2774
+ operation: normalized.operation,
2775
+ endpoint: response.errorDetails?.endpoint,
2776
+ method: response.errorDetails?.method,
2777
+ requestId: response.errorDetails?.requestId,
2778
+ cause: response.errorDetails?.cause,
2779
+ raw: result.raw
2780
+ };
2781
+ }
2782
+ function parseQueryTraceCallsiteFrame(frame) {
2783
+ const trimmed = frame.trim();
2784
+ if (!trimmed) {
2785
+ return null;
2786
+ }
2787
+ let body = trimmed.replace(/^at\s+/, "");
2788
+ if (body.startsWith("async ")) {
2789
+ body = body.slice(6);
2790
+ }
2791
+ let functionName;
2792
+ let location = body;
2793
+ const wrappedMatch = body.match(/^(.*?)\s+\((.*)\)$/);
2794
+ if (wrappedMatch) {
2795
+ functionName = wrappedMatch[1].trim() || void 0;
2796
+ location = wrappedMatch[2].trim();
2797
+ }
2798
+ const locationMatch = location.match(/^(.*):(\d+):(\d+)$/);
2799
+ if (!locationMatch) {
2800
+ return null;
2801
+ }
2802
+ const filePath = locationMatch[1].replace(/^file:\/\//, "");
2803
+ const line = Number(locationMatch[2]);
2804
+ const column = Number(locationMatch[3]);
2805
+ if (!Number.isFinite(line) || !Number.isFinite(column)) {
2806
+ return null;
2807
+ }
2808
+ const normalizedPath = filePath.replace(/\\/g, "/");
2809
+ const fileName = normalizedPath.split("/").at(-1) ?? filePath;
2810
+ return {
2811
+ filePath,
2812
+ fileName,
2813
+ line,
2814
+ column,
2815
+ frame: trimmed,
2816
+ functionName
2817
+ };
2818
+ }
2819
+ function captureQueryTraceCallsite() {
2820
+ const stack = new Error().stack;
2821
+ if (!stack) return null;
2822
+ const frames = stack.split("\n").slice(2).map((frame) => frame.trim()).filter(Boolean);
2823
+ for (const frame of frames) {
2824
+ if (QUERY_TRACE_STACK_SKIP_PATTERNS.some((pattern) => frame.includes(pattern))) {
2825
+ continue;
2826
+ }
2827
+ const callsite = parseQueryTraceCallsiteFrame(frame);
2828
+ if (callsite) return callsite;
2829
+ }
2830
+ const fallback = frames.find((frame) => !frame.includes("captureQueryTraceCallsite"));
2831
+ return fallback ? parseQueryTraceCallsiteFrame(fallback) : null;
2832
+ }
2833
+ function defaultQueryTraceLogger(event) {
2834
+ const target = event.table ?? event.functionName ?? "gateway";
2835
+ const outcomeState = event.outcome?.error ? "error" : "ok";
2836
+ const banner = `[athena-js][trace] ${event.operation.toUpperCase()} ${event.endpoint} ${target} ${event.durationMs}ms ${outcomeState}`;
2837
+ console.info(banner, event);
2838
+ }
2839
+ function captureTraceCallsite(tracer) {
2840
+ return tracer?.captureCallsite() ?? null;
2841
+ }
2842
+ function createTraceCallsiteStore(tracer, initialCallsite) {
2843
+ let storedCallsite = initialCallsite ?? void 0;
2844
+ return {
2845
+ resolve(callsite) {
2846
+ if (callsite) {
2847
+ storedCallsite = callsite;
2848
+ return callsite;
2849
+ }
2850
+ if (storedCallsite !== void 0) {
2851
+ return storedCallsite;
2852
+ }
2853
+ const capturedCallsite = captureTraceCallsite(tracer);
2854
+ if (capturedCallsite) {
2855
+ storedCallsite = capturedCallsite;
2856
+ }
2857
+ return capturedCallsite;
2858
+ }
2859
+ };
2860
+ }
2861
+ function createQueryTracer(experimental) {
2862
+ const traceOption = experimental?.traceQueries;
2863
+ if (!traceOption) {
2864
+ return void 0;
2865
+ }
2866
+ const logger = typeof traceOption === "object" && traceOption.logger ? traceOption.logger : defaultQueryTraceLogger;
2867
+ const emit = (event) => {
2868
+ try {
2869
+ logger(event);
2870
+ } catch (error) {
2871
+ console.warn("[athena-js][trace] logger failed", error);
2872
+ }
2873
+ };
2874
+ return {
2875
+ captureCallsite: captureQueryTraceCallsite,
2876
+ publishSuccess(context, result, durationMs, callsite) {
2877
+ emit({
2878
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2879
+ durationMs,
2880
+ operation: context.operation,
2881
+ endpoint: context.endpoint,
2882
+ table: context.table,
2883
+ functionName: context.functionName,
2884
+ sql: context.sql,
2885
+ payload: context.payload,
2886
+ options: context.options,
2887
+ callsite,
2888
+ outcome: {
2889
+ status: result.status,
2890
+ error: result.error,
2891
+ errorDetails: result.errorDetails ?? null,
2892
+ count: result.count ?? null,
2893
+ data: result.data,
2894
+ raw: result.raw
2895
+ }
2896
+ });
2897
+ },
2898
+ publishFailure(context, error, durationMs, callsite) {
2899
+ emit({
2900
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2901
+ durationMs,
2902
+ operation: context.operation,
2903
+ endpoint: context.endpoint,
2904
+ table: context.table,
2905
+ functionName: context.functionName,
2906
+ sql: context.sql,
2907
+ payload: context.payload,
2908
+ options: context.options,
2909
+ callsite,
2910
+ thrownError: error
2911
+ });
2912
+ }
2913
+ };
2914
+ }
2915
+ async function executeWithQueryTrace(tracer, context, runner, callsiteOverride) {
2916
+ if (!tracer) {
2917
+ return runner();
2918
+ }
2919
+ const callsite = callsiteOverride ?? tracer.captureCallsite();
2920
+ const startedAt = Date.now();
2921
+ try {
2922
+ const result = await runner();
2923
+ tracer.publishSuccess(context, result, Date.now() - startedAt, callsite);
2924
+ return result;
2925
+ } catch (error) {
2926
+ tracer.publishFailure(context, error, Date.now() - startedAt, callsite);
2927
+ throw error;
2928
+ }
2929
+ }
2930
+ function toSingleResult(response) {
2931
+ const payload = response.data;
2932
+ const singleData = Array.isArray(payload) ? payload.length ? payload[0] : null : payload ?? null;
2933
+ return {
2934
+ ...response,
2935
+ data: singleData
2936
+ };
2937
+ }
2938
+ function mergeOptions(...options) {
2939
+ return options.reduce((acc, next) => {
2940
+ if (!next) return acc;
2941
+ return { ...acc, ...next };
2942
+ }, void 0);
2943
+ }
2944
+ function asAthenaJsonObject(value) {
2945
+ return value;
2946
+ }
2947
+ function asAthenaJsonObjectArray(values) {
2948
+ return values;
2949
+ }
2950
+ function createMutationQuery(executor, defaultColumns = DEFAULT_COLUMNS, tracer, initialCallsite) {
2951
+ let selectedColumns = defaultColumns === null ? void 0 : defaultColumns;
2952
+ let selectedOptions;
2953
+ let promise = null;
2954
+ const callsiteStore = createTraceCallsiteStore(tracer, initialCallsite);
2955
+ const run = (columns, options, callsite) => {
2956
+ const payloadColumns = columns ?? selectedColumns;
2957
+ const payloadOptions = options ?? selectedOptions;
2958
+ if (!promise) {
2959
+ promise = executor(payloadColumns, payloadOptions, callsiteStore.resolve(callsite));
2960
+ }
2961
+ return promise;
2962
+ };
2963
+ const mutationQuery = {
2964
+ select(columns = selectedColumns, options) {
2965
+ selectedColumns = columns;
2966
+ selectedOptions = options ?? selectedOptions;
2967
+ return run(columns, options, captureTraceCallsite(tracer));
2968
+ },
2969
+ returning(columns = selectedColumns, options) {
2970
+ return mutationQuery.select(columns, options);
2971
+ },
2972
+ single(columns = selectedColumns, options) {
2973
+ selectedColumns = columns;
2974
+ selectedOptions = options ?? selectedOptions;
2975
+ return run(columns, options, captureTraceCallsite(tracer)).then(toSingleResult);
2976
+ },
2977
+ maybeSingle(columns = selectedColumns, options) {
2978
+ return mutationQuery.single(columns, options);
2979
+ },
2980
+ then(onfulfilled, onrejected) {
2981
+ return run(selectedColumns, selectedOptions).then(onfulfilled, onrejected);
2982
+ },
2983
+ catch(onrejected) {
2984
+ return run(selectedColumns, selectedOptions).catch(onrejected);
2985
+ },
2986
+ finally(onfinally) {
2987
+ return run(selectedColumns, selectedOptions).finally(onfinally);
2988
+ }
2989
+ };
2990
+ return mutationQuery;
2991
+ }
2992
+ function getResourceId(state) {
2993
+ const candidate = state.conditions.find(
2994
+ (condition) => condition.operator === "eq" && (condition.column === "resource_id" || condition.column === "id")
2995
+ );
2996
+ return candidate?.value?.toString();
2997
+ }
2998
+ function stringifyFilterValue2(value) {
2999
+ if (Array.isArray(value)) {
3000
+ return value.join(",");
3001
+ }
3002
+ return String(value);
3003
+ }
3004
+ function normalizeCast(cast) {
3005
+ const normalized = cast.trim().toLowerCase();
3006
+ if (!SAFE_CAST_PATTERN.test(normalized)) {
3007
+ throw new Error(`Invalid cast type "${cast}"`);
3008
+ }
3009
+ return normalized;
3010
+ }
3011
+ function escapeSqlStringLiteral(value) {
3012
+ return value.replace(/'/g, "''");
3013
+ }
3014
+ function toSqlLiteral(value) {
3015
+ if (value === null) return "NULL";
3016
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : "NULL";
3017
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
3018
+ return `'${escapeSqlStringLiteral(value)}'`;
3019
+ }
3020
+ function withCast(expression, cast) {
3021
+ if (!cast) return expression;
3022
+ return `${expression}::${normalizeCast(cast)}`;
3023
+ }
3024
+ function buildSelectColumnsClause(columns) {
3025
+ if (Array.isArray(columns)) {
3026
+ return columns.map((column) => quoteSelectColumnToken(column)).join(", ");
3027
+ }
3028
+ return quoteSelectColumnsExpression(columns);
3029
+ }
3030
+ function parseIdentifierSegment(input) {
3031
+ const trimmed = input.trim();
3032
+ if (!trimmed) return null;
3033
+ if (!trimmed.startsWith('"')) {
3034
+ return {
3035
+ normalizedValue: trimmed.toLowerCase()
3036
+ };
3037
+ }
3038
+ let value = "";
3039
+ let index = 1;
3040
+ let closed = false;
3041
+ while (index < trimmed.length) {
3042
+ const char = trimmed[index];
3043
+ const next = index + 1 < trimmed.length ? trimmed[index + 1] : "";
3044
+ if (char === '"' && next === '"') {
3045
+ value += '"';
3046
+ index += 2;
3047
+ continue;
3048
+ }
3049
+ if (char === '"') {
3050
+ closed = true;
3051
+ index += 1;
3052
+ break;
3053
+ }
3054
+ value += char;
3055
+ index += 1;
3056
+ }
3057
+ if (!closed || trimmed.slice(index).trim().length > 0 || !value.trim()) {
3058
+ return null;
3059
+ }
3060
+ return {
3061
+ normalizedValue: value
3062
+ };
3063
+ }
3064
+ function splitQualifiedTableName(tableName) {
3065
+ const trimmed = tableName.trim();
3066
+ let inQuotes = false;
3067
+ for (let index = 0; index < trimmed.length; index += 1) {
3068
+ const char = trimmed[index];
3069
+ const next = index + 1 < trimmed.length ? trimmed[index + 1] : "";
3070
+ if (char === '"') {
3071
+ if (inQuotes && next === '"') {
3072
+ index += 1;
3073
+ continue;
3074
+ }
3075
+ inQuotes = !inQuotes;
3076
+ continue;
3077
+ }
3078
+ if (char === "." && !inQuotes) {
3079
+ const schemaSegment = trimmed.slice(0, index).trim();
3080
+ const tableSegment = trimmed.slice(index + 1).trim();
3081
+ if (!schemaSegment || !tableSegment) {
3082
+ return null;
3083
+ }
3084
+ return { schemaSegment };
3085
+ }
3086
+ }
3087
+ return null;
3088
+ }
3089
+ function resolveTableNameForCall(tableName, schema) {
3090
+ if (!schema) return tableName;
3091
+ const normalizedSchema = schema.trim();
3092
+ if (!normalizedSchema) {
3093
+ throw new Error("schema option must be a non-empty string");
3094
+ }
3095
+ const normalizedTableName = tableName.trim();
3096
+ const parsedSchema = parseIdentifierSegment(normalizedSchema);
3097
+ if (!parsedSchema) {
3098
+ throw new Error("schema option must be a non-empty string");
3099
+ }
3100
+ const qualified = splitQualifiedTableName(normalizedTableName);
3101
+ if (qualified) {
3102
+ const parsedTableSchema = parseIdentifierSegment(qualified.schemaSegment);
3103
+ const sameSchema = parsedTableSchema ? parsedTableSchema.normalizedValue === parsedSchema.normalizedValue : normalizedTableName.startsWith(`${normalizedSchema}.`);
3104
+ if (sameSchema) {
3105
+ return normalizedTableName;
3106
+ }
3107
+ throw new Error(
3108
+ `schema option "${normalizedSchema}" conflicts with schema-qualified table "${normalizedTableName}"`
3109
+ );
3110
+ }
3111
+ return `${normalizedSchema}.${normalizedTableName}`;
3112
+ }
3113
+ function conditionToSqlClause(condition) {
3114
+ if (!condition.column) return null;
3115
+ const column = withCast(quoteQualifiedIdentifier(condition.column), condition.column_cast);
3116
+ const value = condition.value;
3117
+ const sqlOperator = {
3118
+ eq: "=",
3119
+ neq: "!=",
3120
+ gt: ">",
3121
+ gte: ">=",
3122
+ lt: "<",
3123
+ lte: "<=",
3124
+ like: "LIKE",
3125
+ ilike: "ILIKE"
3126
+ };
3127
+ switch (condition.operator) {
3128
+ case "eq":
3129
+ case "neq":
3130
+ case "gt":
3131
+ case "gte":
3132
+ case "lt":
3133
+ case "lte":
3134
+ case "like":
3135
+ case "ilike": {
3136
+ if (Array.isArray(value) || value === void 0) return null;
3137
+ const rhs = withCast(toSqlLiteral(value), condition.value_cast);
3138
+ return `${column} ${sqlOperator[condition.operator]} ${rhs}`;
3139
+ }
3140
+ case "is": {
3141
+ if (value === null) return `${column} IS NULL`;
3142
+ if (value === true) return `${column} IS TRUE`;
3143
+ if (value === false) return `${column} IS FALSE`;
3144
+ return null;
3145
+ }
3146
+ case "in": {
3147
+ if (!Array.isArray(value)) return null;
3148
+ if (value.length === 0) return "FALSE";
3149
+ const values = value.map((item) => withCast(toSqlLiteral(item), condition.value_cast));
3150
+ return `${column} IN (${values.join(", ")})`;
3151
+ }
3152
+ default:
3153
+ return null;
3154
+ }
3155
+ }
3156
+ function buildTypedSelectQuery(input) {
3157
+ const whereClauses = [];
3158
+ for (const condition of input.conditions) {
3159
+ const clause = conditionToSqlClause(condition);
3160
+ if (!clause) return null;
3161
+ whereClauses.push(clause);
3162
+ }
3163
+ let limit = input.limit;
3164
+ let offset = input.offset;
3165
+ if (limit === void 0 && input.pageSize !== void 0) {
3166
+ limit = input.pageSize;
3167
+ }
3168
+ if (offset === void 0 && input.pageSize !== void 0 && input.currentPage !== void 0 && input.currentPage > 0) {
3169
+ offset = (input.currentPage - 1) * input.pageSize;
3170
+ }
3171
+ const sqlParts = [
3172
+ `SELECT ${buildSelectColumnsClause(input.columns)} FROM ${quoteQualifiedIdentifier(input.tableName)}`
3173
+ ];
3174
+ if (whereClauses.length > 0) {
3175
+ sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
3176
+ }
3177
+ if (input.order?.field) {
3178
+ const direction = input.order.direction === "descending" ? "DESC" : "ASC";
3179
+ sqlParts.push(`ORDER BY ${quoteQualifiedIdentifier(input.order.field)} ${direction}`);
3180
+ }
3181
+ if (limit !== void 0) {
3182
+ sqlParts.push(`LIMIT ${Math.max(0, Math.trunc(limit))}`);
3183
+ }
3184
+ if (offset !== void 0) {
3185
+ sqlParts.push(`OFFSET ${Math.max(0, Math.trunc(offset))}`);
3186
+ }
3187
+ return `${sqlParts.join(" ")};`;
3188
+ }
3189
+ function sanitizeSqlComment(comment) {
3190
+ return comment.replace(/\*\//g, "* /");
3191
+ }
3192
+ function toSqlJsonLiteral(value) {
3193
+ if (value === void 0) return "DEFAULT";
3194
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
3195
+ return toSqlLiteral(value);
3196
+ }
3197
+ return `'${escapeSqlStringLiteral(JSON.stringify(value))}'::jsonb`;
3198
+ }
3199
+ function conditionToDebugSqlClause(condition) {
3200
+ const exact = conditionToSqlClause(condition);
3201
+ if (exact) return exact;
3202
+ const rawCondition = sanitizeSqlComment(JSON.stringify(condition));
3203
+ if (!condition.column) {
3204
+ return `TRUE /* unsupported condition: ${rawCondition} */`;
3205
+ }
3206
+ const column = withCast(quoteQualifiedIdentifier(condition.column), condition.column_cast);
3207
+ const value = condition.value;
3208
+ const rhs = withCast(toSqlJsonLiteral(value), condition.value_cast);
3209
+ switch (condition.operator) {
3210
+ case "contains":
3211
+ return `${column} @> ${rhs}`;
3212
+ case "containedBy":
3213
+ return `${column} <@ ${rhs}`;
3214
+ case "not":
3215
+ return `TRUE /* NOT expression passthrough: ${rawCondition} */`;
3216
+ case "or":
3217
+ return `TRUE /* OR expression passthrough: ${rawCondition} */`;
3218
+ default:
3219
+ return `TRUE /* unsupported condition: ${rawCondition} */`;
3220
+ }
3221
+ }
3222
+ function resolvePagination(input) {
3223
+ let limit = input.limit;
3224
+ let offset = input.offset;
3225
+ if (limit === void 0 && input.pageSize !== void 0) {
3226
+ limit = input.pageSize;
3227
+ }
3228
+ if (offset === void 0 && input.pageSize !== void 0 && input.currentPage !== void 0 && input.currentPage > 0) {
3229
+ offset = (input.currentPage - 1) * input.pageSize;
3230
+ }
3231
+ return { limit, offset };
3232
+ }
3233
+ function appendOrderLimitOffset(sqlParts, order, limit, offset) {
3234
+ if (order?.field) {
3235
+ const direction = order.direction === "descending" ? "DESC" : "ASC";
3236
+ sqlParts.push(`ORDER BY ${quoteQualifiedIdentifier(order.field)} ${direction}`);
3237
+ }
3238
+ if (limit !== void 0) {
3239
+ sqlParts.push(`LIMIT ${Math.max(0, Math.trunc(limit))}`);
3240
+ }
3241
+ if (offset !== void 0) {
3242
+ sqlParts.push(`OFFSET ${Math.max(0, Math.trunc(offset))}`);
3243
+ }
3244
+ }
3245
+ function buildDebugSelectQuery(input) {
3246
+ const sqlParts = [
3247
+ `SELECT ${buildSelectColumnsClause(input.columns)} FROM ${quoteQualifiedIdentifier(input.tableName)}`
3248
+ ];
3249
+ if (input.conditions?.length) {
3250
+ const whereClauses = input.conditions.map(conditionToDebugSqlClause);
3251
+ sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
3252
+ }
3253
+ const pagination = resolvePagination(input);
3254
+ appendOrderLimitOffset(sqlParts, input.order, pagination.limit, pagination.offset);
3255
+ return `${sqlParts.join(" ")};`;
3256
+ }
3257
+ function resolveDebugTableIdentifier(tableName) {
3258
+ if (!tableName?.trim()) {
3259
+ return '"__unknown_table__"';
3260
+ }
3261
+ return quoteQualifiedIdentifier(tableName);
3262
+ }
3263
+ function buildInsertDebugSql(payload) {
3264
+ const rows = Array.isArray(payload.insert_body) ? payload.insert_body : [payload.insert_body];
3265
+ const columns = [];
3266
+ const seen = /* @__PURE__ */ new Set();
3267
+ for (const row of rows) {
3268
+ for (const column of Object.keys(row)) {
3269
+ if (seen.has(column)) continue;
3270
+ seen.add(column);
3271
+ columns.push(column);
3272
+ }
3273
+ }
3274
+ const sqlParts = [`INSERT INTO ${quoteQualifiedIdentifier(payload.table_name)}`];
3275
+ if (!rows.length || !columns.length) {
3276
+ sqlParts.push("DEFAULT VALUES");
3277
+ if (rows.length > 1) {
3278
+ sqlParts.push(`/* trace: ${rows.length} rows collapsed to DEFAULT VALUES */`);
3279
+ }
3280
+ } else {
3281
+ const valuesClause = rows.map((row) => {
3282
+ const values = columns.map((column) => {
3283
+ const hasColumn = Object.prototype.hasOwnProperty.call(row, column);
3284
+ if (!hasColumn) {
3285
+ return payload.default_to_null ? "NULL" : "DEFAULT";
3286
+ }
3287
+ const rowValue = row[column];
3288
+ return toSqlJsonLiteral(rowValue);
3289
+ });
3290
+ return `(${values.join(", ")})`;
3291
+ }).join(", ");
3292
+ const columnClause = columns.map((column) => quoteQualifiedIdentifier(column)).join(", ");
3293
+ sqlParts.push(`(${columnClause})`);
3294
+ sqlParts.push(`VALUES ${valuesClause}`);
3295
+ }
3296
+ if (payload.on_conflict) {
3297
+ const conflictColumns = Array.isArray(payload.on_conflict) ? payload.on_conflict.map((column) => quoteQualifiedIdentifier(column)).join(", ") : payload.on_conflict;
3298
+ if (payload.update_body && Object.keys(payload.update_body).length > 0) {
3299
+ const assignments = Object.entries(payload.update_body).map(
3300
+ ([column, value]) => `${quoteQualifiedIdentifier(column)} = ${toSqlJsonLiteral(value)}`
3301
+ );
3302
+ sqlParts.push(`ON CONFLICT (${conflictColumns}) DO UPDATE SET ${assignments.join(", ")}`);
3303
+ } else {
3304
+ sqlParts.push(`ON CONFLICT (${conflictColumns}) DO NOTHING`);
3305
+ }
3306
+ }
3307
+ if (payload.columns) {
3308
+ sqlParts.push(`RETURNING ${buildSelectColumnsClause(payload.columns)}`);
3309
+ }
3310
+ return `${sqlParts.join(" ")};`;
3311
+ }
3312
+ function buildUpdateDebugSql(payload) {
3313
+ const set = payload.set ?? payload.data ?? {};
3314
+ const assignments = Object.entries(set).map(
3315
+ ([column, value]) => `${quoteQualifiedIdentifier(column)} = ${toSqlJsonLiteral(value)}`
3316
+ );
3317
+ const sqlParts = [
3318
+ `UPDATE ${resolveDebugTableIdentifier(payload.table_name)} SET ${assignments.length ? assignments.join(", ") : "/* empty set */"}`
3319
+ ];
3320
+ if (payload.conditions?.length) {
3321
+ const whereClauses = payload.conditions.map(conditionToDebugSqlClause);
3322
+ sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
3323
+ }
3324
+ const pagination = resolvePagination({
3325
+ currentPage: payload.current_page,
3326
+ pageSize: payload.page_size
3327
+ });
3328
+ appendOrderLimitOffset(sqlParts, payload.sort_by, pagination.limit, pagination.offset);
3329
+ if (payload.columns) {
3330
+ sqlParts.push(`RETURNING ${buildSelectColumnsClause(payload.columns)}`);
3331
+ }
3332
+ return `${sqlParts.join(" ")};`;
3333
+ }
3334
+ function buildDeleteDebugSql(payload) {
3335
+ const sqlParts = [`DELETE FROM ${quoteQualifiedIdentifier(payload.table_name)}`];
3336
+ const whereClauses = [];
3337
+ if (payload.resource_id) {
3338
+ whereClauses.push(`"resource_id" = ${toSqlLiteral(payload.resource_id)}`);
3339
+ }
3340
+ if (payload.conditions?.length) {
3341
+ whereClauses.push(...payload.conditions.map(conditionToDebugSqlClause));
3342
+ }
3343
+ if (whereClauses.length) {
3344
+ sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
3345
+ }
3346
+ const pagination = resolvePagination({
3347
+ currentPage: payload.current_page,
3348
+ pageSize: payload.page_size
3349
+ });
3350
+ appendOrderLimitOffset(sqlParts, payload.sort_by, pagination.limit, pagination.offset);
3351
+ if (payload.columns) {
3352
+ sqlParts.push(`RETURNING ${buildSelectColumnsClause(payload.columns)}`);
3353
+ }
3354
+ return `${sqlParts.join(" ")};`;
3355
+ }
3356
+ function rpcFilterToSqlClause(filter) {
3357
+ const column = quoteQualifiedIdentifier(filter.column);
3358
+ const value = filter.value;
3359
+ switch (filter.operator) {
3360
+ case "eq":
3361
+ case "neq":
3362
+ case "gt":
3363
+ case "gte":
3364
+ case "lt":
3365
+ case "lte":
3366
+ case "like":
3367
+ case "ilike": {
3368
+ if (value === void 0 || Array.isArray(value)) {
3369
+ return `TRUE /* unsupported rpc filter: ${sanitizeSqlComment(JSON.stringify(filter))} */`;
3370
+ }
3371
+ const operatorMap = {
3372
+ eq: "=",
3373
+ neq: "!=",
3374
+ gt: ">",
3375
+ gte: ">=",
3376
+ lt: "<",
3377
+ lte: "<=",
3378
+ like: "LIKE",
3379
+ ilike: "ILIKE"
3380
+ };
3381
+ return `${column} ${operatorMap[filter.operator]} ${toSqlLiteral(value)}`;
3382
+ }
3383
+ case "is":
3384
+ if (value === null) return `${column} IS NULL`;
3385
+ if (value === true) return `${column} IS TRUE`;
3386
+ if (value === false) return `${column} IS FALSE`;
3387
+ return `TRUE /* unsupported rpc filter: ${sanitizeSqlComment(JSON.stringify(filter))} */`;
3388
+ case "in":
3389
+ if (!Array.isArray(value)) {
3390
+ return `TRUE /* unsupported rpc filter: ${sanitizeSqlComment(JSON.stringify(filter))} */`;
3391
+ }
3392
+ if (value.length === 0) return "FALSE";
3393
+ return `${column} IN (${value.map((item) => toSqlLiteral(item)).join(", ")})`;
3394
+ default:
3395
+ return `TRUE /* unsupported rpc filter: ${sanitizeSqlComment(JSON.stringify(filter))} */`;
3396
+ }
3397
+ }
3398
+ function buildRpcDebugSql(payload) {
3399
+ const argsEntries = payload.args ? Object.entries(payload.args) : [];
3400
+ const argsClause = argsEntries.map(([key, value]) => `${quoteQualifiedIdentifier(key)} => ${toSqlJsonLiteral(value)}`).join(", ");
3401
+ const functionRef = payload.schema ? `${quoteQualifiedIdentifier(payload.schema)}.${quoteQualifiedIdentifier(payload.function)}` : quoteQualifiedIdentifier(payload.function);
3402
+ const sqlParts = [
3403
+ `SELECT ${payload.select ? quoteSelectColumnsExpression(payload.select) : "*"} FROM ${functionRef}(${argsClause})`
3404
+ ];
3405
+ if (payload.filters?.length) {
3406
+ sqlParts.push(`WHERE ${payload.filters.map(rpcFilterToSqlClause).join(" AND ")}`);
3407
+ }
3408
+ if (payload.order?.column) {
3409
+ const direction = payload.order.ascending === false ? "DESC" : "ASC";
3410
+ sqlParts.push(`ORDER BY ${quoteQualifiedIdentifier(payload.order.column)} ${direction}`);
3411
+ }
3412
+ if (payload.limit !== void 0) {
3413
+ sqlParts.push(`LIMIT ${Math.max(0, Math.trunc(payload.limit))}`);
3414
+ }
3415
+ if (payload.offset !== void 0) {
3416
+ sqlParts.push(`OFFSET ${Math.max(0, Math.trunc(payload.offset))}`);
3417
+ }
3418
+ return `${sqlParts.join(" ")};`;
3419
+ }
3420
+ function createFilterMethods(state, addCondition, self) {
3421
+ return {
3422
+ eq(column, value) {
3423
+ const columnName = String(column);
3424
+ if (shouldUseUuidTextComparison(columnName, value)) {
3425
+ addCondition("eq", columnName, value, { columnCast: "text" });
3426
+ } else {
3427
+ addCondition("eq", columnName, value);
3428
+ }
3429
+ return self;
3430
+ },
3431
+ eqCast(column, value, cast) {
3432
+ addCondition("eq", String(column), value, { valueCast: cast });
3433
+ return self;
3434
+ },
3435
+ eqUuid(column, value) {
3436
+ addCondition("eq", String(column), value, { valueCast: "uuid" });
3437
+ return self;
3438
+ },
3439
+ match(filters) {
3440
+ Object.entries(filters).forEach(([column, value]) => {
3441
+ if (value === void 0) {
3442
+ return;
3443
+ }
3444
+ if (shouldUseUuidTextComparison(column, value)) {
3445
+ addCondition("eq", column, value, { columnCast: "text" });
3446
+ } else {
3447
+ addCondition("eq", column, value);
3448
+ }
3449
+ });
3450
+ return self;
3451
+ },
3452
+ range(from, to) {
3453
+ state.offset = from;
3454
+ state.limit = to - from + 1;
3455
+ return self;
3456
+ },
3457
+ limit(count) {
3458
+ state.limit = count;
3459
+ return self;
3460
+ },
3461
+ offset(count) {
3462
+ state.offset = count;
3463
+ return self;
3464
+ },
3465
+ currentPage(value) {
3466
+ state.currentPage = value;
3467
+ return self;
3468
+ },
3469
+ pageSize(value) {
3470
+ state.pageSize = value;
3471
+ return self;
3472
+ },
3473
+ totalPages(value) {
3474
+ state.totalPages = value;
3475
+ return self;
3476
+ },
3477
+ order(column, options) {
3478
+ state.order = {
3479
+ field: String(column),
3480
+ direction: options?.ascending === false ? "descending" : "ascending"
3481
+ };
3482
+ return self;
3483
+ },
3484
+ gt(column, value) {
3485
+ addCondition("gt", String(column), value);
3486
+ return self;
3487
+ },
3488
+ gte(column, value) {
3489
+ addCondition("gte", String(column), value);
3490
+ return self;
3491
+ },
3492
+ lt(column, value) {
3493
+ addCondition("lt", String(column), value);
3494
+ return self;
3495
+ },
3496
+ lte(column, value) {
3497
+ addCondition("lte", String(column), value);
3498
+ return self;
3499
+ },
3500
+ neq(column, value) {
3501
+ addCondition("neq", String(column), value);
3502
+ return self;
3503
+ },
3504
+ like(column, value) {
3505
+ addCondition("like", String(column), value);
3506
+ return self;
3507
+ },
3508
+ ilike(column, value) {
3509
+ addCondition("ilike", String(column), value);
3510
+ return self;
3511
+ },
3512
+ is(column, value) {
3513
+ addCondition("is", String(column), value);
3514
+ return self;
3515
+ },
3516
+ in(column, values) {
3517
+ addCondition("in", String(column), values);
3518
+ return self;
3519
+ },
3520
+ contains(column, values) {
3521
+ addCondition("contains", String(column), values);
3522
+ return self;
3523
+ },
3524
+ containedBy(column, values) {
3525
+ addCondition("containedBy", String(column), values);
3526
+ return self;
3527
+ },
3528
+ not(columnOrExpression, operator, value) {
3529
+ const expression = String(columnOrExpression);
3530
+ if (operator != null && value !== void 0) {
3531
+ addCondition("not", void 0, `${expression}.${operator}.${stringifyFilterValue2(value)}`);
3532
+ } else {
3533
+ addCondition("not", void 0, expression);
3534
+ }
3535
+ return self;
3536
+ },
3537
+ or(expression) {
3538
+ addCondition("or", void 0, expression);
3539
+ return self;
3540
+ }
3541
+ };
3542
+ }
3543
+ function toRpcSelect(columns) {
3544
+ if (!columns) return void 0;
3545
+ return Array.isArray(columns) ? columns.join(",") : columns;
3546
+ }
3547
+ function createRpcFilterMethods(filters, self) {
3548
+ const addFilter = (operator, column, value) => {
3549
+ filters.push({ column, operator, value });
3550
+ };
3551
+ return {
3552
+ eq(column, value) {
3553
+ addFilter("eq", column, value);
3554
+ return self;
3555
+ },
3556
+ neq(column, value) {
3557
+ addFilter("neq", column, value);
3558
+ return self;
3559
+ },
3560
+ gt(column, value) {
3561
+ addFilter("gt", column, value);
3562
+ return self;
3563
+ },
3564
+ gte(column, value) {
3565
+ addFilter("gte", column, value);
3566
+ return self;
3567
+ },
3568
+ lt(column, value) {
3569
+ addFilter("lt", column, value);
3570
+ return self;
3571
+ },
3572
+ lte(column, value) {
3573
+ addFilter("lte", column, value);
3574
+ return self;
3575
+ },
3576
+ like(column, value) {
3577
+ addFilter("like", column, value);
3578
+ return self;
3579
+ },
3580
+ ilike(column, value) {
3581
+ addFilter("ilike", column, value);
3582
+ return self;
3583
+ },
3584
+ is(column, value) {
3585
+ addFilter("is", column, value);
3586
+ return self;
3587
+ },
3588
+ in(column, values) {
3589
+ addFilter("in", column, values);
3590
+ return self;
3591
+ }
3592
+ };
3593
+ }
3594
+ function createRpcBuilder(functionName, args, baseOptions, client, formatGatewayResult, tracer, initialCallsite) {
3595
+ const state = {
3596
+ filters: []
3597
+ };
3598
+ let selectedColumns;
3599
+ let selectedOptions;
3600
+ let promise = null;
3601
+ const callsiteStore = createTraceCallsiteStore(tracer, initialCallsite);
3602
+ const executeRpc = async (columns, options, callsite) => {
3603
+ const mergedOptions = mergeOptions(baseOptions, options);
3604
+ const payload = {
3605
+ function: functionName,
3606
+ args,
3607
+ schema: mergedOptions?.schema,
3608
+ select: toRpcSelect(columns),
3609
+ filters: state.filters.length ? [...state.filters] : void 0,
3610
+ count: mergedOptions?.count,
3611
+ head: mergedOptions?.head,
3612
+ limit: state.limit,
3613
+ offset: state.offset,
3614
+ order: state.order
3615
+ };
3616
+ const endpoint = mergedOptions?.get ? `/rpc/${functionName}` : "/gateway/rpc";
3617
+ const sql = buildRpcDebugSql(payload);
3618
+ return executeWithQueryTrace(
3619
+ tracer,
3620
+ {
3621
+ operation: "rpc",
3622
+ endpoint,
3623
+ functionName,
3624
+ sql,
3625
+ payload,
3626
+ options: mergedOptions
3627
+ },
3628
+ async () => {
3629
+ const response = await client.rpcGateway(payload, mergedOptions);
3630
+ return formatGatewayResult(response, { operation: "rpc" });
3631
+ },
3632
+ callsite
3633
+ );
3634
+ };
3635
+ const run = (columns, options, callsite) => {
3636
+ const payloadColumns = columns ?? selectedColumns;
3637
+ const payloadOptions = options ?? selectedOptions;
3638
+ if (!promise) {
3639
+ promise = executeRpc(payloadColumns, payloadOptions, callsiteStore.resolve(callsite));
3640
+ }
3641
+ return promise;
3642
+ };
3643
+ const builder = {};
3644
+ const filterMethods = createRpcFilterMethods(state.filters, builder);
3645
+ Object.assign(builder, filterMethods, {
3646
+ select(columns = selectedColumns, options) {
3647
+ selectedColumns = columns;
3648
+ selectedOptions = options ?? selectedOptions;
3649
+ return run(columns, options, captureTraceCallsite(tracer));
3650
+ },
3651
+ async single(columns, options) {
3652
+ const result = await run(columns, options, captureTraceCallsite(tracer));
3653
+ return toSingleResult(result);
3654
+ },
3655
+ maybeSingle(columns, options) {
3656
+ return builder.single(columns, options);
3657
+ },
3658
+ order(column, options) {
3659
+ state.order = { column, ascending: options?.ascending ?? true };
3660
+ return builder;
3661
+ },
3662
+ limit(count) {
3663
+ state.limit = count;
3664
+ return builder;
3665
+ },
3666
+ offset(count) {
3667
+ state.offset = count;
3668
+ return builder;
3669
+ },
3670
+ range(from, to) {
3671
+ state.offset = from;
3672
+ state.limit = to - from + 1;
3673
+ return builder;
3674
+ },
3675
+ then(onfulfilled, onrejected) {
3676
+ return run(selectedColumns, selectedOptions).then(onfulfilled, onrejected);
3677
+ },
3678
+ catch(onrejected) {
3679
+ return run(selectedColumns, selectedOptions).catch(onrejected);
3680
+ },
3681
+ finally(onfinally) {
3682
+ return run(selectedColumns, selectedOptions).finally(onfinally);
3683
+ }
3684
+ });
3685
+ return builder;
3686
+ }
3687
+ function createTableBuilder(tableName, client, formatGatewayResult, tracer, experimental) {
3688
+ const state = {
3689
+ conditions: []
3690
+ };
3691
+ const addCondition = (operator, column, value, hints) => {
3692
+ const condition = { operator };
3693
+ if (column) {
3694
+ condition.column = column;
3695
+ if (operator === "eq") {
3696
+ condition.eq_column = column;
3697
+ }
3698
+ }
3699
+ if (value !== void 0) {
3700
+ condition.value = value;
3701
+ if (operator === "eq") {
3702
+ condition.eq_value = value;
3703
+ }
3704
+ }
3705
+ if (hints?.valueCast) {
3706
+ condition.value_cast = hints.valueCast;
3707
+ if (operator === "eq") {
3708
+ condition.eq_value_cast = hints.valueCast;
3709
+ }
3710
+ }
3711
+ if (hints?.columnCast) {
3712
+ condition.column_cast = hints.columnCast;
3713
+ if (operator === "eq") {
3714
+ condition.eq_column_cast = hints.columnCast;
3715
+ }
3716
+ }
3717
+ state.conditions.push(condition);
3718
+ };
3719
+ const snapshotState = () => ({
3720
+ conditions: state.conditions.map((condition) => ({ ...condition })),
3721
+ limit: state.limit,
3722
+ offset: state.offset,
3723
+ order: state.order ? { ...state.order } : void 0,
3724
+ currentPage: state.currentPage,
3725
+ pageSize: state.pageSize,
3726
+ totalPages: state.totalPages
3727
+ });
3728
+ const builder = {};
3729
+ const filterMethods = createFilterMethods(
3730
+ state,
3731
+ addCondition,
3732
+ builder
3733
+ );
3734
+ const runSelect = async (columns = DEFAULT_COLUMNS, options, executionState = snapshotState(), callsite) => {
3735
+ const resolvedTableName = resolveTableNameForCall(tableName, options?.schema);
3736
+ const conditions = executionState.conditions.length ? executionState.conditions.map((condition) => ({ ...condition })) : void 0;
3737
+ const hasTypedEqualityComparison = conditions?.some(
3738
+ (condition) => condition.operator === "eq" && (condition.value_cast !== void 0 || condition.column_cast !== void 0)
3739
+ ) ?? false;
3740
+ if (hasTypedEqualityComparison && !options?.head && !options?.count && conditions) {
3741
+ const query = buildTypedSelectQuery({
3742
+ tableName: resolvedTableName,
3743
+ columns,
3744
+ conditions,
3745
+ limit: executionState.limit,
3746
+ offset: executionState.offset,
3747
+ currentPage: executionState.currentPage,
3748
+ pageSize: executionState.pageSize,
3749
+ order: executionState.order
3750
+ });
3751
+ if (query) {
3752
+ const payload2 = { query };
3753
+ return executeWithQueryTrace(
3754
+ tracer,
3755
+ {
3756
+ operation: "select",
3757
+ endpoint: "/gateway/query",
3758
+ table: resolvedTableName,
3759
+ sql: query,
3760
+ payload: payload2,
3761
+ options
3762
+ },
3763
+ async () => {
3764
+ const queryResponse = await client.queryGateway(payload2, options);
3765
+ return formatGatewayResult(queryResponse, { table: resolvedTableName, operation: "select" });
3766
+ },
3767
+ callsite
3768
+ );
3769
+ }
3770
+ }
3771
+ const payload = {
3772
+ table_name: resolvedTableName,
3773
+ columns,
3774
+ conditions,
3775
+ limit: executionState.limit,
3776
+ offset: executionState.offset,
3777
+ current_page: executionState.currentPage,
3778
+ page_size: executionState.pageSize,
3779
+ total_pages: executionState.totalPages,
3780
+ sort_by: executionState.order,
3781
+ strip_nulls: options?.stripNulls ?? true,
3782
+ count: options?.count,
3783
+ head: options?.head
3784
+ };
3785
+ const sql = buildDebugSelectQuery({
3786
+ tableName: resolvedTableName,
3787
+ columns,
3788
+ conditions,
3789
+ limit: executionState.limit,
3790
+ offset: executionState.offset,
3791
+ currentPage: executionState.currentPage,
3792
+ pageSize: executionState.pageSize,
3793
+ order: executionState.order
3794
+ });
3795
+ return executeWithQueryTrace(
3796
+ tracer,
3797
+ {
3798
+ operation: "select",
3799
+ endpoint: "/gateway/fetch",
3800
+ table: resolvedTableName,
3801
+ sql,
3802
+ payload,
3803
+ options
3804
+ },
3805
+ async () => {
3806
+ const response = await client.fetchGateway(payload, options);
3807
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "select" });
3808
+ },
3809
+ callsite
3810
+ );
3811
+ };
3812
+ const createSelectChain = (columns, options, initialCallsite) => {
3813
+ const chain = {};
3814
+ const callsiteStore = createTraceCallsiteStore(tracer, initialCallsite);
3815
+ const filterMethods2 = createFilterMethods(state, addCondition, chain);
3816
+ Object.assign(chain, filterMethods2, {
3817
+ async single(cols, opts) {
3818
+ const r = await runSelect(
3819
+ cols ?? columns,
3820
+ opts ?? options,
3821
+ snapshotState(),
3822
+ callsiteStore.resolve(captureTraceCallsite(tracer))
3823
+ );
3824
+ return toSingleResult(r);
3825
+ },
3826
+ maybeSingle(cols, opts) {
3827
+ return chain.single(cols, opts);
3828
+ },
3829
+ then(onfulfilled, onrejected) {
3830
+ return runSelect(
3831
+ columns,
3832
+ options,
3833
+ snapshotState(),
3834
+ callsiteStore.resolve()
3835
+ ).then(onfulfilled, onrejected);
3836
+ },
3837
+ catch(onrejected) {
3838
+ return runSelect(columns, options, snapshotState(), callsiteStore.resolve()).catch(
3839
+ onrejected
3840
+ );
3841
+ },
3842
+ finally(onfinally) {
3843
+ return runSelect(columns, options, snapshotState(), callsiteStore.resolve()).finally(
3844
+ onfinally
3845
+ );
3846
+ }
3847
+ });
3848
+ return chain;
3849
+ };
3850
+ Object.assign(builder, filterMethods, {
3851
+ reset() {
3852
+ state.conditions = [];
3853
+ state.limit = void 0;
3854
+ state.offset = void 0;
3855
+ state.order = void 0;
3856
+ state.currentPage = void 0;
3857
+ state.pageSize = void 0;
3858
+ state.totalPages = void 0;
3859
+ return builder;
3860
+ },
3861
+ select(columns = DEFAULT_COLUMNS, options) {
3862
+ return createSelectChain(columns, options, captureTraceCallsite(tracer));
3863
+ },
3864
+ async findMany(options) {
3865
+ const columns = compileSelectShape(options.select);
3866
+ const baseState = snapshotState();
3867
+ const executionState = snapshotState();
3868
+ const callsite = captureTraceCallsite(tracer);
3869
+ const compiledWhere = compileWhere(options.where);
3870
+ if (compiledWhere?.length) {
3871
+ executionState.conditions.push(...compiledWhere);
3872
+ }
3873
+ if (options.orderBy !== void 0) {
3874
+ executionState.order = compileOrderBy(options.orderBy);
3875
+ }
3876
+ if (options.limit !== void 0) {
3877
+ executionState.limit = options.limit;
3878
+ }
3879
+ if (experimental?.findManyAst && canUseFindManyAstTransport(baseState)) {
3880
+ const resolvedTableName = resolveTableNameForCall(tableName, void 0);
3881
+ const payload = {
3882
+ table_name: resolvedTableName,
3883
+ select: options.select
3884
+ };
3885
+ if (options.where !== void 0) {
3886
+ payload.where = options.where;
3887
+ }
3888
+ const astOrder = toFindManyAstOrder(executionState.order);
3889
+ if (astOrder !== void 0) {
3890
+ payload.orderBy = astOrder;
3891
+ }
3892
+ if (executionState.limit !== void 0) {
3893
+ payload.limit = executionState.limit;
3894
+ }
3895
+ const sql = buildDebugSelectQuery({
3896
+ tableName: resolvedTableName,
3897
+ columns,
3898
+ conditions: executionState.conditions,
3899
+ limit: executionState.limit,
3900
+ order: executionState.order
3901
+ });
3902
+ return executeWithQueryTrace(
3903
+ tracer,
3904
+ {
3905
+ operation: "select",
3906
+ endpoint: "/gateway/fetch",
3907
+ table: resolvedTableName,
3908
+ sql,
3909
+ payload
3910
+ },
3911
+ async () => {
3912
+ const response = await client.fetchGateway(
3913
+ payload
3914
+ );
3915
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "select" });
3916
+ },
3917
+ callsite
3918
+ );
3919
+ }
3920
+ return runSelect(
3921
+ columns,
3922
+ void 0,
3923
+ executionState,
3924
+ callsite
3925
+ );
3926
+ },
3927
+ insert(values, options) {
3928
+ const mutationCallsite = captureTraceCallsite(tracer);
3929
+ if (Array.isArray(values)) {
3930
+ const executeInsertMany = async (columns, selectOptions, callsite) => {
3931
+ const mergedOptions = mergeOptions(options, selectOptions);
3932
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
3933
+ const payload = {
3934
+ table_name: resolvedTableName,
3935
+ insert_body: asAthenaJsonObjectArray(values)
3936
+ };
3937
+ if (columns) payload.columns = columns;
3938
+ if (mergedOptions?.count) payload.count = mergedOptions.count;
3939
+ if (mergedOptions?.head) payload.head = mergedOptions.head;
3940
+ if (mergedOptions?.defaultToNull !== void 0) {
3941
+ payload.default_to_null = mergedOptions.defaultToNull;
3942
+ }
3943
+ const sql = buildInsertDebugSql(payload);
3944
+ return executeWithQueryTrace(
3945
+ tracer,
3946
+ {
3947
+ operation: "insert",
3948
+ endpoint: "/gateway/insert",
3949
+ table: resolvedTableName,
3950
+ sql,
3951
+ payload,
3952
+ options: mergedOptions
3953
+ },
3954
+ async () => {
3955
+ const response = await client.insertGateway(payload, mergedOptions);
3956
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "insert" });
3957
+ },
3958
+ callsite
3959
+ );
3960
+ };
3961
+ return createMutationQuery(executeInsertMany, DEFAULT_COLUMNS, tracer, mutationCallsite);
3962
+ }
3963
+ const executeInsertOne = async (columns, selectOptions, callsite) => {
3964
+ const mergedOptions = mergeOptions(options, selectOptions);
3965
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
3966
+ const payload = {
3967
+ table_name: resolvedTableName,
3968
+ insert_body: asAthenaJsonObject(values)
3969
+ };
3970
+ if (columns) payload.columns = columns;
3971
+ if (mergedOptions?.count) payload.count = mergedOptions.count;
3972
+ if (mergedOptions?.head) payload.head = mergedOptions.head;
3973
+ if (mergedOptions?.defaultToNull !== void 0) {
3974
+ payload.default_to_null = mergedOptions.defaultToNull;
3975
+ }
3976
+ const sql = buildInsertDebugSql(payload);
3977
+ return executeWithQueryTrace(
3978
+ tracer,
3979
+ {
3980
+ operation: "insert",
3981
+ endpoint: "/gateway/insert",
3982
+ table: resolvedTableName,
3983
+ sql,
3984
+ payload,
3985
+ options: mergedOptions
3986
+ },
3987
+ async () => {
3988
+ const response = await client.insertGateway(payload, mergedOptions);
3989
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "insert" });
3990
+ },
3991
+ callsite
3992
+ );
3993
+ };
3994
+ return createMutationQuery(executeInsertOne, DEFAULT_COLUMNS, tracer, mutationCallsite);
3995
+ },
3996
+ upsert(values, options) {
3997
+ const mutationCallsite = captureTraceCallsite(tracer);
3998
+ if (Array.isArray(values)) {
3999
+ const executeUpsertMany = async (columns, selectOptions, callsite) => {
4000
+ const mergedOptions = mergeOptions(options, selectOptions);
4001
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
4002
+ const payload = {
4003
+ table_name: resolvedTableName,
4004
+ insert_body: asAthenaJsonObjectArray(values),
4005
+ update_body: options?.updateBody ? asAthenaJsonObject(options.updateBody) : void 0
4006
+ };
4007
+ if (columns) payload.columns = columns;
4008
+ if (options?.onConflict) payload.on_conflict = options.onConflict;
4009
+ if (mergedOptions?.count) payload.count = mergedOptions.count;
4010
+ if (mergedOptions?.head) payload.head = mergedOptions.head;
4011
+ if (mergedOptions?.defaultToNull !== void 0) {
4012
+ payload.default_to_null = mergedOptions.defaultToNull;
4013
+ }
4014
+ const sql = buildInsertDebugSql(payload);
4015
+ return executeWithQueryTrace(
4016
+ tracer,
4017
+ {
4018
+ operation: "upsert",
4019
+ endpoint: "/gateway/insert",
4020
+ table: resolvedTableName,
4021
+ sql,
4022
+ payload,
4023
+ options: mergedOptions
4024
+ },
4025
+ async () => {
4026
+ const response = await client.insertGateway(payload, mergedOptions);
4027
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "insert" });
4028
+ },
4029
+ callsite
4030
+ );
4031
+ };
4032
+ return createMutationQuery(executeUpsertMany, DEFAULT_COLUMNS, tracer, mutationCallsite);
4033
+ }
4034
+ const executeUpsertOne = async (columns, selectOptions, callsite) => {
4035
+ const mergedOptions = mergeOptions(options, selectOptions);
4036
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
4037
+ const payload = {
4038
+ table_name: resolvedTableName,
4039
+ insert_body: asAthenaJsonObject(values),
4040
+ update_body: options?.updateBody ? asAthenaJsonObject(options.updateBody) : void 0
4041
+ };
4042
+ if (columns) payload.columns = columns;
4043
+ if (options?.onConflict) payload.on_conflict = options.onConflict;
4044
+ if (mergedOptions?.count) payload.count = mergedOptions.count;
4045
+ if (mergedOptions?.head) payload.head = mergedOptions.head;
4046
+ if (mergedOptions?.defaultToNull !== void 0) {
4047
+ payload.default_to_null = mergedOptions.defaultToNull;
4048
+ }
4049
+ const sql = buildInsertDebugSql(payload);
4050
+ return executeWithQueryTrace(
4051
+ tracer,
4052
+ {
4053
+ operation: "upsert",
4054
+ endpoint: "/gateway/insert",
4055
+ table: resolvedTableName,
4056
+ sql,
4057
+ payload,
4058
+ options: mergedOptions
4059
+ },
4060
+ async () => {
4061
+ const response = await client.insertGateway(payload, mergedOptions);
4062
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "insert" });
4063
+ },
4064
+ callsite
4065
+ );
4066
+ };
4067
+ return createMutationQuery(executeUpsertOne, DEFAULT_COLUMNS, tracer, mutationCallsite);
4068
+ },
4069
+ update(values, options) {
4070
+ const mutationCallsite = captureTraceCallsite(tracer);
4071
+ const executeUpdate = async (columns, selectOptions, callsite) => {
4072
+ const filters = state.conditions.length ? [...state.conditions] : void 0;
4073
+ const mergedOptions = mergeOptions(options, selectOptions);
4074
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
4075
+ const payload = {
4076
+ table_name: resolvedTableName,
4077
+ set: asAthenaJsonObject(values),
4078
+ conditions: filters,
4079
+ strip_nulls: mergedOptions?.stripNulls ?? true
4080
+ };
4081
+ if (state.order) payload.sort_by = state.order;
4082
+ if (state.currentPage !== void 0) payload.current_page = state.currentPage;
4083
+ if (state.pageSize !== void 0) payload.page_size = state.pageSize;
4084
+ if (state.totalPages !== void 0) payload.total_pages = state.totalPages;
4085
+ if (columns) payload.columns = columns;
4086
+ const sql = buildUpdateDebugSql(payload);
4087
+ return executeWithQueryTrace(
4088
+ tracer,
4089
+ {
4090
+ operation: "update",
4091
+ endpoint: "/gateway/update",
4092
+ table: resolvedTableName,
4093
+ sql,
4094
+ payload,
4095
+ options: mergedOptions
4096
+ },
4097
+ async () => {
4098
+ const response = await client.updateGateway(payload, mergedOptions);
4099
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "update" });
4100
+ },
4101
+ callsite
4102
+ );
4103
+ };
4104
+ const mutation = createMutationQuery(executeUpdate, null, tracer, mutationCallsite);
4105
+ const updateChain = {};
4106
+ const filterMethods2 = createFilterMethods(state, addCondition, updateChain);
4107
+ Object.assign(updateChain, filterMethods2, mutation);
4108
+ return updateChain;
4109
+ },
4110
+ delete(options) {
4111
+ const filters = state.conditions.length ? [...state.conditions] : void 0;
4112
+ const resourceId = options?.resourceId ?? getResourceId(state);
4113
+ if (!resourceId && !filters?.length) {
4114
+ throw new Error('delete requires a resource_id either via eq("resource_id", ...) or options.resourceId');
4115
+ }
4116
+ const mutationCallsite = captureTraceCallsite(tracer);
4117
+ const executeDelete = async (columns, selectOptions, callsite) => {
4118
+ const mergedOptions = mergeOptions(options, selectOptions);
4119
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
4120
+ const payload = {
4121
+ table_name: resolvedTableName,
4122
+ resource_id: resourceId,
4123
+ conditions: filters
4124
+ };
4125
+ if (state.order) payload.sort_by = state.order;
4126
+ if (state.currentPage !== void 0) payload.current_page = state.currentPage;
4127
+ if (state.pageSize !== void 0) payload.page_size = state.pageSize;
4128
+ if (state.totalPages !== void 0) payload.total_pages = state.totalPages;
4129
+ if (columns) payload.columns = columns;
4130
+ const sql = buildDeleteDebugSql(payload);
4131
+ return executeWithQueryTrace(
4132
+ tracer,
4133
+ {
4134
+ operation: "delete",
4135
+ endpoint: "/gateway/delete",
4136
+ table: resolvedTableName,
4137
+ sql,
4138
+ payload,
4139
+ options: mergedOptions
4140
+ },
4141
+ async () => {
4142
+ const response = await client.deleteGateway(payload, mergedOptions);
4143
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "delete" });
4144
+ },
4145
+ callsite
4146
+ );
4147
+ };
4148
+ return createMutationQuery(executeDelete, null, tracer, mutationCallsite);
4149
+ },
4150
+ async single(columns, options) {
4151
+ const response = await runSelect(
4152
+ columns ?? DEFAULT_COLUMNS,
4153
+ options,
4154
+ snapshotState(),
4155
+ captureTraceCallsite(tracer)
4156
+ );
4157
+ return toSingleResult(response);
4158
+ },
4159
+ async maybeSingle(columns, options) {
4160
+ return builder.single(columns, options);
4161
+ }
4162
+ });
4163
+ return builder;
4164
+ }
4165
+ function createQueryBuilder(client, formatGatewayResult, tracer) {
4166
+ return async function query(query, options) {
4167
+ const normalizedQuery = query.trim();
4168
+ if (!normalizedQuery) {
4169
+ throw new Error("query requires a non-empty string");
4170
+ }
4171
+ const payload = { query: normalizedQuery };
4172
+ const callsite = captureTraceCallsite(tracer);
4173
+ return executeWithQueryTrace(
4174
+ tracer,
4175
+ {
4176
+ operation: "query",
4177
+ endpoint: "/gateway/query",
4178
+ sql: normalizedQuery,
4179
+ payload,
4180
+ options
4181
+ },
4182
+ async () => {
4183
+ const response = await client.queryGateway(payload, options);
4184
+ return formatGatewayResult(response, { operation: "query" });
4185
+ },
4186
+ callsite
4187
+ );
4188
+ };
4189
+ }
4190
+ function createClientFromConfig(config) {
4191
+ const gateway = createAthenaGatewayClient({
4192
+ baseUrl: config.baseUrl,
4193
+ apiKey: config.apiKey,
4194
+ client: config.client,
4195
+ backend: config.backend,
4196
+ headers: config.headers
4197
+ });
4198
+ const formatGatewayResult = createResultFormatter(config.experimental);
4199
+ const queryTracer = createQueryTracer(config.experimental);
4200
+ const auth = createAuthClient(config.auth);
4201
+ const from = (table) => createTableBuilder(table, gateway, formatGatewayResult, queryTracer, config.experimental);
4202
+ const rpc = (fn, args, options) => {
4203
+ const normalizedFn = fn.trim();
4204
+ if (!normalizedFn) {
4205
+ throw new Error("rpc requires a function name");
4206
+ }
4207
+ return createRpcBuilder(
4208
+ normalizedFn,
4209
+ args,
4210
+ options,
4211
+ gateway,
4212
+ formatGatewayResult,
4213
+ queryTracer,
4214
+ captureTraceCallsite(queryTracer)
4215
+ );
4216
+ };
4217
+ const query = createQueryBuilder(gateway, formatGatewayResult, queryTracer);
4218
+ const db = createDbModule({ from, rpc, query });
4219
+ return {
4220
+ from,
4221
+ db,
4222
+ rpc,
4223
+ query,
4224
+ auth: auth.auth
4225
+ };
4226
+ }
4227
+ var DEFAULT_BACKEND = { type: "athena" };
4228
+ function toBackendConfig(b) {
4229
+ if (!b) return DEFAULT_BACKEND;
4230
+ return typeof b === "string" ? { type: b } : b;
4231
+ }
4232
+ function mergeAuthClientConfig(current, next) {
4233
+ const merged = {
4234
+ ...current ?? {},
4235
+ ...next
4236
+ };
4237
+ if (current?.headers || next.headers) {
4238
+ merged.headers = {
4239
+ ...current?.headers ?? {},
4240
+ ...next.headers ?? {}
4241
+ };
4242
+ }
4243
+ return merged;
4244
+ }
4245
+ function mergeExperimentalOptions(current, next) {
4246
+ const merged = {
4247
+ ...current ?? {},
4248
+ ...next
4249
+ };
4250
+ if (current?.traceQueries && typeof current.traceQueries === "object" && next.traceQueries && typeof next.traceQueries === "object") {
4251
+ merged.traceQueries = {
4252
+ ...current.traceQueries,
4253
+ ...next.traceQueries
4254
+ };
4255
+ }
4256
+ return merged;
4257
+ }
4258
+ var AthenaClientBuilderImpl = class {
4259
+ baseUrl;
4260
+ apiKey;
4261
+ backendConfig = DEFAULT_BACKEND;
4262
+ clientName;
4263
+ defaultHeaders;
4264
+ authConfig;
4265
+ experimentalOptions;
4266
+ isHealthTrackingEnabled = false;
4267
+ url(url) {
4268
+ this.baseUrl = url;
4269
+ return this;
4270
+ }
4271
+ key(apiKey) {
4272
+ this.apiKey = apiKey;
4273
+ return this;
4274
+ }
4275
+ backend(backend) {
4276
+ this.backendConfig = toBackendConfig(backend);
4277
+ return this;
4278
+ }
4279
+ client(clientName) {
4280
+ this.clientName = clientName;
4281
+ return this;
4282
+ }
4283
+ headers(headers) {
4284
+ this.defaultHeaders = headers;
4285
+ return this;
4286
+ }
4287
+ auth(config) {
4288
+ this.authConfig = mergeAuthClientConfig(this.authConfig, config);
4289
+ return this;
4290
+ }
4291
+ experimental(options) {
4292
+ this.experimentalOptions = mergeExperimentalOptions(this.experimentalOptions, options);
4293
+ return this;
4294
+ }
4295
+ options(options) {
4296
+ if (options.client !== void 0) {
4297
+ this.clientName = options.client;
4298
+ }
4299
+ if (options.backend !== void 0) {
4300
+ this.backendConfig = toBackendConfig(options.backend);
4301
+ }
4302
+ if (options.headers !== void 0) {
4303
+ this.defaultHeaders = {
4304
+ ...this.defaultHeaders ?? {},
4305
+ ...options.headers
4306
+ };
4307
+ }
4308
+ if (options.auth !== void 0) {
4309
+ this.authConfig = mergeAuthClientConfig(this.authConfig, options.auth);
4310
+ }
4311
+ if (options.experimental !== void 0) {
4312
+ this.experimentalOptions = mergeExperimentalOptions(this.experimentalOptions, options.experimental);
4313
+ }
4314
+ return this;
4315
+ }
4316
+ healthTracking(enabled) {
4317
+ this.isHealthTrackingEnabled = enabled;
4318
+ return this;
4319
+ }
4320
+ build() {
4321
+ if (!this.baseUrl || !this.apiKey) {
4322
+ throw new Error("AthenaClient requires url and key; call .url() and .key() before .build()");
4323
+ }
4324
+ return createClientFromConfig({
4325
+ baseUrl: this.baseUrl,
4326
+ apiKey: this.apiKey,
4327
+ client: this.clientName,
4328
+ backend: this.backendConfig,
4329
+ headers: this.defaultHeaders,
4330
+ healthTracking: this.isHealthTrackingEnabled,
4331
+ auth: this.authConfig,
4332
+ experimental: this.experimentalOptions
4333
+ });
4334
+ }
4335
+ };
4336
+ var AthenaClient = class _AthenaClient {
4337
+ /** Create a fluent builder for a strongly-typed Athena SDK client. */
4338
+ static builder() {
4339
+ return new AthenaClientBuilderImpl();
4340
+ }
4341
+ /** Build a client from process environment variables. */
4342
+ static fromEnvironment() {
4343
+ const url = process.env.ATHENA_URL ?? process.env.ATHENA_GATEWAY_URL;
4344
+ const key = process.env.ATHENA_API_KEY ?? process.env.ATHENA_GATEWAY_API_KEY;
4345
+ if (!url || !key) {
4346
+ throw new Error(
4347
+ "ATHENA_URL and ATHENA_API_KEY (or ATHENA_GATEWAY_URL and ATHENA_GATEWAY_API_KEY) are required"
4348
+ );
4349
+ }
4350
+ return _AthenaClient.builder().url(url).key(key).build();
4351
+ }
4352
+ };
4353
+ function createClient(url, apiKey, options) {
4354
+ return createClientFromConfig({
4355
+ baseUrl: url,
4356
+ apiKey,
4357
+ client: options?.client,
4358
+ backend: toBackendConfig(options?.backend),
4359
+ headers: options?.headers,
4360
+ auth: options?.auth,
4361
+ experimental: options?.experimental
4362
+ });
4363
+ }
4364
+
4365
+ // src/gateway/types.ts
4366
+ var Backend = {
4367
+ Athena: { type: "athena" },
4368
+ Postgrest: { type: "postgrest" },
4369
+ PostgreSQL: { type: "postgresql" },
4370
+ ScyllaDB: { type: "scylladb" }
4371
+ };
4372
+
4373
+ // src/schema/definitions.ts
4374
+ function defineModel(input) {
4375
+ return input;
4376
+ }
4377
+ function defineSchema(models) {
4378
+ return { models };
4379
+ }
4380
+ function defineDatabase(schemas) {
4381
+ return { schemas };
4382
+ }
4383
+ function defineRegistry(databases) {
4384
+ return databases;
4385
+ }
4386
+
4387
+ // src/schema/typed-client.ts
4388
+ var TenantHeaderMapper = class {
4389
+ constructor(tenantKeyMap) {
4390
+ this.tenantKeyMap = tenantKeyMap;
4391
+ }
4392
+ apply(baseHeaders, tenantContext) {
4393
+ const headers = {
4394
+ ...baseHeaders ?? {}
4395
+ };
4396
+ for (const [tenantKey, headerName] of Object.entries(this.tenantKeyMap)) {
4397
+ const tenantValue = tenantContext[tenantKey];
4398
+ if (tenantValue === void 0 || tenantValue === null) {
4399
+ continue;
4400
+ }
4401
+ headers[headerName] = String(tenantValue);
4402
+ }
4403
+ return Object.keys(headers).length > 0 ? headers : void 0;
4404
+ }
4405
+ };
4406
+ var RegistryNavigator = class {
4407
+ constructor(registry) {
4408
+ this.registry = registry;
4409
+ }
4410
+ resolveModel(database, schema, model) {
4411
+ const databaseDef = this.registry[database];
4412
+ if (!databaseDef) {
4413
+ throw new Error(`Unknown database "${database}"`);
4414
+ }
4415
+ const schemaDef = databaseDef.schemas[schema];
4416
+ if (!schemaDef) {
4417
+ throw new Error(`Unknown schema "${schema}" in database "${database}"`);
4418
+ }
4419
+ const modelDef = schemaDef.models[model];
4420
+ if (!modelDef) {
4421
+ throw new Error(`Unknown model "${model}" in schema "${schema}"`);
4422
+ }
4423
+ return modelDef;
4424
+ }
4425
+ resolveTableName(schema, model, modelDef) {
4426
+ if (modelDef.meta.tableName) {
4427
+ return modelDef.meta.tableName;
4428
+ }
4429
+ const schemaName = modelDef.meta.schema ?? schema;
4430
+ const modelName = modelDef.meta.model ?? model;
4431
+ return `${schemaName}.${modelName}`;
4432
+ }
4433
+ };
4434
+ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
4435
+ registry;
4436
+ tenantKeyMap;
4437
+ tenantContext;
4438
+ db;
4439
+ baseClient;
4440
+ registryNavigator;
4441
+ tenantHeaderMapper;
4442
+ clientOptions;
4443
+ url;
4444
+ apiKey;
4445
+ constructor(input) {
4446
+ this.registry = input.registry;
4447
+ this.url = input.url;
4448
+ this.apiKey = input.apiKey;
4449
+ const tenantKeyMap = input.options?.tenantKeyMap ?? {};
4450
+ const tenantContext = input.options?.tenantContext ?? {};
4451
+ this.tenantKeyMap = tenantKeyMap;
4452
+ this.tenantContext = tenantContext;
4453
+ this.tenantHeaderMapper = new TenantHeaderMapper(tenantKeyMap);
4454
+ this.registryNavigator = new RegistryNavigator(input.registry);
4455
+ this.clientOptions = {
4456
+ backend: input.options?.backend,
4457
+ client: input.options?.client,
4458
+ headers: input.options?.headers
4459
+ };
4460
+ this.baseClient = createClient(this.url, this.apiKey, {
4461
+ backend: this.clientOptions.backend,
4462
+ client: this.clientOptions.client,
4463
+ headers: this.tenantHeaderMapper.apply(this.clientOptions.headers, tenantContext)
4464
+ });
4465
+ this.db = this.baseClient.db;
4466
+ }
4467
+ from(table) {
4468
+ return this.baseClient.from(table);
4469
+ }
4470
+ rpc(fn, args, options) {
4471
+ return this.baseClient.rpc(fn, args, options);
4472
+ }
4473
+ query(query, options) {
4474
+ return this.baseClient.query(query, options);
4475
+ }
4476
+ withTenantContext(context) {
4477
+ return new _TypedAthenaClientImpl({
4478
+ registry: this.registry,
4479
+ url: this.url,
4480
+ apiKey: this.apiKey,
4481
+ options: {
4482
+ ...this.clientOptions,
4483
+ tenantKeyMap: this.tenantKeyMap,
4484
+ tenantContext: {
4485
+ ...this.tenantContext,
4486
+ ...context ?? {}
4487
+ }
4488
+ }
4489
+ });
4490
+ }
4491
+ fromModel(database, schema, model) {
4492
+ const modelDef = this.registryNavigator.resolveModel(database, schema, model);
4493
+ const tableName = this.registryNavigator.resolveTableName(schema, model, modelDef);
4494
+ return this.baseClient.from(tableName);
4495
+ }
4496
+ };
4497
+ function createTypedClient(registry, url, apiKey, options) {
4498
+ return new TypedAthenaClientImpl({
4499
+ registry,
4500
+ url,
4501
+ apiKey,
4502
+ options
4503
+ });
4504
+ }
4505
+
4506
+ // src/schema/model-form.ts
4507
+ function resolveNullishValue(mode) {
4508
+ if (mode === "undefined") return void 0;
4509
+ if (mode === "null") return null;
4510
+ return "";
4511
+ }
4512
+ function isRecord7(value) {
4513
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4514
+ }
4515
+ function isNullableColumn(model, key) {
4516
+ const nullable = model.meta.nullable;
4517
+ return nullable?.[key] === true;
4518
+ }
4519
+ function toModelFormDefaults(model, values, options) {
4520
+ const source = values;
4521
+ if (!isRecord7(source)) {
4522
+ return {};
4523
+ }
4524
+ const mode = options?.nullishMode ?? "empty-string";
4525
+ const nullishValue = resolveNullishValue(mode);
4526
+ const result = {};
4527
+ for (const [key, value] of Object.entries(source)) {
4528
+ if (value === null && isNullableColumn(model, key)) {
4529
+ result[key] = nullishValue;
4530
+ continue;
4531
+ }
4532
+ result[key] = value;
4533
+ }
4534
+ return result;
4535
+ }
4536
+ function toModelPayload(model, formValues, options) {
4537
+ const emptyStringAsNull = options?.emptyStringAsNull ?? true;
4538
+ const stripUndefined = options?.stripUndefined ?? true;
4539
+ const result = {};
4540
+ for (const [key, rawValue] of Object.entries(formValues)) {
4541
+ if (rawValue === void 0 && stripUndefined) {
4542
+ continue;
4543
+ }
4544
+ if (emptyStringAsNull && rawValue === "" && isNullableColumn(model, key)) {
4545
+ result[key] = null;
4546
+ continue;
4547
+ }
4548
+ result[key] = rawValue;
4549
+ }
4550
+ return result;
4551
+ }
4552
+ function createModelFormAdapter(model) {
4553
+ return {
4554
+ model,
4555
+ toDefaults(values, options) {
4556
+ return toModelFormDefaults(model, values, options);
4557
+ },
4558
+ toInsert(values, options) {
4559
+ return toModelPayload(model, values, options);
4560
+ },
4561
+ toUpdate(values, options) {
4562
+ return toModelPayload(model, values, options);
4563
+ }
4564
+ };
4565
+ }
4566
+
4567
+ // src/generator/schema-selection.ts
4568
+ var DEFAULT_POSTGRES_SCHEMAS = ["public"];
4569
+ function collectSchemaNames(input) {
4570
+ if (!input) {
4571
+ return [];
4572
+ }
4573
+ const values = typeof input === "string" ? [input] : input;
4574
+ return values.flatMap((value) => String(value).split(","));
4575
+ }
4576
+ function normalizeSchemaSelection(input) {
4577
+ const schemas = [];
4578
+ const seen = /* @__PURE__ */ new Set();
4579
+ for (const value of collectSchemaNames(input)) {
4580
+ const schema = value.trim();
4581
+ if (!schema || seen.has(schema)) {
4582
+ continue;
4583
+ }
4584
+ seen.add(schema);
4585
+ schemas.push(schema);
4586
+ }
4587
+ return schemas.length > 0 ? schemas : [...DEFAULT_POSTGRES_SCHEMAS];
4588
+ }
4589
+ function resolveProviderSchemas(providerConfig) {
4590
+ if (providerConfig.kind === "postgres") {
4591
+ return normalizeSchemaSelection(providerConfig.schemas);
4592
+ }
4593
+ return [...DEFAULT_POSTGRES_SCHEMAS];
4594
+ }
4595
+
4596
+ // src/generator/postgres-type-mapping.ts
4597
+ var NUMBER_TYPES = /* @__PURE__ */ new Set([
4598
+ "int2",
4599
+ "int4",
4600
+ "float4",
4601
+ "float8",
4602
+ "smallint",
4603
+ "integer",
4604
+ "real",
4605
+ "double precision"
4606
+ ]);
4607
+ var STRING_NUMERIC_TYPES = /* @__PURE__ */ new Set([
4608
+ "int8",
4609
+ "bigint",
4610
+ "serial8",
4611
+ "bigserial",
4612
+ "numeric",
4613
+ "decimal",
4614
+ "money"
4615
+ ]);
4616
+ var TEXT_TYPES = /* @__PURE__ */ new Set([
4617
+ "char",
4618
+ "bpchar",
4619
+ "varchar",
4620
+ "character varying",
4621
+ "text",
4622
+ "citext",
4623
+ "name",
4624
+ "uuid",
4625
+ "date",
4626
+ "time",
4627
+ "timetz",
4628
+ "timestamp",
4629
+ "timestamptz",
4630
+ "interval",
4631
+ "inet",
4632
+ "cidr",
4633
+ "macaddr",
4634
+ "macaddr8",
4635
+ "point",
4636
+ "line",
4637
+ "lseg",
4638
+ "box",
4639
+ "path",
4640
+ "polygon",
4641
+ "circle",
4642
+ "bit",
4643
+ "varbit",
4644
+ "xml",
4645
+ "tsvector",
4646
+ "tsquery",
4647
+ "jsonpath"
4648
+ ]);
4649
+ function normalizeTypeLabel(column) {
4650
+ const preferred = (column.udtName || column.dataType).toLowerCase().trim();
4651
+ if (column.arrayDimensions > 0 && preferred.startsWith("_")) {
4652
+ return preferred.slice(1);
4653
+ }
4654
+ return preferred;
4655
+ }
4656
+ function wrapArrayType(baseType, depth) {
4657
+ let wrapped = baseType;
4658
+ for (let index = 0; index < depth; index += 1) {
4659
+ wrapped = `Array<${wrapped}>`;
4660
+ }
4661
+ return wrapped;
4662
+ }
4663
+ function resolveScalarType(column) {
4664
+ const label = normalizeTypeLabel(column);
4665
+ if (NUMBER_TYPES.has(label)) {
4666
+ return "number";
4667
+ }
4668
+ if (STRING_NUMERIC_TYPES.has(label)) {
4669
+ return "string";
4670
+ }
4671
+ if (label === "bool" || label === "boolean") {
4672
+ return "boolean";
4673
+ }
4674
+ if (label === "bytea") {
4675
+ return "Buffer";
4676
+ }
4677
+ if (label === "json" || label === "jsonb") {
4678
+ return "Record<string, unknown>";
4679
+ }
4680
+ if (TEXT_TYPES.has(label)) {
4681
+ return "string";
4682
+ }
4683
+ if (label.endsWith("range") || label.endsWith("multirange")) {
4684
+ return "string";
4685
+ }
4686
+ return "unknown";
4687
+ }
4688
+ function resolveKindAwareType(column) {
4689
+ if (column.typeKind === "enum") {
4690
+ const values = column.enumValues ?? [];
4691
+ if (values.length === 0) {
4692
+ return "string";
4693
+ }
4694
+ return values.map((value) => `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`).join(" | ");
4695
+ }
4696
+ if (column.typeKind === "composite") {
4697
+ return "Record<string, unknown>";
4698
+ }
4699
+ if (column.typeKind === "domain" || column.typeKind === "range" || column.typeKind === "multirange") {
4700
+ return "string";
4701
+ }
4702
+ return resolveScalarType(column);
4703
+ }
4704
+ function resolvePostgresColumnType(column) {
4705
+ const baseType = resolveKindAwareType(column);
4706
+ if (!column.arrayDimensions || column.arrayDimensions <= 0) {
4707
+ return baseType;
4708
+ }
4709
+ return wrapArrayType(baseType, column.arrayDimensions);
4710
+ }
4711
+
4712
+ // src/browser.ts
4713
+ function throwBrowserUnsupported(apiName) {
4714
+ throw new Error(
4715
+ `@xylex-group/athena: ${apiName} is not available in browser bundles. Use this API in a Node.js runtime.`
4716
+ );
4717
+ }
4718
+ function createPostgresIntrospectionProvider(options) {
4719
+ return throwBrowserUnsupported("createPostgresIntrospectionProvider");
4720
+ }
4721
+ function defineGeneratorConfig(config) {
4722
+ return config;
4723
+ }
4724
+ function findGeneratorConfigPath(cwd) {
4725
+ return throwBrowserUnsupported("findGeneratorConfigPath");
4726
+ }
4727
+ async function loadGeneratorConfig(options = {}) {
4728
+ return throwBrowserUnsupported("loadGeneratorConfig");
4729
+ }
4730
+ function normalizeGeneratorConfig(input) {
4731
+ return throwBrowserUnsupported("normalizeGeneratorConfig");
4732
+ }
4733
+ function generateArtifactsFromSnapshot(snapshot, config) {
4734
+ return throwBrowserUnsupported("generateArtifactsFromSnapshot");
4735
+ }
4736
+ function resolveGeneratorProvider(providerConfig, experimentalFlags) {
4737
+ return throwBrowserUnsupported("resolveGeneratorProvider");
4738
+ }
4739
+ async function runSchemaGenerator(options = {}) {
4740
+ return throwBrowserUnsupported("runSchemaGenerator");
4741
+ }
4742
+
4743
+ export { AthenaClient, AthenaError, AthenaErrorCategory, AthenaErrorCode, AthenaErrorKind, AthenaGatewayError, Backend, DEFAULT_POSTGRES_SCHEMAS, assertInt, coerceInt, createAuthClient, createAuthReactEmailInput, createClient, createModelFormAdapter, createPostgresIntrospectionProvider, createTypedClient, defineAuthEmailTemplate, defineDatabase, defineGeneratorConfig, defineModel, defineRegistry, defineSchema, findGeneratorConfigPath, generateArtifactsFromSnapshot, identifier, isAthenaGatewayError, isOk, loadGeneratorConfig, normalizeAthenaError, normalizeGeneratorConfig, normalizeSchemaSelection, parseBooleanFlag2 as parseBooleanFlag, renderAthenaReactEmail, requireAffected, requireSuccess, resolveGeneratorProvider, resolvePostgresColumnType, resolveProviderSchemas, runSchemaGenerator, toModelFormDefaults, toModelPayload, unwrap, unwrapOne, unwrapRows, withRetry };
4744
+ //# sourceMappingURL=browser.js.map
4745
+ //# sourceMappingURL=browser.js.map