@xylex-group/athena 2.0.0 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +47 -26
  2. package/dist/browser.cjs +3319 -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 +3276 -0
  7. package/dist/browser.js.map +1 -0
  8. package/dist/cli/index.cjs +599 -119
  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 +600 -120
  13. package/dist/cli/index.js.map +1 -1
  14. package/dist/client-BX0NQqOn.d.ts +435 -0
  15. package/dist/client-dpAp-NZK.d.cts +435 -0
  16. package/dist/cookies.cjs +890 -0
  17. package/dist/cookies.cjs.map +1 -0
  18. package/dist/cookies.d.cts +174 -0
  19. package/dist/cookies.d.ts +174 -0
  20. package/dist/cookies.js +869 -0
  21. package/dist/cookies.js.map +1 -0
  22. package/dist/index.cjs +1378 -1023
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +8 -408
  25. package/dist/index.d.ts +8 -408
  26. package/dist/index.js +1379 -1024
  27. package/dist/index.js.map +1 -1
  28. package/dist/{model-form-CVOtC8jq.d.ts → model-form-2hqmoOUX.d.ts} +2 -2
  29. package/dist/{model-form-hXkvHS_3.d.cts → model-form-Cy-zaO0u.d.cts} +2 -2
  30. package/dist/pipeline-BOPszLsL.d.ts +8 -0
  31. package/dist/pipeline-E3FDbs4W.d.cts +8 -0
  32. package/dist/react.d.cts +4 -4
  33. package/dist/react.d.ts +4 -4
  34. package/dist/{types-BnzoaNRC.d.cts → types-BaBzjwXr.d.cts} +1 -1
  35. package/dist/{types-BnzoaNRC.d.ts → types-BaBzjwXr.d.ts} +1 -1
  36. package/dist/{pipeline-CQgV-Yfo.d.ts → types-CeBPrnGj.d.ts} +2 -7
  37. package/dist/{pipeline-C-cN0ACi.d.cts → types-CpqL-pZx.d.cts} +2 -7
  38. package/package.json +21 -1
