@xylex-group/athena 3.1.0 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +17 -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-BnFN2mbd.d.cts} +49 -201
  11. package/dist/{athena-request-headers-DujFFyMU.d.cts → athena-request-headers-Dwdkq2WR.d.ts} +49 -201
  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 +3735 -248
  17. package/dist/browser.cjs.map +1 -1
  18. package/dist/browser.d.cts +11 -10
  19. package/dist/browser.d.ts +11 -10
  20. package/dist/browser.js +3726 -249
  21. package/dist/browser.js.map +1 -1
  22. package/dist/cli/index.cjs +3232 -190
  23. package/dist/cli/index.cjs.map +1 -1
  24. package/dist/cli/index.d.cts +4 -4
  25. package/dist/cli/index.d.ts +4 -4
  26. package/dist/cli/index.js +3232 -190
  27. package/dist/cli/index.js.map +1 -1
  28. package/dist/cloudflare.cjs +12914 -0
  29. package/dist/cloudflare.cjs.map +1 -0
  30. package/dist/cloudflare.d.cts +368 -0
  31. package/dist/cloudflare.d.ts +368 -0
  32. package/dist/cloudflare.js +12885 -0
  33. package/dist/cloudflare.js.map +1 -0
  34. package/dist/cookies.cjs +4 -3
  35. package/dist/cookies.cjs.map +1 -1
  36. package/dist/cookies.js +4 -3
  37. package/dist/cookies.js.map +1 -1
  38. package/dist/env.cjs +130 -0
  39. package/dist/env.cjs.map +1 -0
  40. package/dist/env.d.cts +70 -0
  41. package/dist/env.d.ts +70 -0
  42. package/dist/env.js +122 -0
  43. package/dist/env.js.map +1 -0
  44. package/dist/index.cjs +3749 -241
  45. package/dist/index.cjs.map +1 -1
  46. package/dist/index.d.cts +11 -10
  47. package/dist/index.d.ts +11 -10
  48. package/dist/index.js +3739 -242
  49. package/dist/index.js.map +1 -1
  50. package/dist/{model-form-BhWWsA-7.d.cts → model-form-D0ykVVOs.d.cts} +26 -4
  51. package/dist/{model-form-BbdzJ9Uh.d.ts → model-form-U8NVtfSA.d.ts} +26 -4
  52. package/dist/{module-xFd7_Igv.d.cts → module-CMWlJ1z3.d.cts} +5 -5
  53. package/dist/{module-DKkJKOuJ.d.ts → module-CZ-wPcf2.d.ts} +5 -5
  54. package/dist/next/client.cjs +3212 -196
  55. package/dist/next/client.cjs.map +1 -1
  56. package/dist/next/client.d.cts +6 -5
  57. package/dist/next/client.d.ts +6 -5
  58. package/dist/next/client.js +3212 -196
  59. package/dist/next/client.js.map +1 -1
  60. package/dist/next/server.cjs +4461 -781
  61. package/dist/next/server.cjs.map +1 -1
  62. package/dist/next/server.d.cts +139 -13
  63. package/dist/next/server.d.ts +139 -13
  64. package/dist/next/server.js +4451 -782
  65. package/dist/next/server.js.map +1 -1
  66. package/dist/{pipeline-DuKzYGia.d.cts → pipeline-BCpb4BX1.d.cts} +1 -1
  67. package/dist/{pipeline-wer2G9xW.d.ts → pipeline-CgmXwMeX.d.ts} +1 -1
  68. package/dist/{proxy-request-headers-m4D2Tduy.d.ts → proxy-request-headers-CttlcuRb.d.ts} +1 -1
  69. package/dist/{proxy-request-headers-DGxdoyA0.d.cts → proxy-request-headers-pIBSn1Fw.d.cts} +1 -1
  70. package/dist/react.cjs +290 -31
  71. package/dist/react.cjs.map +1 -1
  72. package/dist/react.d.cts +62 -12
  73. package/dist/react.d.ts +62 -12
  74. package/dist/react.js +290 -32
  75. package/dist/react.js.map +1 -1
  76. package/dist/schema-handlers-CvWqF-dW.d.ts +138 -0
  77. package/dist/schema-handlers-Dr8h9Jg-.d.cts +138 -0
  78. package/dist/social-providers.cjs +1 -1
  79. package/dist/social-providers.cjs.map +1 -1
  80. package/dist/social-providers.d.cts +1 -1
  81. package/dist/social-providers.d.ts +1 -1
  82. package/dist/social-providers.js +1 -1
  83. package/dist/social-providers.js.map +1 -1
  84. package/dist/{types-Bltx6iL6.d.ts → types-B2RZPivM.d.cts} +8 -1
  85. package/dist/{types-Bltx6iL6.d.cts → types-B2RZPivM.d.ts} +8 -1
  86. package/dist/{types-1ztXDgPa.d.cts → types-BKklrX4J.d.ts} +14 -2
  87. package/dist/{types-AOY-GLu8.d.cts → types-BVKpQmfY.d.cts} +11 -0
  88. package/dist/{types-AOY-GLu8.d.ts → types-BVKpQmfY.d.ts} +11 -0
  89. package/dist/{types-CgCv5o6R.d.cts → types-D5dj1v5Z.d.cts} +1 -1
  90. package/dist/{types-CccOiXPo.d.ts → types-DqBFwfhn.d.cts} +14 -2
  91. package/dist/{types-B75PdABb.d.ts → types-S-bTMPiM.d.ts} +1 -1
  92. package/dist/utils.cjs +30 -0
  93. package/dist/utils.cjs.map +1 -1
  94. package/dist/utils.d.cts +4 -3
  95. package/dist/utils.d.ts +4 -3
  96. package/dist/utils.js +30 -1
  97. package/dist/utils.js.map +1 -1
  98. package/dist/{v3-client-CWfZHcKL.d.cts → v3-client-DP-qg82X.d.cts} +323 -5
  99. package/dist/{v3-client-DZp2NEhK.d.ts → v3-client-OAai_JNs.d.ts} +323 -5
  100. package/package.json +25 -4
package/dist/browser.js CHANGED
@@ -1838,6 +1838,8 @@ function buildUpdateDebugSql(payload) {
1838
1838
  sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
1839
1839
  }
1840
1840
  const pagination = resolvePagination({
1841
+ limit: payload.limit,
1842
+ offset: payload.offset,
1841
1843
  currentPage: payload.current_page,
1842
1844
  pageSize: payload.page_size
1843
1845
  });
@@ -1860,6 +1862,8 @@ function buildDeleteDebugSql(payload) {
1860
1862
  sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
1861
1863
  }
1862
1864
  const pagination = resolvePagination({
1865
+ limit: payload.limit,
1866
+ offset: payload.offset,
1863
1867
  currentPage: payload.current_page,
1864
1868
  pageSize: payload.page_size
1865
1869
  });
