@xylex-group/athena 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +1 -1
  2. package/dist/admin.cjs +55 -1
  3. package/dist/admin.cjs.map +1 -1
  4. package/dist/admin.d.cts +32 -8
  5. package/dist/admin.d.ts +32 -8
  6. package/dist/admin.js +54 -2
  7. package/dist/admin.js.map +1 -1
  8. package/dist/athena-auth-url-C1FbVmN6.d.cts +200 -0
  9. package/dist/athena-auth-url-C1FbVmN6.d.ts +200 -0
  10. package/dist/{athena-request-headers-C7Jy-c_D.d.ts → athena-request-headers-DzimbvOA.d.ts} +48 -200
  11. package/dist/{athena-request-headers-DujFFyMU.d.cts → athena-request-headers-Lr_m8xCV.d.cts} +48 -200
  12. package/dist/billing.cjs +1 -1
  13. package/dist/billing.cjs.map +1 -1
  14. package/dist/billing.js +1 -1
  15. package/dist/billing.js.map +1 -1
  16. package/dist/browser.cjs +602 -16
  17. package/dist/browser.cjs.map +1 -1
  18. package/dist/browser.d.cts +8 -7
  19. package/dist/browser.d.ts +8 -7
  20. package/dist/browser.js +593 -17
  21. package/dist/browser.js.map +1 -1
  22. package/dist/cli/index.cjs +141 -6
  23. package/dist/cli/index.cjs.map +1 -1
  24. package/dist/cli/index.d.cts +2 -2
  25. package/dist/cli/index.d.ts +2 -2
  26. package/dist/cli/index.js +141 -6
  27. package/dist/cli/index.js.map +1 -1
  28. package/dist/env.cjs +130 -0
  29. package/dist/env.cjs.map +1 -0
  30. package/dist/env.d.cts +70 -0
  31. package/dist/env.d.ts +70 -0
  32. package/dist/env.js +122 -0
  33. package/dist/env.js.map +1 -0
  34. package/dist/index.cjs +624 -19
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +8 -7
  37. package/dist/index.d.ts +8 -7
  38. package/dist/index.js +615 -20
  39. package/dist/index.js.map +1 -1
  40. package/dist/{model-form-BhWWsA-7.d.cts → model-form-3Gr8rkdT.d.cts} +24 -2
  41. package/dist/{model-form-BbdzJ9Uh.d.ts → model-form-CotpEL7z.d.ts} +24 -2
  42. package/dist/{module-xFd7_Igv.d.cts → module-CQmOaDzP.d.cts} +4 -4
  43. package/dist/{module-DKkJKOuJ.d.ts → module-CWkUTcUc.d.ts} +4 -4
  44. package/dist/next/client.cjs +123 -7
  45. package/dist/next/client.cjs.map +1 -1
  46. package/dist/next/client.d.cts +4 -3
  47. package/dist/next/client.d.ts +4 -3
  48. package/dist/next/client.js +123 -7
  49. package/dist/next/client.js.map +1 -1
  50. package/dist/next/server.cjs +1130 -364
  51. package/dist/next/server.cjs.map +1 -1
  52. package/dist/next/server.d.cts +121 -8
  53. package/dist/next/server.d.ts +121 -8
  54. package/dist/next/server.js +1120 -365
  55. package/dist/next/server.js.map +1 -1
  56. package/dist/{pipeline-DuKzYGia.d.cts → pipeline-BnRKO_Pd.d.cts} +1 -1
  57. package/dist/{pipeline-wer2G9xW.d.ts → pipeline-sWCmlFqu.d.ts} +1 -1
  58. package/dist/{proxy-request-headers-m4D2Tduy.d.ts → proxy-request-headers-CttlcuRb.d.ts} +1 -1
  59. package/dist/{proxy-request-headers-DGxdoyA0.d.cts → proxy-request-headers-pIBSn1Fw.d.cts} +1 -1
  60. package/dist/react.cjs +290 -31
  61. package/dist/react.cjs.map +1 -1
  62. package/dist/react.d.cts +59 -9
  63. package/dist/react.d.ts +59 -9
  64. package/dist/react.js +290 -32
  65. package/dist/react.js.map +1 -1
  66. package/dist/schema-handlers-BtT_IQFi.d.cts +138 -0
  67. package/dist/schema-handlers-VjFDhIMw.d.ts +138 -0
  68. package/dist/social-providers.d.cts +1 -1
  69. package/dist/social-providers.d.ts +1 -1
  70. package/dist/{types-CccOiXPo.d.ts → types-BDX8zS7w.d.ts} +12 -0
  71. package/dist/{types-AOY-GLu8.d.cts → types-BVKpQmfY.d.cts} +11 -0
  72. package/dist/{types-AOY-GLu8.d.ts → types-BVKpQmfY.d.ts} +11 -0
  73. package/dist/{types-1ztXDgPa.d.cts → types-D-Am7YSd.d.cts} +12 -0
  74. package/dist/utils.cjs +30 -0
  75. package/dist/utils.cjs.map +1 -1
  76. package/dist/utils.d.cts +3 -2
  77. package/dist/utils.d.ts +3 -2
  78. package/dist/utils.js +30 -1
  79. package/dist/utils.js.map +1 -1
  80. package/dist/{v3-client-CWfZHcKL.d.cts → v3-client-G1SLeHRa.d.cts} +23 -1
  81. package/dist/{v3-client-DZp2NEhK.d.ts → v3-client-ao8BWQ8v.d.ts} +23 -1
  82. package/package.json +16 -2