@@ -0,0 +1,3276 @@
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 resolveRequestId(headers) {
90
+ return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
91
+ }
92
+ function resolveErrorMessage(payload, fallback) {
93
+ if (isRecord(payload)) {
94
+ const messageCandidates = [payload.error, payload.message, payload.details];
95
+ for (const candidate of messageCandidates) {
96
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
97
+ return candidate.trim();
98
+ }
99
+ }
100
+ }
101
+ if (typeof payload === "string" && payload.trim().length > 0) {
102
+ return payload.trim();
103
+ }
104
+ return fallback;
105
+ }
106
+ function detailsFromError(error) {
107
+ return error.toDetails();
108
+ }
109
+ function toQueryScalar(value) {
110
+ if (value === null || value === void 0) return "null";
111
+ if (typeof value === "boolean") return value ? "true" : "false";
112
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : "null";
113
+ return String(value);
114
+ }
115
+ function toQueryArray(values) {
116
+ return `{${values.map(toQueryScalar).join(",")}}`;
117
+ }
118
+ function toRpcArgumentQueryValue(value) {
119
+ if (Array.isArray(value)) return toQueryArray(value);
120
+ if (value && typeof value === "object") return JSON.stringify(value);
121
+ return toQueryScalar(value);
122
+ }
123
+ function toRpcFilterQueryValue(filter) {
124
+ const value = filter.value;
125
+ switch (filter.operator) {
126
+ case "in": {
127
+ if (!Array.isArray(value)) {
128
+ throw new AthenaGatewayError({
129
+ code: "UNKNOWN_ERROR",
130
+ message: `RPC filter "${filter.column}" with operator "in" requires an array value`,
131
+ status: 0
132
+ });
133
+ }
134
+ return `in.${toQueryArray(value)}`;
135
+ }
136
+ case "is":
137
+ return `is.${toQueryScalar(value)}`;
138
+ case "eq":
139
+ case "neq":
140
+ case "gt":
141
+ case "gte":
142
+ case "lt":
143
+ case "lte":
144
+ case "like":
145
+ case "ilike":
146
+ return `${filter.operator}.${toQueryScalar(value)}`;
147
+ }
148
+ }
149
+ function buildRpcGetEndpoint(payload) {
150
+ const functionName = (payload.function_name ?? payload.function).trim();
151
+ if (!functionName) {
152
+ throw new AthenaGatewayError({
153
+ code: "UNKNOWN_ERROR",
154
+ message: "rpc requires a function name",
155
+ status: 0,
156
+ endpoint: "/gateway/rpc",
157
+ method: "GET"
158
+ });
159
+ }
160
+ const query = new URLSearchParams();
161
+ if (payload.schema) query.set("schema", payload.schema);
162
+ if (payload.select) query.set("select", payload.select);
163
+ if (payload.count) query.set("count", payload.count);
164
+ if (payload.head) query.set("head", "true");
165
+ if (typeof payload.limit === "number") query.set("limit", String(payload.limit));
166
+ if (typeof payload.offset === "number") query.set("offset", String(payload.offset));
167
+ if (payload.order?.column) {
168
+ query.set(
169
+ "order",
170
+ payload.order.ascending === false ? `${payload.order.column}.desc` : payload.order.column
171
+ );
172
+ }
173
+ if (payload.args) {
174
+ for (const [key, value] of Object.entries(payload.args)) {
175
+ query.set(key, toRpcArgumentQueryValue(value));
176
+ }
177
+ }
178
+ if (payload.filters?.length) {
179
+ for (const filter of payload.filters) {
180
+ if (payload.args && Object.prototype.hasOwnProperty.call(payload.args, filter.column)) {
181
+ throw new AthenaGatewayError({
182
+ code: "UNKNOWN_ERROR",
183
+ message: `RPC filter "${filter.column}" conflicts with RPC argument "${filter.column}" in GET mode`,
184
+ status: 0
185
+ });
186
+ }
187
+ query.set(filter.column, toRpcFilterQueryValue(filter));
188
+ }
189
+ }
190
+ const endpoint = `/rpc/${encodeURIComponent(functionName)}`;
191
+ const queryText = query.toString();
192
+ const withQuery = queryText ? `${endpoint}?${queryText}` : endpoint;
193
+ return withQuery;
194
+ }
195
+ function buildHeaders(config, options) {
196
+ const mergedStripNulls = options?.stripNulls ?? true;
197
+ const extraHeaders = {
198
+ ...config.headers ?? {},
199
+ ...options?.headers ?? {}
200
+ };
201
+ const headerClient = extraHeaders["x-athena-client"] ?? extraHeaders["X-Athena-Client"];
202
+ const finalClient = options?.client ?? config.client ?? (typeof headerClient === "string" ? headerClient : void 0) ?? DEFAULT_CLIENT;
203
+ const finalApiKey = options?.apiKey ?? config.apiKey;
204
+ const finalPublishEvent = options?.publishEvent ?? config.publishEvent;
205
+ const headers = {
206
+ "Content-Type": "application/json",
207
+ "X-Athena-Sdk": SDK_HEADER_VALUE
208
+ };
209
+ if (options?.userId ?? config.userId) {
210
+ headers["X-User-Id"] = options?.userId ?? config.userId ?? "";
211
+ }
212
+ if (options?.organizationId ?? config.organizationId) {
213
+ headers["X-Organization-Id"] = options?.organizationId ?? config.organizationId ?? "";
214
+ }
215
+ if (finalClient) {
216
+ headers["X-Athena-Client"] = finalClient;
217
+ }
218
+ const finalBackend = options?.backend ?? config.backend;
219
+ if (finalBackend) {
220
+ const type = typeof finalBackend === "string" ? finalBackend : finalBackend.type;
221
+ if (type) headers["X-Backend-Type"] = type;
222
+ }
223
+ if (typeof mergedStripNulls === "boolean") {
224
+ headers["X-Strip-Nulls"] = mergedStripNulls ? "true" : "false";
225
+ }
226
+ if (finalPublishEvent) {
227
+ headers["X-Publish-Event"] = finalPublishEvent;
228
+ }
229
+ if (finalApiKey) {
230
+ headers["apikey"] = finalApiKey;
231
+ headers["x-api-key"] = headers["x-api-key"] ?? finalApiKey;
232
+ }
233
+ const athenaClientKeys = ["x-athena-client", "X-Athena-Client"];
234
+ Object.entries(extraHeaders).forEach(([key, value]) => {
235
+ if (athenaClientKeys.includes(key)) return;
236
+ const normalized = normalizeHeaderValue(value);
237
+ if (normalized) {
238
+ headers[key] = normalized;
239
+ }
240
+ });
241
+ return headers;
242
+ }
243
+ async function callAthena(config, endpoint, method, payload, options) {
244
+ const baseUrl = (options?.baseUrl ?? config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
245
+ const url = `${baseUrl}${endpoint}`;
246
+ const headers = buildHeaders(config, options);
247
+ try {
248
+ const requestInit = {
249
+ method,
250
+ headers
251
+ };
252
+ if (method !== "GET") {
253
+ requestInit.body = JSON.stringify(payload);
254
+ }
255
+ const response = await fetch(url, requestInit);
256
+ const rawText = await response.text();
257
+ const requestId = resolveRequestId(response.headers);
258
+ const parsedBody = parseResponseBody(
259
+ rawText ?? "",
260
+ response.headers.get("content-type")
261
+ );
262
+ if (parsedBody.parseFailed) {
263
+ const invalidJsonError = new AthenaGatewayError({
264
+ code: "INVALID_JSON",
265
+ message: "Gateway returned malformed JSON",
266
+ status: response.status,
267
+ endpoint,
268
+ method,
269
+ requestId,
270
+ hint: "Verify the gateway response body is valid JSON.",
271
+ cause: rawText.slice(0, 300)
272
+ });
273
+ return {
274
+ ok: false,
275
+ status: response.status,
276
+ data: null,
277
+ error: invalidJsonError.message,
278
+ errorDetails: detailsFromError(invalidJsonError),
279
+ raw: parsedBody.parsed
280
+ };
281
+ }
282
+ const parsed = parsedBody.parsed;
283
+ const parsedPayload = isRecord(parsed) ? parsed : null;
284
+ if (!response.ok) {
285
+ const httpError = new AthenaGatewayError({
286
+ code: "HTTP_ERROR",
287
+ message: resolveErrorMessage(
288
+ parsed,
289
+ `Athena gateway ${method} ${endpoint} failed with status ${response.status}`
290
+ ),
291
+ status: response.status,
292
+ endpoint,
293
+ method,
294
+ requestId
295
+ });
296
+ return {
297
+ ok: false,
298
+ status: response.status,
299
+ data: null,
300
+ error: httpError.message,
301
+ errorDetails: detailsFromError(httpError),
302
+ raw: parsed
303
+ };
304
+ }
305
+ const payloadData = parsedPayload && "data" in parsedPayload ? parsedPayload.data : parsed;
306
+ const payloadCount = parsedPayload && "count" in parsedPayload ? typeof parsedPayload.count === "number" || parsedPayload.count === null ? parsedPayload.count : void 0 : void 0;
307
+ return {
308
+ ok: true,
309
+ status: response.status,
310
+ data: payloadData ?? null,
311
+ count: payloadCount,
312
+ error: void 0,
313
+ errorDetails: null,
314
+ raw: parsed
315
+ };
316
+ } catch (callError) {
317
+ const message = callError instanceof Error ? callError.message : String(callError);
318
+ const networkError = new AthenaGatewayError({
319
+ code: "NETWORK_ERROR",
320
+ message: `Network error while calling ${method} ${endpoint}: ${message}`,
321
+ endpoint,
322
+ method,
323
+ cause: message,
324
+ hint: "Check gateway URL, DNS, and network reachability."
325
+ });
326
+ return {
327
+ ok: false,
328
+ status: 0,
329
+ data: null,
330
+ error: networkError.message,
331
+ errorDetails: detailsFromError(networkError),
332
+ raw: null
333
+ };
334
+ }
335
+ }
336
+ function createAthenaGatewayClient(config = {}) {
337
+ return {
338
+ baseUrl: (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, ""),
339
+ buildHeaders(options) {
340
+ return buildHeaders(config, options);
341
+ },
342
+ fetchGateway(payload, options) {
343
+ return callAthena(config, "/gateway/fetch", "POST", payload, options);
344
+ },
345
+ insertGateway(payload, options) {
346
+ return callAthena(config, "/gateway/insert", "PUT", payload, options);
347
+ },
348
+ updateGateway(payload, options) {
349
+ return callAthena(config, "/gateway/update", "POST", payload, options);
350
+ },
351
+ deleteGateway(payload, options) {
352
+ return callAthena(config, "/gateway/delete", "DELETE", payload, options);
353
+ },
354
+ rpcGateway(payload, options) {
355
+ if (options?.get) {
356
+ const endpoint = buildRpcGetEndpoint(payload);
357
+ return callAthena(config, endpoint, "GET", null, options);
358
+ }
359
+ return callAthena(config, "/gateway/rpc", "POST", payload, options);
360
+ },
361
+ queryGateway(payload, options) {
362
+ return callAthena(config, "/gateway/query", "POST", payload, options);
363
+ }
364
+ };
365
+ }
366
+
367
+ // src/sql-identifiers.ts
368
+ var SIMPLE_IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
369
+ var COMPOSITE_IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;
370
+ var ALIAS_PATTERN = /^([A-Za-z_][A-Za-z0-9_.]*)\s+(?:as\s+)?([A-Za-z_][A-Za-z0-9_]*)$/i;
371
+ function quoteIdentifierSegment(identifier2) {
372
+ return `"${identifier2.replace(/"/g, '""')}"`;
373
+ }
374
+ function quoteQualifiedIdentifier(identifier2) {
375
+ return identifier2.split(".").map((segment) => quoteIdentifierSegment(segment)).join(".");
376
+ }
377
+ function quoteSelectToken(token) {
378
+ if (token === "*") return token;
379
+ if (COMPOSITE_IDENTIFIER_PATTERN.test(token)) {
380
+ return quoteQualifiedIdentifier(token);
381
+ }
382
+ const aliasMatch = ALIAS_PATTERN.exec(token);
383
+ if (!aliasMatch) {
384
+ return token;
385
+ }
386
+ const [, baseIdentifier, aliasIdentifier] = aliasMatch;
387
+ if (!COMPOSITE_IDENTIFIER_PATTERN.test(baseIdentifier) || !SIMPLE_IDENTIFIER_PATTERN.test(aliasIdentifier)) {
388
+ return token;
389
+ }
390
+ return `${quoteQualifiedIdentifier(baseIdentifier)} AS ${quoteIdentifierSegment(aliasIdentifier)}`;
391
+ }
392
+ function canAutoQuoteToken(token) {
393
+ if (token === "*") return true;
394
+ if (COMPOSITE_IDENTIFIER_PATTERN.test(token)) return true;
395
+ const aliasMatch = ALIAS_PATTERN.exec(token);
396
+ if (!aliasMatch) return false;
397
+ const [, baseIdentifier, aliasIdentifier] = aliasMatch;
398
+ return COMPOSITE_IDENTIFIER_PATTERN.test(baseIdentifier) && SIMPLE_IDENTIFIER_PATTERN.test(aliasIdentifier);
399
+ }
400
+ function splitTopLevelCommaSeparated(input) {
401
+ const parts = [];
402
+ let buffer = "";
403
+ let singleQuoted = false;
404
+ let doubleQuoted = false;
405
+ let depth = 0;
406
+ for (let index = 0; index < input.length; index += 1) {
407
+ const char = input[index];
408
+ const next = index + 1 < input.length ? input[index + 1] : "";
409
+ if (singleQuoted) {
410
+ buffer += char;
411
+ if (char === "'" && next === "'") {
412
+ buffer += next;
413
+ index += 1;
414
+ continue;
415
+ }
416
+ if (char === "'") {
417
+ singleQuoted = false;
418
+ }
419
+ continue;
420
+ }
421
+ if (doubleQuoted) {
422
+ buffer += char;
423
+ if (char === '"' && next === '"') {
424
+ buffer += next;
425
+ index += 1;
426
+ continue;
427
+ }
428
+ if (char === '"') {
429
+ doubleQuoted = false;
430
+ }
431
+ continue;
432
+ }
433
+ if (char === "'") {
434
+ singleQuoted = true;
435
+ buffer += char;
436
+ continue;
437
+ }
438
+ if (char === '"') {
439
+ doubleQuoted = true;
440
+ buffer += char;
441
+ continue;
442
+ }
443
+ if (char === "(") {
444
+ depth += 1;
445
+ buffer += char;
446
+ continue;
447
+ }
448
+ if (char === ")") {
449
+ depth -= 1;
450
+ if (depth < 0) return null;
451
+ buffer += char;
452
+ continue;
453
+ }
454
+ if (char === "," && depth === 0) {
455
+ parts.push(buffer.trim());
456
+ buffer = "";
457
+ continue;
458
+ }
459
+ buffer += char;
460
+ }
461
+ if (singleQuoted || doubleQuoted || depth !== 0) {
462
+ return null;
463
+ }
464
+ if (buffer.trim().length > 0) {
465
+ parts.push(buffer.trim());
466
+ }
467
+ return parts;
468
+ }
469
+ function quoteSelectColumnsExpression(columns) {
470
+ const trimmed = columns.trim();
471
+ if (!trimmed || trimmed === "*") return trimmed || "*";
472
+ const tokens = splitTopLevelCommaSeparated(trimmed);
473
+ if (!tokens || tokens.length === 0) {
474
+ return trimmed;
475
+ }
476
+ if (!tokens.every(canAutoQuoteToken)) {
477
+ return trimmed;
478
+ }
479
+ return tokens.map(quoteSelectToken).join(", ");
480
+ }
481
+ var SqlIdentifierPath = class {
482
+ segments;
483
+ constructor(segments) {
484
+ this.segments = segments;
485
+ }
486
+ toSql() {
487
+ return this.segments.map(quoteIdentifierSegment).join(".");
488
+ }
489
+ toString() {
490
+ return this.toSql();
491
+ }
492
+ };
493
+ function identifier(...segments) {
494
+ const expandedSegments = segments.flatMap((segment) => segment.split(".")).map((segment) => segment.trim()).filter((segment) => segment.length > 0);
495
+ return new SqlIdentifierPath(expandedSegments);
496
+ }
497
+
498
+ // src/auth/client.ts
499
+ var DEFAULT_AUTH_BASE_URL = "http://localhost:3001/api/auth";
500
+ var FALLBACK_SDK_VERSION2 = "1.0.0";
501
+ var SDK_NAME2 = "xylex-group/athena-auth";
502
+ var SDK_VERSION2 = typeof process !== "undefined" && process?.env?.npm_package_version ? process.env.npm_package_version : FALLBACK_SDK_VERSION2;
503
+ var SDK_HEADER_VALUE2 = `${SDK_NAME2} ${SDK_VERSION2}`;
504
+ function normalizeBaseUrl(baseUrl) {
505
+ return (baseUrl ?? DEFAULT_AUTH_BASE_URL).replace(/\/$/, "");
506
+ }
507
+ function isRecord2(value) {
508
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
509
+ }
510
+ function normalizeHeaderValue2(value) {
511
+ return value ? value : void 0;
512
+ }
513
+ function parseResponseBody2(rawText, contentType) {
514
+ if (!rawText) {
515
+ return { parsed: null, parseFailed: false };
516
+ }
517
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
518
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
519
+ if (!looksJson) {
520
+ return { parsed: rawText, parseFailed: false };
521
+ }
522
+ try {
523
+ return { parsed: JSON.parse(rawText), parseFailed: false };
524
+ } catch {
525
+ return { parsed: rawText, parseFailed: true };
526
+ }
527
+ }
528
+ function resolveRequestId2(headers) {
529
+ return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
530
+ }
531
+ function resolveErrorMessage2(payload, fallback) {
532
+ if (isRecord2(payload)) {
533
+ const messageCandidates = [payload.error, payload.message, payload.details];
534
+ for (const candidate of messageCandidates) {
535
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
536
+ return candidate.trim();
537
+ }
538
+ }
539
+ }
540
+ if (typeof payload === "string" && payload.trim().length > 0) {
541
+ return payload.trim();
542
+ }
543
+ return fallback;
544
+ }
545
+ function toErrorDetails(input) {
546
+ return {
547
+ code: input.code,
548
+ message: input.message,
549
+ status: input.status,
550
+ endpoint: input.endpoint,
551
+ method: input.method,
552
+ requestId: input.requestId,
553
+ hint: input.hint,
554
+ cause: input.cause
555
+ };
556
+ }
557
+ function mergeCallOptions(base, override) {
558
+ if (!base && !override) return void 0;
559
+ return {
560
+ ...base,
561
+ ...override,
562
+ headers: {
563
+ ...base?.headers ?? {},
564
+ ...override?.headers ?? {}
565
+ }
566
+ };
567
+ }
568
+ function extractFetchOptions(input) {
569
+ if (!input) {
570
+ return {
571
+ payload: void 0,
572
+ fetchOptions: void 0
573
+ };
574
+ }
575
+ const { fetchOptions, ...rest } = input;
576
+ const hasPayloadKeys = Object.keys(rest).length > 0;
577
+ return {
578
+ payload: hasPayloadKeys ? rest : void 0,
579
+ fetchOptions
580
+ };
581
+ }
582
+ function buildHeaders2(config, options) {
583
+ const headers = {
584
+ "Content-Type": "application/json",
585
+ "X-Athena-Sdk": SDK_HEADER_VALUE2
586
+ };
587
+ const apiKey = options?.apiKey ?? config.apiKey;
588
+ if (apiKey) {
589
+ headers.apikey = apiKey;
590
+ headers["x-api-key"] = apiKey;
591
+ }
592
+ const bearerToken = options?.bearerToken ?? config.bearerToken;
593
+ if (bearerToken) {
594
+ headers.Authorization = `Bearer ${bearerToken}`;
595
+ }
596
+ const mergedExtraHeaders = {
597
+ ...config.headers ?? {},
598
+ ...options?.headers ?? {}
599
+ };
600
+ Object.entries(mergedExtraHeaders).forEach(([key, value]) => {
601
+ const normalized = normalizeHeaderValue2(value);
602
+ if (normalized) {
603
+ headers[key] = normalized;
604
+ }
605
+ });
606
+ return headers;
607
+ }
608
+ function appendQueryParam(searchParams, key, value) {
609
+ if (value === void 0 || value === null) return;
610
+ if (Array.isArray(value)) {
611
+ value.forEach((item) => {
612
+ searchParams.append(key, String(item));
613
+ });
614
+ return;
615
+ }
616
+ searchParams.append(key, String(value));
617
+ }
618
+ function buildRequestUrl(baseUrl, endpoint, query) {
619
+ const url = `${baseUrl}${endpoint}`;
620
+ if (!query || Object.keys(query).length === 0) return url;
621
+ const searchParams = new URLSearchParams();
622
+ Object.entries(query).forEach(([key, value]) => appendQueryParam(searchParams, key, value));
623
+ const queryText = searchParams.toString();
624
+ return queryText ? `${url}?${queryText}` : url;
625
+ }
626
+ function inferDefaultMethod(endpoint) {
627
+ if (endpoint.startsWith("/reset-password/")) {
628
+ return "GET";
629
+ }
630
+ switch (endpoint) {
631
+ case "/get-session":
632
+ case "/list-sessions":
633
+ case "/verify-email":
634
+ case "/change-email/verify":
635
+ case "/delete-user/verify":
636
+ case "/email-list":
637
+ case "/email/list":
638
+ case "/delete-user/callback":
639
+ case "/list-accounts":
640
+ case "/passkey/generate-register-options":
641
+ case "/passkey/list-user-passkeys":
642
+ case "/.well-known/webauthn":
643
+ case "/admin/list-users":
644
+ case "/admin/athena-client/list":
645
+ case "/admin/audit-log/list":
646
+ case "/admin/email/get":
647
+ case "/admin/email-failure/list":
648
+ case "/admin/email-failure/get":
649
+ case "/admin/email-template/get":
650
+ case "/admin/email-template/list":
651
+ case "/admin/email/list":
652
+ case "/api-key/get":
653
+ case "/api-key/list":
654
+ case "/organization/get-full-organization":
655
+ case "/organization/list":
656
+ case "/organization/get-invitation":
657
+ case "/organization/list-invitations":
658
+ case "/organization/list-user-invitations":
659
+ case "/organization/list-members":
660
+ case "/organization/get-active-member":
661
+ case "/health":
662
+ case "/ok":
663
+ case "/error":
664
+ return "GET";
665
+ default:
666
+ return "POST";
667
+ }
668
+ }
669
+ async function callAuthEndpoint(config, context, body, query, options) {
670
+ const baseUrl = normalizeBaseUrl(options?.baseUrl ?? config.baseUrl);
671
+ const url = buildRequestUrl(baseUrl, context.endpoint, query);
672
+ const headers = buildHeaders2(config, options);
673
+ const credentials = options?.credentials ?? config.credentials ?? "include";
674
+ const requestInit = {
675
+ method: context.method,
676
+ headers,
677
+ credentials,
678
+ signal: options?.signal
679
+ };
680
+ if (context.method !== "GET") {
681
+ requestInit.body = JSON.stringify(body ?? {});
682
+ }
683
+ const fetcher = config.fetch ?? globalThis.fetch;
684
+ if (!fetcher) {
685
+ const details = toErrorDetails({
686
+ code: "UNKNOWN_ERROR",
687
+ message: "No fetch implementation available for auth client",
688
+ status: 0,
689
+ endpoint: context.endpoint,
690
+ method: context.method,
691
+ hint: "Use Node 18+ or provide `fetch` via createClient(..., { auth: { fetch } }) or createAuthClient({ fetch })"
692
+ });
693
+ return {
694
+ ok: false,
695
+ status: 0,
696
+ data: null,
697
+ error: details.message,
698
+ errorDetails: details,
699
+ raw: null
700
+ };
701
+ }
702
+ try {
703
+ const response = await fetcher(url, requestInit);
704
+ const rawText = await response.text();
705
+ const requestId = resolveRequestId2(response.headers);
706
+ const parsedBody = parseResponseBody2(rawText ?? "", response.headers.get("content-type"));
707
+ if (parsedBody.parseFailed) {
708
+ const details = toErrorDetails({
709
+ code: "INVALID_JSON",
710
+ message: "Auth server returned malformed JSON",
711
+ status: response.status,
712
+ endpoint: context.endpoint,
713
+ method: context.method,
714
+ requestId,
715
+ hint: "Verify the auth endpoint response body is valid JSON.",
716
+ cause: rawText.slice(0, 300)
717
+ });
718
+ return {
719
+ ok: false,
720
+ status: response.status,
721
+ data: null,
722
+ error: details.message,
723
+ errorDetails: details,
724
+ raw: parsedBody.parsed
725
+ };
726
+ }
727
+ const parsed = parsedBody.parsed;
728
+ if (!response.ok) {
729
+ const details = toErrorDetails({
730
+ code: "HTTP_ERROR",
731
+ message: resolveErrorMessage2(
732
+ parsed,
733
+ `Auth endpoint ${context.method} ${context.endpoint} failed with status ${response.status}`
734
+ ),
735
+ status: response.status,
736
+ endpoint: context.endpoint,
737
+ method: context.method,
738
+ requestId
739
+ });
740
+ return {
741
+ ok: false,
742
+ status: response.status,
743
+ data: null,
744
+ error: details.message,
745
+ errorDetails: details,
746
+ raw: parsed
747
+ };
748
+ }
749
+ return {
750
+ ok: true,
751
+ status: response.status,
752
+ data: parsed ?? null,
753
+ error: null,
754
+ errorDetails: null,
755
+ raw: parsed
756
+ };
757
+ } catch (callError) {
758
+ const message = callError instanceof Error ? callError.message : String(callError);
759
+ const details = toErrorDetails({
760
+ code: "NETWORK_ERROR",
761
+ message: `Network error while calling ${context.method} ${context.endpoint}: ${message}`,
762
+ status: 0,
763
+ endpoint: context.endpoint,
764
+ method: context.method,
765
+ cause: message,
766
+ hint: "Check auth server URL, DNS, and network reachability."
767
+ });
768
+ return {
769
+ ok: false,
770
+ status: 0,
771
+ data: null,
772
+ error: details.message,
773
+ errorDetails: details,
774
+ raw: null
775
+ };
776
+ }
777
+ }
778
+ function executePostWithCompatibleInput(config, context, input, options) {
779
+ const { payload, fetchOptions } = extractFetchOptions(input);
780
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
781
+ return callAuthEndpoint(config, context, payload ?? {}, void 0, mergedOptions);
782
+ }
783
+ function executePostWithOptionalInput(config, context, input, options) {
784
+ const { fetchOptions } = extractFetchOptions(input);
785
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
786
+ return callAuthEndpoint(config, context, {}, void 0, mergedOptions);
787
+ }
788
+ function executeGetWithCompatibleInput(config, context, input, options) {
789
+ const { fetchOptions } = extractFetchOptions(input);
790
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
791
+ return callAuthEndpoint(config, context, void 0, void 0, mergedOptions);
792
+ }
793
+ function executeGetWithQueryCompatibleInput(config, context, input, options) {
794
+ const { payload, fetchOptions } = extractFetchOptions(input);
795
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
796
+ const query = payload?.query;
797
+ return callAuthEndpoint(
798
+ config,
799
+ context,
800
+ void 0,
801
+ query,
802
+ mergedOptions
803
+ );
804
+ }
805
+ function createAuthClient(config = {}) {
806
+ const normalizedBaseUrl = normalizeBaseUrl(config.baseUrl);
807
+ const resolvedConfig = {
808
+ ...config,
809
+ baseUrl: normalizedBaseUrl
810
+ };
811
+ const request = (input, options) => {
812
+ const method = input.method ?? (input.body !== void 0 ? "POST" : inferDefaultMethod(input.endpoint));
813
+ const mergedOptions = mergeCallOptions(input.fetchOptions, options);
814
+ return callAuthEndpoint(
815
+ resolvedConfig,
816
+ { endpoint: input.endpoint, method },
817
+ input.body,
818
+ input.query,
819
+ mergedOptions
820
+ );
821
+ };
822
+ const postGeneric = (endpoint, input, options) => {
823
+ const { payload, fetchOptions } = extractFetchOptions(input);
824
+ return request(
825
+ {
826
+ endpoint,
827
+ method: "POST",
828
+ body: payload ?? {},
829
+ fetchOptions
830
+ },
831
+ options
832
+ );
833
+ };
834
+ const getGeneric = (endpoint, input, options) => {
835
+ const { fetchOptions } = extractFetchOptions(input);
836
+ return request(
837
+ {
838
+ endpoint,
839
+ method: "GET",
840
+ fetchOptions
841
+ },
842
+ options
843
+ );
844
+ };
845
+ const getWithQuery = (endpoint, input, options) => {
846
+ const { payload, fetchOptions } = extractFetchOptions(input);
847
+ const query = payload?.query;
848
+ return request(
849
+ {
850
+ endpoint,
851
+ method: "GET",
852
+ query,
853
+ fetchOptions
854
+ },
855
+ options
856
+ );
857
+ };
858
+ const listUserEmailsWithFallback = async (input, options) => {
859
+ const primary = await getWithQuery(
860
+ "/email/list",
861
+ input,
862
+ options
863
+ );
864
+ if (primary.ok || primary.status !== 404 || primary.errorDetails?.code !== "HTTP_ERROR") {
865
+ return primary;
866
+ }
867
+ return getWithQuery(
868
+ "/email-list",
869
+ input,
870
+ options
871
+ );
872
+ };
873
+ const healthWithFallback = async (input, options) => {
874
+ const primary = await getGeneric("/health", input, options);
875
+ if (primary.ok || primary.status !== 404 || primary.errorDetails?.code !== "HTTP_ERROR") {
876
+ return primary;
877
+ }
878
+ const fallback = await getGeneric("/ok", input, options);
879
+ if (!fallback.ok) {
880
+ return {
881
+ ...fallback,
882
+ data: null
883
+ };
884
+ }
885
+ const fallbackStatus = isRecord2(fallback.data) && typeof fallback.data.ok === "boolean" ? fallback.data.ok ? "ok" : "error" : "ok";
886
+ return {
887
+ ...fallback,
888
+ data: {
889
+ status: fallbackStatus
890
+ }
891
+ };
892
+ };
893
+ const signOut = (input, options) => executePostWithOptionalInput(
894
+ resolvedConfig,
895
+ { endpoint: "/sign-out", method: "POST" },
896
+ input,
897
+ options
898
+ );
899
+ const revokeSessions = (input, options) => executePostWithOptionalInput(
900
+ resolvedConfig,
901
+ { endpoint: "/revoke-sessions", method: "POST" },
902
+ input,
903
+ options
904
+ );
905
+ const revokeOtherSessions = (input, options) => executePostWithOptionalInput(
906
+ resolvedConfig,
907
+ { endpoint: "/revoke-other-sessions", method: "POST" },
908
+ input,
909
+ options
910
+ );
911
+ const revokeSession = (input, options) => executePostWithCompatibleInput(
912
+ resolvedConfig,
913
+ { endpoint: "/revoke-session", method: "POST" },
914
+ input,
915
+ options
916
+ );
917
+ const deleteUser = (input, options) => {
918
+ const { payload, fetchOptions } = extractFetchOptions(input);
919
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
920
+ return callAuthEndpoint(
921
+ resolvedConfig,
922
+ { endpoint: "/delete-user", method: "POST" },
923
+ payload ?? {},
924
+ void 0,
925
+ mergedOptions
926
+ );
927
+ };
928
+ const deleteUserCallback = (input, options) => {
929
+ const { payload, fetchOptions } = extractFetchOptions(input);
930
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
931
+ const query = payload ?? {};
932
+ return callAuthEndpoint(
933
+ resolvedConfig,
934
+ { endpoint: "/delete-user/callback", method: "GET" },
935
+ void 0,
936
+ {
937
+ token: query.token,
938
+ callbackURL: query.callbackURL
939
+ },
940
+ mergedOptions
941
+ );
942
+ };
943
+ const resolveResetPasswordToken = (input, options) => {
944
+ const { payload, fetchOptions } = extractFetchOptions(input);
945
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
946
+ const query = payload;
947
+ const token = query?.token?.trim();
948
+ if (!token) {
949
+ throw new Error("resolveResetPasswordToken requires a non-empty token");
950
+ }
951
+ const endpoint = `/reset-password/${encodeURIComponent(token)}`;
952
+ return callAuthEndpoint(
953
+ resolvedConfig,
954
+ { endpoint, method: "GET" },
955
+ void 0,
956
+ query?.callbackURL ? { callbackURL: query.callbackURL } : void 0,
957
+ mergedOptions
958
+ );
959
+ };
960
+ const organization = {
961
+ create: (input, options) => executePostWithCompatibleInput(
962
+ resolvedConfig,
963
+ { endpoint: "/organization/create", method: "POST" },
964
+ input,
965
+ options
966
+ ),
967
+ update: (input, options) => executePostWithCompatibleInput(
968
+ resolvedConfig,
969
+ { endpoint: "/organization/update", method: "POST" },
970
+ input,
971
+ options
972
+ ),
973
+ delete: (input, options) => executePostWithCompatibleInput(
974
+ resolvedConfig,
975
+ { endpoint: "/organization/delete", method: "POST" },
976
+ input,
977
+ options
978
+ ),
979
+ setActive: (input, options) => executePostWithCompatibleInput(
980
+ resolvedConfig,
981
+ { endpoint: "/organization/set-active", method: "POST" },
982
+ input,
983
+ options
984
+ ),
985
+ list: (input, options) => getGeneric(
986
+ "/organization/list",
987
+ input,
988
+ options
989
+ ),
990
+ getFull: (input, options) => executeGetWithQueryCompatibleInput(
991
+ resolvedConfig,
992
+ { endpoint: "/organization/get-full-organization", method: "GET" },
993
+ input,
994
+ options
995
+ ),
996
+ checkSlug: (input, options) => executePostWithCompatibleInput(
997
+ resolvedConfig,
998
+ { endpoint: "/organization/check-slug", method: "POST" },
999
+ input,
1000
+ options
1001
+ ),
1002
+ leave: (input, options) => executePostWithCompatibleInput(
1003
+ resolvedConfig,
1004
+ { endpoint: "/organization/leave", method: "POST" },
1005
+ input,
1006
+ options
1007
+ ),
1008
+ listUserInvitations: (input, options) => executeGetWithQueryCompatibleInput(
1009
+ resolvedConfig,
1010
+ { endpoint: "/organization/list-user-invitations", method: "GET" },
1011
+ input,
1012
+ options
1013
+ ),
1014
+ hasPermission: (input, options) => postGeneric(
1015
+ "/organization/has-permission",
1016
+ input,
1017
+ options
1018
+ ),
1019
+ invitation: {
1020
+ cancel: (input, options) => executePostWithCompatibleInput(
1021
+ resolvedConfig,
1022
+ { endpoint: "/organization/cancel-invitation", method: "POST" },
1023
+ input,
1024
+ options
1025
+ ),
1026
+ accept: (input, options) => executePostWithCompatibleInput(
1027
+ resolvedConfig,
1028
+ { endpoint: "/organization/accept-invitation", method: "POST" },
1029
+ input,
1030
+ options
1031
+ ),
1032
+ get: (input, options) => executeGetWithQueryCompatibleInput(
1033
+ resolvedConfig,
1034
+ { endpoint: "/organization/get-invitation", method: "GET" },
1035
+ input,
1036
+ options
1037
+ ),
1038
+ reject: (input, options) => executePostWithCompatibleInput(
1039
+ resolvedConfig,
1040
+ { endpoint: "/organization/reject-invitation", method: "POST" },
1041
+ input,
1042
+ options
1043
+ ),
1044
+ list: (input, options) => executeGetWithQueryCompatibleInput(
1045
+ resolvedConfig,
1046
+ { endpoint: "/organization/list-invitations", method: "GET" },
1047
+ input,
1048
+ options
1049
+ )
1050
+ },
1051
+ member: {
1052
+ remove: (input, options) => executePostWithCompatibleInput(
1053
+ resolvedConfig,
1054
+ { endpoint: "/organization/remove-member", method: "POST" },
1055
+ input,
1056
+ options
1057
+ ),
1058
+ updateRole: (input, options) => executePostWithCompatibleInput(
1059
+ resolvedConfig,
1060
+ { endpoint: "/organization/update-member-role", method: "POST" },
1061
+ input,
1062
+ options
1063
+ ),
1064
+ invite: (input, options) => executePostWithCompatibleInput(
1065
+ resolvedConfig,
1066
+ { endpoint: "/organization/invite-member", method: "POST" },
1067
+ input,
1068
+ options
1069
+ ),
1070
+ getActive: (input, options) => executeGetWithCompatibleInput(
1071
+ resolvedConfig,
1072
+ { endpoint: "/organization/get-active-member", method: "GET" },
1073
+ input,
1074
+ options
1075
+ ),
1076
+ list: (input, options) => executeGetWithQueryCompatibleInput(
1077
+ resolvedConfig,
1078
+ { endpoint: "/organization/list-members", method: "GET" },
1079
+ input,
1080
+ options
1081
+ )
1082
+ }
1083
+ };
1084
+ const authResetPassword = Object.assign(
1085
+ (input, options) => executePostWithCompatibleInput(
1086
+ resolvedConfig,
1087
+ { endpoint: "/reset-password", method: "POST" },
1088
+ input,
1089
+ options
1090
+ ),
1091
+ {
1092
+ token: resolveResetPasswordToken
1093
+ }
1094
+ );
1095
+ const sessionRevokeBinding = (input, options) => {
1096
+ if (Array.isArray(input)) {
1097
+ if (input.length === 0) {
1098
+ throw new Error("session.revoke requires at least one session token");
1099
+ }
1100
+ if (input.length === 1) {
1101
+ return revokeSession(input[0], options);
1102
+ }
1103
+ return revokeSessions(void 0, options);
1104
+ }
1105
+ const parsed = input;
1106
+ const tokens = Array.isArray(parsed.tokens) ? parsed.tokens.filter((token2) => token2.trim().length > 0) : void 0;
1107
+ if (tokens && tokens.length > 1) {
1108
+ return revokeSessions(
1109
+ parsed.fetchOptions ? { fetchOptions: parsed.fetchOptions } : void 0,
1110
+ options
1111
+ );
1112
+ }
1113
+ if (tokens && tokens.length === 1) {
1114
+ return revokeSession(
1115
+ { token: tokens[0], fetchOptions: parsed.fetchOptions },
1116
+ options
1117
+ );
1118
+ }
1119
+ const token = parsed.token?.trim();
1120
+ if (!token) {
1121
+ throw new Error("session.revoke requires a non-empty token or a non-empty token list");
1122
+ }
1123
+ return revokeSession(
1124
+ {
1125
+ token,
1126
+ fetchOptions: parsed.fetchOptions
1127
+ },
1128
+ options
1129
+ );
1130
+ };
1131
+ const adminUserSessionRevokeBinding = (input, options) => {
1132
+ const requireUserId = (userId) => {
1133
+ const trimmed = String(userId ?? "").trim();
1134
+ if (!trimmed) {
1135
+ throw new Error("admin.user.session.revoke requires a non-empty userId");
1136
+ }
1137
+ return trimmed;
1138
+ };
1139
+ const requireSinglePluralUserId = (sessions2) => {
1140
+ const uniqueUserIds = [...new Set(sessions2.map((session) => requireUserId(session.userId)))];
1141
+ if (uniqueUserIds.length !== 1) {
1142
+ throw new Error("admin.user.session.revoke requires the same userId across plural payloads");
1143
+ }
1144
+ return { userId: uniqueUserIds[0] };
1145
+ };
1146
+ if (Array.isArray(input)) {
1147
+ if (input.length === 0) {
1148
+ throw new Error("admin.user.session.revoke requires at least one payload item");
1149
+ }
1150
+ if (input.length === 1) {
1151
+ return postGeneric(
1152
+ "/admin/revoke-user-session",
1153
+ {
1154
+ ...input[0],
1155
+ userId: requireUserId(input[0].userId)
1156
+ },
1157
+ options
1158
+ );
1159
+ }
1160
+ return postGeneric(
1161
+ "/admin/revoke-user-sessions",
1162
+ requireSinglePluralUserId(input),
1163
+ options
1164
+ );
1165
+ }
1166
+ const parsed = input;
1167
+ const sessions = parsed.sessions;
1168
+ if (sessions && sessions.length === 0) {
1169
+ throw new Error("admin.user.session.revoke requires at least one payload item");
1170
+ }
1171
+ if (sessions && sessions.length === 1) {
1172
+ return postGeneric(
1173
+ "/admin/revoke-user-session",
1174
+ {
1175
+ ...sessions[0],
1176
+ userId: requireUserId(sessions[0].userId),
1177
+ fetchOptions: parsed.fetchOptions
1178
+ },
1179
+ options
1180
+ );
1181
+ }
1182
+ if (sessions && sessions.length > 1) {
1183
+ return postGeneric(
1184
+ "/admin/revoke-user-sessions",
1185
+ {
1186
+ ...requireSinglePluralUserId(sessions),
1187
+ fetchOptions: parsed.fetchOptions
1188
+ },
1189
+ options
1190
+ );
1191
+ }
1192
+ const normalizedUserId = requireUserId(parsed.userId);
1193
+ if (!parsed.sessionToken) {
1194
+ return postGeneric(
1195
+ "/admin/revoke-user-sessions",
1196
+ {
1197
+ userId: normalizedUserId,
1198
+ fetchOptions: parsed.fetchOptions
1199
+ },
1200
+ options
1201
+ );
1202
+ }
1203
+ return postGeneric(
1204
+ "/admin/revoke-user-session",
1205
+ {
1206
+ ...parsed,
1207
+ userId: normalizedUserId
1208
+ },
1209
+ options
1210
+ );
1211
+ };
1212
+ const auth = {
1213
+ getSession: (input, options) => getGeneric("/get-session", input, options),
1214
+ signOut,
1215
+ forgetPassword: (input, options) => postGeneric("/forget-password", input, options),
1216
+ resetPassword: authResetPassword,
1217
+ setPassword: (input, options) => postGeneric("/set-password", input, options),
1218
+ verifyEmail: (input, options) => {
1219
+ const queryInput = {
1220
+ query: {
1221
+ token: input.token,
1222
+ callbackURL: input.callbackURL
1223
+ },
1224
+ fetchOptions: input.fetchOptions
1225
+ };
1226
+ return getWithQuery(
1227
+ "/verify-email",
1228
+ queryInput,
1229
+ options
1230
+ );
1231
+ },
1232
+ sendVerificationEmail: (input, options) => postGeneric("/send-verification-email", input, options),
1233
+ changeEmail: (input, options) => postGeneric("/change-email", input, options),
1234
+ changeEmailVerify: (input, options) => getWithQuery("/change-email/verify", input, options),
1235
+ deleteUserVerify: (input, options) => getWithQuery("/delete-user/verify", input, options),
1236
+ changePassword: (input, options) => postGeneric("/change-password", input, options),
1237
+ user: {
1238
+ update: (input, options) => postGeneric("/update-user", input, options),
1239
+ delete: (input, options) => postGeneric("/delete-user", input, options),
1240
+ email: {
1241
+ list: listUserEmailsWithFallback
1242
+ }
1243
+ },
1244
+ session: {
1245
+ list: (input, options) => getGeneric("/list-sessions", input, options),
1246
+ revoke: sessionRevokeBinding,
1247
+ revokeOther: revokeOtherSessions
1248
+ },
1249
+ social: {
1250
+ link: (input, options) => postGeneric("/link-social", input, options)
1251
+ },
1252
+ account: {
1253
+ list: (input, options) => getGeneric("/list-accounts", input, options),
1254
+ unlink: (input, options) => postGeneric("/unlink-account", input, options)
1255
+ },
1256
+ deleteUser: {
1257
+ callback: deleteUserCallback
1258
+ },
1259
+ refreshToken: (input, options) => postGeneric("/refresh-token", input, options),
1260
+ getAccessToken: (input, options) => postGeneric("/get-access-token", input, options),
1261
+ health: healthWithFallback,
1262
+ ok: (input, options) => getGeneric("/ok", input, options),
1263
+ error: (input, options) => getGeneric("/error", input, options),
1264
+ twoFactor: {
1265
+ getTotpUri: (input, options) => postGeneric("/two-factor/get-totp-uri", input, options),
1266
+ verifyTotp: (input, options) => postGeneric("/two-factor/verify-totp", input, options),
1267
+ sendOtp: (input, options) => postGeneric("/two-factor/send-otp", input, options),
1268
+ verifyOtp: (input, options) => postGeneric("/two-factor/verify-otp", input, options),
1269
+ verifyBackupCode: (input, options) => postGeneric("/two-factor/verify-backup-code", input, options),
1270
+ generateBackupCodes: (input, options) => executePostWithCompatibleInput(
1271
+ resolvedConfig,
1272
+ { endpoint: "/two-factor/generate-backup-codes", method: "POST" },
1273
+ input,
1274
+ options
1275
+ ),
1276
+ enable: (input, options) => postGeneric("/two-factor/enable", input, options),
1277
+ disable: (input, options) => postGeneric("/two-factor/disable", input, options)
1278
+ },
1279
+ passkey: {
1280
+ generateRegisterOptions: (input, options) => getGeneric("/passkey/generate-register-options", input, options),
1281
+ generateAuthenticateOptions: (input, options) => postGeneric("/passkey/generate-authenticate-options", input, options),
1282
+ verifyRegistration: (input, options) => postGeneric("/passkey/verify-registration", input, options),
1283
+ verifyAuthentication: (input, options) => postGeneric("/passkey/verify-authentication", input, options),
1284
+ listUserPasskeys: (input, options) => getGeneric("/passkey/list-user-passkeys", input, options),
1285
+ deletePasskey: (input, options) => postGeneric("/passkey/delete-passkey", input, options),
1286
+ updatePasskey: (input, options) => postGeneric("/passkey/update-passkey", input, options),
1287
+ getRelatedOrigins: (input, options) => getGeneric("/.well-known/webauthn", input, options)
1288
+ },
1289
+ admin: {
1290
+ role: {
1291
+ set: (input, options) => postGeneric("/admin/set-role", input, options)
1292
+ },
1293
+ user: {
1294
+ list: (input, options) => getWithQuery("/admin/list-users", input, options),
1295
+ create: (input, options) => postGeneric("/admin/create-user", input, options),
1296
+ unban: (input, options) => postGeneric("/admin/unban-user", input, options),
1297
+ ban: (input, options) => postGeneric("/admin/ban-user", input, options),
1298
+ impersonate: (input, options) => postGeneric("/admin/impersonate-user", input, options),
1299
+ stopImpersonating: (input, options) => postGeneric("/admin/stop-impersonating", input, options),
1300
+ remove: (input, options) => postGeneric("/admin/remove-user", input, options),
1301
+ setPassword: (input, options) => postGeneric("/admin/set-user-password", input, options),
1302
+ session: {
1303
+ list: (input, options) => postGeneric("/admin/list-user-sessions", input, options),
1304
+ revoke: adminUserSessionRevokeBinding
1305
+ }
1306
+ },
1307
+ hasPermission: (input, options) => postGeneric("/admin/has-permission", input, options),
1308
+ apiKey: {
1309
+ create: (input, options) => postGeneric("/admin/api-key/create", input, options)
1310
+ },
1311
+ athenaClient: {
1312
+ create: (input, options) => postGeneric("/admin/athena-client/create", input, options),
1313
+ list: (input, options) => getWithQuery("/admin/athena-client/list", input, options)
1314
+ },
1315
+ auditLog: {
1316
+ list: (input, options) => getWithQuery("/admin/audit-log/list", input, options)
1317
+ },
1318
+ email: {
1319
+ list: (input, options) => getWithQuery("/admin/email/list", input, options),
1320
+ get: (input, options) => getWithQuery("/admin/email/get", input, options),
1321
+ create: (input, options) => postGeneric("/admin/email/create", input, options),
1322
+ update: (input, options) => postGeneric("/admin/email/update", input, options),
1323
+ delete: (input, options) => postGeneric("/admin/email/delete", input, options),
1324
+ failure: {
1325
+ list: (input, options) => getWithQuery("/admin/email-failure/list", input, options),
1326
+ get: (input, options) => getWithQuery("/admin/email-failure/get", input, options),
1327
+ create: (input, options) => postGeneric("/admin/email-failure/create", input, options),
1328
+ update: (input, options) => postGeneric("/admin/email-failure/update", input, options),
1329
+ delete: (input, options) => postGeneric("/admin/email-failure/delete", input, options)
1330
+ },
1331
+ template: {
1332
+ list: (input, options) => getWithQuery("/admin/email-template/list", input, options),
1333
+ get: (input, options) => getWithQuery("/admin/email-template/get", input, options),
1334
+ create: (input, options) => postGeneric("/admin/email-template/create", input, options),
1335
+ update: (input, options) => postGeneric("/admin/email-template/update", input, options),
1336
+ delete: (input, options) => postGeneric("/admin/email-template/delete", input, options)
1337
+ }
1338
+ },
1339
+ emailTemplate: {
1340
+ get: (input, options) => getWithQuery("/admin/email-template/get", input, options),
1341
+ create: (input, options) => postGeneric("/admin/email-template/create", input, options),
1342
+ delete: (input, options) => postGeneric("/admin/email-template/delete", input, options),
1343
+ list: (input, options) => getWithQuery("/admin/email-template/list", input, options),
1344
+ update: (input, options) => postGeneric("/admin/email-template/update", input, options)
1345
+ }
1346
+ },
1347
+ apiKey: {
1348
+ create: (input, options) => postGeneric("/api-key/create", input, options),
1349
+ get: (input, options) => getWithQuery("/api-key/get", input, options),
1350
+ update: (input, options) => postGeneric("/api-key/update", input, options),
1351
+ delete: (input, options) => postGeneric("/api-key/delete", input, options),
1352
+ list: (input, options) => getWithQuery("/api-key/list", input, options),
1353
+ verify: (input, options) => postGeneric("/api-key/verify", input, options),
1354
+ deleteAllExpired: (input, options) => executePostWithOptionalInput(
1355
+ resolvedConfig,
1356
+ { endpoint: "/api-key/delete-all-expired-api-keys", method: "POST" },
1357
+ input,
1358
+ options
1359
+ )
1360
+ },
1361
+ signIn: {
1362
+ email: (input, options) => postGeneric("/sign-in/email", input, options),
1363
+ username: (input, options) => postGeneric("/sign-in/username", input, options),
1364
+ social: (input, options) => postGeneric("/sign-in/social", input, options)
1365
+ },
1366
+ signUp: {
1367
+ email: (input, options) => postGeneric("/sign-up/email", input, options)
1368
+ },
1369
+ organization,
1370
+ callback: {
1371
+ provider: (input, options) => {
1372
+ const { payload, fetchOptions } = extractFetchOptions(input);
1373
+ const parsed = payload;
1374
+ const provider = String(parsed?.provider ?? "").trim();
1375
+ if (!provider) {
1376
+ throw new Error("callback.provider requires a non-empty provider value");
1377
+ }
1378
+ const code = String(parsed?.code ?? "").trim();
1379
+ const state = String(parsed?.state ?? "").trim();
1380
+ if (!code || !state) {
1381
+ throw new Error("callback.provider requires non-empty code and state values");
1382
+ }
1383
+ const endpoint = `/callback/${encodeURIComponent(provider)}`;
1384
+ return request({
1385
+ endpoint,
1386
+ method: "GET",
1387
+ query: {
1388
+ code,
1389
+ state
1390
+ },
1391
+ fetchOptions
1392
+ }, options);
1393
+ }
1394
+ }
1395
+ };
1396
+ return {
1397
+ baseUrl: normalizedBaseUrl,
1398
+ request,
1399
+ signIn: {
1400
+ email: (input, options) => executePostWithCompatibleInput(
1401
+ resolvedConfig,
1402
+ { endpoint: "/sign-in/email", method: "POST" },
1403
+ input,
1404
+ options
1405
+ ),
1406
+ username: (input, options) => executePostWithCompatibleInput(
1407
+ resolvedConfig,
1408
+ { endpoint: "/sign-in/username", method: "POST" },
1409
+ input,
1410
+ options
1411
+ ),
1412
+ social: (input, options) => executePostWithCompatibleInput(
1413
+ resolvedConfig,
1414
+ { endpoint: "/sign-in/social", method: "POST" },
1415
+ input,
1416
+ options
1417
+ )
1418
+ },
1419
+ signUp: {
1420
+ email: (input, options) => executePostWithCompatibleInput(
1421
+ resolvedConfig,
1422
+ { endpoint: "/sign-up/email", method: "POST" },
1423
+ input,
1424
+ options
1425
+ )
1426
+ },
1427
+ signOut,
1428
+ logout: signOut,
1429
+ getSession: (input, options) => executeGetWithCompatibleInput(
1430
+ resolvedConfig,
1431
+ { endpoint: "/get-session", method: "GET" },
1432
+ input,
1433
+ options
1434
+ ),
1435
+ listSessions: (input, options) => executeGetWithCompatibleInput(
1436
+ resolvedConfig,
1437
+ { endpoint: "/list-sessions", method: "GET" },
1438
+ input,
1439
+ options
1440
+ ),
1441
+ revokeSession,
1442
+ clearSession: revokeSession,
1443
+ revokeSessions,
1444
+ clearSessions: revokeSessions,
1445
+ revokeOtherSessions,
1446
+ clearOtherSessions: revokeOtherSessions,
1447
+ forgetPassword: (input, options) => executePostWithCompatibleInput(
1448
+ resolvedConfig,
1449
+ { endpoint: "/forget-password", method: "POST" },
1450
+ input,
1451
+ options
1452
+ ),
1453
+ resetPassword: (input, options) => executePostWithCompatibleInput(
1454
+ resolvedConfig,
1455
+ { endpoint: "/reset-password", method: "POST" },
1456
+ input,
1457
+ options
1458
+ ),
1459
+ resolveResetPasswordToken,
1460
+ verifyEmail: (input, options) => {
1461
+ const { payload, fetchOptions } = extractFetchOptions(input);
1462
+ const mergedOptions = mergeCallOptions(fetchOptions, options);
1463
+ const query = payload;
1464
+ return callAuthEndpoint(
1465
+ resolvedConfig,
1466
+ { endpoint: "/verify-email", method: "GET" },
1467
+ void 0,
1468
+ query ? {
1469
+ token: query.token,
1470
+ callbackURL: query.callbackURL
1471
+ } : void 0,
1472
+ mergedOptions
1473
+ );
1474
+ },
1475
+ sendVerificationEmail: (input, options) => executePostWithCompatibleInput(
1476
+ resolvedConfig,
1477
+ { endpoint: "/send-verification-email", method: "POST" },
1478
+ input,
1479
+ options
1480
+ ),
1481
+ changeEmail: (input, options) => executePostWithCompatibleInput(
1482
+ resolvedConfig,
1483
+ { endpoint: "/change-email", method: "POST" },
1484
+ input,
1485
+ options
1486
+ ),
1487
+ changePassword: (input, options) => executePostWithCompatibleInput(
1488
+ resolvedConfig,
1489
+ { endpoint: "/change-password", method: "POST" },
1490
+ input,
1491
+ options
1492
+ ),
1493
+ updateUser: (input, options) => executePostWithCompatibleInput(
1494
+ resolvedConfig,
1495
+ { endpoint: "/update-user", method: "POST" },
1496
+ input,
1497
+ options
1498
+ ),
1499
+ deleteUser,
1500
+ deleteUserCallback,
1501
+ linkSocial: (input, options) => executePostWithCompatibleInput(
1502
+ resolvedConfig,
1503
+ { endpoint: "/link-social", method: "POST" },
1504
+ input,
1505
+ options
1506
+ ),
1507
+ listAccounts: (input, options) => executeGetWithCompatibleInput(
1508
+ resolvedConfig,
1509
+ { endpoint: "/list-accounts", method: "GET" },
1510
+ input,
1511
+ options
1512
+ ),
1513
+ unlinkAccount: (input, options) => executePostWithCompatibleInput(
1514
+ resolvedConfig,
1515
+ { endpoint: "/unlink-account", method: "POST" },
1516
+ input,
1517
+ options
1518
+ ),
1519
+ refreshToken: (input, options) => executePostWithCompatibleInput(
1520
+ resolvedConfig,
1521
+ { endpoint: "/refresh-token", method: "POST" },
1522
+ input,
1523
+ options
1524
+ ),
1525
+ getAccessToken: (input, options) => executePostWithCompatibleInput(
1526
+ resolvedConfig,
1527
+ { endpoint: "/get-access-token", method: "POST" },
1528
+ input,
1529
+ options
1530
+ ),
1531
+ organization,
1532
+ auth
1533
+ };
1534
+ }
1535
+
1536
+ // src/auxiliaries.ts
1537
+ var AthenaErrorKind = {
1538
+ UniqueViolation: "unique_violation",
1539
+ NotFound: "not_found",
1540
+ Validation: "validation",
1541
+ Auth: "auth",
1542
+ RateLimit: "rate_limit",
1543
+ Transient: "transient",
1544
+ Unknown: "unknown"
1545
+ };
1546
+ var AthenaErrorCode = {
1547
+ UniqueViolation: "UNIQUE_VIOLATION",
1548
+ NotFound: "NOT_FOUND",
1549
+ ValidationFailed: "VALIDATION_FAILED",
1550
+ AuthUnauthorized: "AUTH_UNAUTHORIZED",
1551
+ AuthForbidden: "AUTH_FORBIDDEN",
1552
+ RateLimited: "RATE_LIMITED",
1553
+ NetworkUnavailable: "NETWORK_UNAVAILABLE",
1554
+ TransientFailure: "TRANSIENT_FAILURE",
1555
+ HttpFailure: "HTTP_FAILURE",
1556
+ Unknown: "UNKNOWN"
1557
+ };
1558
+ var AthenaErrorCategory = {
1559
+ Transport: "transport",
1560
+ Client: "client",
1561
+ Server: "server",
1562
+ Database: "database",
1563
+ Unknown: "unknown"
1564
+ };
1565
+ function parseBooleanFlag(rawValue, fallback) {
1566
+ if (!rawValue) return fallback;
1567
+ const normalized = rawValue.trim().toLowerCase();
1568
+ if (normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on") {
1569
+ return true;
1570
+ }
1571
+ if (normalized === "0" || normalized === "false" || normalized === "no" || normalized === "off") {
1572
+ return false;
1573
+ }
1574
+ return fallback;
1575
+ }
1576
+ var AthenaError = class extends Error {
1577
+ code;
1578
+ kind;
1579
+ category;
1580
+ status;
1581
+ retryable;
1582
+ requestId;
1583
+ context;
1584
+ raw;
1585
+ constructor(input) {
1586
+ super(input.message);
1587
+ this.name = "AthenaError";
1588
+ this.code = input.code;
1589
+ this.kind = input.kind;
1590
+ this.category = input.category;
1591
+ this.status = input.status;
1592
+ this.retryable = input.retryable ?? false;
1593
+ this.requestId = input.requestId;
1594
+ this.context = input.context;
1595
+ this.raw = input.raw;
1596
+ }
1597
+ };
1598
+ function isRecord3(value) {
1599
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1600
+ }
1601
+ function isAthenaErrorKind(value) {
1602
+ return value === "unique_violation" || value === "not_found" || value === "validation" || value === "auth" || value === "rate_limit" || value === "transient" || value === "unknown";
1603
+ }
1604
+ function isAthenaErrorCode(value) {
1605
+ 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";
1606
+ }
1607
+ function isAthenaErrorCategory(value) {
1608
+ return value === "transport" || value === "client" || value === "server" || value === "database" || value === "unknown";
1609
+ }
1610
+ function isNormalizedAthenaError(value) {
1611
+ return isRecord3(value) && isAthenaErrorKind(value.kind) && isAthenaErrorCode(value.code) && isAthenaErrorCategory(value.category) && typeof value.retryable === "boolean" && typeof value.message === "string" && "raw" in value;
1612
+ }
1613
+ function withContextOverrides(normalized, context) {
1614
+ if (!context?.table && !context?.operation) {
1615
+ return normalized;
1616
+ }
1617
+ return {
1618
+ ...normalized,
1619
+ table: context.table ?? normalized.table,
1620
+ operation: context.operation ?? normalized.operation
1621
+ };
1622
+ }
1623
+ function resolveAttachedNormalizedError(resultOrError) {
1624
+ if (!isRecord3(resultOrError)) return void 0;
1625
+ if (!("__athenaNormalizedError" in resultOrError)) return void 0;
1626
+ const candidate = resultOrError.__athenaNormalizedError;
1627
+ return isNormalizedAthenaError(candidate) ? candidate : void 0;
1628
+ }
1629
+ function safeStringify(value) {
1630
+ try {
1631
+ const serialized = JSON.stringify(value);
1632
+ return serialized ?? String(value);
1633
+ } catch {
1634
+ return "[unserializable]";
1635
+ }
1636
+ }
1637
+ function contextHint(context) {
1638
+ if (!context?.identity) return void 0;
1639
+ const identity = typeof context.identity === "string" ? context.identity : safeStringify(context.identity);
1640
+ return `Identity: ${identity}`;
1641
+ }
1642
+ function isAthenaResultLike(value) {
1643
+ return isRecord3(value) && "status" in value && "error" in value && "data" in value && typeof value.status === "number";
1644
+ }
1645
+ function operationFromDetails(details) {
1646
+ if (!details?.endpoint) return void 0;
1647
+ if (details.endpoint === "/gateway/fetch" || details.endpoint === "/gateway/query") return "select";
1648
+ if (details.endpoint === "/gateway/insert") return "insert";
1649
+ if (details.endpoint === "/gateway/update") return "update";
1650
+ if (details.endpoint === "/gateway/delete") return "delete";
1651
+ if (details.endpoint === "/gateway/rpc" || details.endpoint.startsWith("/rpc/")) return "rpc";
1652
+ return void 0;
1653
+ }
1654
+ function matchRegex(input, patterns) {
1655
+ for (const pattern of patterns) {
1656
+ const match = pattern.exec(input);
1657
+ if (match?.[1]) return match[1];
1658
+ }
1659
+ return void 0;
1660
+ }
1661
+ function extractConstraint(message) {
1662
+ return matchRegex(message, [
1663
+ /unique constraint\s+["'`]([^"'`]+)["'`]/i,
1664
+ /constraint\s+["'`]([^"'`]+)["'`]/i
1665
+ ]);
1666
+ }
1667
+ function extractTable(message) {
1668
+ return matchRegex(message, [
1669
+ /(?:table|relation)\s+["'`]([^"'`]+)["'`]/i,
1670
+ /on\s+table\s+([a-zA-Z0-9_.]+)/i
1671
+ ]);
1672
+ }
1673
+ function classifyKind(status, code, message) {
1674
+ const lower = message.toLowerCase();
1675
+ const hasUniquePattern = lower.includes("unique constraint") || lower.includes("duplicate key") || lower.includes("already exists") || lower.includes("duplicate");
1676
+ const hasNotFoundPattern = lower.includes("not found") || lower.includes("no rows");
1677
+ const hasValidationPattern = lower.includes("validation") || lower.includes("invalid") || lower.includes("malformed");
1678
+ const hasAuthPattern = lower.includes("unauthorized") || lower.includes("forbidden") || lower.includes("auth");
1679
+ const hasRateLimitPattern = lower.includes("rate limit") || lower.includes("too many requests");
1680
+ const hasTransientPattern = lower.includes("timeout") || lower.includes("temporar") || lower.includes("connection reset") || lower.includes("socket") || lower.includes("deadlock");
1681
+ if (status === 409 || hasUniquePattern) return "unique_violation";
1682
+ if (status === 404 || hasNotFoundPattern) return "not_found";
1683
+ if (status === 401 || status === 403 || hasAuthPattern) return "auth";
1684
+ if (status === 429 || hasRateLimitPattern) return "rate_limit";
1685
+ if (status === 400 || status === 422 || hasValidationPattern) return "validation";
1686
+ if (code === "NETWORK_ERROR" || status === 0 || status !== void 0 && status >= 500 || hasTransientPattern) {
1687
+ return "transient";
1688
+ }
1689
+ return "unknown";
1690
+ }
1691
+ function toAthenaErrorCode(kind, status, gatewayCode) {
1692
+ if (gatewayCode === "NETWORK_ERROR" || kind === "transient" && status === 0) {
1693
+ return AthenaErrorCode.NetworkUnavailable;
1694
+ }
1695
+ switch (kind) {
1696
+ case "unique_violation":
1697
+ return AthenaErrorCode.UniqueViolation;
1698
+ case "not_found":
1699
+ return AthenaErrorCode.NotFound;
1700
+ case "validation":
1701
+ return AthenaErrorCode.ValidationFailed;
1702
+ case "rate_limit":
1703
+ return AthenaErrorCode.RateLimited;
1704
+ case "auth":
1705
+ if (status === 403) {
1706
+ return AthenaErrorCode.AuthForbidden;
1707
+ }
1708
+ return AthenaErrorCode.AuthUnauthorized;
1709
+ case "transient":
1710
+ return status !== void 0 && status >= 500 ? AthenaErrorCode.HttpFailure : AthenaErrorCode.TransientFailure;
1711
+ case "unknown":
1712
+ default:
1713
+ return status !== void 0 && status >= 400 ? AthenaErrorCode.HttpFailure : AthenaErrorCode.Unknown;
1714
+ }
1715
+ }
1716
+ function toAthenaErrorCategory(kind, status) {
1717
+ if (kind === "transient" && (status === 0 || status === void 0)) {
1718
+ return AthenaErrorCategory.Transport;
1719
+ }
1720
+ if (kind === "unique_violation") return AthenaErrorCategory.Database;
1721
+ if (kind === "validation" || kind === "auth" || kind === "not_found") return AthenaErrorCategory.Client;
1722
+ if (kind === "rate_limit" || kind === "transient") return AthenaErrorCategory.Server;
1723
+ return AthenaErrorCategory.Unknown;
1724
+ }
1725
+ function isRetryable(kind, status) {
1726
+ if (kind === "rate_limit" || kind === "transient") return true;
1727
+ return status !== void 0 && status >= 500;
1728
+ }
1729
+ function toGatewayCode(kind, status) {
1730
+ if (kind === "transient" && (status === 0 || status === void 0)) return "NETWORK_ERROR";
1731
+ if (kind === "validation") return "INVALID_JSON";
1732
+ if (status !== void 0 && status >= 400) return "HTTP_ERROR";
1733
+ return "UNKNOWN_ERROR";
1734
+ }
1735
+ function toAthenaGatewayError(source, fallbackMessage, context) {
1736
+ if (isAthenaGatewayError(source)) {
1737
+ return source;
1738
+ }
1739
+ if (isAthenaResultLike(source) && source.errorDetails) {
1740
+ return new AthenaGatewayError({
1741
+ code: source.errorDetails.code,
1742
+ message: source.error ?? source.errorDetails.message,
1743
+ status: source.status,
1744
+ endpoint: source.errorDetails.endpoint,
1745
+ method: source.errorDetails.method,
1746
+ requestId: source.errorDetails.requestId,
1747
+ hint: source.errorDetails.hint,
1748
+ cause: source.errorDetails.cause
1749
+ });
1750
+ }
1751
+ const normalized = normalizeAthenaError(source, context);
1752
+ const message = isAthenaResultLike(source) && source.error == null && source.errorDetails == null ? fallbackMessage : normalized.message || fallbackMessage;
1753
+ return new AthenaGatewayError({
1754
+ code: toGatewayCode(normalized.kind, normalized.status),
1755
+ message,
1756
+ status: normalized.status ?? 0,
1757
+ hint: normalized.constraint != null ? `Constraint: ${normalized.constraint}` : contextHint(context),
1758
+ cause: typeof normalized.raw === "string" ? normalized.raw : safeStringify(normalized.raw)
1759
+ });
1760
+ }
1761
+ function isOk(result) {
1762
+ return result.error == null && result.status >= 200 && result.status < 300;
1763
+ }
1764
+ function normalizeAthenaError(resultOrError, context) {
1765
+ const attached = resolveAttachedNormalizedError(resultOrError);
1766
+ if (attached) {
1767
+ return withContextOverrides(attached, context);
1768
+ }
1769
+ if (isAthenaResultLike(resultOrError)) {
1770
+ const details = resultOrError.errorDetails;
1771
+ const message2 = resultOrError.error ?? details?.message ?? `Athena ${context?.operation ?? operationFromDetails(details) ?? "request"} failed`;
1772
+ const operation = context?.operation ?? operationFromDetails(details);
1773
+ const table = context?.table ?? extractTable(message2);
1774
+ const constraint = extractConstraint(message2);
1775
+ const kind2 = classifyKind(resultOrError.status, details?.code, message2);
1776
+ const code = toAthenaErrorCode(kind2, resultOrError.status, details?.code);
1777
+ const category = toAthenaErrorCategory(kind2, resultOrError.status);
1778
+ return {
1779
+ kind: kind2,
1780
+ code,
1781
+ category,
1782
+ retryable: isRetryable(kind2, resultOrError.status),
1783
+ status: resultOrError.status,
1784
+ constraint,
1785
+ table,
1786
+ operation,
1787
+ message: message2,
1788
+ raw: resultOrError.raw
1789
+ };
1790
+ }
1791
+ if (isAthenaGatewayError(resultOrError)) {
1792
+ const details = resultOrError.toDetails();
1793
+ const operation = context?.operation ?? operationFromDetails(details);
1794
+ const table = context?.table ?? extractTable(resultOrError.message);
1795
+ const constraint = extractConstraint(resultOrError.message);
1796
+ const kind2 = classifyKind(resultOrError.status, resultOrError.code, resultOrError.message);
1797
+ const code = toAthenaErrorCode(kind2, resultOrError.status, resultOrError.code);
1798
+ const category = toAthenaErrorCategory(kind2, resultOrError.status);
1799
+ return {
1800
+ kind: kind2,
1801
+ code,
1802
+ category,
1803
+ retryable: isRetryable(kind2, resultOrError.status),
1804
+ status: resultOrError.status,
1805
+ constraint,
1806
+ table,
1807
+ operation,
1808
+ message: resultOrError.message,
1809
+ raw: resultOrError
1810
+ };
1811
+ }
1812
+ if (resultOrError instanceof Error) {
1813
+ const maybeStatus = isRecord3(resultOrError) && typeof resultOrError.status === "number" ? resultOrError.status : void 0;
1814
+ const kind2 = classifyKind(maybeStatus, void 0, resultOrError.message);
1815
+ return {
1816
+ kind: kind2,
1817
+ code: toAthenaErrorCode(kind2, maybeStatus),
1818
+ category: toAthenaErrorCategory(kind2, maybeStatus),
1819
+ retryable: isRetryable(kind2, maybeStatus),
1820
+ status: maybeStatus,
1821
+ constraint: extractConstraint(resultOrError.message),
1822
+ table: context?.table ?? extractTable(resultOrError.message),
1823
+ operation: context?.operation,
1824
+ message: resultOrError.message,
1825
+ raw: resultOrError
1826
+ };
1827
+ }
1828
+ const message = typeof resultOrError === "string" ? resultOrError : "Unknown Athena error";
1829
+ const kind = classifyKind(void 0, void 0, message);
1830
+ return {
1831
+ kind,
1832
+ code: toAthenaErrorCode(kind, void 0),
1833
+ category: toAthenaErrorCategory(kind, void 0),
1834
+ retryable: isRetryable(kind, void 0),
1835
+ status: void 0,
1836
+ constraint: extractConstraint(message),
1837
+ table: context?.table ?? extractTable(message),
1838
+ operation: context?.operation,
1839
+ message,
1840
+ raw: resultOrError
1841
+ };
1842
+ }
1843
+ function unwrapRows(result, options) {
1844
+ if (!isOk(result)) {
1845
+ throw toAthenaGatewayError(result, "Athena request failed", options?.context);
1846
+ }
1847
+ if (result.data == null) return [];
1848
+ return Array.isArray(result.data) ? result.data : [result.data];
1849
+ }
1850
+ function unwrap(result, options) {
1851
+ if (!isOk(result)) {
1852
+ throw toAthenaGatewayError(result, "Athena request failed", options?.context);
1853
+ }
1854
+ if (result.data == null && !options?.allowNull) {
1855
+ throw toAthenaGatewayError(result, "Expected data but received null", options?.context);
1856
+ }
1857
+ return result.data;
1858
+ }
1859
+ function unwrapOne(result, options) {
1860
+ const rows = unwrapRows(result, options);
1861
+ if (!rows.length) {
1862
+ if (options?.allowNull) return null;
1863
+ throw toAthenaGatewayError(result, "Expected one row but received none", options?.context);
1864
+ }
1865
+ if (options?.requireExactlyOne && rows.length !== 1) {
1866
+ throw toAthenaGatewayError(
1867
+ result,
1868
+ `Expected exactly one row but received ${rows.length}`,
1869
+ options.context
1870
+ );
1871
+ }
1872
+ return rows[0];
1873
+ }
1874
+ function requireSuccess(result, context) {
1875
+ if (!isOk(result)) {
1876
+ throw toAthenaGatewayError(
1877
+ result,
1878
+ `Athena ${context?.operation ?? "request"} failed`,
1879
+ context
1880
+ );
1881
+ }
1882
+ return result;
1883
+ }
1884
+ function requireAffected(result, options, context) {
1885
+ requireSuccess(result, context);
1886
+ const minimum = options?.min ?? 1;
1887
+ const count = result.count;
1888
+ if (count == null) {
1889
+ throw new AthenaGatewayError({
1890
+ code: "UNKNOWN_ERROR",
1891
+ status: result.status,
1892
+ message: "Expected affected row count but response.count is missing",
1893
+ hint: 'Set call option { count: "exact" } for mutation postcondition checks.',
1894
+ cause: safeStringify(result.raw)
1895
+ });
1896
+ }
1897
+ if (count < minimum) {
1898
+ throw new AthenaGatewayError({
1899
+ code: "UNKNOWN_ERROR",
1900
+ status: result.status,
1901
+ message: `Expected at least ${minimum} affected rows but received ${count}`,
1902
+ hint: contextHint(context),
1903
+ cause: safeStringify(result.raw)
1904
+ });
1905
+ }
1906
+ return count;
1907
+ }
1908
+ function applyBounds(value, options) {
1909
+ if (options?.min !== void 0 && value < options.min) return null;
1910
+ if (options?.max !== void 0 && value > options.max) return null;
1911
+ return value;
1912
+ }
1913
+ function parseIntegerString(value) {
1914
+ const normalized = value.trim();
1915
+ if (!/^[-+]?\d+$/.test(normalized)) return null;
1916
+ const parsed = Number(normalized);
1917
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) return null;
1918
+ return parsed;
1919
+ }
1920
+ function coerceInt(value, options) {
1921
+ if (value == null) return null;
1922
+ if (typeof value === "number") {
1923
+ if (!Number.isFinite(value) || !Number.isInteger(value)) return null;
1924
+ return applyBounds(value, options);
1925
+ }
1926
+ if (typeof value === "string") {
1927
+ const parsed = parseIntegerString(value);
1928
+ if (parsed == null) return null;
1929
+ return applyBounds(parsed, options);
1930
+ }
1931
+ if (typeof value === "bigint") {
1932
+ if (options?.strictBigInt) {
1933
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
1934
+ return null;
1935
+ }
1936
+ }
1937
+ const parsed = Number(value);
1938
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) return null;
1939
+ return applyBounds(parsed, options);
1940
+ }
1941
+ return null;
1942
+ }
1943
+ function assertInt(value, label = "value", options) {
1944
+ const parsed = coerceInt(value, options);
1945
+ if (parsed == null) {
1946
+ throw new TypeError(`${label} must be a finite integer`);
1947
+ }
1948
+ return parsed;
1949
+ }
1950
+ function defaultShouldRetry(error) {
1951
+ const normalized = normalizeAthenaError(error);
1952
+ return normalized.kind === "transient" || normalized.kind === "rate_limit";
1953
+ }
1954
+ function computeDelayMs(attempt, error, config) {
1955
+ const baseDelay = config.baseDelayMs;
1956
+ const rawDelay = typeof config.backoff === "function" ? config.backoff(attempt, error) : config.backoff === "linear" ? baseDelay * attempt : baseDelay * Math.pow(2, attempt - 1);
1957
+ const safeDelay = Number.isFinite(rawDelay) ? Math.max(0, rawDelay) : 0;
1958
+ const clamped = Math.min(config.maxDelayMs, safeDelay);
1959
+ const jitterFactor = typeof config.jitter === "number" ? Math.max(0, Math.min(1, config.jitter)) : config.jitter ? 0.2 : 0;
1960
+ if (!jitterFactor) return clamped;
1961
+ const deviation = clamped * jitterFactor;
1962
+ const offset = (Math.random() * 2 - 1) * deviation;
1963
+ return Math.max(0, clamped + offset);
1964
+ }
1965
+ function sleep(ms) {
1966
+ if (ms <= 0) return Promise.resolve();
1967
+ return new Promise((resolve) => {
1968
+ setTimeout(resolve, ms);
1969
+ });
1970
+ }
1971
+ async function withRetry(config, fn) {
1972
+ const retries = Math.max(0, Math.trunc(config.retries));
1973
+ const shouldRetry = config.shouldRetry ?? defaultShouldRetry;
1974
+ const resolvedConfig = {
1975
+ baseDelayMs: config.baseDelayMs ?? 100,
1976
+ maxDelayMs: config.maxDelayMs ?? 1e4,
1977
+ backoff: config.backoff ?? "exponential",
1978
+ jitter: config.jitter ?? false
1979
+ };
1980
+ for (let attempts = 0; attempts <= retries; attempts += 1) {
1981
+ try {
1982
+ return await fn();
1983
+ } catch (error) {
1984
+ if (attempts >= retries) {
1985
+ throw error;
1986
+ }
1987
+ const currentAttempt = attempts + 1;
1988
+ const retry = await shouldRetry(error, currentAttempt);
1989
+ if (!retry) {
1990
+ throw error;
1991
+ }
1992
+ const delay = computeDelayMs(currentAttempt, error, resolvedConfig);
1993
+ await sleep(delay);
1994
+ }
1995
+ }
1996
+ throw new Error("withRetry reached an unexpected state");
1997
+ }
1998
+
1999
+ // src/db/module.ts
2000
+ function createDbModule(input) {
2001
+ const db = {
2002
+ from(table) {
2003
+ return input.from(table);
2004
+ },
2005
+ select(table, columns, options) {
2006
+ return input.from(table).select(columns, options);
2007
+ },
2008
+ insert(table, values, options) {
2009
+ return Array.isArray(values) ? input.from(table).insert(values, options) : input.from(table).insert(values, options);
2010
+ },
2011
+ upsert(table, values, options) {
2012
+ return Array.isArray(values) ? input.from(table).upsert(values, options) : input.from(table).upsert(values, options);
2013
+ },
2014
+ update(table, values, options) {
2015
+ return input.from(table).update(values, options);
2016
+ },
2017
+ delete(table, options) {
2018
+ return input.from(table).delete(options);
2019
+ },
2020
+ rpc(fn, args, options) {
2021
+ return input.rpc(fn, args, options);
2022
+ },
2023
+ query(query, options) {
2024
+ return input.query(query, options);
2025
+ }
2026
+ };
2027
+ return db;
2028
+ }
2029
+
2030
+ // src/client.ts
2031
+ var DEFAULT_COLUMNS = "*";
2032
+ 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;
2033
+ var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
2034
+ var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
2035
+ function formatResult(response) {
2036
+ const result = {
2037
+ data: response.data ?? null,
2038
+ error: response.error ?? null,
2039
+ errorDetails: response.errorDetails ?? null,
2040
+ status: response.status,
2041
+ raw: response.raw
2042
+ };
2043
+ if (response.count !== void 0) {
2044
+ result.count = response.count;
2045
+ }
2046
+ return result;
2047
+ }
2048
+ function attachNormalizedError(result, normalizedError) {
2049
+ Object.defineProperty(result, ATHENA_NORMALIZED_ERROR_KEY, {
2050
+ value: normalizedError,
2051
+ enumerable: false,
2052
+ configurable: true,
2053
+ writable: false
2054
+ });
2055
+ }
2056
+ function createResultFormatter(experimental) {
2057
+ if (!experimental?.enableErrorNormalization) {
2058
+ return formatResult;
2059
+ }
2060
+ return (response, context) => {
2061
+ const result = formatResult(response);
2062
+ if (result.error == null) {
2063
+ return result;
2064
+ }
2065
+ const normalizedError = normalizeAthenaError(result, context);
2066
+ attachNormalizedError(result, normalizedError);
2067
+ return result;
2068
+ };
2069
+ }
2070
+ function toSingleResult(response) {
2071
+ const payload = response.data;
2072
+ const singleData = Array.isArray(payload) ? payload.length ? payload[0] : null : payload ?? null;
2073
+ return {
2074
+ ...response,
2075
+ data: singleData
2076
+ };
2077
+ }
2078
+ function mergeOptions(...options) {
2079
+ return options.reduce((acc, next) => {
2080
+ if (!next) return acc;
2081
+ return { ...acc, ...next };
2082
+ }, void 0);
2083
+ }
2084
+ function asAthenaJsonObject(value) {
2085
+ return value;
2086
+ }
2087
+ function asAthenaJsonObjectArray(values) {
2088
+ return values;
2089
+ }
2090
+ function createMutationQuery(executor, defaultColumns = DEFAULT_COLUMNS) {
2091
+ let selectedColumns = defaultColumns === null ? void 0 : defaultColumns;
2092
+ let selectedOptions;
2093
+ let promise = null;
2094
+ const run = (columns, options) => {
2095
+ const payloadColumns = columns ?? selectedColumns;
2096
+ const payloadOptions = options ?? selectedOptions;
2097
+ if (!promise) {
2098
+ promise = executor(payloadColumns, payloadOptions);
2099
+ }
2100
+ return promise;
2101
+ };
2102
+ const mutationQuery = {
2103
+ select(columns = selectedColumns, options) {
2104
+ selectedColumns = columns;
2105
+ selectedOptions = options ?? selectedOptions;
2106
+ return run(columns, options);
2107
+ },
2108
+ returning(columns = selectedColumns, options) {
2109
+ return mutationQuery.select(columns, options);
2110
+ },
2111
+ single(columns = selectedColumns, options) {
2112
+ selectedColumns = columns;
2113
+ selectedOptions = options ?? selectedOptions;
2114
+ return run(columns, options).then(toSingleResult);
2115
+ },
2116
+ maybeSingle(columns = selectedColumns, options) {
2117
+ return mutationQuery.single(columns, options);
2118
+ },
2119
+ then(onfulfilled, onrejected) {
2120
+ return run(selectedColumns, selectedOptions).then(onfulfilled, onrejected);
2121
+ },
2122
+ catch(onrejected) {
2123
+ return run(selectedColumns, selectedOptions).catch(onrejected);
2124
+ },
2125
+ finally(onfinally) {
2126
+ return run(selectedColumns, selectedOptions).finally(onfinally);
2127
+ }
2128
+ };
2129
+ return mutationQuery;
2130
+ }
2131
+ function getResourceId(state) {
2132
+ const candidate = state.conditions.find(
2133
+ (condition) => condition.operator === "eq" && (condition.column === "resource_id" || condition.column === "id")
2134
+ );
2135
+ return candidate?.value?.toString();
2136
+ }
2137
+ function stringifyFilterValue(value) {
2138
+ if (Array.isArray(value)) {
2139
+ return value.join(",");
2140
+ }
2141
+ return String(value);
2142
+ }
2143
+ function isUuidString(value) {
2144
+ return UUID_PATTERN.test(value.trim());
2145
+ }
2146
+ function isUuidIdentifierColumn(column) {
2147
+ return column === "id" || /(?:^|_)uuid(?:_|$)/i.test(column) || /_id$/i.test(column);
2148
+ }
2149
+ function shouldUseUuidTextComparison(column, value) {
2150
+ return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
2151
+ }
2152
+ function normalizeCast(cast) {
2153
+ const normalized = cast.trim().toLowerCase();
2154
+ if (!SAFE_CAST_PATTERN.test(normalized)) {
2155
+ throw new Error(`Invalid cast type "${cast}"`);
2156
+ }
2157
+ return normalized;
2158
+ }
2159
+ function escapeSqlStringLiteral(value) {
2160
+ return value.replace(/'/g, "''");
2161
+ }
2162
+ function toSqlLiteral(value) {
2163
+ if (value === null) return "NULL";
2164
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : "NULL";
2165
+ if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
2166
+ return `'${escapeSqlStringLiteral(value)}'`;
2167
+ }
2168
+ function withCast(expression, cast) {
2169
+ if (!cast) return expression;
2170
+ return `${expression}::${normalizeCast(cast)}`;
2171
+ }
2172
+ function buildSelectColumnsClause(columns) {
2173
+ if (Array.isArray(columns)) {
2174
+ return columns.map((column) => quoteQualifiedIdentifier(column)).join(", ");
2175
+ }
2176
+ return quoteSelectColumnsExpression(columns);
2177
+ }
2178
+ function resolveTableNameForCall(tableName, schema) {
2179
+ if (!schema) return tableName;
2180
+ const normalizedSchema = schema.trim();
2181
+ if (!normalizedSchema) {
2182
+ throw new Error("schema option must be a non-empty string");
2183
+ }
2184
+ if (tableName.includes(".")) {
2185
+ if (tableName.startsWith(`${normalizedSchema}.`)) {
2186
+ return tableName;
2187
+ }
2188
+ throw new Error(
2189
+ `schema option "${normalizedSchema}" conflicts with schema-qualified table "${tableName}"`
2190
+ );
2191
+ }
2192
+ return `${normalizedSchema}.${tableName}`;
2193
+ }
2194
+ function conditionToSqlClause(condition) {
2195
+ if (!condition.column) return null;
2196
+ const column = withCast(quoteQualifiedIdentifier(condition.column), condition.column_cast);
2197
+ const value = condition.value;
2198
+ const sqlOperator = {
2199
+ eq: "=",
2200
+ neq: "!=",
2201
+ gt: ">",
2202
+ gte: ">=",
2203
+ lt: "<",
2204
+ lte: "<=",
2205
+ like: "LIKE",
2206
+ ilike: "ILIKE"
2207
+ };
2208
+ switch (condition.operator) {
2209
+ case "eq":
2210
+ case "neq":
2211
+ case "gt":
2212
+ case "gte":
2213
+ case "lt":
2214
+ case "lte":
2215
+ case "like":
2216
+ case "ilike": {
2217
+ if (Array.isArray(value) || value === void 0) return null;
2218
+ const rhs = withCast(toSqlLiteral(value), condition.value_cast);
2219
+ return `${column} ${sqlOperator[condition.operator]} ${rhs}`;
2220
+ }
2221
+ case "is": {
2222
+ if (value === null) return `${column} IS NULL`;
2223
+ if (value === true) return `${column} IS TRUE`;
2224
+ if (value === false) return `${column} IS FALSE`;
2225
+ return null;
2226
+ }
2227
+ case "in": {
2228
+ if (!Array.isArray(value)) return null;
2229
+ if (value.length === 0) return "FALSE";
2230
+ const values = value.map((item) => withCast(toSqlLiteral(item), condition.value_cast));
2231
+ return `${column} IN (${values.join(", ")})`;
2232
+ }
2233
+ default:
2234
+ return null;
2235
+ }
2236
+ }
2237
+ function buildTypedSelectQuery(input) {
2238
+ const whereClauses = [];
2239
+ for (const condition of input.conditions) {
2240
+ const clause = conditionToSqlClause(condition);
2241
+ if (!clause) return null;
2242
+ whereClauses.push(clause);
2243
+ }
2244
+ let limit = input.limit;
2245
+ let offset = input.offset;
2246
+ if (limit === void 0 && input.pageSize !== void 0) {
2247
+ limit = input.pageSize;
2248
+ }
2249
+ if (offset === void 0 && input.pageSize !== void 0 && input.currentPage !== void 0 && input.currentPage > 0) {
2250
+ offset = (input.currentPage - 1) * input.pageSize;
2251
+ }
2252
+ const sqlParts = [
2253
+ `SELECT ${buildSelectColumnsClause(input.columns)} FROM ${quoteQualifiedIdentifier(input.tableName)}`
2254
+ ];
2255
+ if (whereClauses.length > 0) {
2256
+ sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
2257
+ }
2258
+ if (input.order?.field) {
2259
+ const direction = input.order.direction === "descending" ? "DESC" : "ASC";
2260
+ sqlParts.push(`ORDER BY ${quoteQualifiedIdentifier(input.order.field)} ${direction}`);
2261
+ }
2262
+ if (limit !== void 0) {
2263
+ sqlParts.push(`LIMIT ${Math.max(0, Math.trunc(limit))}`);
2264
+ }
2265
+ if (offset !== void 0) {
2266
+ sqlParts.push(`OFFSET ${Math.max(0, Math.trunc(offset))}`);
2267
+ }
2268
+ return `${sqlParts.join(" ")};`;
2269
+ }
2270
+ function createFilterMethods(state, addCondition, self) {
2271
+ return {
2272
+ eq(column, value) {
2273
+ const columnName = String(column);
2274
+ if (shouldUseUuidTextComparison(columnName, value)) {
2275
+ addCondition("eq", columnName, value, { columnCast: "text" });
2276
+ } else {
2277
+ addCondition("eq", columnName, value);
2278
+ }
2279
+ return self;
2280
+ },
2281
+ eqCast(column, value, cast) {
2282
+ addCondition("eq", String(column), value, { valueCast: cast });
2283
+ return self;
2284
+ },
2285
+ eqUuid(column, value) {
2286
+ addCondition("eq", String(column), value, { valueCast: "uuid" });
2287
+ return self;
2288
+ },
2289
+ match(filters) {
2290
+ Object.entries(filters).forEach(([column, value]) => {
2291
+ if (value === void 0) {
2292
+ return;
2293
+ }
2294
+ if (shouldUseUuidTextComparison(column, value)) {
2295
+ addCondition("eq", column, value, { columnCast: "text" });
2296
+ } else {
2297
+ addCondition("eq", column, value);
2298
+ }
2299
+ });
2300
+ return self;
2301
+ },
2302
+ range(from, to) {
2303
+ state.offset = from;
2304
+ state.limit = to - from + 1;
2305
+ return self;
2306
+ },
2307
+ limit(count) {
2308
+ state.limit = count;
2309
+ return self;
2310
+ },
2311
+ offset(count) {
2312
+ state.offset = count;
2313
+ return self;
2314
+ },
2315
+ currentPage(value) {
2316
+ state.currentPage = value;
2317
+ return self;
2318
+ },
2319
+ pageSize(value) {
2320
+ state.pageSize = value;
2321
+ return self;
2322
+ },
2323
+ totalPages(value) {
2324
+ state.totalPages = value;
2325
+ return self;
2326
+ },
2327
+ order(column, options) {
2328
+ state.order = {
2329
+ field: String(column),
2330
+ direction: options?.ascending === false ? "descending" : "ascending"
2331
+ };
2332
+ return self;
2333
+ },
2334
+ gt(column, value) {
2335
+ addCondition("gt", String(column), value);
2336
+ return self;
2337
+ },
2338
+ gte(column, value) {
2339
+ addCondition("gte", String(column), value);
2340
+ return self;
2341
+ },
2342
+ lt(column, value) {
2343
+ addCondition("lt", String(column), value);
2344
+ return self;
2345
+ },
2346
+ lte(column, value) {
2347
+ addCondition("lte", String(column), value);
2348
+ return self;
2349
+ },
2350
+ neq(column, value) {
2351
+ addCondition("neq", String(column), value);
2352
+ return self;
2353
+ },
2354
+ like(column, value) {
2355
+ addCondition("like", String(column), value);
2356
+ return self;
2357
+ },
2358
+ ilike(column, value) {
2359
+ addCondition("ilike", String(column), value);
2360
+ return self;
2361
+ },
2362
+ is(column, value) {
2363
+ addCondition("is", String(column), value);
2364
+ return self;
2365
+ },
2366
+ in(column, values) {
2367
+ addCondition("in", String(column), values);
2368
+ return self;
2369
+ },
2370
+ contains(column, values) {
2371
+ addCondition("contains", String(column), values);
2372
+ return self;
2373
+ },
2374
+ containedBy(column, values) {
2375
+ addCondition("containedBy", String(column), values);
2376
+ return self;
2377
+ },
2378
+ not(columnOrExpression, operator, value) {
2379
+ const expression = String(columnOrExpression);
2380
+ if (operator != null && value !== void 0) {
2381
+ addCondition("not", void 0, `${expression}.${operator}.${stringifyFilterValue(value)}`);
2382
+ } else {
2383
+ addCondition("not", void 0, expression);
2384
+ }
2385
+ return self;
2386
+ },
2387
+ or(expression) {
2388
+ addCondition("or", void 0, expression);
2389
+ return self;
2390
+ }
2391
+ };
2392
+ }
2393
+ function toRpcSelect(columns) {
2394
+ if (!columns) return void 0;
2395
+ return Array.isArray(columns) ? columns.join(",") : columns;
2396
+ }
2397
+ function createRpcFilterMethods(filters, self) {
2398
+ const addFilter = (operator, column, value) => {
2399
+ filters.push({ column, operator, value });
2400
+ };
2401
+ return {
2402
+ eq(column, value) {
2403
+ addFilter("eq", column, value);
2404
+ return self;
2405
+ },
2406
+ neq(column, value) {
2407
+ addFilter("neq", column, value);
2408
+ return self;
2409
+ },
2410
+ gt(column, value) {
2411
+ addFilter("gt", column, value);
2412
+ return self;
2413
+ },
2414
+ gte(column, value) {
2415
+ addFilter("gte", column, value);
2416
+ return self;
2417
+ },
2418
+ lt(column, value) {
2419
+ addFilter("lt", column, value);
2420
+ return self;
2421
+ },
2422
+ lte(column, value) {
2423
+ addFilter("lte", column, value);
2424
+ return self;
2425
+ },
2426
+ like(column, value) {
2427
+ addFilter("like", column, value);
2428
+ return self;
2429
+ },
2430
+ ilike(column, value) {
2431
+ addFilter("ilike", column, value);
2432
+ return self;
2433
+ },
2434
+ is(column, value) {
2435
+ addFilter("is", column, value);
2436
+ return self;
2437
+ },
2438
+ in(column, values) {
2439
+ addFilter("in", column, values);
2440
+ return self;
2441
+ }
2442
+ };
2443
+ }
2444
+ function createRpcBuilder(functionName, args, baseOptions, client, formatGatewayResult) {
2445
+ const state = {
2446
+ filters: []
2447
+ };
2448
+ let selectedColumns;
2449
+ let selectedOptions;
2450
+ let promise = null;
2451
+ const executeRpc = async (columns, options) => {
2452
+ const mergedOptions = mergeOptions(baseOptions, options);
2453
+ const payload = {
2454
+ function: functionName,
2455
+ args,
2456
+ schema: mergedOptions?.schema,
2457
+ select: toRpcSelect(columns),
2458
+ filters: state.filters.length ? [...state.filters] : void 0,
2459
+ count: mergedOptions?.count,
2460
+ head: mergedOptions?.head,
2461
+ limit: state.limit,
2462
+ offset: state.offset,
2463
+ order: state.order
2464
+ };
2465
+ const response = await client.rpcGateway(payload, mergedOptions);
2466
+ return formatGatewayResult(response, { operation: "rpc" });
2467
+ };
2468
+ const run = (columns, options) => {
2469
+ const payloadColumns = columns ?? selectedColumns;
2470
+ const payloadOptions = options ?? selectedOptions;
2471
+ if (!promise) {
2472
+ promise = executeRpc(payloadColumns, payloadOptions);
2473
+ }
2474
+ return promise;
2475
+ };
2476
+ const builder = {};
2477
+ const filterMethods = createRpcFilterMethods(state.filters, builder);
2478
+ Object.assign(builder, filterMethods, {
2479
+ select(columns = selectedColumns, options) {
2480
+ selectedColumns = columns;
2481
+ selectedOptions = options ?? selectedOptions;
2482
+ return run(columns, options);
2483
+ },
2484
+ async single(columns, options) {
2485
+ const result = await run(columns, options);
2486
+ return toSingleResult(result);
2487
+ },
2488
+ maybeSingle(columns, options) {
2489
+ return builder.single(columns, options);
2490
+ },
2491
+ order(column, options) {
2492
+ state.order = { column, ascending: options?.ascending ?? true };
2493
+ return builder;
2494
+ },
2495
+ limit(count) {
2496
+ state.limit = count;
2497
+ return builder;
2498
+ },
2499
+ offset(count) {
2500
+ state.offset = count;
2501
+ return builder;
2502
+ },
2503
+ range(from, to) {
2504
+ state.offset = from;
2505
+ state.limit = to - from + 1;
2506
+ return builder;
2507
+ },
2508
+ then(onfulfilled, onrejected) {
2509
+ return run(selectedColumns, selectedOptions).then(onfulfilled, onrejected);
2510
+ },
2511
+ catch(onrejected) {
2512
+ return run(selectedColumns, selectedOptions).catch(onrejected);
2513
+ },
2514
+ finally(onfinally) {
2515
+ return run(selectedColumns, selectedOptions).finally(onfinally);
2516
+ }
2517
+ });
2518
+ return builder;
2519
+ }
2520
+ function createTableBuilder(tableName, client, formatGatewayResult) {
2521
+ const state = {
2522
+ conditions: []
2523
+ };
2524
+ const addCondition = (operator, column, value, hints) => {
2525
+ const condition = { operator };
2526
+ if (column) {
2527
+ condition.column = column;
2528
+ if (operator === "eq") {
2529
+ condition.eq_column = column;
2530
+ }
2531
+ }
2532
+ if (value !== void 0) {
2533
+ condition.value = value;
2534
+ if (operator === "eq") {
2535
+ condition.eq_value = value;
2536
+ }
2537
+ }
2538
+ if (hints?.valueCast) {
2539
+ condition.value_cast = hints.valueCast;
2540
+ if (operator === "eq") {
2541
+ condition.eq_value_cast = hints.valueCast;
2542
+ }
2543
+ }
2544
+ if (hints?.columnCast) {
2545
+ condition.column_cast = hints.columnCast;
2546
+ if (operator === "eq") {
2547
+ condition.eq_column_cast = hints.columnCast;
2548
+ }
2549
+ }
2550
+ state.conditions.push(condition);
2551
+ };
2552
+ const builder = {};
2553
+ const filterMethods = createFilterMethods(
2554
+ state,
2555
+ addCondition,
2556
+ builder
2557
+ );
2558
+ const runSelect = async (columns = DEFAULT_COLUMNS, options) => {
2559
+ const resolvedTableName = resolveTableNameForCall(tableName, options?.schema);
2560
+ const conditions = state.conditions.length ? state.conditions.map((condition) => ({ ...condition })) : void 0;
2561
+ const hasTypedEqualityComparison = conditions?.some(
2562
+ (condition) => condition.operator === "eq" && (condition.value_cast !== void 0 || condition.column_cast !== void 0)
2563
+ ) ?? false;
2564
+ if (hasTypedEqualityComparison && !options?.head && !options?.count && conditions) {
2565
+ const query = buildTypedSelectQuery({
2566
+ tableName: resolvedTableName,
2567
+ columns,
2568
+ conditions,
2569
+ limit: state.limit,
2570
+ offset: state.offset,
2571
+ currentPage: state.currentPage,
2572
+ pageSize: state.pageSize,
2573
+ order: state.order
2574
+ });
2575
+ if (query) {
2576
+ const queryResponse = await client.queryGateway({ query }, options);
2577
+ return formatGatewayResult(queryResponse, { table: resolvedTableName, operation: "select" });
2578
+ }
2579
+ }
2580
+ const payload = {
2581
+ table_name: resolvedTableName,
2582
+ columns,
2583
+ conditions,
2584
+ limit: state.limit,
2585
+ offset: state.offset,
2586
+ current_page: state.currentPage,
2587
+ page_size: state.pageSize,
2588
+ total_pages: state.totalPages,
2589
+ sort_by: state.order,
2590
+ strip_nulls: options?.stripNulls ?? true,
2591
+ count: options?.count,
2592
+ head: options?.head
2593
+ };
2594
+ const response = await client.fetchGateway(payload, options);
2595
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "select" });
2596
+ };
2597
+ const createSelectChain = (columns, options) => {
2598
+ const chain = {};
2599
+ const filterMethods2 = createFilterMethods(state, addCondition, chain);
2600
+ Object.assign(chain, filterMethods2, {
2601
+ async single(cols, opts) {
2602
+ const r = await runSelect(cols ?? columns, opts ?? options);
2603
+ return toSingleResult(r);
2604
+ },
2605
+ maybeSingle(cols, opts) {
2606
+ return chain.single(cols, opts);
2607
+ },
2608
+ then(onfulfilled, onrejected) {
2609
+ return runSelect(columns, options).then(onfulfilled, onrejected);
2610
+ },
2611
+ catch(onrejected) {
2612
+ return runSelect(columns, options).catch(onrejected);
2613
+ },
2614
+ finally(onfinally) {
2615
+ return runSelect(columns, options).finally(onfinally);
2616
+ }
2617
+ });
2618
+ return chain;
2619
+ };
2620
+ Object.assign(builder, filterMethods, {
2621
+ reset() {
2622
+ state.conditions = [];
2623
+ state.limit = void 0;
2624
+ state.offset = void 0;
2625
+ state.order = void 0;
2626
+ state.currentPage = void 0;
2627
+ state.pageSize = void 0;
2628
+ state.totalPages = void 0;
2629
+ return builder;
2630
+ },
2631
+ select(columns = DEFAULT_COLUMNS, options) {
2632
+ return createSelectChain(columns, options);
2633
+ },
2634
+ insert(values, options) {
2635
+ if (Array.isArray(values)) {
2636
+ const executeInsertMany = async (columns, selectOptions) => {
2637
+ const mergedOptions = mergeOptions(options, selectOptions);
2638
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
2639
+ const payload = {
2640
+ table_name: resolvedTableName,
2641
+ insert_body: asAthenaJsonObjectArray(values)
2642
+ };
2643
+ if (columns) payload.columns = columns;
2644
+ if (mergedOptions?.count) payload.count = mergedOptions.count;
2645
+ if (mergedOptions?.head) payload.head = mergedOptions.head;
2646
+ if (mergedOptions?.defaultToNull !== void 0) {
2647
+ payload.default_to_null = mergedOptions.defaultToNull;
2648
+ }
2649
+ const response = await client.insertGateway(payload, mergedOptions);
2650
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "insert" });
2651
+ };
2652
+ return createMutationQuery(executeInsertMany);
2653
+ }
2654
+ const executeInsertOne = async (columns, selectOptions) => {
2655
+ const mergedOptions = mergeOptions(options, selectOptions);
2656
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
2657
+ const payload = {
2658
+ table_name: resolvedTableName,
2659
+ insert_body: asAthenaJsonObject(values)
2660
+ };
2661
+ if (columns) payload.columns = columns;
2662
+ if (mergedOptions?.count) payload.count = mergedOptions.count;
2663
+ if (mergedOptions?.head) payload.head = mergedOptions.head;
2664
+ if (mergedOptions?.defaultToNull !== void 0) {
2665
+ payload.default_to_null = mergedOptions.defaultToNull;
2666
+ }
2667
+ const response = await client.insertGateway(payload, mergedOptions);
2668
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "insert" });
2669
+ };
2670
+ return createMutationQuery(executeInsertOne);
2671
+ },
2672
+ upsert(values, options) {
2673
+ if (Array.isArray(values)) {
2674
+ const executeUpsertMany = async (columns, selectOptions) => {
2675
+ const mergedOptions = mergeOptions(options, selectOptions);
2676
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
2677
+ const payload = {
2678
+ table_name: resolvedTableName,
2679
+ insert_body: asAthenaJsonObjectArray(values),
2680
+ update_body: options?.updateBody ? asAthenaJsonObject(options.updateBody) : void 0
2681
+ };
2682
+ if (columns) payload.columns = columns;
2683
+ if (options?.onConflict) payload.on_conflict = options.onConflict;
2684
+ if (mergedOptions?.count) payload.count = mergedOptions.count;
2685
+ if (mergedOptions?.head) payload.head = mergedOptions.head;
2686
+ if (mergedOptions?.defaultToNull !== void 0) {
2687
+ payload.default_to_null = mergedOptions.defaultToNull;
2688
+ }
2689
+ const response = await client.insertGateway(payload, mergedOptions);
2690
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "insert" });
2691
+ };
2692
+ return createMutationQuery(executeUpsertMany);
2693
+ }
2694
+ const executeUpsertOne = async (columns, selectOptions) => {
2695
+ const mergedOptions = mergeOptions(options, selectOptions);
2696
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
2697
+ const payload = {
2698
+ table_name: resolvedTableName,
2699
+ insert_body: asAthenaJsonObject(values),
2700
+ update_body: options?.updateBody ? asAthenaJsonObject(options.updateBody) : void 0
2701
+ };
2702
+ if (columns) payload.columns = columns;
2703
+ if (options?.onConflict) payload.on_conflict = options.onConflict;
2704
+ if (mergedOptions?.count) payload.count = mergedOptions.count;
2705
+ if (mergedOptions?.head) payload.head = mergedOptions.head;
2706
+ if (mergedOptions?.defaultToNull !== void 0) {
2707
+ payload.default_to_null = mergedOptions.defaultToNull;
2708
+ }
2709
+ const response = await client.insertGateway(payload, mergedOptions);
2710
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "insert" });
2711
+ };
2712
+ return createMutationQuery(executeUpsertOne);
2713
+ },
2714
+ update(values, options) {
2715
+ const executeUpdate = async (columns, selectOptions) => {
2716
+ const filters = state.conditions.length ? [...state.conditions] : void 0;
2717
+ const mergedOptions = mergeOptions(options, selectOptions);
2718
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
2719
+ const payload = {
2720
+ table_name: resolvedTableName,
2721
+ set: asAthenaJsonObject(values),
2722
+ conditions: filters,
2723
+ strip_nulls: mergedOptions?.stripNulls ?? true
2724
+ };
2725
+ if (state.order) payload.sort_by = state.order;
2726
+ if (state.currentPage !== void 0) payload.current_page = state.currentPage;
2727
+ if (state.pageSize !== void 0) payload.page_size = state.pageSize;
2728
+ if (state.totalPages !== void 0) payload.total_pages = state.totalPages;
2729
+ if (columns) payload.columns = columns;
2730
+ const response = await client.updateGateway(payload, mergedOptions);
2731
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "update" });
2732
+ };
2733
+ const mutation = createMutationQuery(executeUpdate, null);
2734
+ const updateChain = {};
2735
+ const filterMethods2 = createFilterMethods(state, addCondition, updateChain);
2736
+ Object.assign(updateChain, filterMethods2, mutation);
2737
+ return updateChain;
2738
+ },
2739
+ delete(options) {
2740
+ const filters = state.conditions.length ? [...state.conditions] : void 0;
2741
+ const resourceId = options?.resourceId ?? getResourceId(state);
2742
+ if (!resourceId && !filters?.length) {
2743
+ throw new Error('delete requires a resource_id either via eq("resource_id", ...) or options.resourceId');
2744
+ }
2745
+ const executeDelete = async (columns, selectOptions) => {
2746
+ const mergedOptions = mergeOptions(options, selectOptions);
2747
+ const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
2748
+ const payload = {
2749
+ table_name: resolvedTableName,
2750
+ resource_id: resourceId,
2751
+ conditions: filters
2752
+ };
2753
+ if (state.order) payload.sort_by = state.order;
2754
+ if (state.currentPage !== void 0) payload.current_page = state.currentPage;
2755
+ if (state.pageSize !== void 0) payload.page_size = state.pageSize;
2756
+ if (state.totalPages !== void 0) payload.total_pages = state.totalPages;
2757
+ if (columns) payload.columns = columns;
2758
+ const response = await client.deleteGateway(payload, mergedOptions);
2759
+ return formatGatewayResult(response, { table: resolvedTableName, operation: "delete" });
2760
+ };
2761
+ return createMutationQuery(executeDelete, null);
2762
+ },
2763
+ async single(columns, options) {
2764
+ const response = await builder.select(columns, options);
2765
+ return toSingleResult(response);
2766
+ },
2767
+ async maybeSingle(columns, options) {
2768
+ return builder.single(columns, options);
2769
+ }
2770
+ });
2771
+ return builder;
2772
+ }
2773
+ function createQueryBuilder(client, formatGatewayResult) {
2774
+ return async function query(query, options) {
2775
+ const normalizedQuery = query.trim();
2776
+ if (!normalizedQuery) {
2777
+ throw new Error("query requires a non-empty string");
2778
+ }
2779
+ const response = await client.queryGateway({ query: normalizedQuery }, options);
2780
+ return formatGatewayResult(response, { operation: "query" });
2781
+ };
2782
+ }
2783
+ function createClientFromConfig(config) {
2784
+ const gateway = createAthenaGatewayClient({
2785
+ baseUrl: config.baseUrl,
2786
+ apiKey: config.apiKey,
2787
+ client: config.client,
2788
+ backend: config.backend,
2789
+ headers: config.headers
2790
+ });
2791
+ const formatGatewayResult = createResultFormatter(config.experimental);
2792
+ const auth = createAuthClient(config.auth);
2793
+ const from = (table) => createTableBuilder(table, gateway, formatGatewayResult);
2794
+ const rpc = (fn, args, options) => {
2795
+ const normalizedFn = fn.trim();
2796
+ if (!normalizedFn) {
2797
+ throw new Error("rpc requires a function name");
2798
+ }
2799
+ return createRpcBuilder(
2800
+ normalizedFn,
2801
+ args,
2802
+ options,
2803
+ gateway,
2804
+ formatGatewayResult
2805
+ );
2806
+ };
2807
+ const query = createQueryBuilder(gateway, formatGatewayResult);
2808
+ const db = createDbModule({ from, rpc, query });
2809
+ return {
2810
+ from,
2811
+ db,
2812
+ rpc,
2813
+ query,
2814
+ auth: auth.auth
2815
+ };
2816
+ }
2817
+ var DEFAULT_BACKEND = { type: "athena" };
2818
+ function toBackendConfig(b) {
2819
+ if (!b) return DEFAULT_BACKEND;
2820
+ return typeof b === "string" ? { type: b } : b;
2821
+ }
2822
+ var AthenaClientBuilderImpl = class {
2823
+ baseUrl;
2824
+ apiKey;
2825
+ backendConfig = DEFAULT_BACKEND;
2826
+ clientName;
2827
+ defaultHeaders;
2828
+ isHealthTrackingEnabled = false;
2829
+ url(url) {
2830
+ this.baseUrl = url;
2831
+ return this;
2832
+ }
2833
+ key(apiKey) {
2834
+ this.apiKey = apiKey;
2835
+ return this;
2836
+ }
2837
+ backend(backend) {
2838
+ this.backendConfig = toBackendConfig(backend);
2839
+ return this;
2840
+ }
2841
+ client(clientName) {
2842
+ this.clientName = clientName;
2843
+ return this;
2844
+ }
2845
+ headers(headers) {
2846
+ this.defaultHeaders = headers;
2847
+ return this;
2848
+ }
2849
+ healthTracking(enabled) {
2850
+ this.isHealthTrackingEnabled = enabled;
2851
+ return this;
2852
+ }
2853
+ build() {
2854
+ if (!this.baseUrl || !this.apiKey) {
2855
+ throw new Error("AthenaClient requires url and key; call .url() and .key() before .build()");
2856
+ }
2857
+ return createClientFromConfig({
2858
+ baseUrl: this.baseUrl,
2859
+ apiKey: this.apiKey,
2860
+ client: this.clientName,
2861
+ backend: this.backendConfig,
2862
+ headers: this.defaultHeaders,
2863
+ healthTracking: this.isHealthTrackingEnabled
2864
+ });
2865
+ }
2866
+ };
2867
+ var AthenaClient = class _AthenaClient {
2868
+ /** Create a fluent builder for a strongly-typed Athena SDK client. */
2869
+ static builder() {
2870
+ return new AthenaClientBuilderImpl();
2871
+ }
2872
+ /** Build a client from process environment variables. */
2873
+ static fromEnvironment() {
2874
+ const url = process.env.ATHENA_URL ?? process.env.ATHENA_GATEWAY_URL;
2875
+ const key = process.env.ATHENA_API_KEY ?? process.env.ATHENA_GATEWAY_API_KEY;
2876
+ if (!url || !key) {
2877
+ throw new Error(
2878
+ "ATHENA_URL and ATHENA_API_KEY (or ATHENA_GATEWAY_URL and ATHENA_GATEWAY_API_KEY) are required"
2879
+ );
2880
+ }
2881
+ return _AthenaClient.builder().url(url).key(key).build();
2882
+ }
2883
+ };
2884
+ function createClient(url, apiKey, options) {
2885
+ return createClientFromConfig({
2886
+ baseUrl: url,
2887
+ apiKey,
2888
+ client: options?.client,
2889
+ backend: toBackendConfig(options?.backend),
2890
+ headers: options?.headers,
2891
+ auth: options?.auth,
2892
+ experimental: options?.experimental
2893
+ });
2894
+ }
2895
+
2896
+ // src/gateway/types.ts
2897
+ var Backend = {
2898
+ Athena: { type: "athena" },
2899
+ Postgrest: { type: "postgrest" },
2900
+ PostgreSQL: { type: "postgresql" },
2901
+ ScyllaDB: { type: "scylladb" }
2902
+ };
2903
+
2904
+ // src/schema/definitions.ts
2905
+ function defineModel(input) {
2906
+ return input;
2907
+ }
2908
+ function defineSchema(models) {
2909
+ return { models };
2910
+ }
2911
+ function defineDatabase(schemas) {
2912
+ return { schemas };
2913
+ }
2914
+ function defineRegistry(databases) {
2915
+ return databases;
2916
+ }
2917
+
2918
+ // src/schema/typed-client.ts
2919
+ var TenantHeaderMapper = class {
2920
+ constructor(tenantKeyMap) {
2921
+ this.tenantKeyMap = tenantKeyMap;
2922
+ }
2923
+ apply(baseHeaders, tenantContext) {
2924
+ const headers = {
2925
+ ...baseHeaders ?? {}
2926
+ };
2927
+ for (const [tenantKey, headerName] of Object.entries(this.tenantKeyMap)) {
2928
+ const tenantValue = tenantContext[tenantKey];
2929
+ if (tenantValue === void 0 || tenantValue === null) {
2930
+ continue;
2931
+ }
2932
+ headers[headerName] = String(tenantValue);
2933
+ }
2934
+ return Object.keys(headers).length > 0 ? headers : void 0;
2935
+ }
2936
+ };
2937
+ var RegistryNavigator = class {
2938
+ constructor(registry) {
2939
+ this.registry = registry;
2940
+ }
2941
+ resolveModel(database, schema, model) {
2942
+ const databaseDef = this.registry[database];
2943
+ if (!databaseDef) {
2944
+ throw new Error(`Unknown database "${database}"`);
2945
+ }
2946
+ const schemaDef = databaseDef.schemas[schema];
2947
+ if (!schemaDef) {
2948
+ throw new Error(`Unknown schema "${schema}" in database "${database}"`);
2949
+ }
2950
+ const modelDef = schemaDef.models[model];
2951
+ if (!modelDef) {
2952
+ throw new Error(`Unknown model "${model}" in schema "${schema}"`);
2953
+ }
2954
+ return modelDef;
2955
+ }
2956
+ resolveTableName(schema, model, modelDef) {
2957
+ if (modelDef.meta.tableName) {
2958
+ return modelDef.meta.tableName;
2959
+ }
2960
+ const schemaName = modelDef.meta.schema ?? schema;
2961
+ const modelName = modelDef.meta.model ?? model;
2962
+ return `${schemaName}.${modelName}`;
2963
+ }
2964
+ };
2965
+ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
2966
+ registry;
2967
+ tenantKeyMap;
2968
+ tenantContext;
2969
+ db;
2970
+ baseClient;
2971
+ registryNavigator;
2972
+ tenantHeaderMapper;
2973
+ clientOptions;
2974
+ url;
2975
+ apiKey;
2976
+ constructor(input) {
2977
+ this.registry = input.registry;
2978
+ this.url = input.url;
2979
+ this.apiKey = input.apiKey;
2980
+ const tenantKeyMap = input.options?.tenantKeyMap ?? {};
2981
+ const tenantContext = input.options?.tenantContext ?? {};
2982
+ this.tenantKeyMap = tenantKeyMap;
2983
+ this.tenantContext = tenantContext;
2984
+ this.tenantHeaderMapper = new TenantHeaderMapper(tenantKeyMap);
2985
+ this.registryNavigator = new RegistryNavigator(input.registry);
2986
+ this.clientOptions = {
2987
+ backend: input.options?.backend,
2988
+ client: input.options?.client,
2989
+ headers: input.options?.headers
2990
+ };
2991
+ this.baseClient = createClient(this.url, this.apiKey, {
2992
+ backend: this.clientOptions.backend,
2993
+ client: this.clientOptions.client,
2994
+ headers: this.tenantHeaderMapper.apply(this.clientOptions.headers, tenantContext)
2995
+ });
2996
+ this.db = this.baseClient.db;
2997
+ }
2998
+ from(table) {
2999
+ return this.baseClient.from(table);
3000
+ }
3001
+ rpc(fn, args, options) {
3002
+ return this.baseClient.rpc(fn, args, options);
3003
+ }
3004
+ query(query, options) {
3005
+ return this.baseClient.query(query, options);
3006
+ }
3007
+ withTenantContext(context) {
3008
+ return new _TypedAthenaClientImpl({
3009
+ registry: this.registry,
3010
+ url: this.url,
3011
+ apiKey: this.apiKey,
3012
+ options: {
3013
+ ...this.clientOptions,
3014
+ tenantKeyMap: this.tenantKeyMap,
3015
+ tenantContext: {
3016
+ ...this.tenantContext,
3017
+ ...context ?? {}
3018
+ }
3019
+ }
3020
+ });
3021
+ }
3022
+ fromModel(database, schema, model) {
3023
+ const modelDef = this.registryNavigator.resolveModel(database, schema, model);
3024
+ const tableName = this.registryNavigator.resolveTableName(schema, model, modelDef);
3025
+ return this.baseClient.from(tableName);
3026
+ }
3027
+ };
3028
+ function createTypedClient(registry, url, apiKey, options) {
3029
+ return new TypedAthenaClientImpl({
3030
+ registry,
3031
+ url,
3032
+ apiKey,
3033
+ options
3034
+ });
3035
+ }
3036
+
3037
+ // src/schema/model-form.ts
3038
+ function resolveNullishValue(mode) {
3039
+ if (mode === "undefined") return void 0;
3040
+ if (mode === "null") return null;
3041
+ return "";
3042
+ }
3043
+ function isRecord4(value) {
3044
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
3045
+ }
3046
+ function isNullableColumn(model, key) {
3047
+ const nullable = model.meta.nullable;
3048
+ return nullable?.[key] === true;
3049
+ }
3050
+ function toModelFormDefaults(model, values, options) {
3051
+ const source = values;
3052
+ if (!isRecord4(source)) {
3053
+ return {};
3054
+ }
3055
+ const mode = options?.nullishMode ?? "empty-string";
3056
+ const nullishValue = resolveNullishValue(mode);
3057
+ const result = {};
3058
+ for (const [key, value] of Object.entries(source)) {
3059
+ if (value === null && isNullableColumn(model, key)) {
3060
+ result[key] = nullishValue;
3061
+ continue;
3062
+ }
3063
+ result[key] = value;
3064
+ }
3065
+ return result;
3066
+ }
3067
+ function toModelPayload(model, formValues, options) {
3068
+ const emptyStringAsNull = options?.emptyStringAsNull ?? true;
3069
+ const stripUndefined = options?.stripUndefined ?? true;
3070
+ const result = {};
3071
+ for (const [key, rawValue] of Object.entries(formValues)) {
3072
+ if (rawValue === void 0 && stripUndefined) {
3073
+ continue;
3074
+ }
3075
+ if (emptyStringAsNull && rawValue === "" && isNullableColumn(model, key)) {
3076
+ result[key] = null;
3077
+ continue;
3078
+ }
3079
+ result[key] = rawValue;
3080
+ }
3081
+ return result;
3082
+ }
3083
+ function createModelFormAdapter(model) {
3084
+ return {
3085
+ model,
3086
+ toDefaults(values, options) {
3087
+ return toModelFormDefaults(model, values, options);
3088
+ },
3089
+ toInsert(values, options) {
3090
+ return toModelPayload(model, values, options);
3091
+ },
3092
+ toUpdate(values, options) {
3093
+ return toModelPayload(model, values, options);
3094
+ }
3095
+ };
3096
+ }
3097
+
3098
+ // src/generator/schema-selection.ts
3099
+ var DEFAULT_POSTGRES_SCHEMAS = ["public"];
3100
+ function collectSchemaNames(input) {
3101
+ if (!input) {
3102
+ return [];
3103
+ }
3104
+ const values = typeof input === "string" ? [input] : input;
3105
+ return values.flatMap((value) => String(value).split(","));
3106
+ }
3107
+ function normalizeSchemaSelection(input) {
3108
+ const schemas = [];
3109
+ const seen = /* @__PURE__ */ new Set();
3110
+ for (const value of collectSchemaNames(input)) {
3111
+ const schema = value.trim();
3112
+ if (!schema || seen.has(schema)) {
3113
+ continue;
3114
+ }
3115
+ seen.add(schema);
3116
+ schemas.push(schema);
3117
+ }
3118
+ return schemas.length > 0 ? schemas : [...DEFAULT_POSTGRES_SCHEMAS];
3119
+ }
3120
+ function resolveProviderSchemas(providerConfig) {
3121
+ if (providerConfig.kind === "postgres") {
3122
+ return normalizeSchemaSelection(providerConfig.schemas);
3123
+ }
3124
+ return [...DEFAULT_POSTGRES_SCHEMAS];
3125
+ }
3126
+
3127
+ // src/generator/postgres-type-mapping.ts
3128
+ var NUMBER_TYPES = /* @__PURE__ */ new Set([
3129
+ "int2",
3130
+ "int4",
3131
+ "float4",
3132
+ "float8",
3133
+ "smallint",
3134
+ "integer",
3135
+ "real",
3136
+ "double precision"
3137
+ ]);
3138
+ var STRING_NUMERIC_TYPES = /* @__PURE__ */ new Set([
3139
+ "int8",
3140
+ "bigint",
3141
+ "serial8",
3142
+ "bigserial",
3143
+ "numeric",
3144
+ "decimal",
3145
+ "money"
3146
+ ]);
3147
+ var TEXT_TYPES = /* @__PURE__ */ new Set([
3148
+ "char",
3149
+ "bpchar",
3150
+ "varchar",
3151
+ "character varying",
3152
+ "text",
3153
+ "citext",
3154
+ "name",
3155
+ "uuid",
3156
+ "date",
3157
+ "time",
3158
+ "timetz",
3159
+ "timestamp",
3160
+ "timestamptz",
3161
+ "interval",
3162
+ "inet",
3163
+ "cidr",
3164
+ "macaddr",
3165
+ "macaddr8",
3166
+ "point",
3167
+ "line",
3168
+ "lseg",
3169
+ "box",
3170
+ "path",
3171
+ "polygon",
3172
+ "circle",
3173
+ "bit",
3174
+ "varbit",
3175
+ "xml",
3176
+ "tsvector",
3177
+ "tsquery",
3178
+ "jsonpath"
3179
+ ]);
3180
+ function normalizeTypeLabel(column) {
3181
+ const preferred = (column.udtName || column.dataType).toLowerCase().trim();
3182
+ if (column.arrayDimensions > 0 && preferred.startsWith("_")) {
3183
+ return preferred.slice(1);
3184
+ }
3185
+ return preferred;
3186
+ }
3187
+ function wrapArrayType(baseType, depth) {
3188
+ let wrapped = baseType;
3189
+ for (let index = 0; index < depth; index += 1) {
3190
+ wrapped = `Array<${wrapped}>`;
3191
+ }
3192
+ return wrapped;
3193
+ }
3194
+ function resolveScalarType(column) {
3195
+ const label = normalizeTypeLabel(column);
3196
+ if (NUMBER_TYPES.has(label)) {
3197
+ return "number";
3198
+ }
3199
+ if (STRING_NUMERIC_TYPES.has(label)) {
3200
+ return "string";
3201
+ }
3202
+ if (label === "bool" || label === "boolean") {
3203
+ return "boolean";
3204
+ }
3205
+ if (label === "bytea") {
3206
+ return "Buffer";
3207
+ }
3208
+ if (label === "json" || label === "jsonb") {
3209
+ return "Record<string, unknown>";
3210
+ }
3211
+ if (TEXT_TYPES.has(label)) {
3212
+ return "string";
3213
+ }
3214
+ if (label.endsWith("range") || label.endsWith("multirange")) {
3215
+ return "string";
3216
+ }
3217
+ return "unknown";
3218
+ }
3219
+ function resolveKindAwareType(column) {
3220
+ if (column.typeKind === "enum") {
3221
+ const values = column.enumValues ?? [];
3222
+ if (values.length === 0) {
3223
+ return "string";
3224
+ }
3225
+ return values.map((value) => `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`).join(" | ");
3226
+ }
3227
+ if (column.typeKind === "composite") {
3228
+ return "Record<string, unknown>";
3229
+ }
3230
+ if (column.typeKind === "domain" || column.typeKind === "range" || column.typeKind === "multirange") {
3231
+ return "string";
3232
+ }
3233
+ return resolveScalarType(column);
3234
+ }
3235
+ function resolvePostgresColumnType(column) {
3236
+ const baseType = resolveKindAwareType(column);
3237
+ if (!column.arrayDimensions || column.arrayDimensions <= 0) {
3238
+ return baseType;
3239
+ }
3240
+ return wrapArrayType(baseType, column.arrayDimensions);
3241
+ }
3242
+
3243
+ // src/browser.ts
3244
+ function throwBrowserUnsupported(apiName) {
3245
+ throw new Error(
3246
+ `@xylex-group/athena: ${apiName} is not available in browser bundles. Use this API in a Node.js runtime.`
3247
+ );
3248
+ }
3249
+ function createPostgresIntrospectionProvider(_options) {
3250
+ return throwBrowserUnsupported("createPostgresIntrospectionProvider");
3251
+ }
3252
+ function defineGeneratorConfig(config) {
3253
+ return config;
3254
+ }
3255
+ function findGeneratorConfigPath(_cwd) {
3256
+ return throwBrowserUnsupported("findGeneratorConfigPath");
3257
+ }
3258
+ async function loadGeneratorConfig(_options = {}) {
3259
+ return throwBrowserUnsupported("loadGeneratorConfig");
3260
+ }
3261
+ function normalizeGeneratorConfig(_input) {
3262
+ return throwBrowserUnsupported("normalizeGeneratorConfig");
3263
+ }
3264
+ function generateArtifactsFromSnapshot(_snapshot, _config) {
3265
+ return throwBrowserUnsupported("generateArtifactsFromSnapshot");
3266
+ }
3267
+ function resolveGeneratorProvider(_providerConfig, _experimentalFlags) {
3268
+ return throwBrowserUnsupported("resolveGeneratorProvider");
3269
+ }
3270
+ async function runSchemaGenerator(_options = {}) {
3271
+ return throwBrowserUnsupported("runSchemaGenerator");
3272
+ }
3273
+
3274
+ export { AthenaClient, AthenaError, AthenaErrorCategory, AthenaErrorCode, AthenaErrorKind, AthenaGatewayError, Backend, DEFAULT_POSTGRES_SCHEMAS, assertInt, coerceInt, createAuthClient, createClient, createModelFormAdapter, createPostgresIntrospectionProvider, createTypedClient, defineDatabase, defineGeneratorConfig, defineModel, defineRegistry, defineSchema, findGeneratorConfigPath, generateArtifactsFromSnapshot, identifier, isAthenaGatewayError, isOk, loadGeneratorConfig, normalizeAthenaError, normalizeGeneratorConfig, normalizeSchemaSelection, parseBooleanFlag, requireAffected, requireSuccess, resolveGeneratorProvider, resolvePostgresColumnType, resolveProviderSchemas, runSchemaGenerator, toModelFormDefaults, toModelPayload, unwrap, unwrapOne, unwrapRows, withRetry };
3275
+ //# sourceMappingURL=browser.js.map
3276
+ //# sourceMappingURL=browser.js.map