@@ -2003,7 +2007,7 @@ function buildAthenaGatewayUrl(baseUrl, path) {
2003
2007
 
2004
2008
  // package.json
2005
2009
  var package_default = {
2006
- version: "3.1.0"
2010
+ version: "3.5.1"
2007
2011
  };
2008
2012
 
2009
2013
  // src/sdk-version.ts
@@ -2300,13 +2304,14 @@ var LEGACY_COOKIE_PREFIX = "better-auth";
2300
2304
  var DEFAULT_SESSION_MAX_AGE = 7 * 24 * 60 * 60;
2301
2305
  var DEFAULT_CACHE_MAX_AGE = 60 * 5;
2302
2306
  function isProductionRuntime() {
2303
- return typeof process !== "undefined" && process.env?.NODE_ENV === "production";
2307
+ return globalThis.process?.env?.NODE_ENV === "production";
2304
2308
  }
2305
2309
  function getEnvironmentSecret() {
2306
- if (typeof process === "undefined") {
2310
+ const env = globalThis.process?.env;
2311
+ if (!env) {
2307
2312
  return void 0;
2308
2313
  }
2309
- return process.env?.ATHENA_AUTH_SECRET || process.env?.BETTER_AUTH_SECRET || process.env?.AUTH_SECRET;
2314
+ return env.ATHENA_AUTH_SECRET || env.BETTER_AUTH_SECRET || env.AUTH_SECRET;
2310
2315
  }
2311
2316
  function isDynamicBaseURLConfig(baseURL) {
2312
2317
  return typeof baseURL === "object" && baseURL !== null && "allowedHosts" in baseURL && Array.isArray(baseURL.allowedHosts);
@@ -4763,6 +4768,14 @@ function createAuthModule(config = {}, runtimeOptions = {}) {
4763
4768
  changeEmailVerify: (input, options) => getWithQuery("/change-email/verify", input, options),
4764
4769
  deleteUserVerify: (input, options) => getWithQuery("/delete-user/verify", input, options),
4765
4770
  changePassword: (input, options) => postGeneric("/change-password", input, options),
4771
+ // Better Auth UI flat method aliases (also nested under session/account/social/user).
4772
+ listSessions: (input, options) => getGeneric("/list-sessions", input, options),
4773
+ revokeSession: sessionRevokeBinding,
4774
+ revokeOtherSessions,
4775
+ listAccounts: (input, options) => getGeneric("/list-accounts", input, options),
4776
+ unlinkAccount: (input, options) => postGeneric("/unlink-account", input, options),
4777
+ linkSocial: (input, options) => postGeneric("/link-social", input, options),
4778
+ updateUser: (input, options) => postGeneric("/update-user", input, options),
4766
4779
  user: {
4767
4780
  update: (input, options) => postGeneric("/update-user", input, options),
4768
4781
  delete: (input, options) => postGeneric("/delete-user", input, options),
@@ -5868,9 +5881,9 @@ function readHeadersField(value) {
5868
5881
  const headers = value.headers;
5869
5882
  if (!isRecord8(headers)) return {};
5870
5883
  const result = {};
5871
- for (const [key, headerValue2] of Object.entries(headers)) {
5872
- if (typeof headerValue2 === "string") {
5873
- result[key] = headerValue2;
5884
+ for (const [key, headerValue3] of Object.entries(headers)) {
5885
+ if (typeof headerValue3 === "string") {
5886
+ result[key] = headerValue3;
5874
5887
  }
5875
5888
  }
5876
5889
  return result;
@@ -9548,6 +9561,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, beha
9548
9561
  strip_nulls: mergedOptions?.stripNulls ?? true
9549
9562
  };
9550
9563
  if (executionState.order) payload.sort_by = executionState.order;
9564
+ if (executionState.limit !== void 0) payload.limit = executionState.limit;
9565
+ if (executionState.offset !== void 0) payload.offset = executionState.offset;
9551
9566
  if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
9552
9567
  if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
9553
9568
  if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
@@ -9602,6 +9617,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, beha
9602
9617
  conditions: filters
9603
9618
  };
9604
9619
  if (executionState.order) payload.sort_by = executionState.order;
9620
+ if (executionState.limit !== void 0) payload.limit = executionState.limit;
9621
+ if (executionState.offset !== void 0) payload.offset = executionState.offset;
9605
9622
  if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
9606
9623
  if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
9607
9624
  if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
@@ -9653,7 +9670,11 @@ function createQueryBuilder(client, formatGatewayResult, behavior, tracer) {
9653
9670
  if (!normalizedQuery) {
9654
9671
  throw new Error("query requires a non-empty string");
9655
9672
  }
9656
- const payload = { query: normalizedQuery };
9673
+ const params = options?.params;
9674
+ const payload = {
9675
+ query: normalizedQuery,
9676
+ ...Array.isArray(params) ? { params } : {}
9677
+ };
9657
9678
  const callsite = captureTraceCallsite(tracer);
9658
9679
  return executeRead(
9659
9680
  behavior,
@@ -9702,7 +9723,7 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
9702
9723
  }
9703
9724
  function createInternalClientCore(config) {
9704
9725
  const normalizedAuthConfig = normalizeAuthClientConfig(config.auth, config.authUrl);
9705
- const gatewayTransport = createAthenaGatewayClient({
9726
+ const gatewayTransport = config.gatewayTransport ?? createAthenaGatewayClient({
9706
9727
  baseUrl: config.baseUrl,
9707
9728
  apiKey: config.apiKey,
9708
9729
  client: config.client ?? void 0,
@@ -9857,211 +9878,2849 @@ function createInternalClientView(core, resolveContext) {
9857
9878
  };
9858
9879
  }
9859
9880
 
9860
- // src/billing/module.ts
9861
- var SDK_NAME5 = "xylex-group/athena-billing";
9862
- var SDK_HEADER_VALUE4 = buildSdkHeaderValue(SDK_NAME5);
9863
- var AthenaBillingError = class extends Error {
9864
- status;
9865
- endpoint;
9866
- method;
9867
- body;
9868
- constructor(input) {
9869
- super(input.message);
9870
- this.name = "AthenaBillingError";
9871
- this.status = input.status;
9872
- this.endpoint = input.endpoint;
9873
- this.method = input.method;
9874
- this.body = input.body;
9875
- }
9876
- };
9877
- var billingSdkManifest = {
9878
- namespace: "billing",
9879
- envelopeKind: "athena",
9880
- methods: [
9881
- { name: "getCapabilities", method: "GET", path: "/billing/v1/capabilities" },
9882
- { name: "createCheckout", method: "POST", path: "/billing/v1/checkouts" },
9883
- { name: "listProducts", method: "GET", path: "/billing/v1/products" },
9884
- { name: "listPrices", method: "GET", path: "/billing/v1/prices" },
9885
- { name: "listCustomers", method: "GET", path: "/billing/v1/customers" },
9886
- { name: "createCustomer", method: "POST", path: "/billing/v1/customers" },
9887
- { name: "getCustomer", method: "GET", path: "/billing/v1/customers/{id}" },
9888
- { name: "updateCustomer", method: "PATCH", path: "/billing/v1/customers/{id}" },
9889
- { name: "deleteCustomer", method: "DELETE", path: "/billing/v1/customers/{id}" },
9890
- { name: "listPayments", method: "GET", path: "/billing/v1/payments" },
9891
- { name: "createPayment", method: "POST", path: "/billing/v1/payments" },
9892
- { name: "getPayment", method: "GET", path: "/billing/v1/payments/{id}" },
9893
- { name: "cancelPayment", method: "POST", path: "/billing/v1/payments/{id}/cancel" },
9894
- { name: "listPaymentLinks", method: "GET", path: "/billing/v1/payment-links" },
9895
- { name: "createPaymentLink", method: "POST", path: "/billing/v1/payment-links" },
9896
- { name: "getPaymentLink", method: "GET", path: "/billing/v1/payment-links/{id}" },
9897
- { name: "updatePaymentLink", method: "PATCH", path: "/billing/v1/payment-links/{id}" },
9898
- { name: "deletePaymentLink", method: "DELETE", path: "/billing/v1/payment-links/{id}" },
9899
- { name: "listRefunds", method: "GET", path: "/billing/v1/refunds" },
9900
- { name: "createRefund", method: "POST", path: "/billing/v1/refunds" },
9901
- { name: "getRefund", method: "GET", path: "/billing/v1/refunds/{id}" },
9902
- { name: "cancelRefund", method: "POST", path: "/billing/v1/refunds/{id}/cancel" },
9903
- { name: "listSubscriptions", method: "GET", path: "/billing/v1/subscriptions" },
9904
- { name: "createSubscription", method: "POST", path: "/billing/v1/subscriptions" },
9905
- { name: "getSubscription", method: "GET", path: "/billing/v1/subscriptions/{id}" },
9906
- { name: "updateSubscription", method: "PATCH", path: "/billing/v1/subscriptions/{id}" },
9907
- { name: "cancelSubscription", method: "POST", path: "/billing/v1/subscriptions/{id}/cancel" },
9908
- { name: "listInvoices", method: "GET", path: "/billing/v1/invoices" },
9909
- { name: "getInvoice", method: "GET", path: "/billing/v1/invoices/{id}" },
9910
- { name: "listWebhooks", method: "GET", path: "/billing/v1/webhooks" },
9911
- { name: "createWebhook", method: "POST", path: "/billing/v1/webhooks" },
9912
- { name: "getWebhook", method: "GET", path: "/billing/v1/webhooks/{id}" },
9913
- { name: "updateWebhook", method: "PATCH", path: "/billing/v1/webhooks/{id}" },
9914
- { name: "deleteWebhook", method: "DELETE", path: "/billing/v1/webhooks/{id}" },
9915
- { name: "testWebhook", method: "POST", path: "/billing/v1/webhooks/{id}/test" },
9916
- {
9917
- name: "listConnections",
9918
- method: "GET",
9919
- path: "/admin/billing/clients/{client_name}/connections"
9920
- },
9921
- {
9922
- name: "createConnection",
9923
- method: "POST",
9924
- path: "/admin/billing/clients/{client_name}/connections"
9925
- },
9926
- {
9927
- name: "getConnection",
9928
- method: "GET",
9929
- path: "/admin/billing/clients/{client_name}/connections/{connection_id}"
9930
- },
9931
- {
9932
- name: "updateConnection",
9933
- method: "PATCH",
9934
- path: "/admin/billing/clients/{client_name}/connections/{connection_id}"
9935
- },
9936
- {
9937
- name: "deleteConnection",
9938
- method: "DELETE",
9939
- path: "/admin/billing/clients/{client_name}/connections/{connection_id}"
9940
- },
9941
- {
9942
- name: "reconcileDocument",
9943
- method: "POST",
9944
- path: "/admin/billing/clients/{client_name}/connections/{connection_id}/reconcile"
9945
- },
9946
- {
9947
- name: "listWebhookEvents",
9948
- method: "GET",
9949
- path: "/admin/billing/clients/{client_name}/webhook-events"
9881
+ // src/cloudflare/types.ts
9882
+ var CLOUDFLARE_EDGE_BASE_URL = "https://athena.local/cloudflare-edge";
9883
+ var CLOUDFLARE_EDGE_API_KEY = "cloudflare-edge-local";
9884
+
9885
+ // src/cloudflare/capabilities.ts
9886
+ function createGatewayCapabilities(options) {
9887
+ const storageConfigured = options?.storageConfigured ?? true;
9888
+ return {
9889
+ mode: "gateway",
9890
+ db: {
9891
+ engine: options?.engine ?? "postgresql",
9892
+ local: false,
9893
+ layers: {
9894
+ query: true,
9895
+ flatCrud: true,
9896
+ findManyAst: true,
9897
+ rpc: true,
9898
+ relations: true
9899
+ }
9950
9900
  },
9951
- {
9952
- name: "provisionWebhookSinks",
9953
- method: "POST",
9954
- path: "/admin/billing/clients/{client_name}/webhook-sinks/provision"
9901
+ storage: {
9902
+ local: false,
9903
+ objects: storageConfigured,
9904
+ catalogs: storageConfigured ? options?.storageCatalogs ?? true : false,
9905
+ backups: storageConfigured ? options?.storageBackups ?? true : false
9955
9906
  },
9956
- { name: "listGrants", method: "GET", path: "/admin/billing/grants" },
9957
- { name: "listProviders", method: "GET", path: "/admin/billing/providers" },
9958
- {
9959
- name: "listSinkHelpers",
9960
- method: "GET",
9961
- path: "/admin/webhook-sinks/helpers/billing"
9907
+ auth: {
9908
+ remote: options?.authRemote ?? true
9909
+ }
9910
+ };
9911
+ }
9912
+ function createCloudflareEdgeCapabilities(options) {
9913
+ const hasObjects = options.hasR2 || Boolean(options.hasRemoteStorage);
9914
+ return {
9915
+ mode: "cloudflare-edge",
9916
+ db: {
9917
+ engine: "cloudflare-d1",
9918
+ local: true,
9919
+ layers: {
9920
+ query: true,
9921
+ flatCrud: true,
9922
+ findManyAst: options.findManyAst ?? false,
9923
+ rpc: false,
9924
+ relations: false
9925
+ }
9962
9926
  },
9963
- {
9964
- name: "ingestProviderWebhook",
9965
- method: "POST",
9966
- path: "/billing/providers/{provider}/clients/{client_name}/connections/{connection_id}/webhook"
9927
+ storage: {
9928
+ // Local objects only when an R2 binding is present.
9929
+ local: options.hasR2,
9930
+ // Remote hybrid root can still expose storage.objects via the HTTP API.
9931
+ objects: hasObjects,
9932
+ catalogs: false,
9933
+ backups: false
9967
9934
  },
9968
- { name: "getDebugBilling", method: "GET", path: "/debug/billing" }
9969
- ]
9970
- };
9971
- function withPathParam2(path, name, value) {
9972
- return path.replace(`{${name}}`, encodeURIComponent(value));
9973
- }
9974
- function appendQuery3(path, query) {
9975
- if (!query) return path;
9976
- const params = new URLSearchParams();
9977
- for (const [key, value] of Object.entries(query)) {
9978
- if (value === void 0 || value === null) continue;
9979
- params.set(key, String(value));
9980
- }
9981
- const serialized = params.toString();
9982
- return serialized ? `${path}?${serialized}` : path;
9983
- }
9984
- function connectionQuery(input) {
9985
- const query = {
9986
- connectionId: input.connectionId
9935
+ auth: {
9936
+ remote: options.authRemote
9937
+ }
9987
9938
  };
9988
- if (input.clientName) query.clientName = input.clientName;
9989
- if ("cursor" in input && input.cursor) query.cursor = input.cursor;
9990
- if ("source" in input && input.source) query.source = input.source;
9991
- if ("limit" in input && input.limit !== void 0) query.limit = String(input.limit);
9992
- if ("offset" in input && input.offset !== void 0) query.offset = String(input.offset);
9993
- return query;
9994
9939
  }
9995
- function parseEnvelopeData(body) {
9996
- if (body && typeof body === "object" && "data" in body) {
9997
- return body.data;
9940
+
9941
+ // src/cloudflare/d1/runner.ts
9942
+ function resultColumns(rows) {
9943
+ const first = rows.find((value) => value && typeof value === "object" && !Array.isArray(value));
9944
+ if (!first) return [];
9945
+ return Object.keys(first);
9946
+ }
9947
+ function isIdentChar(ch) {
9948
+ if (!ch) return false;
9949
+ return /[A-Za-z0-9_]/.test(ch);
9950
+ }
9951
+ function scanSqlKeywordsOutsideLiterals(sql, onKeyword) {
9952
+ let inSingle = false;
9953
+ let inDouble = false;
9954
+ let inBacktick = false;
9955
+ let inBracket = false;
9956
+ let inLineComment = false;
9957
+ let inBlockComment = false;
9958
+ for (let i = 0; i < sql.length; i += 1) {
9959
+ const ch = sql[i];
9960
+ const next = sql[i + 1];
9961
+ if (inLineComment) {
9962
+ if (ch === "\n" || ch === "\r") inLineComment = false;
9963
+ continue;
9964
+ }
9965
+ if (inBlockComment) {
9966
+ if (ch === "*" && next === "/") {
9967
+ i += 1;
9968
+ inBlockComment = false;
9969
+ }
9970
+ continue;
9971
+ }
9972
+ if (inSingle) {
9973
+ if (ch === "'" && next === "'") {
9974
+ i += 1;
9975
+ continue;
9976
+ }
9977
+ if (ch === "'") inSingle = false;
9978
+ continue;
9979
+ }
9980
+ if (inDouble) {
9981
+ if (ch === '"' && next === '"') {
9982
+ i += 1;
9983
+ continue;
9984
+ }
9985
+ if (ch === '"') inDouble = false;
9986
+ continue;
9987
+ }
9988
+ if (inBacktick) {
9989
+ if (ch === "`" && next === "`") {
9990
+ i += 1;
9991
+ continue;
9992
+ }
9993
+ if (ch === "`") inBacktick = false;
9994
+ continue;
9995
+ }
9996
+ if (inBracket) {
9997
+ if (ch === "]") inBracket = false;
9998
+ continue;
9999
+ }
10000
+ if (ch === "-" && next === "-") {
10001
+ inLineComment = true;
10002
+ i += 1;
10003
+ continue;
10004
+ }
10005
+ if (ch === "/" && next === "*") {
10006
+ inBlockComment = true;
10007
+ i += 1;
10008
+ continue;
10009
+ }
10010
+ if (ch === "'") {
10011
+ inSingle = true;
10012
+ continue;
10013
+ }
10014
+ if (ch === '"') {
10015
+ inDouble = true;
10016
+ continue;
10017
+ }
10018
+ if (ch === "`") {
10019
+ inBacktick = true;
10020
+ continue;
10021
+ }
10022
+ if (ch === "[") {
10023
+ inBracket = true;
10024
+ continue;
10025
+ }
10026
+ if (!isIdentChar(ch) || isIdentChar(sql[i - 1])) {
10027
+ continue;
10028
+ }
10029
+ let end = i + 1;
10030
+ while (end < sql.length && isIdentChar(sql[end])) {
10031
+ end += 1;
10032
+ }
10033
+ const keyword = sql.slice(i, end);
10034
+ if (onKeyword(keyword, i)) {
10035
+ return;
10036
+ }
10037
+ i = end - 1;
9998
10038
  }
9999
- return body;
10000
10039
  }
10001
- function createBillingModule(config) {
10002
- const baseUrl = normalizeAthenaGatewayBaseUrl(config.baseUrl, {
10003
- label: "Athena billing base URL"
10040
+ function sqlContainsKeywordOutsideLiterals(sql, keyword) {
10041
+ const target = keyword.toUpperCase();
10042
+ let found = false;
10043
+ scanSqlKeywordsOutsideLiterals(sql, (token) => {
10044
+ if (token.toUpperCase() === target) {
10045
+ found = true;
10046
+ return true;
10047
+ }
10048
+ return false;
10004
10049
  });
10005
- const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
10006
- async function call(method, path, body, options, responseType = "json") {
10007
- const headers = buildAthenaRequestHeaders({
10008
- profile: "gateway",
10009
- sdkHeaderValue: SDK_HEADER_VALUE4,
10010
- apiKey: options?.apiKey ?? config.apiKey,
10011
- client: config.client,
10012
- configHeaders: {
10013
- ...config.headers ?? {}
10014
- },
10015
- callHeaders: options?.headers,
10016
- contentType: "application/json"
10017
- });
10018
- let requestBody;
10019
- if (body !== void 0 && body !== null) {
10020
- if (typeof body === "string" || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof FormData || body instanceof URLSearchParams) {
10021
- requestBody = body;
10022
- } else {
10023
- requestBody = JSON.stringify(body);
10024
- if (!hasHeaderIgnoreCase(headers, "Content-Type")) {
10025
- headers["Content-Type"] = "application/json";
10026
- }
10050
+ return found;
10051
+ }
10052
+ function sqlFirstKeywordOutsideLiterals(sql) {
10053
+ let first = null;
10054
+ scanSqlKeywordsOutsideLiterals(sql, (token) => {
10055
+ first = token;
10056
+ return true;
10057
+ });
10058
+ return first;
10059
+ }
10060
+ var ROW_PRODUCING_LEAD_KEYWORDS = /* @__PURE__ */ new Set(["SELECT", "PRAGMA", "EXPLAIN", "VALUES"]);
10061
+ var MUTATION_LEAD_KEYWORDS = /* @__PURE__ */ new Set(["INSERT", "UPDATE", "DELETE", "REPLACE"]);
10062
+ var WITH_TERMINAL_KEYWORDS = /* @__PURE__ */ new Set([
10063
+ "SELECT",
10064
+ "INSERT",
10065
+ "UPDATE",
10066
+ "DELETE",
10067
+ "REPLACE",
10068
+ "VALUES",
10069
+ "PRAGMA",
10070
+ "EXPLAIN"
10071
+ ]);
10072
+ function sqlTerminalKeywordAfterWith(sql) {
10073
+ let inSingle = false;
10074
+ let inDouble = false;
10075
+ let inBacktick = false;
10076
+ let inBracket = false;
10077
+ let inLineComment = false;
10078
+ let inBlockComment = false;
10079
+ let depth = 0;
10080
+ let sawWith = false;
10081
+ for (let i = 0; i < sql.length; i += 1) {
10082
+ const ch = sql[i];
10083
+ const next = sql[i + 1];
10084
+ if (inLineComment) {
10085
+ if (ch === "\n" || ch === "\r") inLineComment = false;
10086
+ continue;
10087
+ }
10088
+ if (inBlockComment) {
10089
+ if (ch === "*" && next === "/") {
10090
+ i += 1;
10091
+ inBlockComment = false;
10027
10092
  }
10093
+ continue;
10028
10094
  }
10029
- const targetUrl = `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
10030
- const response = await fetchImpl(targetUrl, {
10031
- method,
10032
- headers,
10033
- body: requestBody,
10034
- signal: options?.signal
10035
- });
10036
- if (responseType === "text") {
10037
- const text = await response.text();
10038
- if (!response.ok) {
10039
- throw new AthenaBillingError({
10040
- message: `Billing request failed (${response.status})`,
10041
- status: response.status,
10042
- endpoint: path,
10043
- method,
10044
- body: text
10045
- });
10095
+ if (inSingle) {
10096
+ if (ch === "'" && next === "'") {
10097
+ i += 1;
10098
+ continue;
10046
10099
  }
10047
- return text;
10100
+ if (ch === "'") inSingle = false;
10101
+ continue;
10048
10102
  }
10049
- const rawText = await response.text();
10050
- let parsed = rawText;
10051
- if (rawText) {
10052
- try {
10053
- parsed = JSON.parse(rawText);
10054
- } catch {
10055
- parsed = rawText;
10103
+ if (inDouble) {
10104
+ if (ch === '"' && next === '"') {
10105
+ i += 1;
10106
+ continue;
10056
10107
  }
10057
- } else {
10058
- parsed = null;
10108
+ if (ch === '"') inDouble = false;
10109
+ continue;
10059
10110
  }
10060
- if (!response.ok) {
10061
- const message = parsed && typeof parsed === "object" && "message" in parsed && typeof parsed.message === "string" ? parsed.message : `Billing request failed (${response.status})`;
10062
- throw new AthenaBillingError({
10063
- message,
10064
- status: response.status,
10111
+ if (inBacktick) {
10112
+ if (ch === "`" && next === "`") {
10113
+ i += 1;
10114
+ continue;
10115
+ }
10116
+ if (ch === "`") inBacktick = false;
10117
+ continue;
10118
+ }
10119
+ if (inBracket) {
10120
+ if (ch === "]") inBracket = false;
10121
+ continue;
10122
+ }
10123
+ if (ch === "-" && next === "-") {
10124
+ inLineComment = true;
10125
+ i += 1;
10126
+ continue;
10127
+ }
10128
+ if (ch === "/" && next === "*") {
10129
+ inBlockComment = true;
10130
+ i += 1;
10131
+ continue;
10132
+ }
10133
+ if (ch === "'") {
10134
+ inSingle = true;
10135
+ continue;
10136
+ }
10137
+ if (ch === '"') {
10138
+ inDouble = true;
10139
+ continue;
10140
+ }
10141
+ if (ch === "`") {
10142
+ inBacktick = true;
10143
+ continue;
10144
+ }
10145
+ if (ch === "[") {
10146
+ inBracket = true;
10147
+ continue;
10148
+ }
10149
+ if (ch === "(") {
10150
+ depth += 1;
10151
+ continue;
10152
+ }
10153
+ if (ch === ")") {
10154
+ if (depth > 0) depth -= 1;
10155
+ continue;
10156
+ }
10157
+ if (depth !== 0 || !isIdentChar(ch) || isIdentChar(sql[i - 1])) {
10158
+ continue;
10159
+ }
10160
+ let end = i + 1;
10161
+ while (end < sql.length && isIdentChar(sql[end])) {
10162
+ end += 1;
10163
+ }
10164
+ const keyword = sql.slice(i, end);
10165
+ const upper = keyword.toUpperCase();
10166
+ if (!sawWith) {
10167
+ if (upper === "WITH") {
10168
+ sawWith = true;
10169
+ }
10170
+ i = end - 1;
10171
+ continue;
10172
+ }
10173
+ if (WITH_TERMINAL_KEYWORDS.has(upper)) {
10174
+ return keyword;
10175
+ }
10176
+ i = end - 1;
10177
+ }
10178
+ return null;
10179
+ }
10180
+ function sqlLeadStatementKeyword(sql) {
10181
+ const first = sqlFirstKeywordOutsideLiterals(sql);
10182
+ if (!first) return null;
10183
+ if (first.toUpperCase() !== "WITH") return first;
10184
+ return sqlTerminalKeywordAfterWith(sql) ?? first;
10185
+ }
10186
+ function statementExpectsResultRows(sql) {
10187
+ const lead = sqlLeadStatementKeyword(sql);
10188
+ if (lead) {
10189
+ const upper = lead.toUpperCase();
10190
+ if (ROW_PRODUCING_LEAD_KEYWORDS.has(upper)) {
10191
+ return true;
10192
+ }
10193
+ if (MUTATION_LEAD_KEYWORDS.has(upper)) {
10194
+ return sqlContainsKeywordOutsideLiterals(sql, "RETURNING");
10195
+ }
10196
+ }
10197
+ return sqlContainsKeywordOutsideLiterals(sql, "RETURNING");
10198
+ }
10199
+ function collectRowsFromBatchResults(results) {
10200
+ const rows = [];
10201
+ for (const item of results) {
10202
+ if (Array.isArray(item.results) && item.results.length > 0) {
10203
+ rows.push(...item.results);
10204
+ }
10205
+ }
10206
+ return rows;
10207
+ }
10208
+ function sumBatchAffectedRows(results, statementCount) {
10209
+ let sum2 = 0;
10210
+ let sawChanges = false;
10211
+ for (const item of results) {
10212
+ const changes = item.meta?.changes;
10213
+ if (typeof changes === "number") {
10214
+ sum2 += changes;
10215
+ sawChanges = true;
10216
+ }
10217
+ }
10218
+ return sawChanges ? sum2 : statementCount;
10219
+ }
10220
+ function matchSqlKeywordAt(query, index, keyword) {
10221
+ const len = keyword.length;
10222
+ if (index + len > query.length) {
10223
+ return null;
10224
+ }
10225
+ const slice = query.slice(index, index + len);
10226
+ if (slice.toLowerCase() !== keyword.toLowerCase()) {
10227
+ return null;
10228
+ }
10229
+ const before = index === 0 ? "" : query[index - 1];
10230
+ const after = index + len >= query.length ? "" : query[index + len];
10231
+ const isIdent = (c) => /[A-Za-z0-9_]/.test(c);
10232
+ if (before && isIdent(before)) {
10233
+ return null;
10234
+ }
10235
+ if (after && isIdent(after)) {
10236
+ return null;
10237
+ }
10238
+ return len;
10239
+ }
10240
+ function splitSqlStatements(query) {
10241
+ const statements = [];
10242
+ let inSingle = false;
10243
+ let inDouble = false;
10244
+ let inBacktick = false;
10245
+ let inBracket = false;
10246
+ let inLineComment = false;
10247
+ let inBlockComment = false;
10248
+ let segmentStart = 0;
10249
+ let segmentHasContent = false;
10250
+ let awaitTriggerBegin = false;
10251
+ let triggerBodyDepth = 0;
10252
+ let caseDepth = 0;
10253
+ const flushSegment = (end) => {
10254
+ if (!segmentHasContent) {
10255
+ segmentStart = end + 1;
10256
+ return;
10257
+ }
10258
+ const sql = query.slice(segmentStart, end).trim();
10259
+ if (sql) {
10260
+ statements.push(sql);
10261
+ }
10262
+ segmentHasContent = false;
10263
+ segmentStart = end + 1;
10264
+ awaitTriggerBegin = false;
10265
+ triggerBodyDepth = 0;
10266
+ caseDepth = 0;
10267
+ };
10268
+ for (let i = 0; i < query.length; i += 1) {
10269
+ const ch = query[i];
10270
+ const next = query[i + 1];
10271
+ if (inLineComment) {
10272
+ if (ch === "\n" || ch === "\r") {
10273
+ inLineComment = false;
10274
+ }
10275
+ continue;
10276
+ }
10277
+ if (inBlockComment) {
10278
+ if (ch === "*" && next === "/") {
10279
+ inBlockComment = false;
10280
+ i += 1;
10281
+ }
10282
+ continue;
10283
+ }
10284
+ if (inSingle) {
10285
+ if (ch === "'" && next === "'") {
10286
+ i += 1;
10287
+ continue;
10288
+ }
10289
+ if (ch === "'") {
10290
+ inSingle = false;
10291
+ }
10292
+ continue;
10293
+ }
10294
+ if (inDouble) {
10295
+ if (ch === '"' && next === '"') {
10296
+ i += 1;
10297
+ continue;
10298
+ }
10299
+ if (ch === '"') {
10300
+ inDouble = false;
10301
+ }
10302
+ continue;
10303
+ }
10304
+ if (inBacktick) {
10305
+ if (ch === "`" && next === "`") {
10306
+ i += 1;
10307
+ continue;
10308
+ }
10309
+ if (ch === "`") {
10310
+ inBacktick = false;
10311
+ }
10312
+ continue;
10313
+ }
10314
+ if (inBracket) {
10315
+ if (ch === "]") {
10316
+ inBracket = false;
10317
+ }
10318
+ continue;
10319
+ }
10320
+ if (ch === "-" && next === "-") {
10321
+ inLineComment = true;
10322
+ i += 1;
10323
+ continue;
10324
+ }
10325
+ if (ch === "/" && next === "*") {
10326
+ inBlockComment = true;
10327
+ i += 1;
10328
+ continue;
10329
+ }
10330
+ if (ch === "'") {
10331
+ inSingle = true;
10332
+ segmentHasContent = true;
10333
+ continue;
10334
+ }
10335
+ if (ch === '"') {
10336
+ inDouble = true;
10337
+ segmentHasContent = true;
10338
+ continue;
10339
+ }
10340
+ if (ch === "`") {
10341
+ inBacktick = true;
10342
+ segmentHasContent = true;
10343
+ continue;
10344
+ }
10345
+ if (ch === "[") {
10346
+ inBracket = true;
10347
+ segmentHasContent = true;
10348
+ continue;
10349
+ }
10350
+ if (/[A-Za-z_]/.test(ch)) {
10351
+ const createLen = matchSqlKeywordAt(query, i, "CREATE");
10352
+ if (createLen != null) {
10353
+ let j2 = i + createLen;
10354
+ const skipWsAndComments = () => {
10355
+ while (j2 < query.length) {
10356
+ const c = query[j2];
10357
+ const n = query[j2 + 1];
10358
+ if (/\s/.test(c)) {
10359
+ j2 += 1;
10360
+ continue;
10361
+ }
10362
+ if (c === "-" && n === "-") {
10363
+ j2 += 2;
10364
+ while (j2 < query.length && query[j2] !== "\n" && query[j2] !== "\r") {
10365
+ j2 += 1;
10366
+ }
10367
+ continue;
10368
+ }
10369
+ if (c === "/" && n === "*") {
10370
+ j2 += 2;
10371
+ while (j2 < query.length) {
10372
+ if (query[j2] === "*" && query[j2 + 1] === "/") {
10373
+ j2 += 2;
10374
+ break;
10375
+ }
10376
+ j2 += 1;
10377
+ }
10378
+ continue;
10379
+ }
10380
+ break;
10381
+ }
10382
+ };
10383
+ skipWsAndComments();
10384
+ const tempLen = matchSqlKeywordAt(query, j2, "TEMPORARY") ?? matchSqlKeywordAt(query, j2, "TEMP");
10385
+ if (tempLen != null) {
10386
+ j2 += tempLen;
10387
+ skipWsAndComments();
10388
+ }
10389
+ const triggerLen = matchSqlKeywordAt(query, j2, "TRIGGER");
10390
+ if (triggerLen != null) {
10391
+ awaitTriggerBegin = true;
10392
+ segmentHasContent = true;
10393
+ i += createLen - 1;
10394
+ continue;
10395
+ }
10396
+ segmentHasContent = true;
10397
+ i += createLen - 1;
10398
+ continue;
10399
+ }
10400
+ const caseLen = matchSqlKeywordAt(query, i, "CASE");
10401
+ if (caseLen != null) {
10402
+ caseDepth += 1;
10403
+ segmentHasContent = true;
10404
+ i += caseLen - 1;
10405
+ continue;
10406
+ }
10407
+ const beginLen = matchSqlKeywordAt(query, i, "BEGIN");
10408
+ if (beginLen != null) {
10409
+ if (awaitTriggerBegin) {
10410
+ triggerBodyDepth += 1;
10411
+ awaitTriggerBegin = false;
10412
+ }
10413
+ segmentHasContent = true;
10414
+ i += beginLen - 1;
10415
+ continue;
10416
+ }
10417
+ const endLen = matchSqlKeywordAt(query, i, "END");
10418
+ if (endLen != null) {
10419
+ if (caseDepth > 0) {
10420
+ caseDepth -= 1;
10421
+ } else if (triggerBodyDepth > 0) {
10422
+ triggerBodyDepth -= 1;
10423
+ }
10424
+ segmentHasContent = true;
10425
+ i += endLen - 1;
10426
+ continue;
10427
+ }
10428
+ let j = i + 1;
10429
+ while (j < query.length && /[A-Za-z0-9_]/.test(query[j])) {
10430
+ j += 1;
10431
+ }
10432
+ segmentHasContent = true;
10433
+ i = j - 1;
10434
+ continue;
10435
+ }
10436
+ if (ch === ";") {
10437
+ if (triggerBodyDepth > 0 || caseDepth > 0) {
10438
+ segmentHasContent = true;
10439
+ continue;
10440
+ }
10441
+ flushSegment(i);
10442
+ continue;
10443
+ }
10444
+ if (!/\s/.test(ch)) {
10445
+ segmentHasContent = true;
10446
+ }
10447
+ }
10448
+ flushSegment(query.length);
10449
+ return statements;
10450
+ }
10451
+ function isMultiStatement(query) {
10452
+ return splitSqlStatements(query).length > 1;
10453
+ }
10454
+ function resolveSessionTarget(db, input) {
10455
+ const sessionValue = input.bookmark?.trim() || input.sessionMode?.trim();
10456
+ if (!sessionValue) {
10457
+ return { target: db, session: null };
10458
+ }
10459
+ if (typeof db.withSession !== "function") {
10460
+ throw new Error("D1 session mode/bookmark requested but withSession is not available");
10461
+ }
10462
+ const session = db.withSession(sessionValue);
10463
+ return { target: session, session };
10464
+ }
10465
+ function normalizeD1BindParams(params) {
10466
+ return params.map((value) => {
10467
+ if (typeof value === "boolean") {
10468
+ return value ? 1 : 0;
10469
+ }
10470
+ return value;
10471
+ });
10472
+ }
10473
+ async function executeD1Query(db, input) {
10474
+ const query = input.query?.trim();
10475
+ if (!query) {
10476
+ return { ok: false, error: "invalid_query", message: "query is required" };
10477
+ }
10478
+ const params = normalizeD1BindParams(Array.isArray(input.params) ? input.params : []);
10479
+ const { target, session } = resolveSessionTarget(db, input);
10480
+ if (isMultiStatement(query)) {
10481
+ if (params.length > 0) {
10482
+ return {
10483
+ ok: false,
10484
+ error: "invalid_query",
10485
+ message: "params are only supported for single prepared statements"
10486
+ };
10487
+ }
10488
+ const resolveBookmark = () => session?.getBookmark() ?? null;
10489
+ const parts = splitSqlStatements(query);
10490
+ if (typeof target.batch === "function") {
10491
+ const prepared = parts.map((part) => target.prepare(part));
10492
+ const results = await target.batch(prepared);
10493
+ const rows2 = collectRowsFromBatchResults(results);
10494
+ return {
10495
+ ok: true,
10496
+ rows: rows2,
10497
+ columns: resultColumns(rows2),
10498
+ // Prefer returned rows; otherwise sum mutation meta.changes (not statement count).
10499
+ count: rows2.length > 0 ? rows2.length : sumBatchAffectedRows(results, parts.length),
10500
+ bookmark: resolveBookmark(),
10501
+ meta: { statementCount: parts.length, results },
10502
+ statementCount: parts.length
10503
+ };
10504
+ }
10505
+ const canExec = typeof target.exec === "function" && !session;
10506
+ if (canExec) {
10507
+ const execResult = await target.exec(query);
10508
+ return {
10509
+ ok: true,
10510
+ rows: [],
10511
+ columns: [],
10512
+ durationMs: execResult.duration,
10513
+ count: execResult.count,
10514
+ bookmark: resolveBookmark(),
10515
+ meta: { statementCount: execResult.count },
10516
+ statementCount: execResult.count
10517
+ };
10518
+ }
10519
+ return {
10520
+ ok: false,
10521
+ error: "invalid_query",
10522
+ message: "multi-statement query requires D1 batch() or exec() support"
10523
+ };
10524
+ }
10525
+ let statement = target.prepare(query);
10526
+ if (params.length > 0) {
10527
+ statement = statement.bind(...params);
10528
+ }
10529
+ const expectsRows = statementExpectsResultRows(query);
10530
+ const result = expectsRows ? await statement.all() : await statement.run();
10531
+ if (result.success === false) {
10532
+ const errorField = result.error;
10533
+ const message = typeof errorField === "string" && errorField.trim() ? errorField : "D1 query failed";
10534
+ return {
10535
+ ok: false,
10536
+ error: "query_failed",
10537
+ message
10538
+ };
10539
+ }
10540
+ const rows = Array.isArray(result.results) ? result.results : [];
10541
+ const bookmark = session?.getBookmark() ?? null;
10542
+ const meta = result.meta ?? {};
10543
+ const changes = typeof meta.changes === "number" ? meta.changes : typeof result.meta?.changes === "number" ? result.meta.changes : void 0;
10544
+ return {
10545
+ ok: true,
10546
+ rows,
10547
+ columns: resultColumns(rows),
10548
+ durationMs: typeof result.meta?.duration === "number" ? result.meta.duration : void 0,
10549
+ count: expectsRows ? rows.length : changes ?? rows.length,
10550
+ bookmark,
10551
+ meta
10552
+ };
10553
+ }
10554
+ async function executeD1Batch(db, input) {
10555
+ const statements = Array.isArray(input.statements) ? input.statements : [];
10556
+ if (statements.length === 0) {
10557
+ return {
10558
+ ok: false,
10559
+ error: "invalid_batch",
10560
+ message: "statements must contain at least one item"
10561
+ };
10562
+ }
10563
+ const { target, session } = resolveSessionTarget(db, input);
10564
+ const prepared = statements.map((item) => {
10565
+ const query = item.query?.trim();
10566
+ if (!query) {
10567
+ throw new Error("statements[].query is required");
10568
+ }
10569
+ const params = normalizeD1BindParams(Array.isArray(item.params) ? item.params : []);
10570
+ let statement = target.prepare(query);
10571
+ if (params.length > 0) {
10572
+ statement = statement.bind(...params);
10573
+ }
10574
+ return statement;
10575
+ });
10576
+ const results = await target.batch(prepared);
10577
+ const bookmark = session?.getBookmark() ?? null;
10578
+ return {
10579
+ ok: true,
10580
+ results,
10581
+ bookmark
10582
+ };
10583
+ }
10584
+
10585
+ // src/cloudflare/d1/sql.ts
10586
+ function asSingle(sql, params) {
10587
+ return { sql, params };
10588
+ }
10589
+ function asBatch(statements) {
10590
+ if (statements.length === 0) {
10591
+ throw new D1SqlCompileError("empty_insert", "batch requires at least one statement");
10592
+ }
10593
+ return {
10594
+ sql: statements[0].sql,
10595
+ params: statements[0].params,
10596
+ statements
10597
+ };
10598
+ }
10599
+ function hasPaginationBounds(payload) {
10600
+ return payload.limit !== void 0 || payload.offset !== void 0 || payload.page_size !== void 0 || payload.current_page !== void 0;
10601
+ }
10602
+ function assertEffectiveMutationBounds(payload) {
10603
+ if (payload.current_page !== void 0 && payload.page_size === void 0 && payload.limit === void 0) {
10604
+ throw new D1SqlCompileError(
10605
+ "page_without_size",
10606
+ "current_page requires page_size (or limit) for bounded update/delete on D1 edge-local"
10607
+ );
10608
+ }
10609
+ const clause = limitOffsetClause(payload);
10610
+ if (!clause.trim()) {
10611
+ throw new D1SqlCompileError(
10612
+ "invalid_pagination_bounds",
10613
+ "Bounded update/delete requires limit, offset, and/or page_size on D1 edge-local"
10614
+ );
10615
+ }
10616
+ }
10617
+ var SQLITE_ROWID_ALIASES = /* @__PURE__ */ new Set(["rowid", "oid", "_rowid_"]);
10618
+ function referencedMutationColumns(payload) {
10619
+ const names = [];
10620
+ for (const condition of payload.conditions ?? []) {
10621
+ const column = (condition.column ?? condition.eq_column ?? "").trim();
10622
+ if (column) names.push(column);
10623
+ }
10624
+ if (payload.sort_by?.field?.trim()) {
10625
+ names.push(payload.sort_by.field.trim());
10626
+ }
10627
+ return names;
10628
+ }
10629
+ function resolveBoundedIdentityColumn(payload, options) {
10630
+ const refs = referencedMutationColumns(payload);
10631
+ const lower = refs.map((name) => name.toLowerCase());
10632
+ if (lower.some((name) => SQLITE_ROWID_ALIASES.has(name))) {
10633
+ throw new D1SqlCompileError(
10634
+ "bounded_mutation_unsafe_identity",
10635
+ "Bounded update/delete cannot use rowid/oid/_rowid_ in filters or order \u2014 those names may be user columns that shadow SQLite row identity. Resolve the table primary key (or a single-column unique index) instead."
10636
+ );
10637
+ }
10638
+ const identity = options?.identityColumn?.trim();
10639
+ if (!identity) {
10640
+ throw new D1SqlCompileError(
10641
+ "bounded_mutation_no_unique_identity",
10642
+ "Bounded update/delete requires a proven unique identity column from the table schema (single-column PRIMARY KEY or UNIQUE index). Cannot assume a column named id."
10643
+ );
10644
+ }
10645
+ if (SQLITE_ROWID_ALIASES.has(identity.toLowerCase())) {
10646
+ throw new D1SqlCompileError(
10647
+ "bounded_mutation_unsafe_identity",
10648
+ `Bounded update/delete cannot use identity column "${identity}" \u2014 it may shadow SQLite row identity.`
10649
+ );
10650
+ }
10651
+ return identity;
10652
+ }
10653
+ function boundedRowidInClause(table2, whereSql, whereParams, payload, options) {
10654
+ assertEffectiveMutationBounds(payload);
10655
+ const identity = resolveBoundedIdentityColumn(payload, options);
10656
+ const identitySql = quoteIdent(identity);
10657
+ const innerWhere = whereSql.replace(/^WHERE\s+/i, "");
10658
+ const parts = [
10659
+ `SELECT ${identitySql} FROM ${quoteIdent(table2)}`,
10660
+ innerWhere ? `WHERE ${innerWhere}` : "",
10661
+ orderClause(payload.sort_by),
10662
+ limitOffsetClause(payload)
10663
+ ].filter(Boolean);
10664
+ return {
10665
+ sql: `${identitySql} IN (${parts.join(" ")})`,
10666
+ params: [...whereParams]
10667
+ };
10668
+ }
10669
+ var D1SqlCompileError = class extends Error {
10670
+ code;
10671
+ constructor(code, message) {
10672
+ super(message);
10673
+ this.name = "D1SqlCompileError";
10674
+ this.code = code;
10675
+ }
10676
+ };
10677
+ var SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
10678
+ function quoteIdent(name) {
10679
+ const trimmed = name.trim();
10680
+ if (!trimmed) {
10681
+ throw new D1SqlCompileError("invalid_identifier", "Identifier is required");
10682
+ }
10683
+ if (trimmed.includes(".")) {
10684
+ throw new D1SqlCompileError(
10685
+ "schema_qualified_name",
10686
+ `Schema-qualified names are unsupported on D1 edge-local: ${trimmed}`
10687
+ );
10688
+ }
10689
+ if (!SAFE_IDENTIFIER.test(trimmed)) {
10690
+ throw new D1SqlCompileError(
10691
+ "invalid_identifier",
10692
+ `Invalid SQL identifier for D1 edge-local: ${trimmed}`
10693
+ );
10694
+ }
10695
+ return quoteQualifiedIdentifier(trimmed);
10696
+ }
10697
+ var RESPONSE_ALIAS_PATTERN2 = /^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*([A-Za-z_][A-Za-z0-9_]*)$/;
10698
+ var SQL_ALIAS_PATTERN2 = /^([A-Za-z_][A-Za-z0-9_]*)\s+(?:as\s+)?([A-Za-z_][A-Za-z0-9_]*)$/i;
10699
+ function quoteSelectTokenStrict(token) {
10700
+ const trimmed = token.trim();
10701
+ if (!trimmed || trimmed === "*") return trimmed || "*";
10702
+ if (SAFE_IDENTIFIER.test(trimmed)) {
10703
+ return quoteQualifiedIdentifier(trimmed);
10704
+ }
10705
+ const responseAlias = RESPONSE_ALIAS_PATTERN2.exec(trimmed);
10706
+ if (responseAlias) {
10707
+ const [, aliasIdentifier, baseIdentifier] = responseAlias;
10708
+ return `${quoteQualifiedIdentifier(baseIdentifier)} AS ${quoteQualifiedIdentifier(aliasIdentifier)}`;
10709
+ }
10710
+ const sqlAlias = SQL_ALIAS_PATTERN2.exec(trimmed);
10711
+ if (sqlAlias) {
10712
+ const [, baseIdentifier, aliasIdentifier] = sqlAlias;
10713
+ return `${quoteQualifiedIdentifier(baseIdentifier)} AS ${quoteQualifiedIdentifier(aliasIdentifier)}`;
10714
+ }
10715
+ throw new D1SqlCompileError(
10716
+ "unsafe_select",
10717
+ `SELECT/RETURNING expressions are not supported on D1 edge-local; use column names or aliases only: ${token}`
10718
+ );
10719
+ }
10720
+ function selectClause(columns) {
10721
+ if (columns === void 0 || columns === "*" || columns === "") return "*";
10722
+ if (typeof columns === "string") {
10723
+ const trimmed = columns.trim();
10724
+ if (!trimmed || trimmed === "*") return "*";
10725
+ return trimmed.split(",").map((part) => quoteSelectTokenStrict(part)).join(", ");
10726
+ }
10727
+ if (columns.length === 0) return "*";
10728
+ return columns.map((column) => quoteSelectTokenStrict(column)).join(", ");
10729
+ }
10730
+ function wantsReturning(payload) {
10731
+ return Boolean(payload.columns) && payload.head !== true;
10732
+ }
10733
+ function conditionToWhere(condition) {
10734
+ const column = condition.column?.trim() || condition.eq_column?.trim() || "";
10735
+ if (!column) {
10736
+ throw new D1SqlCompileError("invalid_condition", "Condition requires a column");
10737
+ }
10738
+ const col = quoteIdent(column);
10739
+ const operator = (condition.operator || "eq").toLowerCase();
10740
+ const value = condition.value !== void 0 ? condition.value : condition.eq_value;
10741
+ switch (operator) {
10742
+ case "eq": {
10743
+ if (Array.isArray(value)) {
10744
+ if (value.length === 0) {
10745
+ return { sql: "1 = 0", params: [] };
10746
+ }
10747
+ const placeholders = value.map(() => "?").join(", ");
10748
+ return { sql: `${col} IN (${placeholders})`, params: [...value] };
10749
+ }
10750
+ if (value === null) {
10751
+ return { sql: `${col} IS NULL`, params: [] };
10752
+ }
10753
+ return { sql: `${col} = ?`, params: [value ?? null] };
10754
+ }
10755
+ case "neq":
10756
+ if (value === null) {
10757
+ return { sql: `${col} IS NOT NULL`, params: [] };
10758
+ }
10759
+ return { sql: `${col} != ?`, params: [value ?? null] };
10760
+ case "gt":
10761
+ return { sql: `${col} > ?`, params: [value ?? null] };
10762
+ case "gte":
10763
+ return { sql: `${col} >= ?`, params: [value ?? null] };
10764
+ case "lt":
10765
+ return { sql: `${col} < ?`, params: [value ?? null] };
10766
+ case "lte":
10767
+ return { sql: `${col} <= ?`, params: [value ?? null] };
10768
+ case "like":
10769
+ return { sql: `${col} LIKE ?`, params: [value ?? null] };
10770
+ case "ilike":
10771
+ return { sql: `${col} LIKE ? COLLATE NOCASE`, params: [value ?? null] };
10772
+ case "in": {
10773
+ const items = Array.isArray(value) ? value : value === void 0 ? [] : [value];
10774
+ if (items.length === 0) {
10775
+ return { sql: "1 = 0", params: [] };
10776
+ }
10777
+ const placeholders = items.map(() => "?").join(", ");
10778
+ return { sql: `${col} IN (${placeholders})`, params: [...items] };
10779
+ }
10780
+ case "is": {
10781
+ if (value === null || value === "null") {
10782
+ return { sql: `${col} IS NULL`, params: [] };
10783
+ }
10784
+ if (value === true || value === "true") {
10785
+ return { sql: `${col} IS TRUE`, params: [] };
10786
+ }
10787
+ if (value === false || value === "false") {
10788
+ return { sql: `${col} IS FALSE`, params: [] };
10789
+ }
10790
+ return { sql: `${col} IS ?`, params: [value] };
10791
+ }
10792
+ case "not":
10793
+ case "or":
10794
+ case "contains":
10795
+ case "containedby":
10796
+ throw new D1SqlCompileError(
10797
+ "unsupported_operator",
10798
+ `Condition operator "${operator}" is not supported on D1 edge-local L1`
10799
+ );
10800
+ default:
10801
+ throw new D1SqlCompileError(
10802
+ "unsupported_operator",
10803
+ `Unknown condition operator "${operator}"`
10804
+ );
10805
+ }
10806
+ }
10807
+ function buildWhere(conditions) {
10808
+ if (!conditions?.length) {
10809
+ return { sql: "", params: [] };
10810
+ }
10811
+ const parts = [];
10812
+ const params = [];
10813
+ for (const condition of conditions) {
10814
+ if (!condition.operator && condition.eq_column) {
10815
+ const clause2 = conditionToWhere({
10816
+ ...condition,
10817
+ operator: "eq",
10818
+ column: condition.eq_column,
10819
+ value: condition.eq_value
10820
+ });
10821
+ parts.push(clause2.sql);
10822
+ params.push(...clause2.params);
10823
+ continue;
10824
+ }
10825
+ const clause = conditionToWhere(condition);
10826
+ parts.push(clause.sql);
10827
+ params.push(...clause.params);
10828
+ }
10829
+ return {
10830
+ sql: parts.length ? `WHERE ${parts.join(" AND ")}` : "",
10831
+ params
10832
+ };
10833
+ }
10834
+ function orderClause(order) {
10835
+ if (!order?.field?.trim()) return "";
10836
+ const direction = order.direction === "descending" ? "DESC" : "ASC";
10837
+ return `ORDER BY ${quoteIdent(order.field)} ${direction}`;
10838
+ }
10839
+ function limitOffsetClause(payload) {
10840
+ let limit = payload.limit;
10841
+ let offset = payload.offset;
10842
+ if (limit === void 0 && payload.page_size !== void 0) {
10843
+ limit = payload.page_size;
10844
+ }
10845
+ if (payload.current_page !== void 0 && offset === void 0) {
10846
+ const pageSize = payload.page_size ?? payload.limit;
10847
+ if (pageSize !== void 0) {
10848
+ offset = Math.max(0, (payload.current_page - 1) * pageSize);
10849
+ }
10850
+ }
10851
+ const parts = [];
10852
+ if (offset !== void 0 && limit === void 0) {
10853
+ parts.push("LIMIT -1");
10854
+ parts.push(`OFFSET ${Math.max(0, Math.trunc(offset))}`);
10855
+ } else {
10856
+ if (limit !== void 0) {
10857
+ parts.push(`LIMIT ${Math.max(0, Math.trunc(limit))}`);
10858
+ }
10859
+ if (offset !== void 0) {
10860
+ parts.push(`OFFSET ${Math.max(0, Math.trunc(offset))}`);
10861
+ }
10862
+ }
10863
+ return parts.join(" ");
10864
+ }
10865
+ function rejectStructuredRelations(payload) {
10866
+ const select = payload.select;
10867
+ if (select && typeof select === "object" && !Array.isArray(select)) {
10868
+ for (const value of Object.values(select)) {
10869
+ if (value && typeof value === "object") {
10870
+ throw new D1SqlCompileError(
10871
+ "relations_unsupported",
10872
+ "Nested relation selects are unsupported on D1 edge-local"
10873
+ );
10874
+ }
10875
+ }
10876
+ }
10877
+ if (payload.view_name) {
10878
+ throw new D1SqlCompileError(
10879
+ "view_unsupported",
10880
+ "view_name is unsupported on D1 edge-local L1"
10881
+ );
10882
+ }
10883
+ }
10884
+ function jsonValue(value) {
10885
+ if (value === void 0) return null;
10886
+ if (value !== null && typeof value === "object") {
10887
+ return JSON.stringify(value);
10888
+ }
10889
+ return value;
10890
+ }
10891
+ function compileD1Fetch(payload) {
10892
+ rejectStructuredRelations(payload);
10893
+ const table2 = payload.table_name?.trim();
10894
+ if (!table2) {
10895
+ throw new D1SqlCompileError("missing_table", "table_name is required for fetch");
10896
+ }
10897
+ let columns = payload.columns;
10898
+ if (payload.select && typeof payload.select === "object" && !Array.isArray(payload.select)) {
10899
+ const keys = Object.entries(payload.select).filter(([, enabled]) => enabled === true || enabled === 1).map(([key]) => key);
10900
+ if (keys.length > 0) {
10901
+ columns = keys;
10902
+ }
10903
+ } else if (typeof payload.select === "string" && payload.select.trim()) {
10904
+ columns = payload.select;
10905
+ }
10906
+ let where = buildWhere(payload.conditions);
10907
+ if (!where.sql && payload.where && typeof payload.where === "object") {
10908
+ const eqConditions = Object.entries(
10909
+ payload.where
10910
+ ).map(([column, value]) => ({
10911
+ column,
10912
+ operator: "eq",
10913
+ value
10914
+ }));
10915
+ where = buildWhere(eqConditions);
10916
+ }
10917
+ if (payload.head === true) {
10918
+ return compileD1CountFromWhere(table2, where);
10919
+ }
10920
+ const parts = [
10921
+ `SELECT ${selectClause(columns)} FROM ${quoteIdent(table2)}`,
10922
+ where.sql,
10923
+ orderClause(payload.sort_by),
10924
+ limitOffsetClause(payload)
10925
+ ].filter(Boolean);
10926
+ return asSingle(parts.join(" "), where.params);
10927
+ }
10928
+ function compileD1Count(payload) {
10929
+ rejectStructuredRelations(payload);
10930
+ const table2 = payload.table_name?.trim();
10931
+ if (!table2) {
10932
+ throw new D1SqlCompileError("missing_table", "table_name is required for count");
10933
+ }
10934
+ let where = buildWhere(payload.conditions);
10935
+ if (!where.sql && payload.where && typeof payload.where === "object") {
10936
+ const eqConditions = Object.entries(
10937
+ payload.where
10938
+ ).map(([column, value]) => ({
10939
+ column,
10940
+ operator: "eq",
10941
+ value
10942
+ }));
10943
+ where = buildWhere(eqConditions);
10944
+ }
10945
+ return compileD1CountFromWhere(table2, where);
10946
+ }
10947
+ function compileD1CountFromWhere(table2, where) {
10948
+ const parts = [
10949
+ `SELECT COUNT(*) AS __athena_count FROM ${quoteIdent(table2)}`,
10950
+ where.sql
10951
+ ].filter(Boolean);
10952
+ return asSingle(parts.join(" "), where.params);
10953
+ }
10954
+ function extractAthenaCount(rows) {
10955
+ const first = rows[0];
10956
+ const rawCount = first && typeof first === "object" && !Array.isArray(first) ? first.__athena_count : void 0;
10957
+ const count = typeof rawCount === "number" ? rawCount : typeof rawCount === "bigint" ? Number(rawCount) : Number(rawCount ?? 0);
10958
+ return Number.isFinite(count) ? count : 0;
10959
+ }
10960
+ function compileSingleRowInsert(table2, row, payload) {
10961
+ const columns = Object.keys(row);
10962
+ if (columns.length === 0) {
10963
+ if (payload.on_conflict) {
10964
+ throw new D1SqlCompileError(
10965
+ "default_values_upsert_unsupported",
10966
+ "DEFAULT VALUES upsert is unsupported on D1 edge-local; provide insert columns or omit onConflict"
10967
+ );
10968
+ }
10969
+ const parts2 = [`INSERT INTO ${quoteIdent(table2)} DEFAULT VALUES`];
10970
+ if (wantsReturning(payload)) {
10971
+ parts2.push(`RETURNING ${selectClause(payload.columns)}`);
10972
+ }
10973
+ return { sql: parts2.join(" "), params: [] };
10974
+ }
10975
+ const params = columns.map((column) => jsonValue(row[column]));
10976
+ const parts = [
10977
+ `INSERT INTO ${quoteIdent(table2)} (${columns.map(quoteIdent).join(", ")})`,
10978
+ `VALUES (${columns.map(() => "?").join(", ")})`
10979
+ ];
10980
+ appendOnConflict(parts, params, payload, columns);
10981
+ if (wantsReturning(payload)) {
10982
+ parts.push(`RETURNING ${selectClause(payload.columns)}`);
10983
+ }
10984
+ return { sql: parts.join(" "), params };
10985
+ }
10986
+ function parseOnConflictColumns(onConflict) {
10987
+ const raw = Array.isArray(onConflict) ? onConflict : [onConflict];
10988
+ const columns = [];
10989
+ for (const item of raw) {
10990
+ for (const part of String(item).split(",")) {
10991
+ const trimmed = part.trim();
10992
+ if (trimmed) columns.push(trimmed);
10993
+ }
10994
+ }
10995
+ if (columns.length === 0) {
10996
+ throw new D1SqlCompileError(
10997
+ "invalid_on_conflict",
10998
+ "on_conflict requires at least one column"
10999
+ );
11000
+ }
11001
+ return columns;
11002
+ }
11003
+ function appendOnConflict(parts, params, payload, insertColumns) {
11004
+ if (!payload.on_conflict) return;
11005
+ const conflictCols = parseOnConflictColumns(payload.on_conflict);
11006
+ const conflictSql = conflictCols.map(quoteIdent).join(", ");
11007
+ if (payload.update_body !== void 0 && payload.update_body !== null) {
11008
+ const entries = Object.entries(payload.update_body);
11009
+ if (entries.length === 0) {
11010
+ parts.push(`ON CONFLICT (${conflictSql}) DO NOTHING`);
11011
+ return;
11012
+ }
11013
+ const assignments2 = entries.map(([column, value]) => {
11014
+ params.push(jsonValue(value));
11015
+ return `${quoteIdent(column)} = ?`;
11016
+ });
11017
+ parts.push(`ON CONFLICT (${conflictSql}) DO UPDATE SET ${assignments2.join(", ")}`);
11018
+ return;
11019
+ }
11020
+ const conflictSet = new Set(conflictCols);
11021
+ const assignments = insertColumns.filter((column) => !conflictSet.has(column)).map((column) => {
11022
+ const quoted = quoteIdent(column);
11023
+ return `${quoted} = excluded.${quoted}`;
11024
+ });
11025
+ if (assignments.length === 0) {
11026
+ parts.push(`ON CONFLICT (${conflictSql}) DO NOTHING`);
11027
+ } else {
11028
+ parts.push(`ON CONFLICT (${conflictSql}) DO UPDATE SET ${assignments.join(", ")}`);
11029
+ }
11030
+ }
11031
+ function compileD1Insert(payload) {
11032
+ const table2 = payload.table_name?.trim();
11033
+ if (!table2) {
11034
+ throw new D1SqlCompileError("missing_table", "table_name is required for insert");
11035
+ }
11036
+ const rows = Array.isArray(payload.insert_body) ? payload.insert_body : [payload.insert_body];
11037
+ if (rows.length === 0) {
11038
+ throw new D1SqlCompileError("empty_insert", "insert_body must not be empty");
11039
+ }
11040
+ const columns = [];
11041
+ const seen = /* @__PURE__ */ new Set();
11042
+ for (const row of rows) {
11043
+ for (const key of Object.keys(row ?? {})) {
11044
+ if (seen.has(key)) continue;
11045
+ seen.add(key);
11046
+ columns.push(key);
11047
+ }
11048
+ }
11049
+ if (columns.length === 0) {
11050
+ if (rows.length === 1) {
11051
+ const compiled = compileSingleRowInsert(table2, {}, payload);
11052
+ return asSingle(compiled.sql, compiled.params);
11053
+ }
11054
+ throw new D1SqlCompileError(
11055
+ "empty_insert",
11056
+ "Multi-row insert_body cannot be empty objects; use a single {} for DEFAULT VALUES"
11057
+ );
11058
+ }
11059
+ const forceNullForMissing = payload.default_to_null === true;
11060
+ const isSparse = rows.some(
11061
+ (row) => columns.some((column) => !Object.prototype.hasOwnProperty.call(row, column))
11062
+ );
11063
+ if (isSparse && !forceNullForMissing && rows.length > 1) {
11064
+ return asBatch(
11065
+ rows.map((row) => compileSingleRowInsert(table2, row, payload))
11066
+ );
11067
+ }
11068
+ if (isSparse && !forceNullForMissing && rows.length === 1) {
11069
+ const compiled = compileSingleRowInsert(table2, rows[0], payload);
11070
+ return asSingle(compiled.sql, compiled.params);
11071
+ }
11072
+ const params = [];
11073
+ const valueGroups = rows.map((row) => {
11074
+ const placeholders = columns.map((column) => {
11075
+ const has = Object.prototype.hasOwnProperty.call(row, column);
11076
+ if (!has) {
11077
+ params.push(null);
11078
+ return "?";
11079
+ }
11080
+ params.push(jsonValue(row[column]));
11081
+ return "?";
11082
+ });
11083
+ return `(${placeholders.join(", ")})`;
11084
+ });
11085
+ const parts = [
11086
+ `INSERT INTO ${quoteIdent(table2)} (${columns.map(quoteIdent).join(", ")})`,
11087
+ `VALUES ${valueGroups.join(", ")}`
11088
+ ];
11089
+ appendOnConflict(parts, params, payload, columns);
11090
+ if (wantsReturning(payload)) {
11091
+ parts.push(`RETURNING ${selectClause(payload.columns)}`);
11092
+ }
11093
+ return asSingle(parts.join(" "), params);
11094
+ }
11095
+ function compileD1Update(payload, options) {
11096
+ const table2 = payload.table_name?.trim();
11097
+ if (!table2) {
11098
+ throw new D1SqlCompileError("missing_table", "table_name is required for update");
11099
+ }
11100
+ const entries = Object.entries(payload.update_body ?? {});
11101
+ if (entries.length === 0) {
11102
+ throw new D1SqlCompileError("empty_update", "update_body must not be empty");
11103
+ }
11104
+ const params = [];
11105
+ const assignments = entries.map(([column, value]) => {
11106
+ params.push(jsonValue(value));
11107
+ return `${quoteIdent(column)} = ?`;
11108
+ });
11109
+ const where = buildWhere(payload.conditions);
11110
+ if (!where.sql) {
11111
+ throw new D1SqlCompileError(
11112
+ "unfiltered_update",
11113
+ "UPDATE requires at least one condition on D1 edge-local"
11114
+ );
11115
+ }
11116
+ if (hasPaginationBounds(payload) || payload.sort_by) {
11117
+ if (!hasPaginationBounds(payload)) {
11118
+ throw new D1SqlCompileError(
11119
+ "order_without_bounds",
11120
+ "UPDATE with sort_by requires limit/offset or page_size/current_page on D1 edge-local"
11121
+ );
11122
+ }
11123
+ const bounded = boundedRowidInClause(
11124
+ table2,
11125
+ where.sql,
11126
+ where.params,
11127
+ {
11128
+ ...payload,
11129
+ conditions: payload.conditions
11130
+ },
11131
+ options
11132
+ );
11133
+ params.push(...bounded.params);
11134
+ const parts2 = [
11135
+ `UPDATE ${quoteIdent(table2)} SET ${assignments.join(", ")}`,
11136
+ `WHERE ${bounded.sql}`
11137
+ ];
11138
+ if (wantsReturning(payload)) {
11139
+ parts2.push(`RETURNING ${selectClause(payload.columns)}`);
11140
+ }
11141
+ return asSingle(parts2.join(" "), params);
11142
+ }
11143
+ params.push(...where.params);
11144
+ const parts = [
11145
+ `UPDATE ${quoteIdent(table2)} SET ${assignments.join(", ")}`,
11146
+ where.sql
11147
+ ];
11148
+ if (wantsReturning(payload)) {
11149
+ parts.push(`RETURNING ${selectClause(payload.columns)}`);
11150
+ }
11151
+ return asSingle(parts.join(" "), params);
11152
+ }
11153
+ function compileD1Delete(payload, options) {
11154
+ const table2 = payload.table_name?.trim();
11155
+ if (!table2) {
11156
+ throw new D1SqlCompileError("missing_table", "table_name is required for delete");
11157
+ }
11158
+ const conditions = [...payload.conditions ?? []];
11159
+ if (payload.resource_id !== void 0 && payload.resource_id !== null) {
11160
+ const hasResourceIdFilter = conditions.some((condition) => {
11161
+ const column = (condition.column ?? condition.eq_column ?? "").trim();
11162
+ return column === "resource_id";
11163
+ });
11164
+ const hasIdFilter = conditions.some((condition) => {
11165
+ const column = (condition.column ?? condition.eq_column ?? "").trim();
11166
+ return column === "id";
11167
+ });
11168
+ if (!hasResourceIdFilter && !hasIdFilter) {
11169
+ conditions.unshift({
11170
+ column: "id",
11171
+ operator: "eq",
11172
+ value: payload.resource_id
11173
+ });
11174
+ }
11175
+ }
11176
+ const where = buildWhere(conditions);
11177
+ if (!where.sql) {
11178
+ throw new D1SqlCompileError(
11179
+ "unfiltered_delete",
11180
+ "DELETE requires at least one condition or resource_id on D1 edge-local"
11181
+ );
11182
+ }
11183
+ if (hasPaginationBounds(payload) || payload.sort_by) {
11184
+ if (!hasPaginationBounds(payload)) {
11185
+ throw new D1SqlCompileError(
11186
+ "order_without_bounds",
11187
+ "DELETE with sort_by requires limit/offset or page_size/current_page on D1 edge-local"
11188
+ );
11189
+ }
11190
+ const bounded = boundedRowidInClause(
11191
+ table2,
11192
+ where.sql,
11193
+ where.params,
11194
+ {
11195
+ ...payload,
11196
+ conditions
11197
+ },
11198
+ options
11199
+ );
11200
+ const parts2 = [`DELETE FROM ${quoteIdent(table2)}`, `WHERE ${bounded.sql}`];
11201
+ if (wantsReturning(payload)) {
11202
+ parts2.push(`RETURNING ${selectClause(payload.columns)}`);
11203
+ }
11204
+ return asSingle(parts2.join(" "), bounded.params);
11205
+ }
11206
+ const parts = [`DELETE FROM ${quoteIdent(table2)}`, where.sql];
11207
+ if (wantsReturning(payload)) {
11208
+ parts.push(`RETURNING ${selectClause(payload.columns)}`);
11209
+ }
11210
+ return asSingle(parts.join(" "), where.params);
11211
+ }
11212
+
11213
+ // src/cloudflare/d1/sql-rewrite.ts
11214
+ var PG_CAST_TYPES = "text|uuid|citext|varchar|bpchar|char|integer|int4|int8|bigint|smallint|boolean|bool|jsonb|json|numeric|decimal|real|float|double precision|timestamptz|timestamp|date|bytea";
11215
+ function mapSqlOutsideLiterals(sql, transform) {
11216
+ let out = "";
11217
+ let buffer = "";
11218
+ let inSingle = false;
11219
+ let inDouble = false;
11220
+ let inBacktick = false;
11221
+ let inBracket = false;
11222
+ let inLineComment = false;
11223
+ let inBlockComment = false;
11224
+ const flushCode = () => {
11225
+ if (buffer) {
11226
+ out += transform(buffer);
11227
+ buffer = "";
11228
+ }
11229
+ };
11230
+ for (let i = 0; i < sql.length; i += 1) {
11231
+ const ch = sql[i];
11232
+ const next = sql[i + 1];
11233
+ if (inLineComment) {
11234
+ out += ch;
11235
+ if (ch === "\n" || ch === "\r") inLineComment = false;
11236
+ continue;
11237
+ }
11238
+ if (inBlockComment) {
11239
+ out += ch;
11240
+ if (ch === "*" && next === "/") {
11241
+ out += next;
11242
+ i += 1;
11243
+ inBlockComment = false;
11244
+ }
11245
+ continue;
11246
+ }
11247
+ if (inSingle) {
11248
+ out += ch;
11249
+ if (ch === "'" && next === "'") {
11250
+ out += next;
11251
+ i += 1;
11252
+ continue;
11253
+ }
11254
+ if (ch === "'") inSingle = false;
11255
+ continue;
11256
+ }
11257
+ if (inDouble) {
11258
+ out += ch;
11259
+ if (ch === '"' && next === '"') {
11260
+ out += next;
11261
+ i += 1;
11262
+ continue;
11263
+ }
11264
+ if (ch === '"') inDouble = false;
11265
+ continue;
11266
+ }
11267
+ if (inBacktick) {
11268
+ out += ch;
11269
+ if (ch === "`" && next === "`") {
11270
+ out += next;
11271
+ i += 1;
11272
+ continue;
11273
+ }
11274
+ if (ch === "`") inBacktick = false;
11275
+ continue;
11276
+ }
11277
+ if (inBracket) {
11278
+ out += ch;
11279
+ if (ch === "]") inBracket = false;
11280
+ continue;
11281
+ }
11282
+ if (ch === "-" && next === "-") {
11283
+ flushCode();
11284
+ out += ch;
11285
+ out += next;
11286
+ i += 1;
11287
+ inLineComment = true;
11288
+ continue;
11289
+ }
11290
+ if (ch === "/" && next === "*") {
11291
+ flushCode();
11292
+ out += ch;
11293
+ out += next;
11294
+ i += 1;
11295
+ inBlockComment = true;
11296
+ continue;
11297
+ }
11298
+ if (ch === "'") {
11299
+ flushCode();
11300
+ out += ch;
11301
+ inSingle = true;
11302
+ continue;
11303
+ }
11304
+ if (ch === '"') {
11305
+ flushCode();
11306
+ out += ch;
11307
+ inDouble = true;
11308
+ continue;
11309
+ }
11310
+ if (ch === "`") {
11311
+ flushCode();
11312
+ out += ch;
11313
+ inBacktick = true;
11314
+ continue;
11315
+ }
11316
+ if (ch === "[") {
11317
+ flushCode();
11318
+ out += ch;
11319
+ inBracket = true;
11320
+ continue;
11321
+ }
11322
+ buffer += ch;
11323
+ }
11324
+ flushCode();
11325
+ return out;
11326
+ }
11327
+ function isIdentChar2(ch) {
11328
+ if (!ch) return false;
11329
+ return /[A-Za-z0-9_]/.test(ch);
11330
+ }
11331
+ function collectLimitOffsetKeywords(sql) {
11332
+ const hits = [];
11333
+ let depth = 0;
11334
+ let statement = 0;
11335
+ let inSingle = false;
11336
+ let inDouble = false;
11337
+ let inBacktick = false;
11338
+ let inBracket = false;
11339
+ let inLineComment = false;
11340
+ let inBlockComment = false;
11341
+ for (let i = 0; i < sql.length; i += 1) {
11342
+ const ch = sql[i];
11343
+ const next = sql[i + 1];
11344
+ if (inLineComment) {
11345
+ if (ch === "\n" || ch === "\r") inLineComment = false;
11346
+ continue;
11347
+ }
11348
+ if (inBlockComment) {
11349
+ if (ch === "*" && next === "/") {
11350
+ i += 1;
11351
+ inBlockComment = false;
11352
+ }
11353
+ continue;
11354
+ }
11355
+ if (inSingle) {
11356
+ if (ch === "'" && next === "'") {
11357
+ i += 1;
11358
+ continue;
11359
+ }
11360
+ if (ch === "'") inSingle = false;
11361
+ continue;
11362
+ }
11363
+ if (inDouble) {
11364
+ if (ch === '"' && next === '"') {
11365
+ i += 1;
11366
+ continue;
11367
+ }
11368
+ if (ch === '"') inDouble = false;
11369
+ continue;
11370
+ }
11371
+ if (inBacktick) {
11372
+ if (ch === "`" && next === "`") {
11373
+ i += 1;
11374
+ continue;
11375
+ }
11376
+ if (ch === "`") inBacktick = false;
11377
+ continue;
11378
+ }
11379
+ if (inBracket) {
11380
+ if (ch === "]") inBracket = false;
11381
+ continue;
11382
+ }
11383
+ if (ch === "-" && next === "-") {
11384
+ inLineComment = true;
11385
+ i += 1;
11386
+ continue;
11387
+ }
11388
+ if (ch === "/" && next === "*") {
11389
+ inBlockComment = true;
11390
+ i += 1;
11391
+ continue;
11392
+ }
11393
+ if (ch === "'") {
11394
+ inSingle = true;
11395
+ continue;
11396
+ }
11397
+ if (ch === '"') {
11398
+ inDouble = true;
11399
+ continue;
11400
+ }
11401
+ if (ch === "`") {
11402
+ inBacktick = true;
11403
+ continue;
11404
+ }
11405
+ if (ch === "[") {
11406
+ inBracket = true;
11407
+ continue;
11408
+ }
11409
+ if (ch === "(") {
11410
+ depth += 1;
11411
+ continue;
11412
+ }
11413
+ if (ch === ")") {
11414
+ depth = Math.max(0, depth - 1);
11415
+ continue;
11416
+ }
11417
+ if (ch === ";" && depth === 0) {
11418
+ statement += 1;
11419
+ continue;
11420
+ }
11421
+ if (!isIdentChar2(ch) || isIdentChar2(sql[i - 1])) {
11422
+ continue;
11423
+ }
11424
+ const rest = sql.slice(i);
11425
+ if (/^LIMIT\b/i.test(rest)) {
11426
+ hits.push({ kind: "limit", start: i, depth, statement });
11427
+ i += 4;
11428
+ continue;
11429
+ }
11430
+ if (/^OFFSET\b/i.test(rest)) {
11431
+ hits.push({ kind: "offset", start: i, depth, statement });
11432
+ i += 5;
11433
+ }
11434
+ }
11435
+ return hits;
11436
+ }
11437
+ function injectLimitBeforeBareOffsets(sql) {
11438
+ const hits = collectLimitOffsetKeywords(sql);
11439
+ if (hits.length === 0) return sql;
11440
+ const injectAt = [];
11441
+ for (const hit of hits) {
11442
+ if (hit.kind !== "offset") continue;
11443
+ let hasLimit = false;
11444
+ for (let i = hits.length - 1; i >= 0; i -= 1) {
11445
+ const prev = hits[i];
11446
+ if (prev.start >= hit.start) continue;
11447
+ if (prev.statement !== hit.statement) continue;
11448
+ if (prev.depth !== hit.depth) continue;
11449
+ if (prev.kind === "limit") {
11450
+ hasLimit = true;
11451
+ break;
11452
+ }
11453
+ if (prev.kind === "offset") {
11454
+ break;
11455
+ }
11456
+ }
11457
+ if (!hasLimit) {
11458
+ injectAt.push(hit.start);
11459
+ }
11460
+ }
11461
+ if (injectAt.length === 0) return sql;
11462
+ let out = sql;
11463
+ for (let i = injectAt.length - 1; i >= 0; i -= 1) {
11464
+ const at = injectAt[i];
11465
+ out = `${out.slice(0, at)}LIMIT -1 ${out.slice(at)}`;
11466
+ }
11467
+ return out;
11468
+ }
11469
+ function rewritePostgresSqlForSqlite(sql) {
11470
+ const castPattern = new RegExp(`::(?:${PG_CAST_TYPES})\\b`, "gi");
11471
+ const withoutCastsAndIlike = mapSqlOutsideLiterals(sql, (chunk) => {
11472
+ let rewritten = chunk.replace(castPattern, "");
11473
+ rewritten = rewritten.replace(/\bILIKE\b/gi, "LIKE");
11474
+ return rewritten;
11475
+ });
11476
+ return injectLimitBeforeBareOffsets(withoutCastsAndIlike);
11477
+ }
11478
+
11479
+ // src/cloudflare/d1/transport.ts
11480
+ function hasPaginationBounds2(payload) {
11481
+ return payload.limit !== void 0 || payload.offset !== void 0 || payload.page_size !== void 0 || payload.current_page !== void 0;
11482
+ }
11483
+ function normalizeSqliteCollation(name) {
11484
+ const raw = String(name ?? "").trim().replace(/^["'`[]|["'`\]]$/g, "");
11485
+ if (!raw) return "BINARY";
11486
+ return raw.toUpperCase();
11487
+ }
11488
+ function findCreateTableColumnListOpen(createSql) {
11489
+ const m = /\bCREATE\s+(?:(?:TEMP|TEMPORARY|VIRTUAL)\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?/i.exec(
11490
+ createSql
11491
+ );
11492
+ if (!m) return -1;
11493
+ let i = m.index + m[0].length;
11494
+ let inSingle = false;
11495
+ let inDouble = false;
11496
+ let inBacktick = false;
11497
+ let inBracket = false;
11498
+ while (i < createSql.length) {
11499
+ const ch = createSql[i];
11500
+ if (inSingle) {
11501
+ if (ch === "'" && createSql[i + 1] === "'") {
11502
+ i += 2;
11503
+ continue;
11504
+ }
11505
+ if (ch === "'") inSingle = false;
11506
+ i++;
11507
+ continue;
11508
+ }
11509
+ if (inDouble) {
11510
+ if (ch === '"') inDouble = false;
11511
+ i++;
11512
+ continue;
11513
+ }
11514
+ if (inBacktick) {
11515
+ if (ch === "`") inBacktick = false;
11516
+ i++;
11517
+ continue;
11518
+ }
11519
+ if (inBracket) {
11520
+ if (ch === "]") inBracket = false;
11521
+ i++;
11522
+ continue;
11523
+ }
11524
+ if (ch === "'") {
11525
+ inSingle = true;
11526
+ i++;
11527
+ continue;
11528
+ }
11529
+ if (ch === '"') {
11530
+ inDouble = true;
11531
+ i++;
11532
+ continue;
11533
+ }
11534
+ if (ch === "`") {
11535
+ inBacktick = true;
11536
+ i++;
11537
+ continue;
11538
+ }
11539
+ if (ch === "[") {
11540
+ inBracket = true;
11541
+ i++;
11542
+ continue;
11543
+ }
11544
+ if (ch === "(") return i;
11545
+ i++;
11546
+ }
11547
+ return -1;
11548
+ }
11549
+ function parseColumnCollationFromCreateSql(createSql, columnName) {
11550
+ if (!createSql || !columnName) return null;
11551
+ const listOpen = findCreateTableColumnListOpen(createSql);
11552
+ if (listOpen < 0) return null;
11553
+ const listStart = listOpen + 1;
11554
+ const escaped = columnName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11555
+ const nameRe = new RegExp(
11556
+ `(?:^|[^\\w])(?:"${escaped}"|\`${escaped}\`|\\[${escaped}\\]|${escaped})\\s+`,
11557
+ "i"
11558
+ );
11559
+ const listSlice = createSql.slice(listStart);
11560
+ let nameMatchAbs = -1;
11561
+ let nameMatchLen = 0;
11562
+ {
11563
+ let i2 = 0;
11564
+ let depth2 = 1;
11565
+ let inSingle2 = false;
11566
+ let inDouble2 = false;
11567
+ let inBacktick2 = false;
11568
+ let inBracket2 = false;
11569
+ let segmentStart = 0;
11570
+ const trySegment = (from, to) => {
11571
+ if (nameMatchAbs >= 0) return;
11572
+ const segment = listSlice.slice(from, to);
11573
+ const m = nameRe.exec(segment);
11574
+ if (!m) return;
11575
+ const leading = segment.slice(0, m.index).trim();
11576
+ if (leading.length > 0) return;
11577
+ nameMatchAbs = listStart + from + m.index;
11578
+ nameMatchLen = m[0].length;
11579
+ };
11580
+ while (i2 < listSlice.length && depth2 > 0) {
11581
+ const ch = listSlice[i2];
11582
+ if (inSingle2) {
11583
+ if (ch === "'" && listSlice[i2 + 1] === "'") {
11584
+ i2 += 2;
11585
+ continue;
11586
+ }
11587
+ if (ch === "'") inSingle2 = false;
11588
+ i2++;
11589
+ continue;
11590
+ }
11591
+ if (inDouble2) {
11592
+ if (ch === '"') inDouble2 = false;
11593
+ i2++;
11594
+ continue;
11595
+ }
11596
+ if (inBacktick2) {
11597
+ if (ch === "`") inBacktick2 = false;
11598
+ i2++;
11599
+ continue;
11600
+ }
11601
+ if (inBracket2) {
11602
+ if (ch === "]") inBracket2 = false;
11603
+ i2++;
11604
+ continue;
11605
+ }
11606
+ if (ch === "'") {
11607
+ inSingle2 = true;
11608
+ i2++;
11609
+ continue;
11610
+ }
11611
+ if (ch === '"') {
11612
+ inDouble2 = true;
11613
+ i2++;
11614
+ continue;
11615
+ }
11616
+ if (ch === "`") {
11617
+ inBacktick2 = true;
11618
+ i2++;
11619
+ continue;
11620
+ }
11621
+ if (ch === "[") {
11622
+ inBracket2 = true;
11623
+ i2++;
11624
+ continue;
11625
+ }
11626
+ if (ch === "(") {
11627
+ depth2++;
11628
+ i2++;
11629
+ continue;
11630
+ }
11631
+ if (ch === ")") {
11632
+ depth2--;
11633
+ if (depth2 === 0) {
11634
+ trySegment(segmentStart, i2);
11635
+ break;
11636
+ }
11637
+ i2++;
11638
+ continue;
11639
+ }
11640
+ if (ch === "," && depth2 === 1) {
11641
+ trySegment(segmentStart, i2);
11642
+ segmentStart = i2 + 1;
11643
+ i2++;
11644
+ continue;
11645
+ }
11646
+ i2++;
11647
+ }
11648
+ }
11649
+ if (nameMatchAbs < 0 || nameMatchLen <= 0) return null;
11650
+ const start = nameMatchAbs + nameMatchLen;
11651
+ let i = start;
11652
+ let depth = 0;
11653
+ let inSingle = false;
11654
+ let inDouble = false;
11655
+ let inBacktick = false;
11656
+ let inBracket = false;
11657
+ while (i < createSql.length) {
11658
+ const ch = createSql[i];
11659
+ if (inSingle) {
11660
+ if (ch === "'" && createSql[i + 1] === "'") {
11661
+ i += 2;
11662
+ continue;
11663
+ }
11664
+ if (ch === "'") inSingle = false;
11665
+ i++;
11666
+ continue;
11667
+ }
11668
+ if (inDouble) {
11669
+ if (ch === '"') inDouble = false;
11670
+ i++;
11671
+ continue;
11672
+ }
11673
+ if (inBacktick) {
11674
+ if (ch === "`") inBacktick = false;
11675
+ i++;
11676
+ continue;
11677
+ }
11678
+ if (inBracket) {
11679
+ if (ch === "]") inBracket = false;
11680
+ i++;
11681
+ continue;
11682
+ }
11683
+ if (ch === "'") {
11684
+ inSingle = true;
11685
+ i++;
11686
+ continue;
11687
+ }
11688
+ if (ch === '"') {
11689
+ inDouble = true;
11690
+ i++;
11691
+ continue;
11692
+ }
11693
+ if (ch === "`") {
11694
+ inBacktick = true;
11695
+ i++;
11696
+ continue;
11697
+ }
11698
+ if (ch === "[") {
11699
+ inBracket = true;
11700
+ i++;
11701
+ continue;
11702
+ }
11703
+ if (ch === "(") {
11704
+ depth++;
11705
+ i++;
11706
+ continue;
11707
+ }
11708
+ if (ch === ")") {
11709
+ if (depth === 0) {
11710
+ break;
11711
+ }
11712
+ depth--;
11713
+ i++;
11714
+ continue;
11715
+ }
11716
+ if (ch === "," && depth === 0) {
11717
+ break;
11718
+ }
11719
+ i++;
11720
+ }
11721
+ const colDef = createSql.slice(start, i);
11722
+ const collRe = /\bCOLLATE\s+("([^"]+)"|'([^']+)'|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][\w$]*))/i;
11723
+ const match = collRe.exec(colDef);
11724
+ if (!match) return null;
11725
+ return match[2] ?? match[3] ?? match[4] ?? match[5] ?? match[6] ?? match[1] ?? null;
11726
+ }
11727
+ async function indexCollationMatchesColumn(d1, table2, tableSafe, indexSafe, columnName, session) {
11728
+ const xinfo = await executeD1Query(d1, {
11729
+ query: `PRAGMA index_xinfo("${indexSafe}")`,
11730
+ params: [],
11731
+ ...session
11732
+ });
11733
+ if (!xinfo.ok) {
11734
+ return false;
11735
+ }
11736
+ const xRows = xinfo.rows ?? [];
11737
+ const keyRows = xRows.filter((row) => {
11738
+ const isKey = row.key === 1 || row.key === true || Number(row.key) === 1;
11739
+ if (!isKey) return false;
11740
+ return typeof row.name === "string" && row.name === columnName;
11741
+ });
11742
+ if (keyRows.length === 0) {
11743
+ const byName = xRows.find(
11744
+ (row) => typeof row.name === "string" && row.name === columnName
11745
+ );
11746
+ if (!byName) return false;
11747
+ keyRows.push(byName);
11748
+ }
11749
+ const indexColl = normalizeSqliteCollation(keyRows[0]?.coll);
11750
+ const master = await executeD1Query(d1, {
11751
+ query: `SELECT sql AS create_sql FROM sqlite_master WHERE type = 'table' AND name = ?`,
11752
+ params: [table2],
11753
+ ...session
11754
+ });
11755
+ let createSql = "";
11756
+ if (master.ok && Array.isArray(master.rows) && master.rows.length > 0) {
11757
+ createSql = String(
11758
+ master.rows[0]?.create_sql ?? ""
11759
+ );
11760
+ }
11761
+ const columnCollRaw = parseColumnCollationFromCreateSql(createSql, columnName);
11762
+ const columnColl = normalizeSqliteCollation(columnCollRaw);
11763
+ return indexColl === columnColl;
11764
+ }
11765
+ async function resolveD1BoundedIdentityColumn(d1, tableName, session) {
11766
+ const table2 = tableName.trim();
11767
+ if (!table2) {
11768
+ throw new D1SqlCompileError("missing_table", "table_name is required for bounded mutation");
11769
+ }
11770
+ const safe = table2.replace(/"/g, '""');
11771
+ const info = await executeD1Query(d1, {
11772
+ query: `PRAGMA table_info("${safe}")`,
11773
+ params: [],
11774
+ ...session
11775
+ });
11776
+ if (!info.ok) {
11777
+ throw new D1SqlCompileError(
11778
+ "bounded_mutation_no_unique_identity",
11779
+ `Unable to introspect table "${table2}" for bounded mutation identity: ${info.message}`
11780
+ );
11781
+ }
11782
+ const cols = info.rows.filter(
11783
+ (row) => typeof row?.name === "string" && row.name.length > 0
11784
+ );
11785
+ const colByName = new Map(cols.map((col) => [col.name, col]));
11786
+ const isNotNullColumn = (name) => {
11787
+ const col = colByName.get(name);
11788
+ if (!col) return false;
11789
+ return col.notnull === 1 || col.notnull === true || Number(col.notnull) === 1;
11790
+ };
11791
+ const isIntegerPrimaryKeyType = (col) => {
11792
+ if (typeof col.pk !== "number" || col.pk <= 0) return false;
11793
+ const declared = String(col.type ?? "").trim().toUpperCase();
11794
+ return declared === "INTEGER";
11795
+ };
11796
+ const loadIndexList = async () => {
11797
+ const indexList = await executeD1Query(d1, {
11798
+ query: `PRAGMA index_list("${safe}")`,
11799
+ params: [],
11800
+ ...session
11801
+ });
11802
+ if (!indexList.ok) return null;
11803
+ return indexList.rows;
11804
+ };
11805
+ const isDescendingIntegerPrimaryKeyException = async (colName, indexes) => {
11806
+ if (indexes) {
11807
+ const hasPkOrigin = indexes.some(
11808
+ (index) => String(index.origin ?? "").toLowerCase() === "pk"
11809
+ );
11810
+ if (hasPkOrigin) return true;
11811
+ const originReported = indexes.some(
11812
+ (index) => index.origin !== void 0 && index.origin !== null && String(index.origin).length > 0
11813
+ );
11814
+ if (indexes.length === 0 || originReported) {
11815
+ return false;
11816
+ }
11817
+ }
11818
+ const master = await executeD1Query(d1, {
11819
+ query: `SELECT sql AS create_sql FROM sqlite_master WHERE type = 'table' AND name = ?`,
11820
+ params: [table2],
11821
+ ...session
11822
+ });
11823
+ if (!master.ok || !Array.isArray(master.rows) || master.rows.length === 0) {
11824
+ return false;
11825
+ }
11826
+ const createSql = String(
11827
+ master.rows[0]?.create_sql ?? ""
11828
+ );
11829
+ if (!createSql) return false;
11830
+ const escaped = colName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11831
+ const inlineDesc = new RegExp(
11832
+ `(?:^|[^\\w])(?:"${escaped}"|${escaped})\\s+INTEGER\\s+PRIMARY\\s+KEY\\s+DESC\\b`,
11833
+ "i"
11834
+ );
11835
+ const tableDesc = new RegExp(
11836
+ `PRIMARY\\s+KEY\\s*\\(\\s*(?:"${escaped}"|${escaped})\\s+DESC\\b`,
11837
+ "i"
11838
+ );
11839
+ return inlineDesc.test(createSql) || tableDesc.test(createSql);
11840
+ };
11841
+ const pkCols = cols.filter((row) => typeof row.pk === "number" && row.pk > 0).sort((a, b) => (a.pk ?? 0) - (b.pk ?? 0));
11842
+ let indexRows;
11843
+ if (pkCols.length === 1 && pkCols[0]?.name) {
11844
+ if (isIntegerPrimaryKeyType(pkCols[0])) {
11845
+ indexRows = await loadIndexList();
11846
+ const isDescException = await isDescendingIntegerPrimaryKeyException(
11847
+ pkCols[0].name,
11848
+ indexRows
11849
+ );
11850
+ if (!isDescException) {
11851
+ return pkCols[0].name;
11852
+ }
11853
+ } else if (isNotNullColumn(pkCols[0].name)) {
11854
+ indexRows = await loadIndexList();
11855
+ const pkIndex = (indexRows ?? []).find(
11856
+ (index) => String(index.origin ?? "").toLowerCase() === "pk"
11857
+ );
11858
+ if (pkIndex && typeof pkIndex.name === "string" && pkIndex.name) {
11859
+ const indexSafe = pkIndex.name.replace(/"/g, '""');
11860
+ const collMatch = await indexCollationMatchesColumn(
11861
+ d1,
11862
+ table2,
11863
+ safe,
11864
+ indexSafe,
11865
+ pkCols[0].name,
11866
+ session
11867
+ );
11868
+ if (collMatch) {
11869
+ return pkCols[0].name;
11870
+ }
11871
+ }
11872
+ }
11873
+ }
11874
+ if (indexRows === void 0) {
11875
+ indexRows = await loadIndexList();
11876
+ }
11877
+ if (indexRows) {
11878
+ for (const index of indexRows) {
11879
+ const unique = index.unique === 1 || index.unique === true || Number(index.unique) === 1;
11880
+ if (!unique || typeof index.name !== "string" || !index.name) continue;
11881
+ const isPartial = index.partial === 1 || index.partial === true || Number(index.partial) === 1;
11882
+ if (isPartial) {
11883
+ continue;
11884
+ }
11885
+ const indexSafe = index.name.replace(/"/g, '""');
11886
+ const indexInfo = await executeD1Query(d1, {
11887
+ query: `PRAGMA index_info("${indexSafe}")`,
11888
+ params: [],
11889
+ ...session
11890
+ });
11891
+ if (!indexInfo.ok) continue;
11892
+ const rawIndexCols = indexInfo.rows ?? [];
11893
+ const hasExpressionTerm = rawIndexCols.some((row) => {
11894
+ const nameOk = typeof row?.name === "string" && row.name.length > 0;
11895
+ if (!nameOk) return true;
11896
+ if (typeof row.cid === "number" && row.cid < 0) return true;
11897
+ return false;
11898
+ });
11899
+ if (hasExpressionTerm || rawIndexCols.length === 0) {
11900
+ continue;
11901
+ }
11902
+ const indexCols = rawIndexCols.filter(
11903
+ (row) => typeof row?.name === "string" && row.name.length > 0
11904
+ );
11905
+ if (indexCols.length === 1 && indexCols[0]?.name) {
11906
+ const identity = indexCols[0].name;
11907
+ if (!isNotNullColumn(identity)) {
11908
+ continue;
11909
+ }
11910
+ const collMatch = await indexCollationMatchesColumn(
11911
+ d1,
11912
+ table2,
11913
+ safe,
11914
+ indexSafe,
11915
+ identity,
11916
+ session
11917
+ );
11918
+ if (!collMatch) {
11919
+ continue;
11920
+ }
11921
+ return identity;
11922
+ }
11923
+ }
11924
+ }
11925
+ throw new D1SqlCompileError(
11926
+ "bounded_mutation_no_unique_identity",
11927
+ `Bounded update/delete on "${table2}" requires a proven single-column PRIMARY KEY or UNIQUE index`
11928
+ );
11929
+ }
11930
+ async function compileOptionsForBoundedMutation(d1, payload, session) {
11931
+ if (!hasPaginationBounds2(payload) && !payload.sort_by) {
11932
+ return void 0;
11933
+ }
11934
+ if (!hasPaginationBounds2(payload)) {
11935
+ return void 0;
11936
+ }
11937
+ const identityColumn = await resolveD1BoundedIdentityColumn(
11938
+ d1,
11939
+ payload.table_name ?? "",
11940
+ session
11941
+ );
11942
+ return { identityColumn };
11943
+ }
11944
+ function headerValue2(options, name) {
11945
+ const headers = options?.headers;
11946
+ if (!headers) return void 0;
11947
+ const lower = name.toLowerCase();
11948
+ for (const [key, value] of Object.entries(headers)) {
11949
+ if (key.toLowerCase() === lower && value?.trim()) {
11950
+ return value.trim();
11951
+ }
11952
+ }
11953
+ return void 0;
11954
+ }
11955
+ function sessionFromOptions(options, defaults) {
11956
+ return {
11957
+ bookmark: headerValue2(options, "x-athena-d1-bookmark") ?? null,
11958
+ sessionMode: headerValue2(options, "x-athena-d1-session-mode") ?? defaults.defaultSessionMode ?? null
11959
+ };
11960
+ }
11961
+ function resolveStripNulls(payloadStrip, callOptions, defaultValue = true) {
11962
+ if (typeof payloadStrip === "boolean") return payloadStrip;
11963
+ if (typeof callOptions?.stripNulls === "boolean") return callOptions.stripNulls;
11964
+ return defaultValue;
11965
+ }
11966
+ function stripNullPropertiesFromRows(rows) {
11967
+ return rows.map((row) => {
11968
+ if (row == null || typeof row !== "object" || Array.isArray(row)) {
11969
+ return row;
11970
+ }
11971
+ const out = {};
11972
+ for (const [key, value] of Object.entries(row)) {
11973
+ if (value !== null) {
11974
+ out[key] = value;
11975
+ }
11976
+ }
11977
+ return out;
11978
+ });
11979
+ }
11980
+ function maybeStripNullRows(rows, strip) {
11981
+ return strip ? stripNullPropertiesFromRows(rows) : rows;
11982
+ }
11983
+ function successResponse(data, count, raw, bookmark) {
11984
+ const response = {
11985
+ ok: true,
11986
+ status: 200,
11987
+ statusText: "OK",
11988
+ data,
11989
+ count: count ?? null,
11990
+ error: void 0,
11991
+ errorDetails: null,
11992
+ raw
11993
+ };
11994
+ if (bookmark) {
11995
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
11996
+ const rawRecord = raw;
11997
+ rawRecord.bookmark = bookmark;
11998
+ }
11999
+ }
12000
+ return response;
12001
+ }
12002
+ function errorResponse(status, code, message, endpoint, method, hint) {
12003
+ const error = new AthenaGatewayError({
12004
+ code,
12005
+ message,
12006
+ status,
12007
+ endpoint,
12008
+ method,
12009
+ hint
12010
+ });
12011
+ return {
12012
+ ok: false,
12013
+ status,
12014
+ statusText: null,
12015
+ data: null,
12016
+ error: error.message,
12017
+ errorDetails: error.toDetails(),
12018
+ raw: { error: message, code }
12019
+ };
12020
+ }
12021
+ function compileErrorResponse(error, endpoint, method) {
12022
+ if (error instanceof D1SqlCompileError) {
12023
+ return errorResponse(
12024
+ 400,
12025
+ "HTTP_ERROR",
12026
+ error.message,
12027
+ endpoint,
12028
+ method,
12029
+ `D1 SQL compile failed (${error.code})`
12030
+ );
12031
+ }
12032
+ const message = error instanceof Error ? error.message : String(error);
12033
+ return errorResponse(500, "UNKNOWN_ERROR", message, endpoint, method);
12034
+ }
12035
+ function createCloudflareD1GatewayTransport(options) {
12036
+ const { d1 } = options;
12037
+ async function runCompiled(compiled, callOptions, endpoint, method, mapResult, stripNulls = true) {
12038
+ try {
12039
+ const session = sessionFromOptions(callOptions, options);
12040
+ if (compiled.statements && compiled.statements.length > 1) {
12041
+ const batch = await executeD1Batch(d1, {
12042
+ statements: compiled.statements.map((statement) => ({
12043
+ query: statement.sql,
12044
+ params: statement.params
12045
+ })),
12046
+ ...session
12047
+ });
12048
+ if (!batch.ok) {
12049
+ return errorResponse(400, "HTTP_ERROR", batch.message, endpoint, method);
12050
+ }
12051
+ const rows2 = maybeStripNullRows(
12052
+ batch.results.flatMap(
12053
+ (item) => Array.isArray(item.results) ? item.results : []
12054
+ ),
12055
+ stripNulls
12056
+ );
12057
+ const changes = batch.results.reduce((sum2, item) => {
12058
+ const meta = item?.meta;
12059
+ const n = meta && typeof meta === "object" && typeof meta.changes === "number" ? meta.changes : 0;
12060
+ return sum2 + n;
12061
+ }, 0);
12062
+ const count = rows2.length > 0 ? rows2.length : changes;
12063
+ const mapped2 = mapResult?.(rows2, count) ?? {
12064
+ data: rows2,
12065
+ count
12066
+ };
12067
+ return successResponse(mapped2.data, mapped2.count, batch, batch.bookmark);
12068
+ }
12069
+ const result = await executeD1Query(d1, {
12070
+ query: compiled.sql,
12071
+ params: compiled.params,
12072
+ ...session
12073
+ });
12074
+ if (!result.ok) {
12075
+ return errorResponse(400, "HTTP_ERROR", result.message, endpoint, method);
12076
+ }
12077
+ const rows = maybeStripNullRows(result.rows, stripNulls);
12078
+ const mapped = mapResult?.(rows, result.count) ?? {
12079
+ data: rows,
12080
+ count: result.count
12081
+ };
12082
+ return successResponse(mapped.data, mapped.count, result, result.bookmark);
12083
+ } catch (error) {
12084
+ const message = error instanceof Error ? error.message : String(error);
12085
+ return errorResponse(500, "UNKNOWN_ERROR", message, endpoint, method);
12086
+ }
12087
+ }
12088
+ return {
12089
+ baseUrl: CLOUDFLARE_EDGE_BASE_URL,
12090
+ buildHeaders(callOptions) {
12091
+ return { ...callOptions?.headers ?? {} };
12092
+ },
12093
+ async resolveCallOptions(callOptions) {
12094
+ return callOptions;
12095
+ },
12096
+ async verifyConnection(connectionOptions) {
12097
+ const baseUrl = CLOUDFLARE_EDGE_BASE_URL;
12098
+ try {
12099
+ const result = await executeD1Query(d1, { query: "SELECT 1 AS ok" });
12100
+ if (!result.ok) {
12101
+ return {
12102
+ ok: false,
12103
+ reachable: false,
12104
+ status: 500,
12105
+ statusText: null,
12106
+ baseUrl,
12107
+ url: `${baseUrl}/d1`,
12108
+ error: result.message,
12109
+ errorDetails: null,
12110
+ raw: result
12111
+ };
12112
+ }
12113
+ return {
12114
+ ok: true,
12115
+ reachable: true,
12116
+ status: 200,
12117
+ statusText: "OK",
12118
+ baseUrl,
12119
+ url: `${baseUrl}/d1`,
12120
+ error: void 0,
12121
+ errorDetails: null,
12122
+ raw: result
12123
+ };
12124
+ } catch (error) {
12125
+ const message = error instanceof Error ? error.message : String(error);
12126
+ return {
12127
+ ok: false,
12128
+ reachable: false,
12129
+ status: 0,
12130
+ statusText: null,
12131
+ baseUrl,
12132
+ url: `${baseUrl}/d1`,
12133
+ error: message,
12134
+ errorDetails: null,
12135
+ raw: null
12136
+ };
12137
+ }
12138
+ },
12139
+ async fetchGateway(payload, callOptions) {
12140
+ try {
12141
+ if (payload && typeof payload === "object" && "operation" in payload) {
12142
+ return errorResponse(
12143
+ 400,
12144
+ "HTTP_ERROR",
12145
+ "Direct AST operation payloads are unsupported on D1 edge-local",
12146
+ "/gateway/fetch",
12147
+ "POST"
12148
+ );
12149
+ }
12150
+ const compiled = compileD1Fetch(payload);
12151
+ const stripNulls = resolveStripNulls(payload.strip_nulls, callOptions, true);
12152
+ if (payload.head === true) {
12153
+ return runCompiled(
12154
+ compiled,
12155
+ callOptions,
12156
+ "/gateway/fetch",
12157
+ "POST",
12158
+ (rows) => ({ data: [], count: extractAthenaCount(rows) }),
12159
+ // COUNT rows are meta, not user-facing object rows
12160
+ false
12161
+ );
12162
+ }
12163
+ const wantsTotalCount = payload.count === "exact" || payload.count === "planned" || payload.count === "estimated";
12164
+ if (wantsTotalCount) {
12165
+ const session = sessionFromOptions(callOptions, options);
12166
+ const countCompiled = compileD1Count(payload);
12167
+ const batch = await executeD1Batch(d1, {
12168
+ statements: [
12169
+ {
12170
+ query: compiled.sql,
12171
+ params: compiled.params
12172
+ },
12173
+ {
12174
+ query: countCompiled.sql,
12175
+ params: countCompiled.params
12176
+ }
12177
+ ],
12178
+ ...session
12179
+ });
12180
+ if (!batch.ok) {
12181
+ return errorResponse(400, "HTTP_ERROR", batch.message, "/gateway/fetch", "POST");
12182
+ }
12183
+ const dataItem = batch.results[0];
12184
+ const countItem = batch.results[1];
12185
+ if (!dataItem || dataItem.success === false) {
12186
+ const message = dataItem && typeof dataItem.error === "string" && dataItem.error.trim() ? dataItem.error : "D1 page query failed";
12187
+ return errorResponse(400, "HTTP_ERROR", message, "/gateway/fetch", "POST");
12188
+ }
12189
+ if (!countItem || countItem.success === false) {
12190
+ const message = countItem && typeof countItem.error === "string" && countItem.error.trim() ? countItem.error : "D1 count query failed";
12191
+ return errorResponse(400, "HTTP_ERROR", message, "/gateway/fetch", "POST");
12192
+ }
12193
+ const dataRows = Array.isArray(dataItem.results) ? dataItem.results : [];
12194
+ const countRows = Array.isArray(countItem.results) ? countItem.results : [];
12195
+ const total = extractAthenaCount(countRows);
12196
+ const rows = maybeStripNullRows(dataRows, stripNulls);
12197
+ return successResponse(
12198
+ rows,
12199
+ total,
12200
+ { data: dataItem, count: countItem, batch },
12201
+ batch.bookmark
12202
+ );
12203
+ }
12204
+ return runCompiled(compiled, callOptions, "/gateway/fetch", "POST", void 0, stripNulls);
12205
+ } catch (error) {
12206
+ return compileErrorResponse(error, "/gateway/fetch", "POST");
12207
+ }
12208
+ },
12209
+ async insertGateway(payload, callOptions) {
12210
+ try {
12211
+ const compiled = compileD1Insert(payload);
12212
+ const stripNulls = resolveStripNulls(void 0, callOptions, true);
12213
+ return runCompiled(compiled, callOptions, "/gateway/insert", "PUT", void 0, stripNulls);
12214
+ } catch (error) {
12215
+ return compileErrorResponse(error, "/gateway/insert", "PUT");
12216
+ }
12217
+ },
12218
+ async updateGateway(payload, callOptions) {
12219
+ try {
12220
+ const session = sessionFromOptions(callOptions, options);
12221
+ const compileOptions = await compileOptionsForBoundedMutation(d1, payload, session);
12222
+ const compiled = compileD1Update(payload, compileOptions);
12223
+ const stripNulls = resolveStripNulls(payload.strip_nulls, callOptions, true);
12224
+ return runCompiled(compiled, callOptions, "/gateway/update", "POST", void 0, stripNulls);
12225
+ } catch (error) {
12226
+ return compileErrorResponse(error, "/gateway/update", "POST");
12227
+ }
12228
+ },
12229
+ async deleteGateway(payload, callOptions) {
12230
+ try {
12231
+ const session = sessionFromOptions(callOptions, options);
12232
+ const compileOptions = await compileOptionsForBoundedMutation(d1, payload, session);
12233
+ const compiled = compileD1Delete(payload, compileOptions);
12234
+ const stripNulls = resolveStripNulls(void 0, callOptions, true);
12235
+ return runCompiled(compiled, callOptions, "/gateway/delete", "DELETE", void 0, stripNulls);
12236
+ } catch (error) {
12237
+ return compileErrorResponse(error, "/gateway/delete", "DELETE");
12238
+ }
12239
+ },
12240
+ async rpcGateway(payload, callOptions) {
12241
+ return errorResponse(
12242
+ 400,
12243
+ "HTTP_ERROR",
12244
+ "RPC is unsupported on D1 edge-local mode",
12245
+ "/gateway/rpc",
12246
+ "POST",
12247
+ "Use flat CRUD or raw query SQL instead"
12248
+ );
12249
+ },
12250
+ async queryGateway(payload, callOptions) {
12251
+ try {
12252
+ const params = payload.params ?? callOptions?.params;
12253
+ const session = sessionFromOptions(callOptions, options);
12254
+ const query = rewritePostgresSqlForSqlite(payload.query);
12255
+ const result = await executeD1Query(d1, {
12256
+ query,
12257
+ params: Array.isArray(params) ? params : [],
12258
+ ...session
12259
+ });
12260
+ if (!result.ok) {
12261
+ return errorResponse(400, "HTTP_ERROR", result.message, "/gateway/query", "POST");
12262
+ }
12263
+ const stripNulls = resolveStripNulls(void 0, callOptions, true);
12264
+ const rows = maybeStripNullRows(result.rows, stripNulls);
12265
+ return successResponse(
12266
+ rows,
12267
+ result.count,
12268
+ { ...result, query },
12269
+ result.bookmark
12270
+ );
12271
+ } catch (error) {
12272
+ const message = error instanceof Error ? error.message : String(error);
12273
+ return errorResponse(500, "UNKNOWN_ERROR", message, "/gateway/query", "POST");
12274
+ }
12275
+ }
12276
+ };
12277
+ }
12278
+
12279
+ // src/config/errors.ts
12280
+ var AthenaConfigurationError = class extends Error {
12281
+ code;
12282
+ service;
12283
+ constructor(code, message, service) {
12284
+ super(message);
12285
+ this.name = "AthenaConfigurationError";
12286
+ this.code = code;
12287
+ this.service = service;
12288
+ }
12289
+ };
12290
+
12291
+ // src/cloudflare/execution-mode.ts
12292
+ var ATHENA_EXECUTION_MODE_ENV_KEY = "ATHENA_EXECUTION_MODE";
12293
+ var ATHENA_EXECUTION_PREFER_ENV_KEY = "ATHENA_EXECUTION_PREFER";
12294
+ var MODE_ALIASES = {
12295
+ gateway: "gateway",
12296
+ server: "gateway",
12297
+ remote: "gateway",
12298
+ http: "gateway",
12299
+ edge: "edge",
12300
+ cloudflare: "edge",
12301
+ "cloudflare-edge": "edge",
12302
+ d1: "edge",
12303
+ local: "edge",
12304
+ auto: "auto"
12305
+ };
12306
+ function normalizeOptional(value) {
12307
+ const trimmed = value?.trim();
12308
+ return trimmed || void 0;
12309
+ }
12310
+ function normalizeModeString(value) {
12311
+ if (value == null) return void 0;
12312
+ const key = value.trim().toLowerCase();
12313
+ if (!key) return void 0;
12314
+ const mapped = MODE_ALIASES[key];
12315
+ if (!mapped) {
12316
+ throw new AthenaConfigurationError(
12317
+ "ATHENA_NO_SERVICE_CONFIGURED",
12318
+ `Unknown Athena execution mode "${value}". Use gateway | edge | auto (aliases: server, remote, cloudflare, d1).`,
12319
+ "db"
12320
+ );
12321
+ }
12322
+ return mapped;
12323
+ }
12324
+ function isD1Binding(value) {
12325
+ return Boolean(
12326
+ value && typeof value === "object" && typeof value.prepare === "function"
12327
+ );
12328
+ }
12329
+ var GATEWAY_URL_ENV_KEYS = [
12330
+ "ATHENA_URL",
12331
+ "NEXT_PUBLIC_ATHENA_URL",
12332
+ "ATHENA_DB_URL",
12333
+ "ATHENA_GATEWAY_URL",
12334
+ "NEXT_PUBLIC_ATHENA_DB_API_URL"
12335
+ ];
12336
+ function resolveGatewayUrl(url, env) {
12337
+ if (normalizeOptional(url)) {
12338
+ return normalizeOptional(url);
12339
+ }
12340
+ for (const key of GATEWAY_URL_ENV_KEYS) {
12341
+ const value = normalizeOptional(env[key]);
12342
+ if (value) return value;
12343
+ }
12344
+ return void 0;
12345
+ }
12346
+ function resolvePrefer(prefer, env) {
12347
+ const raw = normalizeOptional(typeof prefer === "string" ? prefer : prefer ?? void 0) ?? normalizeOptional(env[ATHENA_EXECUTION_PREFER_ENV_KEY]) ?? "edge";
12348
+ const key = raw.toLowerCase();
12349
+ if (key === "gateway" || key === "server" || key === "remote" || key === "http") {
12350
+ return "gateway";
12351
+ }
12352
+ if (key === "edge" || key === "d1" || key === "cloudflare" || key === "local") {
12353
+ return "edge";
12354
+ }
12355
+ throw new AthenaConfigurationError(
12356
+ "ATHENA_NO_SERVICE_CONFIGURED",
12357
+ `Unknown Athena execution prefer "${raw}". Use edge | gateway.`,
12358
+ "db"
12359
+ );
12360
+ }
12361
+ function resolveAthenaExecutionMode(input = {}) {
12362
+ const env = input.env ?? {};
12363
+ const fromEnv = normalizeModeString(env[ATHENA_EXECUTION_MODE_ENV_KEY]);
12364
+ const requested = normalizeModeString(input.mode) ?? fromEnv ?? "auto";
12365
+ const url = resolveGatewayUrl(input.url, env);
12366
+ const hasD1 = isD1Binding(input.d1);
12367
+ const hasGateway = Boolean(url);
12368
+ if (requested === "gateway") {
12369
+ if (!hasGateway) {
12370
+ throw new AthenaConfigurationError(
12371
+ "ATHENA_NO_SERVICE_CONFIGURED",
12372
+ 'Athena execution mode is "gateway" but no url / ATHENA_URL / ATHENA_DB_URL / ATHENA_GATEWAY_URL was provided.',
12373
+ "db"
12374
+ );
12375
+ }
12376
+ return "gateway";
12377
+ }
12378
+ if (requested === "edge") {
12379
+ if (!hasD1) {
12380
+ throw new AthenaConfigurationError(
12381
+ "ATHENA_NO_SERVICE_CONFIGURED",
12382
+ 'Athena execution mode is "edge" but no D1 binding was provided (db.d1 / config.d1 / env.DB).',
12383
+ "db"
12384
+ );
12385
+ }
12386
+ return "edge";
12387
+ }
12388
+ if (hasD1 && hasGateway) {
12389
+ return resolvePrefer(input.prefer, env);
12390
+ }
12391
+ if (hasD1) return "edge";
12392
+ if (hasGateway) return "gateway";
12393
+ throw new AthenaConfigurationError(
12394
+ "ATHENA_NO_SERVICE_CONFIGURED",
12395
+ 'Cannot resolve Athena execution mode: provide mode "gateway" with url/key, mode "edge" with d1, or mode "auto" with either a D1 binding or a gateway URL (ATHENA_URL / ATHENA_DB_URL / ATHENA_GATEWAY_URL).',
12396
+ "db"
12397
+ );
12398
+ }
12399
+
12400
+ // src/cloudflare/r2/storage.ts
12401
+ function normalizePrefix(prefix) {
12402
+ if (!prefix?.trim()) return "";
12403
+ const normalized = prefix.replace(/^\/+/, "").replace(/\/?$/, "/");
12404
+ if (normalized.includes("\0")) {
12405
+ throw new Error("storage prefix must not contain null bytes");
12406
+ }
12407
+ if (normalized.split("/").some((segment) => segment === "..")) {
12408
+ throw new Error('storage prefix must not contain ".." path segments');
12409
+ }
12410
+ return normalized;
12411
+ }
12412
+ function assertSafeObjectKey(key) {
12413
+ if (typeof key !== "string" || !key.trim()) {
12414
+ throw new Error("Object key is required");
12415
+ }
12416
+ if (key.includes("\0")) {
12417
+ throw new Error("Object key must not contain null bytes");
12418
+ }
12419
+ const cleaned = key.replace(/^\/+/, "");
12420
+ if (!cleaned) {
12421
+ throw new Error("Object key is required");
12422
+ }
12423
+ const segments = cleaned.split("/");
12424
+ if (segments.some((segment) => segment === "..")) {
12425
+ throw new Error('Object key must not contain ".." path segments');
12426
+ }
12427
+ return cleaned;
12428
+ }
12429
+ function joinKey(prefix, key) {
12430
+ return `${prefix}${assertSafeObjectKey(key)}`;
12431
+ }
12432
+ function toLogicalKey(prefix, physicalKey) {
12433
+ if (!prefix) return physicalKey;
12434
+ if (physicalKey.startsWith(prefix)) {
12435
+ return physicalKey.slice(prefix.length);
12436
+ }
12437
+ return physicalKey;
12438
+ }
12439
+ function toPhysicalKey(prefix, key) {
12440
+ return joinKey(prefix, key);
12441
+ }
12442
+ function unsupported(method) {
12443
+ throw new Error(
12444
+ `storage.${method} is not available in Cloudflare edge-local R2 object mode. Only putObject / getObject / deleteObject / listObjects are supported (L3a).`
12445
+ );
12446
+ }
12447
+ function createCloudflareR2StorageModule(options) {
12448
+ const prefix = normalizePrefix(options.prefix);
12449
+ const { r2 } = options;
12450
+ const putObject = async (input) => {
12451
+ const logical = assertSafeObjectKey(input.key);
12452
+ const physical = toPhysicalKey(prefix, logical);
12453
+ await r2.put(physical, input.body, {
12454
+ httpMetadata: input.contentType ? { contentType: input.contentType } : void 0,
12455
+ customMetadata: input.metadata
12456
+ });
12457
+ return { key: logical };
12458
+ };
12459
+ const getObject = async (input) => {
12460
+ const logical = assertSafeObjectKey(input.key);
12461
+ const physical = toPhysicalKey(prefix, logical);
12462
+ const object = await r2.get(physical);
12463
+ if (!object) return null;
12464
+ return {
12465
+ key: toLogicalKey(prefix, object.key),
12466
+ size: object.size,
12467
+ contentType: object.httpMetadata?.contentType,
12468
+ body: object
12469
+ };
12470
+ };
12471
+ const deleteObject = async (input) => {
12472
+ const logicalKeys = (Array.isArray(input.key) ? input.key : [input.key]).map(
12473
+ (key) => assertSafeObjectKey(key)
12474
+ );
12475
+ const physicalKeys = logicalKeys.map((key) => toPhysicalKey(prefix, key));
12476
+ await r2.delete(physicalKeys.length === 1 ? physicalKeys[0] : physicalKeys);
12477
+ return { deleted: logicalKeys };
12478
+ };
12479
+ const listObjects = async (input) => {
12480
+ const relative = input?.prefix?.trim() ? assertSafeObjectKey(input.prefix) : "";
12481
+ const listPrefix = `${prefix}${relative}`;
12482
+ const listed = await r2.list({
12483
+ prefix: listPrefix || void 0,
12484
+ limit: input?.limit,
12485
+ cursor: input?.cursor
12486
+ });
12487
+ return {
12488
+ objects: listed.objects.map((object) => ({
12489
+ key: toLogicalKey(prefix, object.key),
12490
+ size: object.size,
12491
+ etag: object.etag,
12492
+ uploaded: object.uploaded
12493
+ })),
12494
+ truncated: listed.truncated,
12495
+ cursor: listed.cursor
12496
+ };
12497
+ };
12498
+ const base = {
12499
+ putObject,
12500
+ getObject,
12501
+ deleteObject,
12502
+ listObjects
12503
+ };
12504
+ return new Proxy(base, {
12505
+ get(target, property, receiver) {
12506
+ if (property in target) {
12507
+ return Reflect.get(target, property, receiver);
12508
+ }
12509
+ if (typeof property === "string") {
12510
+ return (...args) => {
12511
+ return unsupported(property);
12512
+ };
12513
+ }
12514
+ return void 0;
12515
+ }
12516
+ });
12517
+ }
12518
+
12519
+ // src/billing/module.ts
12520
+ var SDK_NAME5 = "xylex-group/athena-billing";
12521
+ var SDK_HEADER_VALUE4 = buildSdkHeaderValue(SDK_NAME5);
12522
+ var AthenaBillingError = class extends Error {
12523
+ status;
12524
+ endpoint;
12525
+ method;
12526
+ body;
12527
+ constructor(input) {
12528
+ super(input.message);
12529
+ this.name = "AthenaBillingError";
12530
+ this.status = input.status;
12531
+ this.endpoint = input.endpoint;
12532
+ this.method = input.method;
12533
+ this.body = input.body;
12534
+ }
12535
+ };
12536
+ var billingSdkManifest = {
12537
+ namespace: "billing",
12538
+ envelopeKind: "athena",
12539
+ methods: [
12540
+ { name: "getCapabilities", method: "GET", path: "/billing/v1/capabilities" },
12541
+ { name: "createCheckout", method: "POST", path: "/billing/v1/checkouts" },
12542
+ { name: "listProducts", method: "GET", path: "/billing/v1/products" },
12543
+ { name: "listPrices", method: "GET", path: "/billing/v1/prices" },
12544
+ { name: "listCustomers", method: "GET", path: "/billing/v1/customers" },
12545
+ { name: "createCustomer", method: "POST", path: "/billing/v1/customers" },
12546
+ { name: "getCustomer", method: "GET", path: "/billing/v1/customers/{id}" },
12547
+ { name: "updateCustomer", method: "PATCH", path: "/billing/v1/customers/{id}" },
12548
+ { name: "deleteCustomer", method: "DELETE", path: "/billing/v1/customers/{id}" },
12549
+ { name: "listPayments", method: "GET", path: "/billing/v1/payments" },
12550
+ { name: "createPayment", method: "POST", path: "/billing/v1/payments" },
12551
+ { name: "getPayment", method: "GET", path: "/billing/v1/payments/{id}" },
12552
+ { name: "cancelPayment", method: "POST", path: "/billing/v1/payments/{id}/cancel" },
12553
+ { name: "listPaymentLinks", method: "GET", path: "/billing/v1/payment-links" },
12554
+ { name: "createPaymentLink", method: "POST", path: "/billing/v1/payment-links" },
12555
+ { name: "getPaymentLink", method: "GET", path: "/billing/v1/payment-links/{id}" },
12556
+ { name: "updatePaymentLink", method: "PATCH", path: "/billing/v1/payment-links/{id}" },
12557
+ { name: "deletePaymentLink", method: "DELETE", path: "/billing/v1/payment-links/{id}" },
12558
+ { name: "listRefunds", method: "GET", path: "/billing/v1/refunds" },
12559
+ { name: "createRefund", method: "POST", path: "/billing/v1/refunds" },
12560
+ { name: "getRefund", method: "GET", path: "/billing/v1/refunds/{id}" },
12561
+ { name: "cancelRefund", method: "POST", path: "/billing/v1/refunds/{id}/cancel" },
12562
+ { name: "listSubscriptions", method: "GET", path: "/billing/v1/subscriptions" },
12563
+ { name: "createSubscription", method: "POST", path: "/billing/v1/subscriptions" },
12564
+ { name: "getSubscription", method: "GET", path: "/billing/v1/subscriptions/{id}" },
12565
+ { name: "updateSubscription", method: "PATCH", path: "/billing/v1/subscriptions/{id}" },
12566
+ { name: "cancelSubscription", method: "POST", path: "/billing/v1/subscriptions/{id}/cancel" },
12567
+ { name: "listInvoices", method: "GET", path: "/billing/v1/invoices" },
12568
+ { name: "getInvoice", method: "GET", path: "/billing/v1/invoices/{id}" },
12569
+ { name: "listWebhooks", method: "GET", path: "/billing/v1/webhooks" },
12570
+ { name: "createWebhook", method: "POST", path: "/billing/v1/webhooks" },
12571
+ { name: "getWebhook", method: "GET", path: "/billing/v1/webhooks/{id}" },
12572
+ { name: "updateWebhook", method: "PATCH", path: "/billing/v1/webhooks/{id}" },
12573
+ { name: "deleteWebhook", method: "DELETE", path: "/billing/v1/webhooks/{id}" },
12574
+ { name: "testWebhook", method: "POST", path: "/billing/v1/webhooks/{id}/test" },
12575
+ {
12576
+ name: "listConnections",
12577
+ method: "GET",
12578
+ path: "/admin/billing/clients/{client_name}/connections"
12579
+ },
12580
+ {
12581
+ name: "createConnection",
12582
+ method: "POST",
12583
+ path: "/admin/billing/clients/{client_name}/connections"
12584
+ },
12585
+ {
12586
+ name: "getConnection",
12587
+ method: "GET",
12588
+ path: "/admin/billing/clients/{client_name}/connections/{connection_id}"
12589
+ },
12590
+ {
12591
+ name: "updateConnection",
12592
+ method: "PATCH",
12593
+ path: "/admin/billing/clients/{client_name}/connections/{connection_id}"
12594
+ },
12595
+ {
12596
+ name: "deleteConnection",
12597
+ method: "DELETE",
12598
+ path: "/admin/billing/clients/{client_name}/connections/{connection_id}"
12599
+ },
12600
+ {
12601
+ name: "reconcileDocument",
12602
+ method: "POST",
12603
+ path: "/admin/billing/clients/{client_name}/connections/{connection_id}/reconcile"
12604
+ },
12605
+ {
12606
+ name: "listWebhookEvents",
12607
+ method: "GET",
12608
+ path: "/admin/billing/clients/{client_name}/webhook-events"
12609
+ },
12610
+ {
12611
+ name: "provisionWebhookSinks",
12612
+ method: "POST",
12613
+ path: "/admin/billing/clients/{client_name}/webhook-sinks/provision"
12614
+ },
12615
+ { name: "listGrants", method: "GET", path: "/admin/billing/grants" },
12616
+ { name: "listProviders", method: "GET", path: "/admin/billing/providers" },
12617
+ {
12618
+ name: "listSinkHelpers",
12619
+ method: "GET",
12620
+ path: "/admin/webhook-sinks/helpers/billing"
12621
+ },
12622
+ {
12623
+ name: "ingestProviderWebhook",
12624
+ method: "POST",
12625
+ path: "/billing/providers/{provider}/clients/{client_name}/connections/{connection_id}/webhook"
12626
+ },
12627
+ { name: "getDebugBilling", method: "GET", path: "/debug/billing" }
12628
+ ]
12629
+ };
12630
+ function withPathParam2(path, name, value) {
12631
+ return path.replace(`{${name}}`, encodeURIComponent(value));
12632
+ }
12633
+ function appendQuery3(path, query) {
12634
+ if (!query) return path;
12635
+ const params = new URLSearchParams();
12636
+ for (const [key, value] of Object.entries(query)) {
12637
+ if (value === void 0 || value === null) continue;
12638
+ params.set(key, String(value));
12639
+ }
12640
+ const serialized = params.toString();
12641
+ return serialized ? `${path}?${serialized}` : path;
12642
+ }
12643
+ function connectionQuery(input) {
12644
+ const query = {
12645
+ connectionId: input.connectionId
12646
+ };
12647
+ if (input.clientName) query.clientName = input.clientName;
12648
+ if ("cursor" in input && input.cursor) query.cursor = input.cursor;
12649
+ if ("source" in input && input.source) query.source = input.source;
12650
+ if ("limit" in input && input.limit !== void 0) query.limit = String(input.limit);
12651
+ if ("offset" in input && input.offset !== void 0) query.offset = String(input.offset);
12652
+ return query;
12653
+ }
12654
+ function parseEnvelopeData(body) {
12655
+ if (body && typeof body === "object" && "data" in body) {
12656
+ return body.data;
12657
+ }
12658
+ return body;
12659
+ }
12660
+ function createBillingModule(config) {
12661
+ const baseUrl = normalizeAthenaGatewayBaseUrl(config.baseUrl, {
12662
+ label: "Athena billing base URL"
12663
+ });
12664
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
12665
+ async function call(method, path, body, options, responseType = "json") {
12666
+ const headers = buildAthenaRequestHeaders({
12667
+ profile: "gateway",
12668
+ sdkHeaderValue: SDK_HEADER_VALUE4,
12669
+ apiKey: options?.apiKey ?? config.apiKey,
12670
+ client: config.client,
12671
+ configHeaders: {
12672
+ ...config.headers ?? {}
12673
+ },
12674
+ callHeaders: options?.headers,
12675
+ contentType: "application/json"
12676
+ });
12677
+ let requestBody;
12678
+ if (body !== void 0 && body !== null) {
12679
+ if (typeof body === "string" || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof FormData || body instanceof URLSearchParams) {
12680
+ requestBody = body;
12681
+ } else {
12682
+ requestBody = JSON.stringify(body);
12683
+ if (!hasHeaderIgnoreCase(headers, "Content-Type")) {
12684
+ headers["Content-Type"] = "application/json";
12685
+ }
12686
+ }
12687
+ }
12688
+ const targetUrl = `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
12689
+ const response = await fetchImpl(targetUrl, {
12690
+ method,
12691
+ headers,
12692
+ body: requestBody,
12693
+ signal: options?.signal
12694
+ });
12695
+ if (responseType === "text") {
12696
+ const text = await response.text();
12697
+ if (!response.ok) {
12698
+ throw new AthenaBillingError({
12699
+ message: `Billing request failed (${response.status})`,
12700
+ status: response.status,
12701
+ endpoint: path,
12702
+ method,
12703
+ body: text
12704
+ });
12705
+ }
12706
+ return text;
12707
+ }
12708
+ const rawText = await response.text();
12709
+ let parsed = rawText;
12710
+ if (rawText) {
12711
+ try {
12712
+ parsed = JSON.parse(rawText);
12713
+ } catch {
12714
+ parsed = rawText;
12715
+ }
12716
+ } else {
12717
+ parsed = null;
12718
+ }
12719
+ if (!response.ok) {
12720
+ const message = parsed && typeof parsed === "object" && "message" in parsed && typeof parsed.message === "string" ? parsed.message : `Billing request failed (${response.status})`;
12721
+ throw new AthenaBillingError({
12722
+ message,
12723
+ status: response.status,
10065
12724
  endpoint: path,
10066
12725
  method,
10067
12726
  body: parsed
@@ -10547,28 +13206,92 @@ function createBillingModule(config) {
10547
13206
  };
10548
13207
  }
10549
13208
 
10550
- // src/config/errors.ts
10551
- var AthenaConfigurationError = class extends Error {
10552
- code;
10553
- service;
10554
- constructor(code, message, service) {
10555
- super(message);
10556
- this.name = "AthenaConfigurationError";
10557
- this.code = code;
10558
- this.service = service;
13209
+ // src/context/merge.ts
13210
+ function mergeAthenaRequestContexts(base, override) {
13211
+ if (!base && !override) return void 0;
13212
+ return {
13213
+ ...base,
13214
+ ...override,
13215
+ headers: base?.headers || override?.headers ? {
13216
+ ...base?.headers ?? {},
13217
+ ...override?.headers ?? {}
13218
+ } : void 0
13219
+ };
13220
+ }
13221
+
13222
+ // src/diagnostics.ts
13223
+ function readProcessEnv2() {
13224
+ try {
13225
+ return globalThis.process?.env ?? {};
13226
+ } catch {
13227
+ return {};
13228
+ }
13229
+ }
13230
+ function isTruthyEnv(value) {
13231
+ if (!value) return false;
13232
+ const normalized = value.trim().toLowerCase();
13233
+ return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
13234
+ }
13235
+ function isQuietAthenaDiagnosticsEnvironment(env = readProcessEnv2()) {
13236
+ const nodeEnv = env.NODE_ENV?.trim().toLowerCase();
13237
+ if (nodeEnv === "production") {
13238
+ return true;
13239
+ }
13240
+ if (isTruthyEnv(env.OPENNEXT_BUILD)) {
13241
+ return true;
13242
+ }
13243
+ const nextPhase = env.NEXT_PHASE?.trim();
13244
+ if (nextPhase === "phase-production-build") {
13245
+ return true;
13246
+ }
13247
+ if (isTruthyEnv(env.CI) && nodeEnv !== "test") {
13248
+ if (nodeEnv === "production" || isTruthyEnv(env.OPENNEXT_BUILD)) {
13249
+ return true;
13250
+ }
13251
+ }
13252
+ return false;
13253
+ }
13254
+ function resolveBooleanFlag(explicit, mode, quiet) {
13255
+ if (typeof explicit === "boolean") {
13256
+ return explicit;
13257
+ }
13258
+ if (mode === true) {
13259
+ return true;
13260
+ }
13261
+ if (mode === false) {
13262
+ return false;
13263
+ }
13264
+ if (mode === "auto") {
13265
+ return false;
13266
+ }
13267
+ return false;
13268
+ }
13269
+ function resolveAthenaClientDiagnostics(input) {
13270
+ const env = input.env ?? readProcessEnv2();
13271
+ const quiet = isQuietAthenaDiagnosticsEnvironment(env);
13272
+ const mode = input.diagnostics;
13273
+ const effectiveMode = mode === "auto" && quiet ? false : mode;
13274
+ const debugAst = resolveBooleanFlag(input.debugAst, effectiveMode);
13275
+ const findManyAst = resolveBooleanFlag(input.findManyAst, effectiveMode);
13276
+ let traceQueries;
13277
+ if (input.traceQueries !== void 0) {
13278
+ if (typeof input.traceQueries === "boolean") {
13279
+ traceQueries = input.traceQueries;
13280
+ } else if (effectiveMode === false || mode === "auto" && quiet) {
13281
+ const enabled = input.traceQueries.enabled;
13282
+ traceQueries = typeof enabled === "boolean" ? enabled ? input.traceQueries : false : false;
13283
+ } else {
13284
+ traceQueries = input.traceQueries;
13285
+ }
13286
+ } else if (effectiveMode === true) {
13287
+ traceQueries = true;
13288
+ } else {
13289
+ traceQueries = false;
10559
13290
  }
10560
- };
10561
-
10562
- // src/context/merge.ts
10563
- function mergeAthenaRequestContexts(base, override) {
10564
- if (!base && !override) return void 0;
10565
13291
  return {
10566
- ...base,
10567
- ...override,
10568
- headers: base?.headers || override?.headers ? {
10569
- ...base?.headers ?? {},
10570
- ...override?.headers ?? {}
10571
- } : void 0
13292
+ debugAst,
13293
+ findManyAst,
13294
+ traceQueries
10572
13295
  };
10573
13296
  }
10574
13297
 
@@ -10580,7 +13303,13 @@ var ENV_CHAT_URL_KEYS = ["ATHENA_CHAT_URL", "NEXT_PUBLIC_ATHENA_CHAT_URL"];
10580
13303
  var ENV_CHAT_WS_URL_KEYS = ["ATHENA_CHAT_WS_URL", "NEXT_PUBLIC_ATHENA_CHAT_WS_URL"];
10581
13304
  var ENV_STORAGE_URL_KEYS = ["ATHENA_STORAGE_URL", "NEXT_PUBLIC_ATHENA_STORAGE_URL"];
10582
13305
  var ENV_KEY_KEYS = ["ATHENA_API_KEY", "NEXT_PUBLIC_ATHENA_API_KEY", "ATHENA_GATEWAY_API_KEY", "X_API_KEY"];
10583
- var ENV_CLIENT_KEYS = ["ATHENA_CLIENT", "NEXT_PUBLIC_ATHENA_CLIENT"];
13306
+ var ENV_CLIENT_KEYS = [
13307
+ "ATHENA_CLIENT",
13308
+ "ATHENA_GATEWAY_CLIENT",
13309
+ "ATHENA_GENERATOR_CLIENT",
13310
+ "NEXT_PUBLIC_ATHENA_CLIENT",
13311
+ "NEXT_PUBLIC_ATHENA_GATEWAY_CLIENT"
13312
+ ];
10584
13313
  var MISSING_DB_SENTINEL = "https://athena.invalid/db";
10585
13314
  function readFirstEnv(env, keys) {
10586
13315
  for (const key of keys) {
@@ -10589,14 +13318,30 @@ function readFirstEnv(env, keys) {
10589
13318
  }
10590
13319
  return void 0;
10591
13320
  }
10592
- function normalizeOptional(value) {
13321
+ function readFirstEnvHttpUrl(env, keys) {
13322
+ for (const key of keys) {
13323
+ const value = env?.[key]?.trim();
13324
+ if (value && isAbsoluteHttpUrl(value)) return value;
13325
+ }
13326
+ return void 0;
13327
+ }
13328
+ function normalizeOptional2(value) {
10593
13329
  const normalized = value?.trim();
10594
13330
  return normalized || void 0;
10595
13331
  }
13332
+ function isAbsoluteHttpUrl(value) {
13333
+ try {
13334
+ const url = new URL(value);
13335
+ return url.protocol === "http:" || url.protocol === "https:";
13336
+ } catch {
13337
+ return false;
13338
+ }
13339
+ }
10596
13340
  function appendPath(baseUrl, path) {
10597
13341
  return `${baseUrl.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
10598
13342
  }
10599
13343
  function toWebSocketUrl(baseUrl) {
13344
+ if (!isAbsoluteHttpUrl(baseUrl)) return void 0;
10600
13345
  const url = new URL(baseUrl);
10601
13346
  url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
10602
13347
  url.pathname = `${url.pathname.replace(/\/+$/, "")}/wss/gateway`;
@@ -10606,11 +13351,11 @@ function toWebSocketUrl(baseUrl) {
10606
13351
  }
10607
13352
  function resolveCore(config) {
10608
13353
  const env = config.env;
10609
- const explicitRoot = normalizeOptional(config.url);
10610
- const envRoot = readFirstEnv(env, ENV_URL_KEYS);
10611
- const root = explicitRoot ?? envRoot;
10612
- const explicitRootWinsOverEnvServices = explicitRoot !== void 0;
10613
- const resolveService = (explicit, envKeys, path) => normalizeOptional(explicit) ?? (explicitRootWinsOverEnvServices && root ? appendPath(root, path) : void 0) ?? readFirstEnv(env, envKeys) ?? (root ? appendPath(root, path) : void 0);
13354
+ const explicitRoot = normalizeOptional2(config.url);
13355
+ const envRoot = readFirstEnvHttpUrl(env, ENV_URL_KEYS);
13356
+ const root = explicitRoot && isAbsoluteHttpUrl(explicitRoot) ? explicitRoot : explicitRoot ? void 0 : envRoot;
13357
+ const explicitRootWinsOverEnvServices = Boolean(root && explicitRoot && isAbsoluteHttpUrl(explicitRoot));
13358
+ const resolveService = (explicit, envKeys, path) => normalizeOptional2(explicit) ?? (explicitRootWinsOverEnvServices && root ? appendPath(root, path) : void 0) ?? readFirstEnvHttpUrl(env, envKeys) ?? (root ? appendPath(root, path) : void 0);
10614
13359
  const dbUrl = resolveService(config.db?.url, ENV_DB_URL_KEYS, "db");
10615
13360
  const urls = {
10616
13361
  db: dbUrl,
@@ -10618,8 +13363,8 @@ function resolveCore(config) {
10618
13363
  chat: resolveService(config.chat?.url, ENV_CHAT_URL_KEYS, "chat"),
10619
13364
  storage: resolveService(config.storage?.url, ENV_STORAGE_URL_KEYS, "storage"),
10620
13365
  // Billing lives on the main Athena HTTP surface (same host as gateway/db).
10621
- billing: normalizeOptional(config.billing?.url) ?? dbUrl ?? root ?? void 0,
10622
- chatWs: normalizeOptional(config.chat?.wsUrl) ?? (explicitRootWinsOverEnvServices && root ? toWebSocketUrl(root) : void 0) ?? readFirstEnv(env, ENV_CHAT_WS_URL_KEYS) ?? (root ? toWebSocketUrl(root) : void 0)
13366
+ billing: normalizeOptional2(config.billing?.url) ?? dbUrl ?? root ?? void 0,
13367
+ chatWs: normalizeOptional2(config.chat?.wsUrl) ?? (explicitRootWinsOverEnvServices && root ? toWebSocketUrl(root) : void 0) ?? readFirstEnvHttpUrl(env, ENV_CHAT_WS_URL_KEYS) ?? (root ? toWebSocketUrl(root) : void 0)
10623
13368
  };
10624
13369
  if (!urls.db && !urls.auth && !urls.chat && !urls.storage && !urls.billing) {
10625
13370
  throw new AthenaConfigurationError(
@@ -10628,7 +13373,7 @@ function resolveCore(config) {
10628
13373
  "db"
10629
13374
  );
10630
13375
  }
10631
- const key = normalizeOptional(config.key) ?? readFirstEnv(env, ENV_KEY_KEYS);
13376
+ const key = normalizeOptional2(config.key) ?? readFirstEnv(env, ENV_KEY_KEYS);
10632
13377
  if (!key) {
10633
13378
  throw new AthenaConfigurationError(
10634
13379
  "ATHENA_API_KEY_REQUIRED",
@@ -10639,7 +13384,7 @@ function resolveCore(config) {
10639
13384
  config,
10640
13385
  urls,
10641
13386
  key,
10642
- client: normalizeOptional(config.client) ?? readFirstEnv(env, ENV_CLIENT_KEYS)
13387
+ client: normalizeOptional2(config.client) ?? readFirstEnv(env, ENV_CLIENT_KEYS)
10643
13388
  };
10644
13389
  return {
10645
13390
  ...base,
@@ -10654,7 +13399,20 @@ async function resolveConfiguredContext(core, viewContext) {
10654
13399
  function createInternalConfig(core) {
10655
13400
  const { config, urls } = core;
10656
13401
  const { url: _authUrl, ...authOptions } = config.auth ?? {};
10657
- const { url: _storageUrl, directUpload, ...storageOptions } = config.storage ?? {};
13402
+ const {
13403
+ url: _storageUrl,
13404
+ directUpload,
13405
+ r2: _r2,
13406
+ prefix: _r2Prefix,
13407
+ ...storageOptions
13408
+ } = config.storage ?? {};
13409
+ const diagnostics = resolveAthenaClientDiagnostics({
13410
+ diagnostics: config.diagnostics,
13411
+ debugAst: config.debugAst,
13412
+ findManyAst: config.findManyAst,
13413
+ traceQueries: config.traceQueries,
13414
+ env: config.env
13415
+ });
10658
13416
  return {
10659
13417
  baseUrl: urls.db ?? MISSING_DB_SENTINEL,
10660
13418
  apiKey: core.key,
@@ -10671,14 +13429,15 @@ function createInternalConfig(core) {
10671
13429
  models: config.models,
10672
13430
  behavior: {
10673
13431
  retryReads: config.retryReads,
10674
- traceQueries: config.traceQueries,
10675
- debugAst: config.debugAst,
10676
- findManyAst: config.findManyAst
13432
+ traceQueries: diagnostics.traceQueries,
13433
+ debugAst: diagnostics.debugAst,
13434
+ findManyAst: diagnostics.findManyAst
10677
13435
  },
10678
13436
  storage: {
10679
13437
  ...storageOptions,
10680
13438
  ...directUpload ? { directUpload } : {}
10681
- }
13439
+ },
13440
+ gatewayTransport: config.gatewayTransport
10682
13441
  };
10683
13442
  }
10684
13443
  function serviceGuard(urls, service) {
@@ -10701,6 +13460,232 @@ function createUnavailableNamespace(service, urls, path = []) {
10701
13460
  }
10702
13461
  });
10703
13462
  }
13463
+ function isD1Binding2(value) {
13464
+ return Boolean(
13465
+ value && typeof value === "object" && typeof value.prepare === "function"
13466
+ );
13467
+ }
13468
+ function isR2Binding(value) {
13469
+ return Boolean(
13470
+ value && typeof value === "object" && typeof value.put === "function" && typeof value.get === "function"
13471
+ );
13472
+ }
13473
+ function foldBindingAliases(config) {
13474
+ const d1 = config.db?.d1 ?? config.d1;
13475
+ const r2 = config.storage?.r2 ?? config.r2;
13476
+ const sessionMode = config.db?.sessionMode ?? config.sessionMode;
13477
+ const prefix = config.storage?.prefix ?? config.storagePrefix;
13478
+ let next = { ...config };
13479
+ if (d1 !== void 0 || sessionMode !== void 0) {
13480
+ next = {
13481
+ ...next,
13482
+ db: {
13483
+ ...next.db,
13484
+ ...d1 !== void 0 ? { d1 } : {},
13485
+ ...sessionMode !== void 0 ? { sessionMode } : {}
13486
+ }
13487
+ };
13488
+ }
13489
+ if (r2 !== void 0 || prefix !== void 0) {
13490
+ next = {
13491
+ ...next,
13492
+ storage: {
13493
+ ...next.storage,
13494
+ ...r2 !== void 0 ? { r2 } : {},
13495
+ ...prefix !== void 0 ? { prefix } : {}
13496
+ }
13497
+ };
13498
+ }
13499
+ const {
13500
+ d1: _d1,
13501
+ r2: _r2,
13502
+ storagePrefix: _storagePrefix,
13503
+ sessionMode: _sessionMode,
13504
+ ...rest
13505
+ } = next;
13506
+ return rest;
13507
+ }
13508
+ function applyExecutionMode(config) {
13509
+ const d1 = config.db?.d1;
13510
+ const hasD1 = isD1Binding2(d1);
13511
+ const hasUrl = Boolean(
13512
+ normalizeOptional2(config.url) ?? normalizeOptional2(config.db?.url) ?? (config.env ? normalizeOptional2(config.env.ATHENA_URL) ?? normalizeOptional2(config.env.NEXT_PUBLIC_ATHENA_URL) : void 0)
13513
+ );
13514
+ const hasModeHint = config.mode != null || config.prefer != null || Boolean(config.env?.ATHENA_EXECUTION_MODE) || Boolean(config.env?.ATHENA_EXECUTION_PREFER);
13515
+ if (!hasD1 && !hasModeHint) {
13516
+ return config;
13517
+ }
13518
+ if (hasD1 && !hasUrl && !hasModeHint) {
13519
+ return config;
13520
+ }
13521
+ let resolved;
13522
+ try {
13523
+ resolved = resolveAthenaExecutionMode({
13524
+ mode: config.mode,
13525
+ prefer: config.prefer,
13526
+ d1: hasD1 ? d1 : null,
13527
+ url: config.url ?? config.db?.url,
13528
+ env: config.env
13529
+ });
13530
+ } catch (error) {
13531
+ if (!hasModeHint) return config;
13532
+ throw error;
13533
+ }
13534
+ if (resolved === "gateway" && hasD1) {
13535
+ const { d1: _drop, sessionMode: _sm, ...dbRest } = config.db ?? {};
13536
+ return {
13537
+ ...config,
13538
+ db: Object.keys(dbRest).length > 0 ? dbRest : void 0,
13539
+ gatewayTransport: void 0
13540
+ };
13541
+ }
13542
+ return config;
13543
+ }
13544
+ function resolveUnifiedRemoteRoot(config) {
13545
+ return normalizeOptional2(config.url) ?? readFirstEnv(config.env, ENV_URL_KEYS);
13546
+ }
13547
+ function isEdgeLocalSentinelUrl(url) {
13548
+ if (!url) return false;
13549
+ return url === CLOUDFLARE_EDGE_BASE_URL || url.startsWith("https://athena.local/") || url.startsWith("http://athena.local/");
13550
+ }
13551
+ function hasRemoteDbGatewayUrl(config) {
13552
+ const dbUrl = normalizeOptional2(config.db?.url) ?? readFirstEnv(config.env, ENV_DB_URL_KEYS);
13553
+ return Boolean(dbUrl && !isEdgeLocalSentinelUrl(dbUrl));
13554
+ }
13555
+ function hasRemoteHttpServices(config) {
13556
+ return Boolean(
13557
+ resolveUnifiedRemoteRoot(config) || hasRemoteDbGatewayUrl(config) || normalizeOptional2(config.auth?.url) || readFirstEnv(config.env, ENV_AUTH_URL_KEYS) || normalizeOptional2(config.storage?.url) || readFirstEnv(config.env, ENV_STORAGE_URL_KEYS) || normalizeOptional2(config.chat?.url) || readFirstEnv(config.env, ENV_CHAT_URL_KEYS) || normalizeOptional2(config.billing?.url)
13558
+ );
13559
+ }
13560
+ function hasRemoteHttpStorage(config) {
13561
+ return Boolean(
13562
+ normalizeOptional2(config.storage?.url) || readFirstEnv(config.env, ENV_STORAGE_URL_KEYS) || resolveUnifiedRemoteRoot(config)
13563
+ );
13564
+ }
13565
+ function hasRemoteAuthService(config) {
13566
+ return Boolean(
13567
+ normalizeOptional2(config.auth?.url) || readFirstEnv(config.env, ENV_AUTH_URL_KEYS) || resolveUnifiedRemoteRoot(config)
13568
+ );
13569
+ }
13570
+ function materializeEdgeBindings(config) {
13571
+ const d1 = config.db?.d1;
13572
+ const r2 = config.storage?.r2;
13573
+ const hasD1 = isD1Binding2(d1);
13574
+ const hasR2 = isR2Binding(r2);
13575
+ if (!hasD1 && !hasR2) {
13576
+ return config;
13577
+ }
13578
+ if (hasD1 && d1 && typeof d1.prepare !== "function") {
13579
+ throw new AthenaConfigurationError(
13580
+ "ATHENA_NO_SERVICE_CONFIGURED",
13581
+ "db.d1 must be a D1 binding with prepare().",
13582
+ "db"
13583
+ );
13584
+ }
13585
+ const remoteRoot = resolveUnifiedRemoteRoot(config);
13586
+ const remoteServices = hasRemoteHttpServices(config);
13587
+ const remoteStorage = hasRemoteHttpStorage(config);
13588
+ const remoteAuth = hasRemoteAuthService(config);
13589
+ const next = { ...config };
13590
+ if (hasD1 && d1) {
13591
+ if (!config.gatewayTransport) {
13592
+ next.gatewayTransport = createCloudflareD1GatewayTransport({
13593
+ d1,
13594
+ defaultSessionMode: config.db?.sessionMode
13595
+ });
13596
+ }
13597
+ const explicitDbUrl = normalizeOptional2(config.db?.url);
13598
+ const remoteDbGateway = hasRemoteDbGatewayUrl(config);
13599
+ next.db = {
13600
+ ...config.db,
13601
+ d1,
13602
+ url: explicitDbUrl ?? (remoteDbGateway ? void 0 : CLOUDFLARE_EDGE_BASE_URL)
13603
+ };
13604
+ const explicitKey = normalizeOptional2(config.key);
13605
+ if (explicitKey) {
13606
+ next.key = explicitKey;
13607
+ } else if (!remoteServices) {
13608
+ next.key = CLOUDFLARE_EDGE_API_KEY;
13609
+ } else {
13610
+ next.key = void 0;
13611
+ }
13612
+ if (remoteRoot) {
13613
+ next.billing = {
13614
+ ...config.billing ?? {},
13615
+ url: normalizeOptional2(config.billing?.url) ?? remoteRoot
13616
+ };
13617
+ }
13618
+ if (!config.capabilities) {
13619
+ next.capabilities = createCloudflareEdgeCapabilities({
13620
+ hasR2,
13621
+ // Explicit storage.url / env storage URL / unified remote root all count.
13622
+ hasRemoteStorage: remoteStorage,
13623
+ authRemote: remoteAuth,
13624
+ findManyAst: false
13625
+ });
13626
+ }
13627
+ } else if (hasR2 && r2) {
13628
+ if (!remoteRoot && !normalizeOptional2(config.db?.url) && !normalizeOptional2(config.storage?.url) && !readFirstEnv(config.env, ENV_STORAGE_URL_KEYS)) {
13629
+ next.storage = {
13630
+ ...config.storage,
13631
+ r2,
13632
+ // Local sentinel so resolveCore accepts a storage-only binding client.
13633
+ url: CLOUDFLARE_EDGE_BASE_URL
13634
+ };
13635
+ if (!remoteServices) {
13636
+ next.key = normalizeOptional2(config.key) ?? CLOUDFLARE_EDGE_API_KEY;
13637
+ } else if (normalizeOptional2(config.key)) {
13638
+ next.key = normalizeOptional2(config.key);
13639
+ } else {
13640
+ next.key = void 0;
13641
+ }
13642
+ }
13643
+ if (!config.capabilities) {
13644
+ if (remoteRoot || normalizeOptional2(config.db?.url) || readFirstEnv(config.env, ENV_DB_URL_KEYS)) {
13645
+ const base = createGatewayCapabilities({
13646
+ authRemote: remoteAuth,
13647
+ storageConfigured: true
13648
+ });
13649
+ next.capabilities = {
13650
+ ...base,
13651
+ storage: {
13652
+ ...base.storage,
13653
+ local: true,
13654
+ objects: true
13655
+ }
13656
+ };
13657
+ } else {
13658
+ next.capabilities = {
13659
+ mode: "cloudflare-edge",
13660
+ db: {
13661
+ engine: "unknown",
13662
+ local: false,
13663
+ layers: {
13664
+ query: false,
13665
+ flatCrud: false,
13666
+ findManyAst: false,
13667
+ rpc: false,
13668
+ relations: false
13669
+ }
13670
+ },
13671
+ storage: {
13672
+ local: true,
13673
+ objects: true,
13674
+ catalogs: false,
13675
+ backups: false
13676
+ },
13677
+ auth: {
13678
+ remote: remoteAuth
13679
+ }
13680
+ };
13681
+ }
13682
+ }
13683
+ }
13684
+ return next;
13685
+ }
13686
+ function normalizeCreateClientConfig(config) {
13687
+ return materializeEdgeBindings(applyExecutionMode(foldBindingAliases(config)));
13688
+ }
10704
13689
  function createClientView(core, viewContext) {
10705
13690
  const resolved = createInternalClientView(
10706
13691
  core.internalCore,
@@ -10718,12 +13703,23 @@ function createClientView(core, viewContext) {
10718
13703
  },
10719
13704
  ...billingOptions
10720
13705
  }) : createUnavailableNamespace("billing", core.urls);
13706
+ const capabilities = core.config.capabilities ?? createGatewayCapabilities({
13707
+ authRemote: Boolean(core.urls.auth),
13708
+ // Match unavailable storage proxy when no storage URL was resolved.
13709
+ storageConfigured: Boolean(core.urls.storage)
13710
+ });
13711
+ const r2 = core.config.storage?.r2;
13712
+ const storageModule = isR2Binding(r2) ? createCloudflareR2StorageModule({
13713
+ r2,
13714
+ prefix: core.config.storage?.prefix ?? void 0
13715
+ }) : core.urls.storage ? resolved.storage : createUnavailableNamespace("storage", core.urls);
10721
13716
  const client = {
10722
13717
  db: core.urls.db ? resolved.db : createUnavailableNamespace("db", core.urls),
10723
13718
  auth: core.urls.auth ? resolved.auth : createUnavailableNamespace("auth", core.urls),
10724
13719
  chat: core.urls.chat ? resolved.chat : createUnavailableNamespace("chat", core.urls),
10725
- storage: core.urls.storage ? resolved.storage : createUnavailableNamespace("storage", core.urls),
13720
+ storage: storageModule,
10726
13721
  billing: billingModule,
13722
+ capabilities,
10727
13723
  from: ((...args) => {
10728
13724
  requireDb();
10729
13725
  return Reflect.apply(resolved.from, resolved, args);
@@ -10747,13 +13743,34 @@ function createClientView(core, viewContext) {
10747
13743
  return resolved.verifyConnection(options);
10748
13744
  },
10749
13745
  withContext(context) {
13746
+ warnIfEmptyRequestContext(context);
10750
13747
  return createClientView(core, mergeAthenaRequestContexts(viewContext, context));
10751
13748
  }
10752
13749
  };
10753
13750
  return Object.freeze(client);
10754
13751
  }
13752
+ function isEmptyAthenaRequestContext(context) {
13753
+ if (!context) return true;
13754
+ const hasHeaders = context.headers != null && Object.keys(context.headers).length > 0;
13755
+ return context.userId == null && context.organizationId == null && !normalizeOptionalContextString(context.cookie) && !normalizeOptionalContextString(context.bearerToken) && !normalizeOptionalContextString(context.sessionToken) && !context.forceNoCache && !hasHeaders;
13756
+ }
13757
+ function normalizeOptionalContextString(value) {
13758
+ const trimmed = value?.trim();
13759
+ return trimmed || void 0;
13760
+ }
13761
+ function warnIfEmptyRequestContext(context) {
13762
+ if (!isEmptyAthenaRequestContext(context)) return;
13763
+ const nodeEnv = globalThis.process?.env?.NODE_ENV;
13764
+ if (nodeEnv === "production") {
13765
+ return;
13766
+ }
13767
+ console.warn(
13768
+ "[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 })."
13769
+ );
13770
+ }
10755
13771
  function createClient(config) {
10756
- return createClientView(resolveCore(config));
13772
+ const normalized = normalizeCreateClientConfig(config);
13773
+ return createClientView(resolveCore(normalized));
10757
13774
  }
10758
13775
 
10759
13776
  // src/gateway/types.ts
@@ -12107,6 +15124,27 @@ function resolveTotalItemsFromPage({
12107
15124
  }
12108
15125
  return clampAthenaReadQueryTotalItems(exactCount, limit);
12109
15126
  }
15127
+ function resolveAthenaReadQueryPageFetch({
15128
+ page,
15129
+ pageSize,
15130
+ limit
15131
+ }) {
15132
+ const safePage = Math.max(1, Math.trunc(page) || 1);
15133
+ const safePageSize = Math.max(1, Math.trunc(pageSize) || 1);
15134
+ if (!limit || limit < 1) {
15135
+ return { page: safePage, pageSize: safePageSize, shouldFetch: true };
15136
+ }
15137
+ const totalCap = Math.trunc(limit);
15138
+ const offset = (safePage - 1) * safePageSize;
15139
+ if (offset >= totalCap) {
15140
+ return { page: safePage, pageSize: safePageSize, shouldFetch: false };
15141
+ }
15142
+ return {
15143
+ page: safePage,
15144
+ pageSize: Math.min(safePageSize, totalCap - offset),
15145
+ shouldFetch: true
15146
+ };
15147
+ }
12110
15148
  async function executeAthenaReadQuery({
12111
15149
  client,
12112
15150
  page,
@@ -12125,15 +15163,29 @@ async function executeAthenaReadQuery({
12125
15163
  count: "exact",
12126
15164
  head: true
12127
15165
  });
15166
+ const pageFetch = resolveAthenaReadQueryPageFetch({
15167
+ limit: query.limit,
15168
+ page,
15169
+ pageSize
15170
+ });
15171
+ if (!pageFetch.shouldFetch) {
15172
+ return {
15173
+ rows: [],
15174
+ totalItems: resolveTotalItemsFromPage({
15175
+ countCandidates: [countResult.count],
15176
+ limit: query.limit,
15177
+ page: pageFetch.page,
15178
+ pageSize,
15179
+ rowCount: 0
15180
+ })
15181
+ };
15182
+ }
12128
15183
  if ((query.mode ?? "findMany") === "select") {
12129
- const selectBuilder = applyAthenaReadQuerySelectLimit(
12130
- applyAthenaReadQuerySelectOrder(
12131
- applyAthenaReadQueryFilters(baseBuilder, query.filters),
12132
- query.orderBy
12133
- ),
12134
- query.limit
15184
+ const selectBuilder = applyAthenaReadQuerySelectOrder(
15185
+ applyAthenaReadQueryFilters(baseBuilder, query.filters),
15186
+ query.orderBy
12135
15187
  );
12136
- const result2 = await selectBuilder.currentPage(page).pageSize(pageSize).select(buildAthenaReadQuerySelectString(query.columns), {
15188
+ const result2 = await selectBuilder.currentPage(pageFetch.page).pageSize(pageFetch.pageSize).select(buildAthenaReadQuerySelectString(query.columns), {
12137
15189
  count: "exact"
12138
15190
  });
12139
15191
  const rows2 = flattenAthenaReadQueryRows(
@@ -12147,7 +15199,7 @@ async function executeAthenaReadQuery({
12147
15199
  totalItems: resolveTotalItemsFromPage({
12148
15200
  countCandidates: [countResult.count, result2.count],
12149
15201
  limit: query.limit,
12150
- page,
15202
+ page: pageFetch.page,
12151
15203
  pageSize,
12152
15204
  rowCount: rows2.length
12153
15205
  })
@@ -12155,12 +15207,11 @@ async function executeAthenaReadQuery({
12155
15207
  }
12156
15208
  const findManyOrderBy = buildAthenaReadQueryFindManyOrderBy(query.orderBy);
12157
15209
  const findManyOptions = {
12158
- ...query.limit ? { limit: query.limit } : {},
12159
15210
  ...findManyOrderBy ? { orderBy: findManyOrderBy } : {},
12160
15211
  select: buildAthenaReadQueryFindManySelect(query.columns),
12161
15212
  ...query.filters?.length ? { where: buildAthenaReadQueryFindManyWhere(query.filters) } : {}
12162
15213
  };
12163
- const result = await baseBuilder.currentPage(page).pageSize(pageSize).findMany(findManyOptions);
15214
+ const result = await baseBuilder.currentPage(pageFetch.page).pageSize(pageFetch.pageSize).findMany(findManyOptions);
12164
15215
  const rows = flattenAthenaReadQueryRows(
12165
15216
  Array.isArray(result.data) ? result.data : [],
12166
15217
  query.columns,
@@ -12172,7 +15223,7 @@ async function executeAthenaReadQuery({
12172
15223
  totalItems: resolveTotalItemsFromPage({
12173
15224
  countCandidates: [countResult.count, result.count],
12174
15225
  limit: query.limit,
12175
- page,
15226
+ page: pageFetch.page,
12176
15227
  pageSize,
12177
15228
  rowCount: rows.length
12178
15229
  })
@@ -12180,6 +15231,432 @@ async function executeAthenaReadQuery({
12180
15231
  }
12181
15232
  var executeAthenaTableQuery = executeAthenaReadQuery;
12182
15233
 
15234
+ // src/tables/catalog.ts
15235
+ var POSTGRES_CATALOG_SQL = {
15236
+ columns: `
15237
+ SELECT
15238
+ n.nspname AS schema_name,
15239
+ c.relname AS table_name,
15240
+ a.attname AS column_name,
15241
+ format_type(a.atttypid, a.atttypmod) AS data_type,
15242
+ NOT a.attnotnull AS is_nullable
15243
+ FROM pg_attribute a
15244
+ JOIN pg_class c ON c.oid = a.attrelid
15245
+ JOIN pg_namespace n ON n.oid = c.relnamespace
15246
+ WHERE c.relkind IN ('r', 'p')
15247
+ AND a.attnum > 0
15248
+ AND NOT a.attisdropped
15249
+ AND n.nspname = ANY($1::text[])
15250
+ ORDER BY n.nspname, c.relname, a.attnum;
15251
+ `,
15252
+ foreignKeys: `
15253
+ SELECT
15254
+ sn.nspname AS source_schema,
15255
+ sc.relname AS source_table,
15256
+ con.conname AS constraint_name,
15257
+ ARRAY_AGG(sa.attname ORDER BY cols.ordinality) AS source_columns,
15258
+ tn.nspname AS target_schema,
15259
+ tc.relname AS target_table,
15260
+ ARRAY_AGG(ta.attname ORDER BY cols.ordinality) AS target_columns,
15261
+ EXISTS (
15262
+ SELECT 1
15263
+ FROM pg_constraint uq
15264
+ WHERE uq.conrelid = con.conrelid
15265
+ AND uq.contype IN ('p', 'u')
15266
+ AND uq.conkey = con.conkey
15267
+ ) AS source_is_unique
15268
+ FROM pg_constraint con
15269
+ JOIN pg_class sc ON sc.oid = con.conrelid
15270
+ JOIN pg_namespace sn ON sn.oid = sc.relnamespace
15271
+ JOIN pg_class tc ON tc.oid = con.confrelid
15272
+ JOIN pg_namespace tn ON tn.oid = tc.relnamespace
15273
+ JOIN unnest(con.conkey, con.confkey) WITH ORDINALITY AS cols(source_attnum, target_attnum, ordinality) ON TRUE
15274
+ JOIN pg_attribute sa ON sa.attrelid = con.conrelid AND sa.attnum = cols.source_attnum
15275
+ JOIN pg_attribute ta ON ta.attrelid = con.confrelid AND ta.attnum = cols.target_attnum
15276
+ WHERE con.contype = 'f'
15277
+ AND sn.nspname = ANY($1::text[])
15278
+ AND tn.nspname = ANY($1::text[])
15279
+ GROUP BY
15280
+ sn.nspname,
15281
+ sc.relname,
15282
+ con.conname,
15283
+ tn.nspname,
15284
+ tc.relname,
15285
+ con.conkey,
15286
+ con.conrelid
15287
+ ORDER BY sn.nspname, sc.relname, con.conname;
15288
+ `,
15289
+ primaryKeys: `
15290
+ SELECT
15291
+ n.nspname AS schema_name,
15292
+ c.relname AS table_name,
15293
+ ARRAY_AGG(a.attname ORDER BY ck.ordinality) AS columns
15294
+ FROM pg_constraint con
15295
+ JOIN pg_class c ON c.oid = con.conrelid
15296
+ JOIN pg_namespace n ON n.oid = c.relnamespace
15297
+ JOIN unnest(con.conkey) WITH ORDINALITY AS ck(attnum, ordinality) ON TRUE
15298
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ck.attnum
15299
+ WHERE con.contype = 'p'
15300
+ AND n.nspname = ANY($1::text[])
15301
+ GROUP BY n.nspname, c.relname
15302
+ ORDER BY n.nspname, c.relname;
15303
+ `
15304
+ };
15305
+ function parseAthenaTableSchemaScope(value) {
15306
+ return value.split(",").map((entry) => entry.trim()).filter(
15307
+ (entry, index, values) => entry.length > 0 && values.indexOf(entry) === index
15308
+ );
15309
+ }
15310
+ function escapeSqlLiteral(value) {
15311
+ return value.replace(/'/g, "''");
15312
+ }
15313
+ function buildSchemaArrayLiteral(schemas) {
15314
+ const literals = schemas.map((schema) => `'${escapeSqlLiteral(schema)}'`).join(", ");
15315
+ return `ARRAY[${literals}]`;
15316
+ }
15317
+ function inlineSchemaLiteral(sql, schemas) {
15318
+ return sql.replace(
15319
+ /\$1::text\[\]/g,
15320
+ `${buildSchemaArrayLiteral(schemas)}::text[]`
15321
+ );
15322
+ }
15323
+ function buildAthenaTableCatalogQueries(schemas) {
15324
+ return {
15325
+ columns: inlineSchemaLiteral(POSTGRES_CATALOG_SQL.columns, schemas),
15326
+ foreignKeys: inlineSchemaLiteral(POSTGRES_CATALOG_SQL.foreignKeys, schemas),
15327
+ primaryKeys: inlineSchemaLiteral(POSTGRES_CATALOG_SQL.primaryKeys, schemas)
15328
+ };
15329
+ }
15330
+ function tableKey(schema, table2) {
15331
+ return `${schema}.${table2}`;
15332
+ }
15333
+ function relationKey(...parts) {
15334
+ const base = parts.join("_").replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
15335
+ return base.length > 0 ? base : "relation";
15336
+ }
15337
+ function parsePostgresArrayLiteral(text) {
15338
+ const body = text.slice(1, -1).trim();
15339
+ if (!body) {
15340
+ return [];
15341
+ }
15342
+ const values = [];
15343
+ let current = "";
15344
+ let inQuotes = false;
15345
+ let escaped = false;
15346
+ for (const char of body) {
15347
+ if (escaped) {
15348
+ current += char;
15349
+ escaped = false;
15350
+ continue;
15351
+ }
15352
+ if (char === "\\") {
15353
+ escaped = true;
15354
+ continue;
15355
+ }
15356
+ if (char === '"') {
15357
+ inQuotes = !inQuotes;
15358
+ continue;
15359
+ }
15360
+ if (char === "," && !inQuotes) {
15361
+ values.push(current);
15362
+ current = "";
15363
+ continue;
15364
+ }
15365
+ current += char;
15366
+ }
15367
+ values.push(current);
15368
+ return values.map((value) => value.trim()).filter((value) => value.length > 0);
15369
+ }
15370
+ function coerceStringArray(value) {
15371
+ if (value == null) {
15372
+ return [];
15373
+ }
15374
+ if (Array.isArray(value)) {
15375
+ return value.map((entry) => entry.trim()).filter(Boolean);
15376
+ }
15377
+ if (typeof value !== "string") {
15378
+ return [];
15379
+ }
15380
+ const trimmedValue = value.trim();
15381
+ if (!trimmedValue) {
15382
+ return [];
15383
+ }
15384
+ if (trimmedValue.startsWith("{") && trimmedValue.endsWith("}")) {
15385
+ return parsePostgresArrayLiteral(trimmedValue);
15386
+ }
15387
+ return trimmedValue.split(",").map((entry) => entry.trim()).filter(Boolean);
15388
+ }
15389
+ function createTableCatalog() {
15390
+ const tables = /* @__PURE__ */ new Map();
15391
+ const ensureTable = (schema, name) => {
15392
+ const id = tableKey(schema, name);
15393
+ const existingTable = tables.get(id);
15394
+ if (existingTable) {
15395
+ return existingTable;
15396
+ }
15397
+ const nextTable = {
15398
+ columns: [],
15399
+ id,
15400
+ name,
15401
+ primaryKey: [],
15402
+ relationMap: /* @__PURE__ */ new Map(),
15403
+ schema
15404
+ };
15405
+ tables.set(id, nextTable);
15406
+ return nextTable;
15407
+ };
15408
+ const upsertRelation = (table2, key, relation) => {
15409
+ table2.relationMap.set(key, relation);
15410
+ };
15411
+ return {
15412
+ addColumnRows(columnRows) {
15413
+ for (const row of columnRows) {
15414
+ const table2 = ensureTable(row.schema_name, row.table_name);
15415
+ table2.columns.push({
15416
+ dataType: row.data_type,
15417
+ isNullable: row.is_nullable,
15418
+ isPrimaryKey: false,
15419
+ name: row.column_name
15420
+ });
15421
+ }
15422
+ },
15423
+ addForeignKeyRows(foreignKeyRows) {
15424
+ for (const row of foreignKeyRows) {
15425
+ const sourceTable = ensureTable(row.source_schema, row.source_table);
15426
+ const targetTable = ensureTable(row.target_schema, row.target_table);
15427
+ upsertRelation(
15428
+ sourceTable,
15429
+ relationKey(row.constraint_name, row.target_table),
15430
+ {
15431
+ name: row.constraint_name,
15432
+ targetSchema: row.target_schema,
15433
+ targetTable: row.target_table
15434
+ }
15435
+ );
15436
+ upsertRelation(targetTable, relationKey(row.source_table), {
15437
+ name: relationKey(row.source_table, row.constraint_name),
15438
+ targetSchema: row.source_schema,
15439
+ targetTable: row.source_table
15440
+ });
15441
+ }
15442
+ },
15443
+ addManyToManyRows(foreignKeyRows) {
15444
+ const foreignKeysBySourceTable = /* @__PURE__ */ new Map();
15445
+ for (const foreignKey of foreignKeyRows) {
15446
+ const key = tableKey(foreignKey.source_schema, foreignKey.source_table);
15447
+ const current = foreignKeysBySourceTable.get(key) ?? {
15448
+ foreignKeys: [],
15449
+ schema: foreignKey.source_schema,
15450
+ table: foreignKey.source_table
15451
+ };
15452
+ current.foreignKeys.push(foreignKey);
15453
+ foreignKeysBySourceTable.set(key, current);
15454
+ }
15455
+ for (const candidate of foreignKeysBySourceTable.values()) {
15456
+ const bridgeTable = tables.get(
15457
+ tableKey(candidate.schema, candidate.table)
15458
+ );
15459
+ if (!bridgeTable || candidate.foreignKeys.length !== 2) {
15460
+ continue;
15461
+ }
15462
+ const combinedForeignColumns = Array.from(
15463
+ new Set(
15464
+ candidate.foreignKeys.flatMap(
15465
+ (foreignKey) => coerceStringArray(foreignKey.source_columns)
15466
+ )
15467
+ )
15468
+ );
15469
+ if (bridgeTable.primaryKey.length === 0 || combinedForeignColumns.length !== bridgeTable.primaryKey.length || !bridgeTable.primaryKey.every(
15470
+ (column) => combinedForeignColumns.includes(column)
15471
+ )) {
15472
+ continue;
15473
+ }
15474
+ const [firstForeignKey, secondForeignKey] = candidate.foreignKeys;
15475
+ const firstTarget = tables.get(
15476
+ tableKey(firstForeignKey.target_schema, firstForeignKey.target_table)
15477
+ );
15478
+ const secondTarget = tables.get(
15479
+ tableKey(
15480
+ secondForeignKey.target_schema,
15481
+ secondForeignKey.target_table
15482
+ )
15483
+ );
15484
+ if (!(firstTarget && secondTarget)) {
15485
+ continue;
15486
+ }
15487
+ upsertRelation(
15488
+ firstTarget,
15489
+ relationKey(candidate.table, secondForeignKey.target_table),
15490
+ {
15491
+ name: relationKey(
15492
+ candidate.table,
15493
+ secondForeignKey.constraint_name
15494
+ ),
15495
+ targetSchema: secondForeignKey.target_schema,
15496
+ targetTable: secondForeignKey.target_table
15497
+ }
15498
+ );
15499
+ upsertRelation(
15500
+ secondTarget,
15501
+ relationKey(candidate.table, firstForeignKey.target_table),
15502
+ {
15503
+ name: relationKey(candidate.table, firstForeignKey.constraint_name),
15504
+ targetSchema: firstForeignKey.target_schema,
15505
+ targetTable: firstForeignKey.target_table
15506
+ }
15507
+ );
15508
+ }
15509
+ },
15510
+ addPrimaryKeyRows(primaryKeyRows) {
15511
+ for (const row of primaryKeyRows) {
15512
+ const table2 = ensureTable(row.schema_name, row.table_name);
15513
+ const primaryKey = coerceStringArray(row.columns);
15514
+ table2.primaryKey = primaryKey;
15515
+ for (const columnName of primaryKey) {
15516
+ const column = table2.columns.find(
15517
+ (candidate) => candidate.name === columnName
15518
+ );
15519
+ if (column) {
15520
+ column.isPrimaryKey = true;
15521
+ }
15522
+ }
15523
+ }
15524
+ },
15525
+ toResponse(database) {
15526
+ return {
15527
+ database,
15528
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
15529
+ tables: [...tables.values()].map((table2) => ({
15530
+ columns: [...table2.columns].sort(
15531
+ (left, right) => left.name.localeCompare(right.name)
15532
+ ),
15533
+ id: table2.id,
15534
+ name: table2.name,
15535
+ primaryKey: [...table2.primaryKey],
15536
+ relations: [...table2.relationMap.values()].map((relation) => ({
15537
+ columns: tables.get(
15538
+ tableKey(relation.targetSchema, relation.targetTable)
15539
+ )?.columns ?? [],
15540
+ name: relation.name,
15541
+ targetSchema: relation.targetSchema,
15542
+ targetTable: relation.targetTable
15543
+ })).sort(
15544
+ (left, right) => left.name.localeCompare(right.name)
15545
+ ),
15546
+ schema: table2.schema
15547
+ })).sort(
15548
+ (left, right) => left.id.localeCompare(right.id)
15549
+ )
15550
+ };
15551
+ }
15552
+ };
15553
+ }
15554
+ async function queryRows(client, query) {
15555
+ const result = await client.query(query);
15556
+ if (result.error || result.status < 200 || result.status >= 300) {
15557
+ 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}.`;
15558
+ throw new Error(errorMessage);
15559
+ }
15560
+ return Array.isArray(result.data) ? result.data : [];
15561
+ }
15562
+ function isAthenaTableSchemaConfig(value) {
15563
+ if (typeof value !== "object" || value === null) {
15564
+ return false;
15565
+ }
15566
+ const config = value;
15567
+ return typeof config.gatewayUrl === "string" && typeof config.gatewayKey === "string" && typeof config.gatewayDatabase === "string" && typeof config.schemaScope === "string" && typeof config.clientName === "string";
15568
+ }
15569
+ function hasAthenaTableSchemaCredentials(config) {
15570
+ return config.gatewayUrl.trim().length > 0 && config.gatewayKey.trim().length > 0 && config.gatewayDatabase.trim().length > 0;
15571
+ }
15572
+ async function fetchAthenaTableCatalog(config, options = {}) {
15573
+ const schemas = parseAthenaTableSchemaScope(config.schemaScope);
15574
+ if (schemas.length === 0) {
15575
+ return {
15576
+ database: config.gatewayDatabase,
15577
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
15578
+ tables: []
15579
+ };
15580
+ }
15581
+ const queries = buildAthenaTableCatalogQueries(schemas);
15582
+ const client = options.client ?? createClient({
15583
+ url: config.gatewayUrl.trim(),
15584
+ key: config.gatewayKey.trim(),
15585
+ client: config.clientName.trim() || void 0
15586
+ });
15587
+ const [columnRows, primaryKeyRows, foreignKeyRows] = await Promise.all([
15588
+ queryRows(client, queries.columns),
15589
+ queryRows(client, queries.primaryKeys),
15590
+ queryRows(client, queries.foreignKeys)
15591
+ ]);
15592
+ const catalog = createTableCatalog();
15593
+ catalog.addColumnRows(columnRows);
15594
+ catalog.addPrimaryKeyRows(primaryKeyRows);
15595
+ catalog.addForeignKeyRows(foreignKeyRows);
15596
+ catalog.addManyToManyRows(foreignKeyRows);
15597
+ return catalog.toResponse(config.gatewayDatabase);
15598
+ }
15599
+ var fetchTableCatalog = fetchAthenaTableCatalog;
15600
+
15601
+ // src/tables/schema-handlers.ts
15602
+ var ATHENA_TABLE_SCHEMA_ROUTE = "/api/tables/schema";
15603
+ function json2(body, init) {
15604
+ const headers = new Headers(init?.headers);
15605
+ if (!headers.has("content-type")) {
15606
+ headers.set("content-type", "application/json; charset=utf-8");
15607
+ }
15608
+ return new Response(JSON.stringify(body), {
15609
+ status: init?.status ?? 200,
15610
+ headers
15611
+ });
15612
+ }
15613
+ async function handleAthenaTableSchemaPost(request2, options) {
15614
+ const payload = await request2.json().catch(() => null);
15615
+ let config = isAthenaTableSchemaConfig(
15616
+ payload?.config
15617
+ ) ? payload.config : null;
15618
+ if (config && options?.resolveConfig) {
15619
+ config = await options.resolveConfig(config, request2);
15620
+ }
15621
+ if (!config || !isAthenaTableSchemaConfig(config)) {
15622
+ return json2(
15623
+ {
15624
+ error: "The Athena tables showcase config is invalid."
15625
+ },
15626
+ { status: 400 }
15627
+ );
15628
+ }
15629
+ if (!hasAthenaTableSchemaCredentials(config)) {
15630
+ return json2(
15631
+ {
15632
+ error: "Gateway URL, API key, and database are required for schema introspection."
15633
+ },
15634
+ { status: 400 }
15635
+ );
15636
+ }
15637
+ try {
15638
+ const response = await fetchAthenaTableCatalog(
15639
+ config,
15640
+ {
15641
+ client: options?.client
15642
+ }
15643
+ );
15644
+ return json2(response);
15645
+ } catch (error) {
15646
+ return json2(
15647
+ {
15648
+ error: error instanceof Error ? error.message : "Athena schema introspection failed."
15649
+ },
15650
+ { status: 500 }
15651
+ );
15652
+ }
15653
+ }
15654
+ function createAthenaTableSchemaHandlers(options) {
15655
+ return {
15656
+ POST: (request2) => handleAthenaTableSchemaPost(request2, options)
15657
+ };
15658
+ }
15659
+
12183
15660
  // src/browser.ts
12184
15661
  function throwBrowserUnsupported(apiName) {
12185
15662
  throw new Error(
@@ -12211,6 +15688,6 @@ async function runSchemaGenerator(options = {}) {
12211
15688
  return throwBrowserUnsupported("runSchemaGenerator");
12212
15689
  }
12213
15690
 
12214
- export { ATHENA_AUTH_ADMIN_LIMITS, ATHENA_AUTH_BASE_ERROR_CODES, ATHENA_AUTH_MAX_ADMIN_JSON_BYTES, ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH, ATHENA_AUTH_MAX_TEMPLATE_VARIABLES, ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH, AthenaBillingError, AthenaChatError, AthenaConfigurationError, AthenaError, AthenaErrorCategory, AthenaErrorCode, AthenaErrorKind, AthenaGatewayError, AthenaStorageError, AthenaStorageErrorCode, Backend, DEFAULT_POSTGRES_SCHEMAS, applyAthenaReadQueryFilters, applyAthenaReadQuerySelectLimit, applyAthenaReadQuerySelectOrder, applyAthenaTableFilters, applyAthenaTableSelectLimit, applyAthenaTableSelectOrder, assertInt, athenaAuth, billingSdkManifest, boolean, buildAthenaReadQueryFindManyOrderBy, buildAthenaReadQueryFindManySelect, buildAthenaReadQueryFindManyWhere, buildAthenaReadQuerySelectString, buildAthenaTableFindManyOrderBy, buildAthenaTableFindManySelect, buildAthenaTableFindManyWhere, buildAthenaTableSelectString, chatSdkManifest, clampAthenaReadQueryTotalItems, clampAthenaTableTotalItems, coerceInt, createAthenaStorageError, createAuthReactEmailInput, createBillingModule, createClient, createModelFormAdapter, createPostgresIntrospectionProvider, defineAthenaAuthConfig, defineAuthEmailTemplate, defineDatabase, defineGeneratorConfig, defineModel, defineRegistry, defineSchema, enumeration, executeAthenaReadQuery, executeAthenaTableQuery, filterIntrospectionSnapshot, findGeneratorConfigPath, flattenAthenaReadQueryRows, flattenAthenaRows, generateArtifactsFromSnapshot, generatorEnv, getAthenaDebugAst, identifier, isAthenaGatewayError, isOk, json, loadGeneratorConfig, normalizeAthenaError, normalizeAthenaGatewayBaseUrl, normalizeAthenaReadQueryOrderBy, normalizeAthenaTableOrderBy, normalizeGeneratorConfig, normalizeSchemaSelection, normalizeTableSelection, number, parseBooleanFlag2 as parseBooleanFlag, renderAthenaReactEmail, requireAffected, requireSuccess, resolveGeneratorProvider, resolvePostgresColumnType, resolveProviderSchemas, runSchemaGenerator, storageSdkManifest, string, table, toModelFormDefaults, toModelPayload, unwrap, unwrapChatMessage, unwrapChatRoom, unwrapOne, unwrapRows, verifyAthenaGatewayUrl, withRetry };
15691
+ export { ATHENA_AUTH_ADMIN_LIMITS, ATHENA_AUTH_BASE_ERROR_CODES, ATHENA_AUTH_MAX_ADMIN_JSON_BYTES, ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH, ATHENA_AUTH_MAX_TEMPLATE_VARIABLES, ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH, ATHENA_TABLE_SCHEMA_ROUTE, AthenaBillingError, AthenaChatError, AthenaConfigurationError, AthenaError, AthenaErrorCategory, AthenaErrorCode, AthenaErrorKind, AthenaGatewayError, AthenaStorageError, AthenaStorageErrorCode, Backend, DEFAULT_POSTGRES_SCHEMAS, applyAthenaReadQueryFilters, applyAthenaReadQuerySelectLimit, applyAthenaReadQuerySelectOrder, applyAthenaTableFilters, applyAthenaTableSelectLimit, applyAthenaTableSelectOrder, assertInt, athenaAuth, billingSdkManifest, boolean, buildAthenaReadQueryFindManyOrderBy, buildAthenaReadQueryFindManySelect, buildAthenaReadQueryFindManyWhere, buildAthenaReadQuerySelectString, buildAthenaTableCatalogQueries, buildAthenaTableFindManyOrderBy, buildAthenaTableFindManySelect, buildAthenaTableFindManyWhere, buildAthenaTableSelectString, chatSdkManifest, clampAthenaReadQueryTotalItems, clampAthenaTableTotalItems, coerceInt, createAthenaStorageError, createAthenaTableSchemaHandlers, createAuthReactEmailInput, createBillingModule, createClient, createModelFormAdapter, createPostgresIntrospectionProvider, defineAthenaAuthConfig, defineAuthEmailTemplate, defineDatabase, defineGeneratorConfig, defineModel, defineRegistry, defineSchema, enumeration, executeAthenaReadQuery, executeAthenaTableQuery, fetchAthenaTableCatalog, fetchTableCatalog, filterIntrospectionSnapshot, findGeneratorConfigPath, flattenAthenaReadQueryRows, flattenAthenaRows, generateArtifactsFromSnapshot, generatorEnv, getAthenaDebugAst, handleAthenaTableSchemaPost, hasAthenaTableSchemaCredentials, identifier, isAthenaGatewayError, isAthenaTableSchemaConfig, isOk, json, loadGeneratorConfig, normalizeAthenaError, normalizeAthenaGatewayBaseUrl, normalizeAthenaReadQueryOrderBy, normalizeAthenaTableOrderBy, normalizeGeneratorConfig, normalizeSchemaSelection, normalizeTableSelection, number, parseAthenaTableSchemaScope, parseBooleanFlag2 as parseBooleanFlag, renderAthenaReactEmail, requireAffected, requireSuccess, resolveAthenaReadQueryPageFetch, resolveGeneratorProvider, resolvePostgresColumnType, resolveProviderSchemas, runSchemaGenerator, storageSdkManifest, string, table, toModelFormDefaults, toModelPayload, unwrap, unwrapChatMessage, unwrapChatRoom, unwrapOne, unwrapRows, verifyAthenaGatewayUrl, withRetry };
12215
15692
  //# sourceMappingURL=browser.js.map
12216
15693
  //# sourceMappingURL=browser.js.map