package/dist/browser.cjs CHANGED
@@ -2005,7 +2005,7 @@ function buildAthenaGatewayUrl(baseUrl, path) {
2005
2005
 
2006
2006
  // package.json
2007
2007
  var package_default = {
2008
- version: "3.1.0"
2008
+ version: "3.3.0"
2009
2009
  };
2010
2010
 
2011
2011
  // src/sdk-version.ts
@@ -4765,6 +4765,14 @@ function createAuthModule(config = {}, runtimeOptions = {}) {
4765
4765
  changeEmailVerify: (input, options) => getWithQuery("/change-email/verify", input, options),
4766
4766
  deleteUserVerify: (input, options) => getWithQuery("/delete-user/verify", input, options),
4767
4767
  changePassword: (input, options) => postGeneric("/change-password", input, options),
4768
+ // Better Auth UI flat method aliases (also nested under session/account/social/user).
4769
+ listSessions: (input, options) => getGeneric("/list-sessions", input, options),
4770
+ revokeSession: sessionRevokeBinding,
4771
+ revokeOtherSessions,
4772
+ listAccounts: (input, options) => getGeneric("/list-accounts", input, options),
4773
+ unlinkAccount: (input, options) => postGeneric("/unlink-account", input, options),
4774
+ linkSocial: (input, options) => postGeneric("/link-social", input, options),
4775
+ updateUser: (input, options) => postGeneric("/update-user", input, options),
4768
4776
  user: {
4769
4777
  update: (input, options) => postGeneric("/update-user", input, options),
4770
4778
  delete: (input, options) => postGeneric("/delete-user", input, options),
@@ -10574,6 +10582,82 @@ function mergeAthenaRequestContexts(base, override) {
10574
10582
  };
10575
10583
  }
10576
10584
 
10585
+ // src/diagnostics.ts
10586
+ function readProcessEnv2() {
10587
+ try {
10588
+ return globalThis.process?.env ?? {};
10589
+ } catch {
10590
+ return {};
10591
+ }
10592
+ }
10593
+ function isTruthyEnv(value) {
10594
+ if (!value) return false;
10595
+ const normalized = value.trim().toLowerCase();
10596
+ return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
10597
+ }
10598
+ function isQuietAthenaDiagnosticsEnvironment(env = readProcessEnv2()) {
10599
+ const nodeEnv = env.NODE_ENV?.trim().toLowerCase();
10600
+ if (nodeEnv === "production") {
10601
+ return true;
10602
+ }
10603
+ if (isTruthyEnv(env.OPENNEXT_BUILD)) {
10604
+ return true;
10605
+ }
10606
+ const nextPhase = env.NEXT_PHASE?.trim();
10607
+ if (nextPhase === "phase-production-build") {
10608
+ return true;
10609
+ }
10610
+ if (isTruthyEnv(env.CI) && nodeEnv !== "test") {
10611
+ if (nodeEnv === "production" || isTruthyEnv(env.OPENNEXT_BUILD)) {
10612
+ return true;
10613
+ }
10614
+ }
10615
+ return false;
10616
+ }
10617
+ function resolveBooleanFlag(explicit, mode, quiet) {
10618
+ if (typeof explicit === "boolean") {
10619
+ return explicit;
10620
+ }
10621
+ if (mode === true) {
10622
+ return true;
10623
+ }
10624
+ if (mode === false) {
10625
+ return false;
10626
+ }
10627
+ if (mode === "auto") {
10628
+ return false;
10629
+ }
10630
+ return false;
10631
+ }
10632
+ function resolveAthenaClientDiagnostics(input) {
10633
+ const env = input.env ?? readProcessEnv2();
10634
+ const quiet = isQuietAthenaDiagnosticsEnvironment(env);
10635
+ const mode = input.diagnostics;
10636
+ const effectiveMode = mode === "auto" && quiet ? false : mode;
10637
+ const debugAst = resolveBooleanFlag(input.debugAst, effectiveMode);
10638
+ const findManyAst = resolveBooleanFlag(input.findManyAst, effectiveMode);
10639
+ let traceQueries;
10640
+ if (input.traceQueries !== void 0) {
10641
+ if (typeof input.traceQueries === "boolean") {
10642
+ traceQueries = input.traceQueries;
10643
+ } else if (effectiveMode === false || mode === "auto" && quiet) {
10644
+ const enabled = input.traceQueries.enabled;
10645
+ traceQueries = typeof enabled === "boolean" ? enabled ? input.traceQueries : false : false;
10646
+ } else {
10647
+ traceQueries = input.traceQueries;
10648
+ }
10649
+ } else if (effectiveMode === true) {
10650
+ traceQueries = true;
10651
+ } else {
10652
+ traceQueries = false;
10653
+ }
10654
+ return {
10655
+ debugAst,
10656
+ findManyAst,
10657
+ traceQueries
10658
+ };
10659
+ }
10660
+
10577
10661
  // src/v3-client.ts
10578
10662
  var ENV_URL_KEYS = ["ATHENA_URL", "NEXT_PUBLIC_ATHENA_URL"];
10579
10663
  var ENV_DB_URL_KEYS = ["ATHENA_DB_URL", "ATHENA_GATEWAY_URL", "NEXT_PUBLIC_ATHENA_DB_API_URL"];
@@ -10582,7 +10666,13 @@ var ENV_CHAT_URL_KEYS = ["ATHENA_CHAT_URL", "NEXT_PUBLIC_ATHENA_CHAT_URL"];
10582
10666
  var ENV_CHAT_WS_URL_KEYS = ["ATHENA_CHAT_WS_URL", "NEXT_PUBLIC_ATHENA_CHAT_WS_URL"];
10583
10667
  var ENV_STORAGE_URL_KEYS = ["ATHENA_STORAGE_URL", "NEXT_PUBLIC_ATHENA_STORAGE_URL"];
10584
10668
  var ENV_KEY_KEYS = ["ATHENA_API_KEY", "NEXT_PUBLIC_ATHENA_API_KEY", "ATHENA_GATEWAY_API_KEY", "X_API_KEY"];
10585
- var ENV_CLIENT_KEYS = ["ATHENA_CLIENT", "NEXT_PUBLIC_ATHENA_CLIENT"];
10669
+ var ENV_CLIENT_KEYS = [
10670
+ "ATHENA_CLIENT",
10671
+ "ATHENA_GATEWAY_CLIENT",
10672
+ "ATHENA_GENERATOR_CLIENT",
10673
+ "NEXT_PUBLIC_ATHENA_CLIENT",
10674
+ "NEXT_PUBLIC_ATHENA_GATEWAY_CLIENT"
10675
+ ];
10586
10676
  var MISSING_DB_SENTINEL = "https://athena.invalid/db";
10587
10677
  function readFirstEnv(env, keys) {
10588
10678
  for (const key of keys) {
@@ -10657,6 +10747,13 @@ function createInternalConfig(core) {
10657
10747
  const { config, urls } = core;
10658
10748
  const { url: _authUrl, ...authOptions } = config.auth ?? {};
10659
10749
  const { url: _storageUrl, directUpload, ...storageOptions } = config.storage ?? {};
10750
+ const diagnostics = resolveAthenaClientDiagnostics({
10751
+ diagnostics: config.diagnostics,
10752
+ debugAst: config.debugAst,
10753
+ findManyAst: config.findManyAst,
10754
+ traceQueries: config.traceQueries,
10755
+ env: config.env
10756
+ });
10660
10757
  return {
10661
10758
  baseUrl: urls.db ?? MISSING_DB_SENTINEL,
10662
10759
  apiKey: core.key,
@@ -10673,9 +10770,9 @@ function createInternalConfig(core) {
10673
10770
  models: config.models,
10674
10771
  behavior: {
10675
10772
  retryReads: config.retryReads,
10676
- traceQueries: config.traceQueries,
10677
- debugAst: config.debugAst,
10678
- findManyAst: config.findManyAst
10773
+ traceQueries: diagnostics.traceQueries,
10774
+ debugAst: diagnostics.debugAst,
10775
+ findManyAst: diagnostics.findManyAst
10679
10776
  },
10680
10777
  storage: {
10681
10778
  ...storageOptions,
@@ -10749,11 +10846,30 @@ function createClientView(core, viewContext) {
10749
10846
  return resolved.verifyConnection(options);
10750
10847
  },
10751
10848
  withContext(context) {
10849
+ warnIfEmptyRequestContext(context);
10752
10850
  return createClientView(core, mergeAthenaRequestContexts(viewContext, context));
10753
10851
  }
10754
10852
  };
10755
10853
  return Object.freeze(client);
10756
10854
  }
10855
+ function isEmptyAthenaRequestContext(context) {
10856
+ if (!context) return true;
10857
+ const hasHeaders = context.headers != null && Object.keys(context.headers).length > 0;
10858
+ return context.userId == null && context.organizationId == null && !normalizeOptionalContextString(context.cookie) && !normalizeOptionalContextString(context.bearerToken) && !normalizeOptionalContextString(context.sessionToken) && !context.forceNoCache && !hasHeaders;
10859
+ }
10860
+ function normalizeOptionalContextString(value) {
10861
+ const trimmed = value?.trim();
10862
+ return trimmed || void 0;
10863
+ }
10864
+ function warnIfEmptyRequestContext(context) {
10865
+ if (!isEmptyAthenaRequestContext(context)) return;
10866
+ if (typeof process !== "undefined" && process.env?.NODE_ENV === "production") {
10867
+ return;
10868
+ }
10869
+ console.warn(
10870
+ "[athena] withContext({}) has no userId, organizationId, cookie, bearerToken, sessionToken, headers, or forceNoCache. Gateway scope headers will not change. Pass identity fields, or use createAthenaServerClient({ session, scope })."
10871
+ );
10872
+ }
10757
10873
  function createClient(config) {
10758
10874
  return createClientView(resolveCore(config));
10759
10875
  }
@@ -12109,6 +12225,27 @@ function resolveTotalItemsFromPage({
12109
12225
  }
12110
12226
  return clampAthenaReadQueryTotalItems(exactCount, limit);
12111
12227
  }
12228
+ function resolveAthenaReadQueryPageFetch({
12229
+ page,
12230
+ pageSize,
12231
+ limit
12232
+ }) {
12233
+ const safePage = Math.max(1, Math.trunc(page) || 1);
12234
+ const safePageSize = Math.max(1, Math.trunc(pageSize) || 1);
12235
+ if (!limit || limit < 1) {
12236
+ return { page: safePage, pageSize: safePageSize, shouldFetch: true };
12237
+ }
12238
+ const totalCap = Math.trunc(limit);
12239
+ const offset = (safePage - 1) * safePageSize;
12240
+ if (offset >= totalCap) {
12241
+ return { page: safePage, pageSize: safePageSize, shouldFetch: false };
12242
+ }
12243
+ return {
12244
+ page: safePage,
12245
+ pageSize: Math.min(safePageSize, totalCap - offset),
12246
+ shouldFetch: true
12247
+ };
12248
+ }
12112
12249
  async function executeAthenaReadQuery({
12113
12250
  client,
12114
12251
  page,
@@ -12127,15 +12264,29 @@ async function executeAthenaReadQuery({
12127
12264
  count: "exact",
12128
12265
  head: true
12129
12266
  });
12267
+ const pageFetch = resolveAthenaReadQueryPageFetch({
12268
+ limit: query.limit,
12269
+ page,
12270
+ pageSize
12271
+ });
12272
+ if (!pageFetch.shouldFetch) {
12273
+ return {
12274
+ rows: [],
12275
+ totalItems: resolveTotalItemsFromPage({
12276
+ countCandidates: [countResult.count],
12277
+ limit: query.limit,
12278
+ page: pageFetch.page,
12279
+ pageSize,
12280
+ rowCount: 0
12281
+ })
12282
+ };
12283
+ }
12130
12284
  if ((query.mode ?? "findMany") === "select") {
12131
- const selectBuilder = applyAthenaReadQuerySelectLimit(
12132
- applyAthenaReadQuerySelectOrder(
12133
- applyAthenaReadQueryFilters(baseBuilder, query.filters),
12134
- query.orderBy
12135
- ),
12136
- query.limit
12285
+ const selectBuilder = applyAthenaReadQuerySelectOrder(
12286
+ applyAthenaReadQueryFilters(baseBuilder, query.filters),
12287
+ query.orderBy
12137
12288
  );
12138
- const result2 = await selectBuilder.currentPage(page).pageSize(pageSize).select(buildAthenaReadQuerySelectString(query.columns), {
12289
+ const result2 = await selectBuilder.currentPage(pageFetch.page).pageSize(pageFetch.pageSize).select(buildAthenaReadQuerySelectString(query.columns), {
12139
12290
  count: "exact"
12140
12291
  });
12141
12292
  const rows2 = flattenAthenaReadQueryRows(
@@ -12149,7 +12300,7 @@ async function executeAthenaReadQuery({
12149
12300
  totalItems: resolveTotalItemsFromPage({
12150
12301
  countCandidates: [countResult.count, result2.count],
12151
12302
  limit: query.limit,
12152
- page,
12303
+ page: pageFetch.page,
12153
12304
  pageSize,
12154
12305
  rowCount: rows2.length
12155
12306
  })
@@ -12157,12 +12308,11 @@ async function executeAthenaReadQuery({
12157
12308
  }
12158
12309
  const findManyOrderBy = buildAthenaReadQueryFindManyOrderBy(query.orderBy);
12159
12310
  const findManyOptions = {
12160
- ...query.limit ? { limit: query.limit } : {},
12161
12311
  ...findManyOrderBy ? { orderBy: findManyOrderBy } : {},
12162
12312
  select: buildAthenaReadQueryFindManySelect(query.columns),
12163
12313
  ...query.filters?.length ? { where: buildAthenaReadQueryFindManyWhere(query.filters) } : {}
12164
12314
  };
12165
- const result = await baseBuilder.currentPage(page).pageSize(pageSize).findMany(findManyOptions);
12315
+ const result = await baseBuilder.currentPage(pageFetch.page).pageSize(pageFetch.pageSize).findMany(findManyOptions);
12166
12316
  const rows = flattenAthenaReadQueryRows(
12167
12317
  Array.isArray(result.data) ? result.data : [],
12168
12318
  query.columns,
@@ -12174,7 +12324,7 @@ async function executeAthenaReadQuery({
12174
12324
  totalItems: resolveTotalItemsFromPage({
12175
12325
  countCandidates: [countResult.count, result.count],
12176
12326
  limit: query.limit,
12177
- page,
12327
+ page: pageFetch.page,
12178
12328
  pageSize,
12179
12329
  rowCount: rows.length
12180
12330
  })
@@ -12182,6 +12332,432 @@ async function executeAthenaReadQuery({
12182
12332
  }
12183
12333
  var executeAthenaTableQuery = executeAthenaReadQuery;
12184
12334
 
12335
+ // src/tables/catalog.ts
12336
+ var POSTGRES_CATALOG_SQL = {
12337
+ columns: `
12338
+ SELECT
12339
+ n.nspname AS schema_name,
12340
+ c.relname AS table_name,
12341
+ a.attname AS column_name,
12342
+ format_type(a.atttypid, a.atttypmod) AS data_type,
12343
+ NOT a.attnotnull AS is_nullable
12344
+ FROM pg_attribute a
12345
+ JOIN pg_class c ON c.oid = a.attrelid
12346
+ JOIN pg_namespace n ON n.oid = c.relnamespace
12347
+ WHERE c.relkind IN ('r', 'p')
12348
+ AND a.attnum > 0
12349
+ AND NOT a.attisdropped
12350
+ AND n.nspname = ANY($1::text[])
12351
+ ORDER BY n.nspname, c.relname, a.attnum;
12352
+ `,
12353
+ foreignKeys: `
12354
+ SELECT
12355
+ sn.nspname AS source_schema,
12356
+ sc.relname AS source_table,
12357
+ con.conname AS constraint_name,
12358
+ ARRAY_AGG(sa.attname ORDER BY cols.ordinality) AS source_columns,
12359
+ tn.nspname AS target_schema,
12360
+ tc.relname AS target_table,
12361
+ ARRAY_AGG(ta.attname ORDER BY cols.ordinality) AS target_columns,
12362
+ EXISTS (
12363
+ SELECT 1
12364
+ FROM pg_constraint uq
12365
+ WHERE uq.conrelid = con.conrelid
12366
+ AND uq.contype IN ('p', 'u')
12367
+ AND uq.conkey = con.conkey
12368
+ ) AS source_is_unique
12369
+ FROM pg_constraint con
12370
+ JOIN pg_class sc ON sc.oid = con.conrelid
12371
+ JOIN pg_namespace sn ON sn.oid = sc.relnamespace
12372
+ JOIN pg_class tc ON tc.oid = con.confrelid
12373
+ JOIN pg_namespace tn ON tn.oid = tc.relnamespace
12374
+ JOIN unnest(con.conkey, con.confkey) WITH ORDINALITY AS cols(source_attnum, target_attnum, ordinality) ON TRUE
12375
+ JOIN pg_attribute sa ON sa.attrelid = con.conrelid AND sa.attnum = cols.source_attnum
12376
+ JOIN pg_attribute ta ON ta.attrelid = con.confrelid AND ta.attnum = cols.target_attnum
12377
+ WHERE con.contype = 'f'
12378
+ AND sn.nspname = ANY($1::text[])
12379
+ AND tn.nspname = ANY($1::text[])
12380
+ GROUP BY
12381
+ sn.nspname,
12382
+ sc.relname,
12383
+ con.conname,
12384
+ tn.nspname,
12385
+ tc.relname,
12386
+ con.conkey,
12387
+ con.conrelid
12388
+ ORDER BY sn.nspname, sc.relname, con.conname;
12389
+ `,
12390
+ primaryKeys: `
12391
+ SELECT
12392
+ n.nspname AS schema_name,
12393
+ c.relname AS table_name,
12394
+ ARRAY_AGG(a.attname ORDER BY ck.ordinality) AS columns
12395
+ FROM pg_constraint con
12396
+ JOIN pg_class c ON c.oid = con.conrelid
12397
+ JOIN pg_namespace n ON n.oid = c.relnamespace
12398
+ JOIN unnest(con.conkey) WITH ORDINALITY AS ck(attnum, ordinality) ON TRUE
12399
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ck.attnum
12400
+ WHERE con.contype = 'p'
12401
+ AND n.nspname = ANY($1::text[])
12402
+ GROUP BY n.nspname, c.relname
12403
+ ORDER BY n.nspname, c.relname;
12404
+ `
12405
+ };
12406
+ function parseAthenaTableSchemaScope(value) {
12407
+ return value.split(",").map((entry) => entry.trim()).filter(
12408
+ (entry, index, values) => entry.length > 0 && values.indexOf(entry) === index
12409
+ );
12410
+ }
12411
+ function escapeSqlLiteral(value) {
12412
+ return value.replace(/'/g, "''");
12413
+ }
12414
+ function buildSchemaArrayLiteral(schemas) {
12415
+ const literals = schemas.map((schema) => `'${escapeSqlLiteral(schema)}'`).join(", ");
12416
+ return `ARRAY[${literals}]`;
12417
+ }
12418
+ function inlineSchemaLiteral(sql, schemas) {
12419
+ return sql.replace(
12420
+ /\$1::text\[\]/g,
12421
+ `${buildSchemaArrayLiteral(schemas)}::text[]`
12422
+ );
12423
+ }
12424
+ function buildAthenaTableCatalogQueries(schemas) {
12425
+ return {
12426
+ columns: inlineSchemaLiteral(POSTGRES_CATALOG_SQL.columns, schemas),
12427
+ foreignKeys: inlineSchemaLiteral(POSTGRES_CATALOG_SQL.foreignKeys, schemas),
12428
+ primaryKeys: inlineSchemaLiteral(POSTGRES_CATALOG_SQL.primaryKeys, schemas)
12429
+ };
12430
+ }
12431
+ function tableKey(schema, table2) {
12432
+ return `${schema}.${table2}`;
12433
+ }
12434
+ function relationKey(...parts) {
12435
+ const base = parts.join("_").replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
12436
+ return base.length > 0 ? base : "relation";
12437
+ }
12438
+ function parsePostgresArrayLiteral(text) {
12439
+ const body = text.slice(1, -1).trim();
12440
+ if (!body) {
12441
+ return [];
12442
+ }
12443
+ const values = [];
12444
+ let current = "";
12445
+ let inQuotes = false;
12446
+ let escaped = false;
12447
+ for (const char of body) {
12448
+ if (escaped) {
12449
+ current += char;
12450
+ escaped = false;
12451
+ continue;
12452
+ }
12453
+ if (char === "\\") {
12454
+ escaped = true;
12455
+ continue;
12456
+ }
12457
+ if (char === '"') {
12458
+ inQuotes = !inQuotes;
12459
+ continue;
12460
+ }
12461
+ if (char === "," && !inQuotes) {
12462
+ values.push(current);
12463
+ current = "";
12464
+ continue;
12465
+ }
12466
+ current += char;
12467
+ }
12468
+ values.push(current);
12469
+ return values.map((value) => value.trim()).filter((value) => value.length > 0);
12470
+ }
12471
+ function coerceStringArray(value) {
12472
+ if (value == null) {
12473
+ return [];
12474
+ }
12475
+ if (Array.isArray(value)) {
12476
+ return value.map((entry) => entry.trim()).filter(Boolean);
12477
+ }
12478
+ if (typeof value !== "string") {
12479
+ return [];
12480
+ }
12481
+ const trimmedValue = value.trim();
12482
+ if (!trimmedValue) {
12483
+ return [];
12484
+ }
12485
+ if (trimmedValue.startsWith("{") && trimmedValue.endsWith("}")) {
12486
+ return parsePostgresArrayLiteral(trimmedValue);
12487
+ }
12488
+ return trimmedValue.split(",").map((entry) => entry.trim()).filter(Boolean);
12489
+ }
12490
+ function createTableCatalog() {
12491
+ const tables = /* @__PURE__ */ new Map();
12492
+ const ensureTable = (schema, name) => {
12493
+ const id = tableKey(schema, name);
12494
+ const existingTable = tables.get(id);
12495
+ if (existingTable) {
12496
+ return existingTable;
12497
+ }
12498
+ const nextTable = {
12499
+ columns: [],
12500
+ id,
12501
+ name,
12502
+ primaryKey: [],
12503
+ relationMap: /* @__PURE__ */ new Map(),
12504
+ schema
12505
+ };
12506
+ tables.set(id, nextTable);
12507
+ return nextTable;
12508
+ };
12509
+ const upsertRelation = (table2, key, relation) => {
12510
+ table2.relationMap.set(key, relation);
12511
+ };
12512
+ return {
12513
+ addColumnRows(columnRows) {
12514
+ for (const row of columnRows) {
12515
+ const table2 = ensureTable(row.schema_name, row.table_name);
12516
+ table2.columns.push({
12517
+ dataType: row.data_type,
12518
+ isNullable: row.is_nullable,
12519
+ isPrimaryKey: false,
12520
+ name: row.column_name
12521
+ });
12522
+ }
12523
+ },
12524
+ addForeignKeyRows(foreignKeyRows) {
12525
+ for (const row of foreignKeyRows) {
12526
+ const sourceTable = ensureTable(row.source_schema, row.source_table);
12527
+ const targetTable = ensureTable(row.target_schema, row.target_table);
12528
+ upsertRelation(
12529
+ sourceTable,
12530
+ relationKey(row.constraint_name, row.target_table),
12531
+ {
12532
+ name: row.constraint_name,
12533
+ targetSchema: row.target_schema,
12534
+ targetTable: row.target_table
12535
+ }
12536
+ );
12537
+ upsertRelation(targetTable, relationKey(row.source_table), {
12538
+ name: relationKey(row.source_table, row.constraint_name),
12539
+ targetSchema: row.source_schema,
12540
+ targetTable: row.source_table
12541
+ });
12542
+ }
12543
+ },
12544
+ addManyToManyRows(foreignKeyRows) {
12545
+ const foreignKeysBySourceTable = /* @__PURE__ */ new Map();
12546
+ for (const foreignKey of foreignKeyRows) {
12547
+ const key = tableKey(foreignKey.source_schema, foreignKey.source_table);
12548
+ const current = foreignKeysBySourceTable.get(key) ?? {
12549
+ foreignKeys: [],
12550
+ schema: foreignKey.source_schema,
12551
+ table: foreignKey.source_table
12552
+ };
12553
+ current.foreignKeys.push(foreignKey);
12554
+ foreignKeysBySourceTable.set(key, current);
12555
+ }
12556
+ for (const candidate of foreignKeysBySourceTable.values()) {
12557
+ const bridgeTable = tables.get(
12558
+ tableKey(candidate.schema, candidate.table)
12559
+ );
12560
+ if (!bridgeTable || candidate.foreignKeys.length !== 2) {
12561
+ continue;
12562
+ }
12563
+ const combinedForeignColumns = Array.from(
12564
+ new Set(
12565
+ candidate.foreignKeys.flatMap(
12566
+ (foreignKey) => coerceStringArray(foreignKey.source_columns)
12567
+ )
12568
+ )
12569
+ );
12570
+ if (bridgeTable.primaryKey.length === 0 || combinedForeignColumns.length !== bridgeTable.primaryKey.length || !bridgeTable.primaryKey.every(
12571
+ (column) => combinedForeignColumns.includes(column)
12572
+ )) {
12573
+ continue;
12574
+ }
12575
+ const [firstForeignKey, secondForeignKey] = candidate.foreignKeys;
12576
+ const firstTarget = tables.get(
12577
+ tableKey(firstForeignKey.target_schema, firstForeignKey.target_table)
12578
+ );
12579
+ const secondTarget = tables.get(
12580
+ tableKey(
12581
+ secondForeignKey.target_schema,
12582
+ secondForeignKey.target_table
12583
+ )
12584
+ );
12585
+ if (!(firstTarget && secondTarget)) {
12586
+ continue;
12587
+ }
12588
+ upsertRelation(
12589
+ firstTarget,
12590
+ relationKey(candidate.table, secondForeignKey.target_table),
12591
+ {
12592
+ name: relationKey(
12593
+ candidate.table,
12594
+ secondForeignKey.constraint_name
12595
+ ),
12596
+ targetSchema: secondForeignKey.target_schema,
12597
+ targetTable: secondForeignKey.target_table
12598
+ }
12599
+ );
12600
+ upsertRelation(
12601
+ secondTarget,
12602
+ relationKey(candidate.table, firstForeignKey.target_table),
12603
+ {
12604
+ name: relationKey(candidate.table, firstForeignKey.constraint_name),
12605
+ targetSchema: firstForeignKey.target_schema,
12606
+ targetTable: firstForeignKey.target_table
12607
+ }
12608
+ );
12609
+ }
12610
+ },
12611
+ addPrimaryKeyRows(primaryKeyRows) {
12612
+ for (const row of primaryKeyRows) {
12613
+ const table2 = ensureTable(row.schema_name, row.table_name);
12614
+ const primaryKey = coerceStringArray(row.columns);
12615
+ table2.primaryKey = primaryKey;
12616
+ for (const columnName of primaryKey) {
12617
+ const column = table2.columns.find(
12618
+ (candidate) => candidate.name === columnName
12619
+ );
12620
+ if (column) {
12621
+ column.isPrimaryKey = true;
12622
+ }
12623
+ }
12624
+ }
12625
+ },
12626
+ toResponse(database) {
12627
+ return {
12628
+ database,
12629
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
12630
+ tables: [...tables.values()].map((table2) => ({
12631
+ columns: [...table2.columns].sort(
12632
+ (left, right) => left.name.localeCompare(right.name)
12633
+ ),
12634
+ id: table2.id,
12635
+ name: table2.name,
12636
+ primaryKey: [...table2.primaryKey],
12637
+ relations: [...table2.relationMap.values()].map((relation) => ({
12638
+ columns: tables.get(
12639
+ tableKey(relation.targetSchema, relation.targetTable)
12640
+ )?.columns ?? [],
12641
+ name: relation.name,
12642
+ targetSchema: relation.targetSchema,
12643
+ targetTable: relation.targetTable
12644
+ })).sort(
12645
+ (left, right) => left.name.localeCompare(right.name)
12646
+ ),
12647
+ schema: table2.schema
12648
+ })).sort(
12649
+ (left, right) => left.id.localeCompare(right.id)
12650
+ )
12651
+ };
12652
+ }
12653
+ };
12654
+ }
12655
+ async function queryRows(client, query) {
12656
+ const result = await client.query(query);
12657
+ if (result.error || result.status < 200 || result.status >= 300) {
12658
+ const errorMessage = typeof result.error === "string" ? result.error : result.error && typeof result.error === "object" && "message" in result.error && typeof result.error.message === "string" ? result.error.message : `Athena gateway query failed with status ${result.status}.`;
12659
+ throw new Error(errorMessage);
12660
+ }
12661
+ return Array.isArray(result.data) ? result.data : [];
12662
+ }
12663
+ function isAthenaTableSchemaConfig(value) {
12664
+ if (typeof value !== "object" || value === null) {
12665
+ return false;
12666
+ }
12667
+ const config = value;
12668
+ return typeof config.gatewayUrl === "string" && typeof config.gatewayKey === "string" && typeof config.gatewayDatabase === "string" && typeof config.schemaScope === "string" && typeof config.clientName === "string";
12669
+ }
12670
+ function hasAthenaTableSchemaCredentials(config) {
12671
+ return config.gatewayUrl.trim().length > 0 && config.gatewayKey.trim().length > 0 && config.gatewayDatabase.trim().length > 0;
12672
+ }
12673
+ async function fetchAthenaTableCatalog(config, options = {}) {
12674
+ const schemas = parseAthenaTableSchemaScope(config.schemaScope);
12675
+ if (schemas.length === 0) {
12676
+ return {
12677
+ database: config.gatewayDatabase,
12678
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
12679
+ tables: []
12680
+ };
12681
+ }
12682
+ const queries = buildAthenaTableCatalogQueries(schemas);
12683
+ const client = options.client ?? createClient({
12684
+ url: config.gatewayUrl.trim(),
12685
+ key: config.gatewayKey.trim(),
12686
+ client: config.clientName.trim() || void 0
12687
+ });
12688
+ const [columnRows, primaryKeyRows, foreignKeyRows] = await Promise.all([
12689
+ queryRows(client, queries.columns),
12690
+ queryRows(client, queries.primaryKeys),
12691
+ queryRows(client, queries.foreignKeys)
12692
+ ]);
12693
+ const catalog = createTableCatalog();
12694
+ catalog.addColumnRows(columnRows);
12695
+ catalog.addPrimaryKeyRows(primaryKeyRows);
12696
+ catalog.addForeignKeyRows(foreignKeyRows);
12697
+ catalog.addManyToManyRows(foreignKeyRows);
12698
+ return catalog.toResponse(config.gatewayDatabase);
12699
+ }
12700
+ var fetchTableCatalog = fetchAthenaTableCatalog;
12701
+
12702
+ // src/tables/schema-handlers.ts
12703
+ var ATHENA_TABLE_SCHEMA_ROUTE = "/api/tables/schema";
12704
+ function json2(body, init) {
12705
+ const headers = new Headers(init?.headers);
12706
+ if (!headers.has("content-type")) {
12707
+ headers.set("content-type", "application/json; charset=utf-8");
12708
+ }
12709
+ return new Response(JSON.stringify(body), {
12710
+ status: init?.status ?? 200,
12711
+ headers
12712
+ });
12713
+ }
12714
+ async function handleAthenaTableSchemaPost(request2, options) {
12715
+ const payload = await request2.json().catch(() => null);
12716
+ let config = isAthenaTableSchemaConfig(
12717
+ payload?.config
12718
+ ) ? payload.config : null;
12719
+ if (config && options?.resolveConfig) {
12720
+ config = await options.resolveConfig(config, request2);
12721
+ }
12722
+ if (!config || !isAthenaTableSchemaConfig(config)) {
12723
+ return json2(
12724
+ {
12725
+ error: "The Athena tables showcase config is invalid."
12726
+ },
12727
+ { status: 400 }
12728
+ );
12729
+ }
12730
+ if (!hasAthenaTableSchemaCredentials(config)) {
12731
+ return json2(
12732
+ {
12733
+ error: "Gateway URL, API key, and database are required for schema introspection."
12734
+ },
12735
+ { status: 400 }
12736
+ );
12737
+ }
12738
+ try {
12739
+ const response = await fetchAthenaTableCatalog(
12740
+ config,
12741
+ {
12742
+ client: options?.client
12743
+ }
12744
+ );
12745
+ return json2(response);
12746
+ } catch (error) {
12747
+ return json2(
12748
+ {
12749
+ error: error instanceof Error ? error.message : "Athena schema introspection failed."
12750
+ },
12751
+ { status: 500 }
12752
+ );
12753
+ }
12754
+ }
12755
+ function createAthenaTableSchemaHandlers(options) {
12756
+ return {
12757
+ POST: (request2) => handleAthenaTableSchemaPost(request2, options)
12758
+ };
12759
+ }
12760
+
12185
12761
  // src/browser.ts
12186
12762
  function throwBrowserUnsupported(apiName) {
12187
12763
  throw new Error(
@@ -12219,6 +12795,7 @@ exports.ATHENA_AUTH_MAX_ADMIN_JSON_BYTES = ATHENA_AUTH_MAX_ADMIN_JSON_BYTES;
12219
12795
  exports.ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH = ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH;
12220
12796
  exports.ATHENA_AUTH_MAX_TEMPLATE_VARIABLES = ATHENA_AUTH_MAX_TEMPLATE_VARIABLES;
12221
12797
  exports.ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH = ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH;
12798
+ exports.ATHENA_TABLE_SCHEMA_ROUTE = ATHENA_TABLE_SCHEMA_ROUTE;
12222
12799
  exports.AthenaBillingError = AthenaBillingError;
12223
12800
  exports.AthenaChatError = AthenaChatError;
12224
12801
  exports.AthenaConfigurationError = AthenaConfigurationError;
@@ -12245,6 +12822,7 @@ exports.buildAthenaReadQueryFindManyOrderBy = buildAthenaReadQueryFindManyOrderB
12245
12822
  exports.buildAthenaReadQueryFindManySelect = buildAthenaReadQueryFindManySelect;
12246
12823
  exports.buildAthenaReadQueryFindManyWhere = buildAthenaReadQueryFindManyWhere;
12247
12824
  exports.buildAthenaReadQuerySelectString = buildAthenaReadQuerySelectString;
12825
+ exports.buildAthenaTableCatalogQueries = buildAthenaTableCatalogQueries;
12248
12826
  exports.buildAthenaTableFindManyOrderBy = buildAthenaTableFindManyOrderBy;
12249
12827
  exports.buildAthenaTableFindManySelect = buildAthenaTableFindManySelect;
12250
12828
  exports.buildAthenaTableFindManyWhere = buildAthenaTableFindManyWhere;
@@ -12254,6 +12832,7 @@ exports.clampAthenaReadQueryTotalItems = clampAthenaReadQueryTotalItems;
12254
12832
  exports.clampAthenaTableTotalItems = clampAthenaTableTotalItems;
12255
12833
  exports.coerceInt = coerceInt;
12256
12834
  exports.createAthenaStorageError = createAthenaStorageError;
12835
+ exports.createAthenaTableSchemaHandlers = createAthenaTableSchemaHandlers;
12257
12836
  exports.createAuthReactEmailInput = createAuthReactEmailInput;
12258
12837
  exports.createBillingModule = createBillingModule;
12259
12838
  exports.createClient = createClient;
@@ -12269,6 +12848,8 @@ exports.defineSchema = defineSchema;
12269
12848
  exports.enumeration = enumeration;
12270
12849
  exports.executeAthenaReadQuery = executeAthenaReadQuery;
12271
12850
  exports.executeAthenaTableQuery = executeAthenaTableQuery;
12851
+ exports.fetchAthenaTableCatalog = fetchAthenaTableCatalog;
12852
+ exports.fetchTableCatalog = fetchTableCatalog;
12272
12853
  exports.filterIntrospectionSnapshot = filterIntrospectionSnapshot;
12273
12854
  exports.findGeneratorConfigPath = findGeneratorConfigPath;
12274
12855
  exports.flattenAthenaReadQueryRows = flattenAthenaReadQueryRows;
@@ -12276,8 +12857,11 @@ exports.flattenAthenaRows = flattenAthenaRows;
12276
12857
  exports.generateArtifactsFromSnapshot = generateArtifactsFromSnapshot;
12277
12858
  exports.generatorEnv = generatorEnv;
12278
12859
  exports.getAthenaDebugAst = getAthenaDebugAst;
12860
+ exports.handleAthenaTableSchemaPost = handleAthenaTableSchemaPost;
12861
+ exports.hasAthenaTableSchemaCredentials = hasAthenaTableSchemaCredentials;
12279
12862
  exports.identifier = identifier;
12280
12863
  exports.isAthenaGatewayError = isAthenaGatewayError;
12864
+ exports.isAthenaTableSchemaConfig = isAthenaTableSchemaConfig;
12281
12865
  exports.isOk = isOk;
12282
12866
  exports.json = json;
12283
12867
  exports.loadGeneratorConfig = loadGeneratorConfig;
@@ -12289,10 +12873,12 @@ exports.normalizeGeneratorConfig = normalizeGeneratorConfig;
12289
12873
  exports.normalizeSchemaSelection = normalizeSchemaSelection;
12290
12874
  exports.normalizeTableSelection = normalizeTableSelection;
12291
12875
  exports.number = number;
12876
+ exports.parseAthenaTableSchemaScope = parseAthenaTableSchemaScope;
12292
12877
  exports.parseBooleanFlag = parseBooleanFlag2;
12293
12878
  exports.renderAthenaReactEmail = renderAthenaReactEmail;
12294
12879
  exports.requireAffected = requireAffected;
12295
12880
  exports.requireSuccess = requireSuccess;
12881
+ exports.resolveAthenaReadQueryPageFetch = resolveAthenaReadQueryPageFetch;
12296
12882
  exports.resolveGeneratorProvider = resolveGeneratorProvider;
12297
12883
  exports.resolvePostgresColumnType = resolvePostgresColumnType;
12298
12884
  exports.resolveProviderSchemas = resolveProviderSchemas;