@xylex-group/athena 3.3.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 (82) hide show
  1. package/README.md +17 -1
  2. package/dist/{athena-request-headers-Lr_m8xCV.d.cts → athena-request-headers-BnFN2mbd.d.cts} +1 -1
  3. package/dist/{athena-request-headers-DzimbvOA.d.ts → athena-request-headers-Dwdkq2WR.d.ts} +1 -1
  4. package/dist/billing.cjs +1 -1
  5. package/dist/billing.cjs.map +1 -1
  6. package/dist/billing.js +1 -1
  7. package/dist/billing.js.map +1 -1
  8. package/dist/browser.cjs +3064 -163
  9. package/dist/browser.cjs.map +1 -1
  10. package/dist/browser.d.cts +10 -10
  11. package/dist/browser.d.ts +10 -10
  12. package/dist/browser.js +3064 -163
  13. package/dist/browser.js.map +1 -1
  14. package/dist/cli/index.cjs +2990 -83
  15. package/dist/cli/index.cjs.map +1 -1
  16. package/dist/cli/index.d.cts +4 -4
  17. package/dist/cli/index.d.ts +4 -4
  18. package/dist/cli/index.js +2990 -83
  19. package/dist/cli/index.js.map +1 -1
  20. package/dist/cloudflare.cjs +12914 -0
  21. package/dist/cloudflare.cjs.map +1 -0
  22. package/dist/cloudflare.d.cts +368 -0
  23. package/dist/cloudflare.d.ts +368 -0
  24. package/dist/cloudflare.js +12885 -0
  25. package/dist/cloudflare.js.map +1 -0
  26. package/dist/cookies.cjs +4 -3
  27. package/dist/cookies.cjs.map +1 -1
  28. package/dist/cookies.js +4 -3
  29. package/dist/cookies.js.map +1 -1
  30. package/dist/env.cjs +1 -1
  31. package/dist/env.cjs.map +1 -1
  32. package/dist/env.js +1 -1
  33. package/dist/env.js.map +1 -1
  34. package/dist/index.cjs +2989 -86
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +10 -10
  37. package/dist/index.d.ts +10 -10
  38. package/dist/index.js +2989 -87
  39. package/dist/index.js.map +1 -1
  40. package/dist/{model-form-3Gr8rkdT.d.cts → model-form-D0ykVVOs.d.cts} +3 -3
  41. package/dist/{model-form-CotpEL7z.d.ts → model-form-U8NVtfSA.d.ts} +3 -3
  42. package/dist/{module-CQmOaDzP.d.cts → module-CMWlJ1z3.d.cts} +4 -4
  43. package/dist/{module-CWkUTcUc.d.ts → module-CZ-wPcf2.d.ts} +4 -4
  44. package/dist/next/client.cjs +3025 -125
  45. package/dist/next/client.cjs.map +1 -1
  46. package/dist/next/client.d.cts +4 -4
  47. package/dist/next/client.d.ts +4 -4
  48. package/dist/next/client.js +3025 -125
  49. package/dist/next/client.js.map +1 -1
  50. package/dist/next/server.cjs +3108 -194
  51. package/dist/next/server.cjs.map +1 -1
  52. package/dist/next/server.d.cts +22 -9
  53. package/dist/next/server.d.ts +22 -9
  54. package/dist/next/server.js +3108 -194
  55. package/dist/next/server.js.map +1 -1
  56. package/dist/{pipeline-BnRKO_Pd.d.cts → pipeline-BCpb4BX1.d.cts} +1 -1
  57. package/dist/{pipeline-sWCmlFqu.d.ts → pipeline-CgmXwMeX.d.ts} +1 -1
  58. package/dist/react.cjs +1 -1
  59. package/dist/react.cjs.map +1 -1
  60. package/dist/react.d.cts +6 -6
  61. package/dist/react.d.ts +6 -6
  62. package/dist/react.js +1 -1
  63. package/dist/react.js.map +1 -1
  64. package/dist/{schema-handlers-VjFDhIMw.d.ts → schema-handlers-CvWqF-dW.d.ts} +1 -1
  65. package/dist/{schema-handlers-BtT_IQFi.d.cts → schema-handlers-Dr8h9Jg-.d.cts} +1 -1
  66. package/dist/social-providers.cjs +1 -1
  67. package/dist/social-providers.cjs.map +1 -1
  68. package/dist/social-providers.js +1 -1
  69. package/dist/social-providers.js.map +1 -1
  70. package/dist/{types-Bltx6iL6.d.cts → types-B2RZPivM.d.cts} +8 -1
  71. package/dist/{types-Bltx6iL6.d.ts → types-B2RZPivM.d.ts} +8 -1
  72. package/dist/{types-BDX8zS7w.d.ts → types-BKklrX4J.d.ts} +2 -2
  73. package/dist/{types-CgCv5o6R.d.cts → types-D5dj1v5Z.d.cts} +1 -1
  74. package/dist/{types-D-Am7YSd.d.cts → types-DqBFwfhn.d.cts} +2 -2
  75. package/dist/{types-B75PdABb.d.ts → types-S-bTMPiM.d.ts} +1 -1
  76. package/dist/utils.cjs.map +1 -1
  77. package/dist/utils.d.cts +2 -2
  78. package/dist/utils.d.ts +2 -2
  79. package/dist/utils.js.map +1 -1
  80. package/dist/{v3-client-G1SLeHRa.d.cts → v3-client-DP-qg82X.d.cts} +300 -4
  81. package/dist/{v3-client-ao8BWQ8v.d.ts → v3-client-OAai_JNs.d.ts} +300 -4
  82. package/package.json +10 -3
@@ -17,6 +17,20 @@ function mergeAthenaRequestContexts(base, override) {
17
17
  };
18
18
  }
19
19
 
20
+ // src/node-env.ts
21
+ function getProcess() {
22
+ return globalThis.process;
23
+ }
24
+ function getProcessEnv() {
25
+ return getProcess()?.env;
26
+ }
27
+ function getNodeEnv() {
28
+ return getProcessEnv()?.NODE_ENV;
29
+ }
30
+ function isNodeProductionEnv() {
31
+ return getNodeEnv() === "production";
32
+ }
33
+
20
34
  // src/gateway/errors.ts
21
35
  var AthenaGatewayError = class _AthenaGatewayError extends Error {
22
36
  code;
@@ -1636,6 +1650,8 @@ function buildUpdateDebugSql(payload) {
1636
1650
  sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
1637
1651
  }
1638
1652
  const pagination = resolvePagination({
1653
+ limit: payload.limit,
1654
+ offset: payload.offset,
1639
1655
  currentPage: payload.current_page,
1640
1656
  pageSize: payload.page_size
1641
1657
  });
@@ -1658,6 +1674,8 @@ function buildDeleteDebugSql(payload) {
1658
1674
  sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
1659
1675
  }
1660
1676
  const pagination = resolvePagination({
1677
+ limit: payload.limit,
1678
+ offset: payload.offset,
1661
1679
  currentPage: payload.current_page,
1662
1680
  pageSize: payload.page_size
1663
1681
  });
@@ -1801,7 +1819,7 @@ function buildAthenaGatewayUrl(baseUrl, path) {
1801
1819
 
1802
1820
  // package.json
1803
1821
  var package_default = {
1804
- version: "3.3.0"
1822
+ version: "3.5.1"
1805
1823
  };
1806
1824
 
1807
1825
  // src/sdk-version.ts
@@ -5016,9 +5034,9 @@ function readHeadersField(value) {
5016
5034
  const headers = value.headers;
5017
5035
  if (!isRecord8(headers)) return {};
5018
5036
  const result = {};
5019
- for (const [key, headerValue2] of Object.entries(headers)) {
5020
- if (typeof headerValue2 === "string") {
5021
- result[key] = headerValue2;
5037
+ for (const [key, headerValue3] of Object.entries(headers)) {
5038
+ if (typeof headerValue3 === "string") {
5039
+ result[key] = headerValue3;
5022
5040
  }
5023
5041
  }
5024
5042
  return result;
@@ -8643,6 +8661,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, beha
8643
8661
  strip_nulls: mergedOptions?.stripNulls ?? true
8644
8662
  };
8645
8663
  if (executionState.order) payload.sort_by = executionState.order;
8664
+ if (executionState.limit !== void 0) payload.limit = executionState.limit;
8665
+ if (executionState.offset !== void 0) payload.offset = executionState.offset;
8646
8666
  if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
8647
8667
  if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
8648
8668
  if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
@@ -8697,6 +8717,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, beha
8697
8717
  conditions: filters
8698
8718
  };
8699
8719
  if (executionState.order) payload.sort_by = executionState.order;
8720
+ if (executionState.limit !== void 0) payload.limit = executionState.limit;
8721
+ if (executionState.offset !== void 0) payload.offset = executionState.offset;
8700
8722
  if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
8701
8723
  if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
8702
8724
  if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
@@ -8748,7 +8770,11 @@ function createQueryBuilder(client, formatGatewayResult, behavior, tracer) {
8748
8770
  if (!normalizedQuery) {
8749
8771
  throw new Error("query requires a non-empty string");
8750
8772
  }
8751
- const payload = { query: normalizedQuery };
8773
+ const params = options?.params;
8774
+ const payload = {
8775
+ query: normalizedQuery,
8776
+ ...Array.isArray(params) ? { params } : {}
8777
+ };
8752
8778
  const callsite = captureTraceCallsite(tracer);
8753
8779
  return executeRead(
8754
8780
  behavior,
@@ -8797,7 +8823,7 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8797
8823
  }
8798
8824
  function createInternalClientCore(config) {
8799
8825
  const normalizedAuthConfig = normalizeAuthClientConfig(config.auth, config.authUrl);
8800
- const gatewayTransport = createAthenaGatewayClient({
8826
+ const gatewayTransport = config.gatewayTransport ?? createAthenaGatewayClient({
8801
8827
  baseUrl: config.baseUrl,
8802
8828
  apiKey: config.apiKey,
8803
8829
  client: config.client ?? void 0,
@@ -8952,174 +8978,2812 @@ function createInternalClientView(core, resolveContext) {
8952
8978
  };
8953
8979
  }
8954
8980
 
8955
- // src/billing/module.ts
8956
- var SDK_NAME5 = "xylex-group/athena-billing";
8957
- var SDK_HEADER_VALUE4 = buildSdkHeaderValue(SDK_NAME5);
8958
- var AthenaBillingError = class extends Error {
8959
- status;
8960
- endpoint;
8961
- method;
8962
- body;
8963
- constructor(input) {
8964
- super(input.message);
8965
- this.name = "AthenaBillingError";
8966
- this.status = input.status;
8967
- this.endpoint = input.endpoint;
8968
- this.method = input.method;
8969
- this.body = input.body;
8970
- }
8971
- };
8972
- function withPathParam2(path, name, value) {
8973
- return path.replace(`{${name}}`, encodeURIComponent(value));
8974
- }
8975
- function appendQuery3(path, query) {
8976
- if (!query) return path;
8977
- const params = new URLSearchParams();
8978
- for (const [key, value] of Object.entries(query)) {
8979
- if (value === void 0 || value === null) continue;
8980
- params.set(key, String(value));
8981
- }
8982
- const serialized = params.toString();
8983
- return serialized ? `${path}?${serialized}` : path;
8981
+ // src/cloudflare/types.ts
8982
+ var CLOUDFLARE_EDGE_BASE_URL = "https://athena.local/cloudflare-edge";
8983
+ var CLOUDFLARE_EDGE_API_KEY = "cloudflare-edge-local";
8984
+
8985
+ // src/cloudflare/capabilities.ts
8986
+ function createGatewayCapabilities(options) {
8987
+ const storageConfigured = options?.storageConfigured ?? true;
8988
+ return {
8989
+ mode: "gateway",
8990
+ db: {
8991
+ engine: options?.engine ?? "postgresql",
8992
+ local: false,
8993
+ layers: {
8994
+ query: true,
8995
+ flatCrud: true,
8996
+ findManyAst: true,
8997
+ rpc: true,
8998
+ relations: true
8999
+ }
9000
+ },
9001
+ storage: {
9002
+ local: false,
9003
+ objects: storageConfigured,
9004
+ catalogs: storageConfigured ? options?.storageCatalogs ?? true : false,
9005
+ backups: storageConfigured ? options?.storageBackups ?? true : false
9006
+ },
9007
+ auth: {
9008
+ remote: options?.authRemote ?? true
9009
+ }
9010
+ };
8984
9011
  }
8985
- function connectionQuery(input) {
8986
- const query = {
8987
- connectionId: input.connectionId
9012
+ function createCloudflareEdgeCapabilities(options) {
9013
+ const hasObjects = options.hasR2 || Boolean(options.hasRemoteStorage);
9014
+ return {
9015
+ mode: "cloudflare-edge",
9016
+ db: {
9017
+ engine: "cloudflare-d1",
9018
+ local: true,
9019
+ layers: {
9020
+ query: true,
9021
+ flatCrud: true,
9022
+ findManyAst: options.findManyAst ?? false,
9023
+ rpc: false,
9024
+ relations: false
9025
+ }
9026
+ },
9027
+ storage: {
9028
+ // Local objects only when an R2 binding is present.
9029
+ local: options.hasR2,
9030
+ // Remote hybrid root can still expose storage.objects via the HTTP API.
9031
+ objects: hasObjects,
9032
+ catalogs: false,
9033
+ backups: false
9034
+ },
9035
+ auth: {
9036
+ remote: options.authRemote
9037
+ }
8988
9038
  };
8989
- if (input.clientName) query.clientName = input.clientName;
8990
- if ("cursor" in input && input.cursor) query.cursor = input.cursor;
8991
- if ("source" in input && input.source) query.source = input.source;
8992
- if ("limit" in input && input.limit !== void 0) query.limit = String(input.limit);
8993
- if ("offset" in input && input.offset !== void 0) query.offset = String(input.offset);
8994
- return query;
8995
9039
  }
8996
- function parseEnvelopeData(body) {
8997
- if (body && typeof body === "object" && "data" in body) {
8998
- return body.data;
9040
+
9041
+ // src/cloudflare/d1/runner.ts
9042
+ function resultColumns(rows) {
9043
+ const first = rows.find((value) => value && typeof value === "object" && !Array.isArray(value));
9044
+ if (!first) return [];
9045
+ return Object.keys(first);
9046
+ }
9047
+ function isIdentChar(ch) {
9048
+ if (!ch) return false;
9049
+ return /[A-Za-z0-9_]/.test(ch);
9050
+ }
9051
+ function scanSqlKeywordsOutsideLiterals(sql, onKeyword) {
9052
+ let inSingle = false;
9053
+ let inDouble = false;
9054
+ let inBacktick = false;
9055
+ let inBracket = false;
9056
+ let inLineComment = false;
9057
+ let inBlockComment = false;
9058
+ for (let i = 0; i < sql.length; i += 1) {
9059
+ const ch = sql[i];
9060
+ const next = sql[i + 1];
9061
+ if (inLineComment) {
9062
+ if (ch === "\n" || ch === "\r") inLineComment = false;
9063
+ continue;
9064
+ }
9065
+ if (inBlockComment) {
9066
+ if (ch === "*" && next === "/") {
9067
+ i += 1;
9068
+ inBlockComment = false;
9069
+ }
9070
+ continue;
9071
+ }
9072
+ if (inSingle) {
9073
+ if (ch === "'" && next === "'") {
9074
+ i += 1;
9075
+ continue;
9076
+ }
9077
+ if (ch === "'") inSingle = false;
9078
+ continue;
9079
+ }
9080
+ if (inDouble) {
9081
+ if (ch === '"' && next === '"') {
9082
+ i += 1;
9083
+ continue;
9084
+ }
9085
+ if (ch === '"') inDouble = false;
9086
+ continue;
9087
+ }
9088
+ if (inBacktick) {
9089
+ if (ch === "`" && next === "`") {
9090
+ i += 1;
9091
+ continue;
9092
+ }
9093
+ if (ch === "`") inBacktick = false;
9094
+ continue;
9095
+ }
9096
+ if (inBracket) {
9097
+ if (ch === "]") inBracket = false;
9098
+ continue;
9099
+ }
9100
+ if (ch === "-" && next === "-") {
9101
+ inLineComment = true;
9102
+ i += 1;
9103
+ continue;
9104
+ }
9105
+ if (ch === "/" && next === "*") {
9106
+ inBlockComment = true;
9107
+ i += 1;
9108
+ continue;
9109
+ }
9110
+ if (ch === "'") {
9111
+ inSingle = true;
9112
+ continue;
9113
+ }
9114
+ if (ch === '"') {
9115
+ inDouble = true;
9116
+ continue;
9117
+ }
9118
+ if (ch === "`") {
9119
+ inBacktick = true;
9120
+ continue;
9121
+ }
9122
+ if (ch === "[") {
9123
+ inBracket = true;
9124
+ continue;
9125
+ }
9126
+ if (!isIdentChar(ch) || isIdentChar(sql[i - 1])) {
9127
+ continue;
9128
+ }
9129
+ let end = i + 1;
9130
+ while (end < sql.length && isIdentChar(sql[end])) {
9131
+ end += 1;
9132
+ }
9133
+ const keyword = sql.slice(i, end);
9134
+ if (onKeyword(keyword, i)) {
9135
+ return;
9136
+ }
9137
+ i = end - 1;
8999
9138
  }
9000
- return body;
9001
9139
  }
9002
- function createBillingModule(config) {
9003
- const baseUrl = normalizeAthenaGatewayBaseUrl(config.baseUrl, {
9004
- label: "Athena billing base URL"
9140
+ function sqlContainsKeywordOutsideLiterals(sql, keyword) {
9141
+ const target = keyword.toUpperCase();
9142
+ let found = false;
9143
+ scanSqlKeywordsOutsideLiterals(sql, (token) => {
9144
+ if (token.toUpperCase() === target) {
9145
+ found = true;
9146
+ return true;
9147
+ }
9148
+ return false;
9005
9149
  });
9006
- const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
9007
- async function call(method, path, body, options, responseType = "json") {
9008
- const headers = buildAthenaRequestHeaders({
9009
- profile: "gateway",
9010
- sdkHeaderValue: SDK_HEADER_VALUE4,
9011
- apiKey: options?.apiKey ?? config.apiKey,
9012
- client: config.client,
9013
- configHeaders: {
9014
- ...config.headers ?? {}
9015
- },
9016
- callHeaders: options?.headers,
9017
- contentType: "application/json"
9018
- });
9019
- let requestBody;
9020
- if (body !== void 0 && body !== null) {
9021
- if (typeof body === "string" || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof FormData || body instanceof URLSearchParams) {
9022
- requestBody = body;
9023
- } else {
9024
- requestBody = JSON.stringify(body);
9025
- if (!hasHeaderIgnoreCase(headers, "Content-Type")) {
9026
- headers["Content-Type"] = "application/json";
9027
- }
9150
+ return found;
9151
+ }
9152
+ function sqlFirstKeywordOutsideLiterals(sql) {
9153
+ let first = null;
9154
+ scanSqlKeywordsOutsideLiterals(sql, (token) => {
9155
+ first = token;
9156
+ return true;
9157
+ });
9158
+ return first;
9159
+ }
9160
+ var ROW_PRODUCING_LEAD_KEYWORDS = /* @__PURE__ */ new Set(["SELECT", "PRAGMA", "EXPLAIN", "VALUES"]);
9161
+ var MUTATION_LEAD_KEYWORDS = /* @__PURE__ */ new Set(["INSERT", "UPDATE", "DELETE", "REPLACE"]);
9162
+ var WITH_TERMINAL_KEYWORDS = /* @__PURE__ */ new Set([
9163
+ "SELECT",
9164
+ "INSERT",
9165
+ "UPDATE",
9166
+ "DELETE",
9167
+ "REPLACE",
9168
+ "VALUES",
9169
+ "PRAGMA",
9170
+ "EXPLAIN"
9171
+ ]);
9172
+ function sqlTerminalKeywordAfterWith(sql) {
9173
+ let inSingle = false;
9174
+ let inDouble = false;
9175
+ let inBacktick = false;
9176
+ let inBracket = false;
9177
+ let inLineComment = false;
9178
+ let inBlockComment = false;
9179
+ let depth = 0;
9180
+ let sawWith = false;
9181
+ for (let i = 0; i < sql.length; i += 1) {
9182
+ const ch = sql[i];
9183
+ const next = sql[i + 1];
9184
+ if (inLineComment) {
9185
+ if (ch === "\n" || ch === "\r") inLineComment = false;
9186
+ continue;
9187
+ }
9188
+ if (inBlockComment) {
9189
+ if (ch === "*" && next === "/") {
9190
+ i += 1;
9191
+ inBlockComment = false;
9028
9192
  }
9193
+ continue;
9029
9194
  }
9030
- const targetUrl = `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
9031
- const response = await fetchImpl(targetUrl, {
9032
- method,
9033
- headers,
9034
- body: requestBody,
9035
- signal: options?.signal
9036
- });
9037
- if (responseType === "text") {
9038
- const text = await response.text();
9039
- if (!response.ok) {
9040
- throw new AthenaBillingError({
9041
- message: `Billing request failed (${response.status})`,
9042
- status: response.status,
9043
- endpoint: path,
9044
- method,
9045
- body: text
9046
- });
9195
+ if (inSingle) {
9196
+ if (ch === "'" && next === "'") {
9197
+ i += 1;
9198
+ continue;
9047
9199
  }
9048
- return text;
9200
+ if (ch === "'") inSingle = false;
9201
+ continue;
9049
9202
  }
9050
- const rawText = await response.text();
9051
- let parsed = rawText;
9052
- if (rawText) {
9053
- try {
9054
- parsed = JSON.parse(rawText);
9055
- } catch {
9056
- parsed = rawText;
9203
+ if (inDouble) {
9204
+ if (ch === '"' && next === '"') {
9205
+ i += 1;
9206
+ continue;
9057
9207
  }
9058
- } else {
9059
- parsed = null;
9208
+ if (ch === '"') inDouble = false;
9209
+ continue;
9060
9210
  }
9061
- if (!response.ok) {
9062
- const message = parsed && typeof parsed === "object" && "message" in parsed && typeof parsed.message === "string" ? parsed.message : `Billing request failed (${response.status})`;
9063
- throw new AthenaBillingError({
9064
- message,
9065
- status: response.status,
9066
- endpoint: path,
9067
- method,
9068
- body: parsed
9069
- });
9211
+ if (inBacktick) {
9212
+ if (ch === "`" && next === "`") {
9213
+ i += 1;
9214
+ continue;
9215
+ }
9216
+ if (ch === "`") inBacktick = false;
9217
+ continue;
9070
9218
  }
9071
- return parseEnvelopeData(parsed);
9219
+ if (inBracket) {
9220
+ if (ch === "]") inBracket = false;
9221
+ continue;
9222
+ }
9223
+ if (ch === "-" && next === "-") {
9224
+ inLineComment = true;
9225
+ i += 1;
9226
+ continue;
9227
+ }
9228
+ if (ch === "/" && next === "*") {
9229
+ inBlockComment = true;
9230
+ i += 1;
9231
+ continue;
9232
+ }
9233
+ if (ch === "'") {
9234
+ inSingle = true;
9235
+ continue;
9236
+ }
9237
+ if (ch === '"') {
9238
+ inDouble = true;
9239
+ continue;
9240
+ }
9241
+ if (ch === "`") {
9242
+ inBacktick = true;
9243
+ continue;
9244
+ }
9245
+ if (ch === "[") {
9246
+ inBracket = true;
9247
+ continue;
9248
+ }
9249
+ if (ch === "(") {
9250
+ depth += 1;
9251
+ continue;
9252
+ }
9253
+ if (ch === ")") {
9254
+ if (depth > 0) depth -= 1;
9255
+ continue;
9256
+ }
9257
+ if (depth !== 0 || !isIdentChar(ch) || isIdentChar(sql[i - 1])) {
9258
+ continue;
9259
+ }
9260
+ let end = i + 1;
9261
+ while (end < sql.length && isIdentChar(sql[end])) {
9262
+ end += 1;
9263
+ }
9264
+ const keyword = sql.slice(i, end);
9265
+ const upper = keyword.toUpperCase();
9266
+ if (!sawWith) {
9267
+ if (upper === "WITH") {
9268
+ sawWith = true;
9269
+ }
9270
+ i = end - 1;
9271
+ continue;
9272
+ }
9273
+ if (WITH_TERMINAL_KEYWORDS.has(upper)) {
9274
+ return keyword;
9275
+ }
9276
+ i = end - 1;
9072
9277
  }
9073
- return {
9074
- getCapabilities(input, options) {
9075
- return call(
9076
- "GET",
9077
- appendQuery3("/billing/v1/capabilities", connectionQuery(input)),
9078
- void 0,
9079
- options
9080
- );
9081
- },
9082
- createCheckout(body, options) {
9083
- return call("POST", "/billing/v1/checkouts", body, options);
9084
- },
9085
- listProducts(input, options) {
9086
- return call(
9087
- "GET",
9088
- appendQuery3("/billing/v1/products", connectionQuery(input)),
9089
- void 0,
9090
- options
9091
- );
9092
- },
9093
- listPrices(input, options) {
9094
- return call(
9095
- "GET",
9096
- appendQuery3("/billing/v1/prices", {
9097
- ...connectionQuery(input),
9098
- ...input.productId ? { productId: input.productId } : {}
9099
- }),
9100
- void 0,
9101
- options
9102
- );
9103
- },
9104
- listCustomers(input, options) {
9105
- return call(
9106
- "GET",
9107
- appendQuery3("/billing/v1/customers", connectionQuery(input)),
9108
- void 0,
9109
- options
9110
- );
9111
- },
9112
- createCustomer(input, options) {
9113
- return call(
9114
- "POST",
9115
- "/billing/v1/customers",
9116
- {
9117
- connectionId: input.connectionId,
9118
- clientName: input.clientName,
9119
- email: input.email,
9120
- name: input.name,
9121
- metadata: input.metadata ?? {},
9122
- idempotencyKey: input.idempotencyKey
9278
+ return null;
9279
+ }
9280
+ function sqlLeadStatementKeyword(sql) {
9281
+ const first = sqlFirstKeywordOutsideLiterals(sql);
9282
+ if (!first) return null;
9283
+ if (first.toUpperCase() !== "WITH") return first;
9284
+ return sqlTerminalKeywordAfterWith(sql) ?? first;
9285
+ }
9286
+ function statementExpectsResultRows(sql) {
9287
+ const lead = sqlLeadStatementKeyword(sql);
9288
+ if (lead) {
9289
+ const upper = lead.toUpperCase();
9290
+ if (ROW_PRODUCING_LEAD_KEYWORDS.has(upper)) {
9291
+ return true;
9292
+ }
9293
+ if (MUTATION_LEAD_KEYWORDS.has(upper)) {
9294
+ return sqlContainsKeywordOutsideLiterals(sql, "RETURNING");
9295
+ }
9296
+ }
9297
+ return sqlContainsKeywordOutsideLiterals(sql, "RETURNING");
9298
+ }
9299
+ function collectRowsFromBatchResults(results) {
9300
+ const rows = [];
9301
+ for (const item of results) {
9302
+ if (Array.isArray(item.results) && item.results.length > 0) {
9303
+ rows.push(...item.results);
9304
+ }
9305
+ }
9306
+ return rows;
9307
+ }
9308
+ function sumBatchAffectedRows(results, statementCount) {
9309
+ let sum2 = 0;
9310
+ let sawChanges = false;
9311
+ for (const item of results) {
9312
+ const changes = item.meta?.changes;
9313
+ if (typeof changes === "number") {
9314
+ sum2 += changes;
9315
+ sawChanges = true;
9316
+ }
9317
+ }
9318
+ return sawChanges ? sum2 : statementCount;
9319
+ }
9320
+ function matchSqlKeywordAt(query, index, keyword) {
9321
+ const len = keyword.length;
9322
+ if (index + len > query.length) {
9323
+ return null;
9324
+ }
9325
+ const slice = query.slice(index, index + len);
9326
+ if (slice.toLowerCase() !== keyword.toLowerCase()) {
9327
+ return null;
9328
+ }
9329
+ const before = index === 0 ? "" : query[index - 1];
9330
+ const after = index + len >= query.length ? "" : query[index + len];
9331
+ const isIdent = (c) => /[A-Za-z0-9_]/.test(c);
9332
+ if (before && isIdent(before)) {
9333
+ return null;
9334
+ }
9335
+ if (after && isIdent(after)) {
9336
+ return null;
9337
+ }
9338
+ return len;
9339
+ }
9340
+ function splitSqlStatements(query) {
9341
+ const statements = [];
9342
+ let inSingle = false;
9343
+ let inDouble = false;
9344
+ let inBacktick = false;
9345
+ let inBracket = false;
9346
+ let inLineComment = false;
9347
+ let inBlockComment = false;
9348
+ let segmentStart = 0;
9349
+ let segmentHasContent = false;
9350
+ let awaitTriggerBegin = false;
9351
+ let triggerBodyDepth = 0;
9352
+ let caseDepth = 0;
9353
+ const flushSegment = (end) => {
9354
+ if (!segmentHasContent) {
9355
+ segmentStart = end + 1;
9356
+ return;
9357
+ }
9358
+ const sql = query.slice(segmentStart, end).trim();
9359
+ if (sql) {
9360
+ statements.push(sql);
9361
+ }
9362
+ segmentHasContent = false;
9363
+ segmentStart = end + 1;
9364
+ awaitTriggerBegin = false;
9365
+ triggerBodyDepth = 0;
9366
+ caseDepth = 0;
9367
+ };
9368
+ for (let i = 0; i < query.length; i += 1) {
9369
+ const ch = query[i];
9370
+ const next = query[i + 1];
9371
+ if (inLineComment) {
9372
+ if (ch === "\n" || ch === "\r") {
9373
+ inLineComment = false;
9374
+ }
9375
+ continue;
9376
+ }
9377
+ if (inBlockComment) {
9378
+ if (ch === "*" && next === "/") {
9379
+ inBlockComment = false;
9380
+ i += 1;
9381
+ }
9382
+ continue;
9383
+ }
9384
+ if (inSingle) {
9385
+ if (ch === "'" && next === "'") {
9386
+ i += 1;
9387
+ continue;
9388
+ }
9389
+ if (ch === "'") {
9390
+ inSingle = false;
9391
+ }
9392
+ continue;
9393
+ }
9394
+ if (inDouble) {
9395
+ if (ch === '"' && next === '"') {
9396
+ i += 1;
9397
+ continue;
9398
+ }
9399
+ if (ch === '"') {
9400
+ inDouble = false;
9401
+ }
9402
+ continue;
9403
+ }
9404
+ if (inBacktick) {
9405
+ if (ch === "`" && next === "`") {
9406
+ i += 1;
9407
+ continue;
9408
+ }
9409
+ if (ch === "`") {
9410
+ inBacktick = false;
9411
+ }
9412
+ continue;
9413
+ }
9414
+ if (inBracket) {
9415
+ if (ch === "]") {
9416
+ inBracket = false;
9417
+ }
9418
+ continue;
9419
+ }
9420
+ if (ch === "-" && next === "-") {
9421
+ inLineComment = true;
9422
+ i += 1;
9423
+ continue;
9424
+ }
9425
+ if (ch === "/" && next === "*") {
9426
+ inBlockComment = true;
9427
+ i += 1;
9428
+ continue;
9429
+ }
9430
+ if (ch === "'") {
9431
+ inSingle = true;
9432
+ segmentHasContent = true;
9433
+ continue;
9434
+ }
9435
+ if (ch === '"') {
9436
+ inDouble = true;
9437
+ segmentHasContent = true;
9438
+ continue;
9439
+ }
9440
+ if (ch === "`") {
9441
+ inBacktick = true;
9442
+ segmentHasContent = true;
9443
+ continue;
9444
+ }
9445
+ if (ch === "[") {
9446
+ inBracket = true;
9447
+ segmentHasContent = true;
9448
+ continue;
9449
+ }
9450
+ if (/[A-Za-z_]/.test(ch)) {
9451
+ const createLen = matchSqlKeywordAt(query, i, "CREATE");
9452
+ if (createLen != null) {
9453
+ let j2 = i + createLen;
9454
+ const skipWsAndComments = () => {
9455
+ while (j2 < query.length) {
9456
+ const c = query[j2];
9457
+ const n = query[j2 + 1];
9458
+ if (/\s/.test(c)) {
9459
+ j2 += 1;
9460
+ continue;
9461
+ }
9462
+ if (c === "-" && n === "-") {
9463
+ j2 += 2;
9464
+ while (j2 < query.length && query[j2] !== "\n" && query[j2] !== "\r") {
9465
+ j2 += 1;
9466
+ }
9467
+ continue;
9468
+ }
9469
+ if (c === "/" && n === "*") {
9470
+ j2 += 2;
9471
+ while (j2 < query.length) {
9472
+ if (query[j2] === "*" && query[j2 + 1] === "/") {
9473
+ j2 += 2;
9474
+ break;
9475
+ }
9476
+ j2 += 1;
9477
+ }
9478
+ continue;
9479
+ }
9480
+ break;
9481
+ }
9482
+ };
9483
+ skipWsAndComments();
9484
+ const tempLen = matchSqlKeywordAt(query, j2, "TEMPORARY") ?? matchSqlKeywordAt(query, j2, "TEMP");
9485
+ if (tempLen != null) {
9486
+ j2 += tempLen;
9487
+ skipWsAndComments();
9488
+ }
9489
+ const triggerLen = matchSqlKeywordAt(query, j2, "TRIGGER");
9490
+ if (triggerLen != null) {
9491
+ awaitTriggerBegin = true;
9492
+ segmentHasContent = true;
9493
+ i += createLen - 1;
9494
+ continue;
9495
+ }
9496
+ segmentHasContent = true;
9497
+ i += createLen - 1;
9498
+ continue;
9499
+ }
9500
+ const caseLen = matchSqlKeywordAt(query, i, "CASE");
9501
+ if (caseLen != null) {
9502
+ caseDepth += 1;
9503
+ segmentHasContent = true;
9504
+ i += caseLen - 1;
9505
+ continue;
9506
+ }
9507
+ const beginLen = matchSqlKeywordAt(query, i, "BEGIN");
9508
+ if (beginLen != null) {
9509
+ if (awaitTriggerBegin) {
9510
+ triggerBodyDepth += 1;
9511
+ awaitTriggerBegin = false;
9512
+ }
9513
+ segmentHasContent = true;
9514
+ i += beginLen - 1;
9515
+ continue;
9516
+ }
9517
+ const endLen = matchSqlKeywordAt(query, i, "END");
9518
+ if (endLen != null) {
9519
+ if (caseDepth > 0) {
9520
+ caseDepth -= 1;
9521
+ } else if (triggerBodyDepth > 0) {
9522
+ triggerBodyDepth -= 1;
9523
+ }
9524
+ segmentHasContent = true;
9525
+ i += endLen - 1;
9526
+ continue;
9527
+ }
9528
+ let j = i + 1;
9529
+ while (j < query.length && /[A-Za-z0-9_]/.test(query[j])) {
9530
+ j += 1;
9531
+ }
9532
+ segmentHasContent = true;
9533
+ i = j - 1;
9534
+ continue;
9535
+ }
9536
+ if (ch === ";") {
9537
+ if (triggerBodyDepth > 0 || caseDepth > 0) {
9538
+ segmentHasContent = true;
9539
+ continue;
9540
+ }
9541
+ flushSegment(i);
9542
+ continue;
9543
+ }
9544
+ if (!/\s/.test(ch)) {
9545
+ segmentHasContent = true;
9546
+ }
9547
+ }
9548
+ flushSegment(query.length);
9549
+ return statements;
9550
+ }
9551
+ function isMultiStatement(query) {
9552
+ return splitSqlStatements(query).length > 1;
9553
+ }
9554
+ function resolveSessionTarget(db, input) {
9555
+ const sessionValue = input.bookmark?.trim() || input.sessionMode?.trim();
9556
+ if (!sessionValue) {
9557
+ return { target: db, session: null };
9558
+ }
9559
+ if (typeof db.withSession !== "function") {
9560
+ throw new Error("D1 session mode/bookmark requested but withSession is not available");
9561
+ }
9562
+ const session = db.withSession(sessionValue);
9563
+ return { target: session, session };
9564
+ }
9565
+ function normalizeD1BindParams(params) {
9566
+ return params.map((value) => {
9567
+ if (typeof value === "boolean") {
9568
+ return value ? 1 : 0;
9569
+ }
9570
+ return value;
9571
+ });
9572
+ }
9573
+ async function executeD1Query(db, input) {
9574
+ const query = input.query?.trim();
9575
+ if (!query) {
9576
+ return { ok: false, error: "invalid_query", message: "query is required" };
9577
+ }
9578
+ const params = normalizeD1BindParams(Array.isArray(input.params) ? input.params : []);
9579
+ const { target, session } = resolveSessionTarget(db, input);
9580
+ if (isMultiStatement(query)) {
9581
+ if (params.length > 0) {
9582
+ return {
9583
+ ok: false,
9584
+ error: "invalid_query",
9585
+ message: "params are only supported for single prepared statements"
9586
+ };
9587
+ }
9588
+ const resolveBookmark = () => session?.getBookmark() ?? null;
9589
+ const parts = splitSqlStatements(query);
9590
+ if (typeof target.batch === "function") {
9591
+ const prepared = parts.map((part) => target.prepare(part));
9592
+ const results = await target.batch(prepared);
9593
+ const rows2 = collectRowsFromBatchResults(results);
9594
+ return {
9595
+ ok: true,
9596
+ rows: rows2,
9597
+ columns: resultColumns(rows2),
9598
+ // Prefer returned rows; otherwise sum mutation meta.changes (not statement count).
9599
+ count: rows2.length > 0 ? rows2.length : sumBatchAffectedRows(results, parts.length),
9600
+ bookmark: resolveBookmark(),
9601
+ meta: { statementCount: parts.length, results },
9602
+ statementCount: parts.length
9603
+ };
9604
+ }
9605
+ const canExec = typeof target.exec === "function" && !session;
9606
+ if (canExec) {
9607
+ const execResult = await target.exec(query);
9608
+ return {
9609
+ ok: true,
9610
+ rows: [],
9611
+ columns: [],
9612
+ durationMs: execResult.duration,
9613
+ count: execResult.count,
9614
+ bookmark: resolveBookmark(),
9615
+ meta: { statementCount: execResult.count },
9616
+ statementCount: execResult.count
9617
+ };
9618
+ }
9619
+ return {
9620
+ ok: false,
9621
+ error: "invalid_query",
9622
+ message: "multi-statement query requires D1 batch() or exec() support"
9623
+ };
9624
+ }
9625
+ let statement = target.prepare(query);
9626
+ if (params.length > 0) {
9627
+ statement = statement.bind(...params);
9628
+ }
9629
+ const expectsRows = statementExpectsResultRows(query);
9630
+ const result = expectsRows ? await statement.all() : await statement.run();
9631
+ if (result.success === false) {
9632
+ const errorField = result.error;
9633
+ const message = typeof errorField === "string" && errorField.trim() ? errorField : "D1 query failed";
9634
+ return {
9635
+ ok: false,
9636
+ error: "query_failed",
9637
+ message
9638
+ };
9639
+ }
9640
+ const rows = Array.isArray(result.results) ? result.results : [];
9641
+ const bookmark = session?.getBookmark() ?? null;
9642
+ const meta = result.meta ?? {};
9643
+ const changes = typeof meta.changes === "number" ? meta.changes : typeof result.meta?.changes === "number" ? result.meta.changes : void 0;
9644
+ return {
9645
+ ok: true,
9646
+ rows,
9647
+ columns: resultColumns(rows),
9648
+ durationMs: typeof result.meta?.duration === "number" ? result.meta.duration : void 0,
9649
+ count: expectsRows ? rows.length : changes ?? rows.length,
9650
+ bookmark,
9651
+ meta
9652
+ };
9653
+ }
9654
+ async function executeD1Batch(db, input) {
9655
+ const statements = Array.isArray(input.statements) ? input.statements : [];
9656
+ if (statements.length === 0) {
9657
+ return {
9658
+ ok: false,
9659
+ error: "invalid_batch",
9660
+ message: "statements must contain at least one item"
9661
+ };
9662
+ }
9663
+ const { target, session } = resolveSessionTarget(db, input);
9664
+ const prepared = statements.map((item) => {
9665
+ const query = item.query?.trim();
9666
+ if (!query) {
9667
+ throw new Error("statements[].query is required");
9668
+ }
9669
+ const params = normalizeD1BindParams(Array.isArray(item.params) ? item.params : []);
9670
+ let statement = target.prepare(query);
9671
+ if (params.length > 0) {
9672
+ statement = statement.bind(...params);
9673
+ }
9674
+ return statement;
9675
+ });
9676
+ const results = await target.batch(prepared);
9677
+ const bookmark = session?.getBookmark() ?? null;
9678
+ return {
9679
+ ok: true,
9680
+ results,
9681
+ bookmark
9682
+ };
9683
+ }
9684
+
9685
+ // src/cloudflare/d1/sql.ts
9686
+ function asSingle(sql, params) {
9687
+ return { sql, params };
9688
+ }
9689
+ function asBatch(statements) {
9690
+ if (statements.length === 0) {
9691
+ throw new D1SqlCompileError("empty_insert", "batch requires at least one statement");
9692
+ }
9693
+ return {
9694
+ sql: statements[0].sql,
9695
+ params: statements[0].params,
9696
+ statements
9697
+ };
9698
+ }
9699
+ function hasPaginationBounds(payload) {
9700
+ return payload.limit !== void 0 || payload.offset !== void 0 || payload.page_size !== void 0 || payload.current_page !== void 0;
9701
+ }
9702
+ function assertEffectiveMutationBounds(payload) {
9703
+ if (payload.current_page !== void 0 && payload.page_size === void 0 && payload.limit === void 0) {
9704
+ throw new D1SqlCompileError(
9705
+ "page_without_size",
9706
+ "current_page requires page_size (or limit) for bounded update/delete on D1 edge-local"
9707
+ );
9708
+ }
9709
+ const clause = limitOffsetClause(payload);
9710
+ if (!clause.trim()) {
9711
+ throw new D1SqlCompileError(
9712
+ "invalid_pagination_bounds",
9713
+ "Bounded update/delete requires limit, offset, and/or page_size on D1 edge-local"
9714
+ );
9715
+ }
9716
+ }
9717
+ var SQLITE_ROWID_ALIASES = /* @__PURE__ */ new Set(["rowid", "oid", "_rowid_"]);
9718
+ function referencedMutationColumns(payload) {
9719
+ const names = [];
9720
+ for (const condition of payload.conditions ?? []) {
9721
+ const column = (condition.column ?? condition.eq_column ?? "").trim();
9722
+ if (column) names.push(column);
9723
+ }
9724
+ if (payload.sort_by?.field?.trim()) {
9725
+ names.push(payload.sort_by.field.trim());
9726
+ }
9727
+ return names;
9728
+ }
9729
+ function resolveBoundedIdentityColumn(payload, options) {
9730
+ const refs = referencedMutationColumns(payload);
9731
+ const lower = refs.map((name) => name.toLowerCase());
9732
+ if (lower.some((name) => SQLITE_ROWID_ALIASES.has(name))) {
9733
+ throw new D1SqlCompileError(
9734
+ "bounded_mutation_unsafe_identity",
9735
+ "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."
9736
+ );
9737
+ }
9738
+ const identity = options?.identityColumn?.trim();
9739
+ if (!identity) {
9740
+ throw new D1SqlCompileError(
9741
+ "bounded_mutation_no_unique_identity",
9742
+ "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."
9743
+ );
9744
+ }
9745
+ if (SQLITE_ROWID_ALIASES.has(identity.toLowerCase())) {
9746
+ throw new D1SqlCompileError(
9747
+ "bounded_mutation_unsafe_identity",
9748
+ `Bounded update/delete cannot use identity column "${identity}" \u2014 it may shadow SQLite row identity.`
9749
+ );
9750
+ }
9751
+ return identity;
9752
+ }
9753
+ function boundedRowidInClause(table, whereSql, whereParams, payload, options) {
9754
+ assertEffectiveMutationBounds(payload);
9755
+ const identity = resolveBoundedIdentityColumn(payload, options);
9756
+ const identitySql = quoteIdent(identity);
9757
+ const innerWhere = whereSql.replace(/^WHERE\s+/i, "");
9758
+ const parts = [
9759
+ `SELECT ${identitySql} FROM ${quoteIdent(table)}`,
9760
+ innerWhere ? `WHERE ${innerWhere}` : "",
9761
+ orderClause(payload.sort_by),
9762
+ limitOffsetClause(payload)
9763
+ ].filter(Boolean);
9764
+ return {
9765
+ sql: `${identitySql} IN (${parts.join(" ")})`,
9766
+ params: [...whereParams]
9767
+ };
9768
+ }
9769
+ var D1SqlCompileError = class extends Error {
9770
+ code;
9771
+ constructor(code, message) {
9772
+ super(message);
9773
+ this.name = "D1SqlCompileError";
9774
+ this.code = code;
9775
+ }
9776
+ };
9777
+ var SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
9778
+ function quoteIdent(name) {
9779
+ const trimmed = name.trim();
9780
+ if (!trimmed) {
9781
+ throw new D1SqlCompileError("invalid_identifier", "Identifier is required");
9782
+ }
9783
+ if (trimmed.includes(".")) {
9784
+ throw new D1SqlCompileError(
9785
+ "schema_qualified_name",
9786
+ `Schema-qualified names are unsupported on D1 edge-local: ${trimmed}`
9787
+ );
9788
+ }
9789
+ if (!SAFE_IDENTIFIER.test(trimmed)) {
9790
+ throw new D1SqlCompileError(
9791
+ "invalid_identifier",
9792
+ `Invalid SQL identifier for D1 edge-local: ${trimmed}`
9793
+ );
9794
+ }
9795
+ return quoteQualifiedIdentifier(trimmed);
9796
+ }
9797
+ var RESPONSE_ALIAS_PATTERN2 = /^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*([A-Za-z_][A-Za-z0-9_]*)$/;
9798
+ var SQL_ALIAS_PATTERN2 = /^([A-Za-z_][A-Za-z0-9_]*)\s+(?:as\s+)?([A-Za-z_][A-Za-z0-9_]*)$/i;
9799
+ function quoteSelectTokenStrict(token) {
9800
+ const trimmed = token.trim();
9801
+ if (!trimmed || trimmed === "*") return trimmed || "*";
9802
+ if (SAFE_IDENTIFIER.test(trimmed)) {
9803
+ return quoteQualifiedIdentifier(trimmed);
9804
+ }
9805
+ const responseAlias = RESPONSE_ALIAS_PATTERN2.exec(trimmed);
9806
+ if (responseAlias) {
9807
+ const [, aliasIdentifier, baseIdentifier] = responseAlias;
9808
+ return `${quoteQualifiedIdentifier(baseIdentifier)} AS ${quoteQualifiedIdentifier(aliasIdentifier)}`;
9809
+ }
9810
+ const sqlAlias = SQL_ALIAS_PATTERN2.exec(trimmed);
9811
+ if (sqlAlias) {
9812
+ const [, baseIdentifier, aliasIdentifier] = sqlAlias;
9813
+ return `${quoteQualifiedIdentifier(baseIdentifier)} AS ${quoteQualifiedIdentifier(aliasIdentifier)}`;
9814
+ }
9815
+ throw new D1SqlCompileError(
9816
+ "unsafe_select",
9817
+ `SELECT/RETURNING expressions are not supported on D1 edge-local; use column names or aliases only: ${token}`
9818
+ );
9819
+ }
9820
+ function selectClause(columns) {
9821
+ if (columns === void 0 || columns === "*" || columns === "") return "*";
9822
+ if (typeof columns === "string") {
9823
+ const trimmed = columns.trim();
9824
+ if (!trimmed || trimmed === "*") return "*";
9825
+ return trimmed.split(",").map((part) => quoteSelectTokenStrict(part)).join(", ");
9826
+ }
9827
+ if (columns.length === 0) return "*";
9828
+ return columns.map((column) => quoteSelectTokenStrict(column)).join(", ");
9829
+ }
9830
+ function wantsReturning(payload) {
9831
+ return Boolean(payload.columns) && payload.head !== true;
9832
+ }
9833
+ function conditionToWhere(condition) {
9834
+ const column = condition.column?.trim() || condition.eq_column?.trim() || "";
9835
+ if (!column) {
9836
+ throw new D1SqlCompileError("invalid_condition", "Condition requires a column");
9837
+ }
9838
+ const col = quoteIdent(column);
9839
+ const operator = (condition.operator || "eq").toLowerCase();
9840
+ const value = condition.value !== void 0 ? condition.value : condition.eq_value;
9841
+ switch (operator) {
9842
+ case "eq": {
9843
+ if (Array.isArray(value)) {
9844
+ if (value.length === 0) {
9845
+ return { sql: "1 = 0", params: [] };
9846
+ }
9847
+ const placeholders = value.map(() => "?").join(", ");
9848
+ return { sql: `${col} IN (${placeholders})`, params: [...value] };
9849
+ }
9850
+ if (value === null) {
9851
+ return { sql: `${col} IS NULL`, params: [] };
9852
+ }
9853
+ return { sql: `${col} = ?`, params: [value ?? null] };
9854
+ }
9855
+ case "neq":
9856
+ if (value === null) {
9857
+ return { sql: `${col} IS NOT NULL`, params: [] };
9858
+ }
9859
+ return { sql: `${col} != ?`, params: [value ?? null] };
9860
+ case "gt":
9861
+ return { sql: `${col} > ?`, params: [value ?? null] };
9862
+ case "gte":
9863
+ return { sql: `${col} >= ?`, params: [value ?? null] };
9864
+ case "lt":
9865
+ return { sql: `${col} < ?`, params: [value ?? null] };
9866
+ case "lte":
9867
+ return { sql: `${col} <= ?`, params: [value ?? null] };
9868
+ case "like":
9869
+ return { sql: `${col} LIKE ?`, params: [value ?? null] };
9870
+ case "ilike":
9871
+ return { sql: `${col} LIKE ? COLLATE NOCASE`, params: [value ?? null] };
9872
+ case "in": {
9873
+ const items = Array.isArray(value) ? value : value === void 0 ? [] : [value];
9874
+ if (items.length === 0) {
9875
+ return { sql: "1 = 0", params: [] };
9876
+ }
9877
+ const placeholders = items.map(() => "?").join(", ");
9878
+ return { sql: `${col} IN (${placeholders})`, params: [...items] };
9879
+ }
9880
+ case "is": {
9881
+ if (value === null || value === "null") {
9882
+ return { sql: `${col} IS NULL`, params: [] };
9883
+ }
9884
+ if (value === true || value === "true") {
9885
+ return { sql: `${col} IS TRUE`, params: [] };
9886
+ }
9887
+ if (value === false || value === "false") {
9888
+ return { sql: `${col} IS FALSE`, params: [] };
9889
+ }
9890
+ return { sql: `${col} IS ?`, params: [value] };
9891
+ }
9892
+ case "not":
9893
+ case "or":
9894
+ case "contains":
9895
+ case "containedby":
9896
+ throw new D1SqlCompileError(
9897
+ "unsupported_operator",
9898
+ `Condition operator "${operator}" is not supported on D1 edge-local L1`
9899
+ );
9900
+ default:
9901
+ throw new D1SqlCompileError(
9902
+ "unsupported_operator",
9903
+ `Unknown condition operator "${operator}"`
9904
+ );
9905
+ }
9906
+ }
9907
+ function buildWhere(conditions) {
9908
+ if (!conditions?.length) {
9909
+ return { sql: "", params: [] };
9910
+ }
9911
+ const parts = [];
9912
+ const params = [];
9913
+ for (const condition of conditions) {
9914
+ if (!condition.operator && condition.eq_column) {
9915
+ const clause2 = conditionToWhere({
9916
+ ...condition,
9917
+ operator: "eq",
9918
+ column: condition.eq_column,
9919
+ value: condition.eq_value
9920
+ });
9921
+ parts.push(clause2.sql);
9922
+ params.push(...clause2.params);
9923
+ continue;
9924
+ }
9925
+ const clause = conditionToWhere(condition);
9926
+ parts.push(clause.sql);
9927
+ params.push(...clause.params);
9928
+ }
9929
+ return {
9930
+ sql: parts.length ? `WHERE ${parts.join(" AND ")}` : "",
9931
+ params
9932
+ };
9933
+ }
9934
+ function orderClause(order) {
9935
+ if (!order?.field?.trim()) return "";
9936
+ const direction = order.direction === "descending" ? "DESC" : "ASC";
9937
+ return `ORDER BY ${quoteIdent(order.field)} ${direction}`;
9938
+ }
9939
+ function limitOffsetClause(payload) {
9940
+ let limit = payload.limit;
9941
+ let offset = payload.offset;
9942
+ if (limit === void 0 && payload.page_size !== void 0) {
9943
+ limit = payload.page_size;
9944
+ }
9945
+ if (payload.current_page !== void 0 && offset === void 0) {
9946
+ const pageSize = payload.page_size ?? payload.limit;
9947
+ if (pageSize !== void 0) {
9948
+ offset = Math.max(0, (payload.current_page - 1) * pageSize);
9949
+ }
9950
+ }
9951
+ const parts = [];
9952
+ if (offset !== void 0 && limit === void 0) {
9953
+ parts.push("LIMIT -1");
9954
+ parts.push(`OFFSET ${Math.max(0, Math.trunc(offset))}`);
9955
+ } else {
9956
+ if (limit !== void 0) {
9957
+ parts.push(`LIMIT ${Math.max(0, Math.trunc(limit))}`);
9958
+ }
9959
+ if (offset !== void 0) {
9960
+ parts.push(`OFFSET ${Math.max(0, Math.trunc(offset))}`);
9961
+ }
9962
+ }
9963
+ return parts.join(" ");
9964
+ }
9965
+ function rejectStructuredRelations(payload) {
9966
+ const select = payload.select;
9967
+ if (select && typeof select === "object" && !Array.isArray(select)) {
9968
+ for (const value of Object.values(select)) {
9969
+ if (value && typeof value === "object") {
9970
+ throw new D1SqlCompileError(
9971
+ "relations_unsupported",
9972
+ "Nested relation selects are unsupported on D1 edge-local"
9973
+ );
9974
+ }
9975
+ }
9976
+ }
9977
+ if (payload.view_name) {
9978
+ throw new D1SqlCompileError(
9979
+ "view_unsupported",
9980
+ "view_name is unsupported on D1 edge-local L1"
9981
+ );
9982
+ }
9983
+ }
9984
+ function jsonValue(value) {
9985
+ if (value === void 0) return null;
9986
+ if (value !== null && typeof value === "object") {
9987
+ return JSON.stringify(value);
9988
+ }
9989
+ return value;
9990
+ }
9991
+ function compileD1Fetch(payload) {
9992
+ rejectStructuredRelations(payload);
9993
+ const table = payload.table_name?.trim();
9994
+ if (!table) {
9995
+ throw new D1SqlCompileError("missing_table", "table_name is required for fetch");
9996
+ }
9997
+ let columns = payload.columns;
9998
+ if (payload.select && typeof payload.select === "object" && !Array.isArray(payload.select)) {
9999
+ const keys = Object.entries(payload.select).filter(([, enabled]) => enabled === true || enabled === 1).map(([key]) => key);
10000
+ if (keys.length > 0) {
10001
+ columns = keys;
10002
+ }
10003
+ } else if (typeof payload.select === "string" && payload.select.trim()) {
10004
+ columns = payload.select;
10005
+ }
10006
+ let where = buildWhere(payload.conditions);
10007
+ if (!where.sql && payload.where && typeof payload.where === "object") {
10008
+ const eqConditions = Object.entries(
10009
+ payload.where
10010
+ ).map(([column, value]) => ({
10011
+ column,
10012
+ operator: "eq",
10013
+ value
10014
+ }));
10015
+ where = buildWhere(eqConditions);
10016
+ }
10017
+ if (payload.head === true) {
10018
+ return compileD1CountFromWhere(table, where);
10019
+ }
10020
+ const parts = [
10021
+ `SELECT ${selectClause(columns)} FROM ${quoteIdent(table)}`,
10022
+ where.sql,
10023
+ orderClause(payload.sort_by),
10024
+ limitOffsetClause(payload)
10025
+ ].filter(Boolean);
10026
+ return asSingle(parts.join(" "), where.params);
10027
+ }
10028
+ function compileD1Count(payload) {
10029
+ rejectStructuredRelations(payload);
10030
+ const table = payload.table_name?.trim();
10031
+ if (!table) {
10032
+ throw new D1SqlCompileError("missing_table", "table_name is required for count");
10033
+ }
10034
+ let where = buildWhere(payload.conditions);
10035
+ if (!where.sql && payload.where && typeof payload.where === "object") {
10036
+ const eqConditions = Object.entries(
10037
+ payload.where
10038
+ ).map(([column, value]) => ({
10039
+ column,
10040
+ operator: "eq",
10041
+ value
10042
+ }));
10043
+ where = buildWhere(eqConditions);
10044
+ }
10045
+ return compileD1CountFromWhere(table, where);
10046
+ }
10047
+ function compileD1CountFromWhere(table, where) {
10048
+ const parts = [
10049
+ `SELECT COUNT(*) AS __athena_count FROM ${quoteIdent(table)}`,
10050
+ where.sql
10051
+ ].filter(Boolean);
10052
+ return asSingle(parts.join(" "), where.params);
10053
+ }
10054
+ function extractAthenaCount(rows) {
10055
+ const first = rows[0];
10056
+ const rawCount = first && typeof first === "object" && !Array.isArray(first) ? first.__athena_count : void 0;
10057
+ const count = typeof rawCount === "number" ? rawCount : typeof rawCount === "bigint" ? Number(rawCount) : Number(rawCount ?? 0);
10058
+ return Number.isFinite(count) ? count : 0;
10059
+ }
10060
+ function compileSingleRowInsert(table, row, payload) {
10061
+ const columns = Object.keys(row);
10062
+ if (columns.length === 0) {
10063
+ if (payload.on_conflict) {
10064
+ throw new D1SqlCompileError(
10065
+ "default_values_upsert_unsupported",
10066
+ "DEFAULT VALUES upsert is unsupported on D1 edge-local; provide insert columns or omit onConflict"
10067
+ );
10068
+ }
10069
+ const parts2 = [`INSERT INTO ${quoteIdent(table)} DEFAULT VALUES`];
10070
+ if (wantsReturning(payload)) {
10071
+ parts2.push(`RETURNING ${selectClause(payload.columns)}`);
10072
+ }
10073
+ return { sql: parts2.join(" "), params: [] };
10074
+ }
10075
+ const params = columns.map((column) => jsonValue(row[column]));
10076
+ const parts = [
10077
+ `INSERT INTO ${quoteIdent(table)} (${columns.map(quoteIdent).join(", ")})`,
10078
+ `VALUES (${columns.map(() => "?").join(", ")})`
10079
+ ];
10080
+ appendOnConflict(parts, params, payload, columns);
10081
+ if (wantsReturning(payload)) {
10082
+ parts.push(`RETURNING ${selectClause(payload.columns)}`);
10083
+ }
10084
+ return { sql: parts.join(" "), params };
10085
+ }
10086
+ function parseOnConflictColumns(onConflict) {
10087
+ const raw = Array.isArray(onConflict) ? onConflict : [onConflict];
10088
+ const columns = [];
10089
+ for (const item of raw) {
10090
+ for (const part of String(item).split(",")) {
10091
+ const trimmed = part.trim();
10092
+ if (trimmed) columns.push(trimmed);
10093
+ }
10094
+ }
10095
+ if (columns.length === 0) {
10096
+ throw new D1SqlCompileError(
10097
+ "invalid_on_conflict",
10098
+ "on_conflict requires at least one column"
10099
+ );
10100
+ }
10101
+ return columns;
10102
+ }
10103
+ function appendOnConflict(parts, params, payload, insertColumns) {
10104
+ if (!payload.on_conflict) return;
10105
+ const conflictCols = parseOnConflictColumns(payload.on_conflict);
10106
+ const conflictSql = conflictCols.map(quoteIdent).join(", ");
10107
+ if (payload.update_body !== void 0 && payload.update_body !== null) {
10108
+ const entries = Object.entries(payload.update_body);
10109
+ if (entries.length === 0) {
10110
+ parts.push(`ON CONFLICT (${conflictSql}) DO NOTHING`);
10111
+ return;
10112
+ }
10113
+ const assignments2 = entries.map(([column, value]) => {
10114
+ params.push(jsonValue(value));
10115
+ return `${quoteIdent(column)} = ?`;
10116
+ });
10117
+ parts.push(`ON CONFLICT (${conflictSql}) DO UPDATE SET ${assignments2.join(", ")}`);
10118
+ return;
10119
+ }
10120
+ const conflictSet = new Set(conflictCols);
10121
+ const assignments = insertColumns.filter((column) => !conflictSet.has(column)).map((column) => {
10122
+ const quoted = quoteIdent(column);
10123
+ return `${quoted} = excluded.${quoted}`;
10124
+ });
10125
+ if (assignments.length === 0) {
10126
+ parts.push(`ON CONFLICT (${conflictSql}) DO NOTHING`);
10127
+ } else {
10128
+ parts.push(`ON CONFLICT (${conflictSql}) DO UPDATE SET ${assignments.join(", ")}`);
10129
+ }
10130
+ }
10131
+ function compileD1Insert(payload) {
10132
+ const table = payload.table_name?.trim();
10133
+ if (!table) {
10134
+ throw new D1SqlCompileError("missing_table", "table_name is required for insert");
10135
+ }
10136
+ const rows = Array.isArray(payload.insert_body) ? payload.insert_body : [payload.insert_body];
10137
+ if (rows.length === 0) {
10138
+ throw new D1SqlCompileError("empty_insert", "insert_body must not be empty");
10139
+ }
10140
+ const columns = [];
10141
+ const seen = /* @__PURE__ */ new Set();
10142
+ for (const row of rows) {
10143
+ for (const key of Object.keys(row ?? {})) {
10144
+ if (seen.has(key)) continue;
10145
+ seen.add(key);
10146
+ columns.push(key);
10147
+ }
10148
+ }
10149
+ if (columns.length === 0) {
10150
+ if (rows.length === 1) {
10151
+ const compiled = compileSingleRowInsert(table, {}, payload);
10152
+ return asSingle(compiled.sql, compiled.params);
10153
+ }
10154
+ throw new D1SqlCompileError(
10155
+ "empty_insert",
10156
+ "Multi-row insert_body cannot be empty objects; use a single {} for DEFAULT VALUES"
10157
+ );
10158
+ }
10159
+ const forceNullForMissing = payload.default_to_null === true;
10160
+ const isSparse = rows.some(
10161
+ (row) => columns.some((column) => !Object.prototype.hasOwnProperty.call(row, column))
10162
+ );
10163
+ if (isSparse && !forceNullForMissing && rows.length > 1) {
10164
+ return asBatch(
10165
+ rows.map((row) => compileSingleRowInsert(table, row, payload))
10166
+ );
10167
+ }
10168
+ if (isSparse && !forceNullForMissing && rows.length === 1) {
10169
+ const compiled = compileSingleRowInsert(table, rows[0], payload);
10170
+ return asSingle(compiled.sql, compiled.params);
10171
+ }
10172
+ const params = [];
10173
+ const valueGroups = rows.map((row) => {
10174
+ const placeholders = columns.map((column) => {
10175
+ const has = Object.prototype.hasOwnProperty.call(row, column);
10176
+ if (!has) {
10177
+ params.push(null);
10178
+ return "?";
10179
+ }
10180
+ params.push(jsonValue(row[column]));
10181
+ return "?";
10182
+ });
10183
+ return `(${placeholders.join(", ")})`;
10184
+ });
10185
+ const parts = [
10186
+ `INSERT INTO ${quoteIdent(table)} (${columns.map(quoteIdent).join(", ")})`,
10187
+ `VALUES ${valueGroups.join(", ")}`
10188
+ ];
10189
+ appendOnConflict(parts, params, payload, columns);
10190
+ if (wantsReturning(payload)) {
10191
+ parts.push(`RETURNING ${selectClause(payload.columns)}`);
10192
+ }
10193
+ return asSingle(parts.join(" "), params);
10194
+ }
10195
+ function compileD1Update(payload, options) {
10196
+ const table = payload.table_name?.trim();
10197
+ if (!table) {
10198
+ throw new D1SqlCompileError("missing_table", "table_name is required for update");
10199
+ }
10200
+ const entries = Object.entries(payload.update_body ?? {});
10201
+ if (entries.length === 0) {
10202
+ throw new D1SqlCompileError("empty_update", "update_body must not be empty");
10203
+ }
10204
+ const params = [];
10205
+ const assignments = entries.map(([column, value]) => {
10206
+ params.push(jsonValue(value));
10207
+ return `${quoteIdent(column)} = ?`;
10208
+ });
10209
+ const where = buildWhere(payload.conditions);
10210
+ if (!where.sql) {
10211
+ throw new D1SqlCompileError(
10212
+ "unfiltered_update",
10213
+ "UPDATE requires at least one condition on D1 edge-local"
10214
+ );
10215
+ }
10216
+ if (hasPaginationBounds(payload) || payload.sort_by) {
10217
+ if (!hasPaginationBounds(payload)) {
10218
+ throw new D1SqlCompileError(
10219
+ "order_without_bounds",
10220
+ "UPDATE with sort_by requires limit/offset or page_size/current_page on D1 edge-local"
10221
+ );
10222
+ }
10223
+ const bounded = boundedRowidInClause(
10224
+ table,
10225
+ where.sql,
10226
+ where.params,
10227
+ {
10228
+ ...payload,
10229
+ conditions: payload.conditions
10230
+ },
10231
+ options
10232
+ );
10233
+ params.push(...bounded.params);
10234
+ const parts2 = [
10235
+ `UPDATE ${quoteIdent(table)} SET ${assignments.join(", ")}`,
10236
+ `WHERE ${bounded.sql}`
10237
+ ];
10238
+ if (wantsReturning(payload)) {
10239
+ parts2.push(`RETURNING ${selectClause(payload.columns)}`);
10240
+ }
10241
+ return asSingle(parts2.join(" "), params);
10242
+ }
10243
+ params.push(...where.params);
10244
+ const parts = [
10245
+ `UPDATE ${quoteIdent(table)} SET ${assignments.join(", ")}`,
10246
+ where.sql
10247
+ ];
10248
+ if (wantsReturning(payload)) {
10249
+ parts.push(`RETURNING ${selectClause(payload.columns)}`);
10250
+ }
10251
+ return asSingle(parts.join(" "), params);
10252
+ }
10253
+ function compileD1Delete(payload, options) {
10254
+ const table = payload.table_name?.trim();
10255
+ if (!table) {
10256
+ throw new D1SqlCompileError("missing_table", "table_name is required for delete");
10257
+ }
10258
+ const conditions = [...payload.conditions ?? []];
10259
+ if (payload.resource_id !== void 0 && payload.resource_id !== null) {
10260
+ const hasResourceIdFilter = conditions.some((condition) => {
10261
+ const column = (condition.column ?? condition.eq_column ?? "").trim();
10262
+ return column === "resource_id";
10263
+ });
10264
+ const hasIdFilter = conditions.some((condition) => {
10265
+ const column = (condition.column ?? condition.eq_column ?? "").trim();
10266
+ return column === "id";
10267
+ });
10268
+ if (!hasResourceIdFilter && !hasIdFilter) {
10269
+ conditions.unshift({
10270
+ column: "id",
10271
+ operator: "eq",
10272
+ value: payload.resource_id
10273
+ });
10274
+ }
10275
+ }
10276
+ const where = buildWhere(conditions);
10277
+ if (!where.sql) {
10278
+ throw new D1SqlCompileError(
10279
+ "unfiltered_delete",
10280
+ "DELETE requires at least one condition or resource_id on D1 edge-local"
10281
+ );
10282
+ }
10283
+ if (hasPaginationBounds(payload) || payload.sort_by) {
10284
+ if (!hasPaginationBounds(payload)) {
10285
+ throw new D1SqlCompileError(
10286
+ "order_without_bounds",
10287
+ "DELETE with sort_by requires limit/offset or page_size/current_page on D1 edge-local"
10288
+ );
10289
+ }
10290
+ const bounded = boundedRowidInClause(
10291
+ table,
10292
+ where.sql,
10293
+ where.params,
10294
+ {
10295
+ ...payload,
10296
+ conditions
10297
+ },
10298
+ options
10299
+ );
10300
+ const parts2 = [`DELETE FROM ${quoteIdent(table)}`, `WHERE ${bounded.sql}`];
10301
+ if (wantsReturning(payload)) {
10302
+ parts2.push(`RETURNING ${selectClause(payload.columns)}`);
10303
+ }
10304
+ return asSingle(parts2.join(" "), bounded.params);
10305
+ }
10306
+ const parts = [`DELETE FROM ${quoteIdent(table)}`, where.sql];
10307
+ if (wantsReturning(payload)) {
10308
+ parts.push(`RETURNING ${selectClause(payload.columns)}`);
10309
+ }
10310
+ return asSingle(parts.join(" "), where.params);
10311
+ }
10312
+
10313
+ // src/cloudflare/d1/sql-rewrite.ts
10314
+ 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";
10315
+ function mapSqlOutsideLiterals(sql, transform) {
10316
+ let out = "";
10317
+ let buffer = "";
10318
+ let inSingle = false;
10319
+ let inDouble = false;
10320
+ let inBacktick = false;
10321
+ let inBracket = false;
10322
+ let inLineComment = false;
10323
+ let inBlockComment = false;
10324
+ const flushCode = () => {
10325
+ if (buffer) {
10326
+ out += transform(buffer);
10327
+ buffer = "";
10328
+ }
10329
+ };
10330
+ for (let i = 0; i < sql.length; i += 1) {
10331
+ const ch = sql[i];
10332
+ const next = sql[i + 1];
10333
+ if (inLineComment) {
10334
+ out += ch;
10335
+ if (ch === "\n" || ch === "\r") inLineComment = false;
10336
+ continue;
10337
+ }
10338
+ if (inBlockComment) {
10339
+ out += ch;
10340
+ if (ch === "*" && next === "/") {
10341
+ out += next;
10342
+ i += 1;
10343
+ inBlockComment = false;
10344
+ }
10345
+ continue;
10346
+ }
10347
+ if (inSingle) {
10348
+ out += ch;
10349
+ if (ch === "'" && next === "'") {
10350
+ out += next;
10351
+ i += 1;
10352
+ continue;
10353
+ }
10354
+ if (ch === "'") inSingle = false;
10355
+ continue;
10356
+ }
10357
+ if (inDouble) {
10358
+ out += ch;
10359
+ if (ch === '"' && next === '"') {
10360
+ out += next;
10361
+ i += 1;
10362
+ continue;
10363
+ }
10364
+ if (ch === '"') inDouble = false;
10365
+ continue;
10366
+ }
10367
+ if (inBacktick) {
10368
+ out += ch;
10369
+ if (ch === "`" && next === "`") {
10370
+ out += next;
10371
+ i += 1;
10372
+ continue;
10373
+ }
10374
+ if (ch === "`") inBacktick = false;
10375
+ continue;
10376
+ }
10377
+ if (inBracket) {
10378
+ out += ch;
10379
+ if (ch === "]") inBracket = false;
10380
+ continue;
10381
+ }
10382
+ if (ch === "-" && next === "-") {
10383
+ flushCode();
10384
+ out += ch;
10385
+ out += next;
10386
+ i += 1;
10387
+ inLineComment = true;
10388
+ continue;
10389
+ }
10390
+ if (ch === "/" && next === "*") {
10391
+ flushCode();
10392
+ out += ch;
10393
+ out += next;
10394
+ i += 1;
10395
+ inBlockComment = true;
10396
+ continue;
10397
+ }
10398
+ if (ch === "'") {
10399
+ flushCode();
10400
+ out += ch;
10401
+ inSingle = true;
10402
+ continue;
10403
+ }
10404
+ if (ch === '"') {
10405
+ flushCode();
10406
+ out += ch;
10407
+ inDouble = true;
10408
+ continue;
10409
+ }
10410
+ if (ch === "`") {
10411
+ flushCode();
10412
+ out += ch;
10413
+ inBacktick = true;
10414
+ continue;
10415
+ }
10416
+ if (ch === "[") {
10417
+ flushCode();
10418
+ out += ch;
10419
+ inBracket = true;
10420
+ continue;
10421
+ }
10422
+ buffer += ch;
10423
+ }
10424
+ flushCode();
10425
+ return out;
10426
+ }
10427
+ function isIdentChar2(ch) {
10428
+ if (!ch) return false;
10429
+ return /[A-Za-z0-9_]/.test(ch);
10430
+ }
10431
+ function collectLimitOffsetKeywords(sql) {
10432
+ const hits = [];
10433
+ let depth = 0;
10434
+ let statement = 0;
10435
+ let inSingle = false;
10436
+ let inDouble = false;
10437
+ let inBacktick = false;
10438
+ let inBracket = false;
10439
+ let inLineComment = false;
10440
+ let inBlockComment = false;
10441
+ for (let i = 0; i < sql.length; i += 1) {
10442
+ const ch = sql[i];
10443
+ const next = sql[i + 1];
10444
+ if (inLineComment) {
10445
+ if (ch === "\n" || ch === "\r") inLineComment = false;
10446
+ continue;
10447
+ }
10448
+ if (inBlockComment) {
10449
+ if (ch === "*" && next === "/") {
10450
+ i += 1;
10451
+ inBlockComment = false;
10452
+ }
10453
+ continue;
10454
+ }
10455
+ if (inSingle) {
10456
+ if (ch === "'" && next === "'") {
10457
+ i += 1;
10458
+ continue;
10459
+ }
10460
+ if (ch === "'") inSingle = false;
10461
+ continue;
10462
+ }
10463
+ if (inDouble) {
10464
+ if (ch === '"' && next === '"') {
10465
+ i += 1;
10466
+ continue;
10467
+ }
10468
+ if (ch === '"') inDouble = false;
10469
+ continue;
10470
+ }
10471
+ if (inBacktick) {
10472
+ if (ch === "`" && next === "`") {
10473
+ i += 1;
10474
+ continue;
10475
+ }
10476
+ if (ch === "`") inBacktick = false;
10477
+ continue;
10478
+ }
10479
+ if (inBracket) {
10480
+ if (ch === "]") inBracket = false;
10481
+ continue;
10482
+ }
10483
+ if (ch === "-" && next === "-") {
10484
+ inLineComment = true;
10485
+ i += 1;
10486
+ continue;
10487
+ }
10488
+ if (ch === "/" && next === "*") {
10489
+ inBlockComment = true;
10490
+ i += 1;
10491
+ continue;
10492
+ }
10493
+ if (ch === "'") {
10494
+ inSingle = true;
10495
+ continue;
10496
+ }
10497
+ if (ch === '"') {
10498
+ inDouble = true;
10499
+ continue;
10500
+ }
10501
+ if (ch === "`") {
10502
+ inBacktick = true;
10503
+ continue;
10504
+ }
10505
+ if (ch === "[") {
10506
+ inBracket = true;
10507
+ continue;
10508
+ }
10509
+ if (ch === "(") {
10510
+ depth += 1;
10511
+ continue;
10512
+ }
10513
+ if (ch === ")") {
10514
+ depth = Math.max(0, depth - 1);
10515
+ continue;
10516
+ }
10517
+ if (ch === ";" && depth === 0) {
10518
+ statement += 1;
10519
+ continue;
10520
+ }
10521
+ if (!isIdentChar2(ch) || isIdentChar2(sql[i - 1])) {
10522
+ continue;
10523
+ }
10524
+ const rest = sql.slice(i);
10525
+ if (/^LIMIT\b/i.test(rest)) {
10526
+ hits.push({ kind: "limit", start: i, depth, statement });
10527
+ i += 4;
10528
+ continue;
10529
+ }
10530
+ if (/^OFFSET\b/i.test(rest)) {
10531
+ hits.push({ kind: "offset", start: i, depth, statement });
10532
+ i += 5;
10533
+ }
10534
+ }
10535
+ return hits;
10536
+ }
10537
+ function injectLimitBeforeBareOffsets(sql) {
10538
+ const hits = collectLimitOffsetKeywords(sql);
10539
+ if (hits.length === 0) return sql;
10540
+ const injectAt = [];
10541
+ for (const hit of hits) {
10542
+ if (hit.kind !== "offset") continue;
10543
+ let hasLimit = false;
10544
+ for (let i = hits.length - 1; i >= 0; i -= 1) {
10545
+ const prev = hits[i];
10546
+ if (prev.start >= hit.start) continue;
10547
+ if (prev.statement !== hit.statement) continue;
10548
+ if (prev.depth !== hit.depth) continue;
10549
+ if (prev.kind === "limit") {
10550
+ hasLimit = true;
10551
+ break;
10552
+ }
10553
+ if (prev.kind === "offset") {
10554
+ break;
10555
+ }
10556
+ }
10557
+ if (!hasLimit) {
10558
+ injectAt.push(hit.start);
10559
+ }
10560
+ }
10561
+ if (injectAt.length === 0) return sql;
10562
+ let out = sql;
10563
+ for (let i = injectAt.length - 1; i >= 0; i -= 1) {
10564
+ const at = injectAt[i];
10565
+ out = `${out.slice(0, at)}LIMIT -1 ${out.slice(at)}`;
10566
+ }
10567
+ return out;
10568
+ }
10569
+ function rewritePostgresSqlForSqlite(sql) {
10570
+ const castPattern = new RegExp(`::(?:${PG_CAST_TYPES})\\b`, "gi");
10571
+ const withoutCastsAndIlike = mapSqlOutsideLiterals(sql, (chunk) => {
10572
+ let rewritten = chunk.replace(castPattern, "");
10573
+ rewritten = rewritten.replace(/\bILIKE\b/gi, "LIKE");
10574
+ return rewritten;
10575
+ });
10576
+ return injectLimitBeforeBareOffsets(withoutCastsAndIlike);
10577
+ }
10578
+
10579
+ // src/cloudflare/d1/transport.ts
10580
+ function hasPaginationBounds2(payload) {
10581
+ return payload.limit !== void 0 || payload.offset !== void 0 || payload.page_size !== void 0 || payload.current_page !== void 0;
10582
+ }
10583
+ function normalizeSqliteCollation(name) {
10584
+ const raw = String(name ?? "").trim().replace(/^["'`[]|["'`\]]$/g, "");
10585
+ if (!raw) return "BINARY";
10586
+ return raw.toUpperCase();
10587
+ }
10588
+ function findCreateTableColumnListOpen(createSql) {
10589
+ const m = /\bCREATE\s+(?:(?:TEMP|TEMPORARY|VIRTUAL)\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?/i.exec(
10590
+ createSql
10591
+ );
10592
+ if (!m) return -1;
10593
+ let i = m.index + m[0].length;
10594
+ let inSingle = false;
10595
+ let inDouble = false;
10596
+ let inBacktick = false;
10597
+ let inBracket = false;
10598
+ while (i < createSql.length) {
10599
+ const ch = createSql[i];
10600
+ if (inSingle) {
10601
+ if (ch === "'" && createSql[i + 1] === "'") {
10602
+ i += 2;
10603
+ continue;
10604
+ }
10605
+ if (ch === "'") inSingle = false;
10606
+ i++;
10607
+ continue;
10608
+ }
10609
+ if (inDouble) {
10610
+ if (ch === '"') inDouble = false;
10611
+ i++;
10612
+ continue;
10613
+ }
10614
+ if (inBacktick) {
10615
+ if (ch === "`") inBacktick = false;
10616
+ i++;
10617
+ continue;
10618
+ }
10619
+ if (inBracket) {
10620
+ if (ch === "]") inBracket = false;
10621
+ i++;
10622
+ continue;
10623
+ }
10624
+ if (ch === "'") {
10625
+ inSingle = true;
10626
+ i++;
10627
+ continue;
10628
+ }
10629
+ if (ch === '"') {
10630
+ inDouble = true;
10631
+ i++;
10632
+ continue;
10633
+ }
10634
+ if (ch === "`") {
10635
+ inBacktick = true;
10636
+ i++;
10637
+ continue;
10638
+ }
10639
+ if (ch === "[") {
10640
+ inBracket = true;
10641
+ i++;
10642
+ continue;
10643
+ }
10644
+ if (ch === "(") return i;
10645
+ i++;
10646
+ }
10647
+ return -1;
10648
+ }
10649
+ function parseColumnCollationFromCreateSql(createSql, columnName) {
10650
+ if (!createSql || !columnName) return null;
10651
+ const listOpen = findCreateTableColumnListOpen(createSql);
10652
+ if (listOpen < 0) return null;
10653
+ const listStart = listOpen + 1;
10654
+ const escaped = columnName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10655
+ const nameRe = new RegExp(
10656
+ `(?:^|[^\\w])(?:"${escaped}"|\`${escaped}\`|\\[${escaped}\\]|${escaped})\\s+`,
10657
+ "i"
10658
+ );
10659
+ const listSlice = createSql.slice(listStart);
10660
+ let nameMatchAbs = -1;
10661
+ let nameMatchLen = 0;
10662
+ {
10663
+ let i2 = 0;
10664
+ let depth2 = 1;
10665
+ let inSingle2 = false;
10666
+ let inDouble2 = false;
10667
+ let inBacktick2 = false;
10668
+ let inBracket2 = false;
10669
+ let segmentStart = 0;
10670
+ const trySegment = (from, to) => {
10671
+ if (nameMatchAbs >= 0) return;
10672
+ const segment = listSlice.slice(from, to);
10673
+ const m = nameRe.exec(segment);
10674
+ if (!m) return;
10675
+ const leading = segment.slice(0, m.index).trim();
10676
+ if (leading.length > 0) return;
10677
+ nameMatchAbs = listStart + from + m.index;
10678
+ nameMatchLen = m[0].length;
10679
+ };
10680
+ while (i2 < listSlice.length && depth2 > 0) {
10681
+ const ch = listSlice[i2];
10682
+ if (inSingle2) {
10683
+ if (ch === "'" && listSlice[i2 + 1] === "'") {
10684
+ i2 += 2;
10685
+ continue;
10686
+ }
10687
+ if (ch === "'") inSingle2 = false;
10688
+ i2++;
10689
+ continue;
10690
+ }
10691
+ if (inDouble2) {
10692
+ if (ch === '"') inDouble2 = false;
10693
+ i2++;
10694
+ continue;
10695
+ }
10696
+ if (inBacktick2) {
10697
+ if (ch === "`") inBacktick2 = false;
10698
+ i2++;
10699
+ continue;
10700
+ }
10701
+ if (inBracket2) {
10702
+ if (ch === "]") inBracket2 = false;
10703
+ i2++;
10704
+ continue;
10705
+ }
10706
+ if (ch === "'") {
10707
+ inSingle2 = true;
10708
+ i2++;
10709
+ continue;
10710
+ }
10711
+ if (ch === '"') {
10712
+ inDouble2 = true;
10713
+ i2++;
10714
+ continue;
10715
+ }
10716
+ if (ch === "`") {
10717
+ inBacktick2 = true;
10718
+ i2++;
10719
+ continue;
10720
+ }
10721
+ if (ch === "[") {
10722
+ inBracket2 = true;
10723
+ i2++;
10724
+ continue;
10725
+ }
10726
+ if (ch === "(") {
10727
+ depth2++;
10728
+ i2++;
10729
+ continue;
10730
+ }
10731
+ if (ch === ")") {
10732
+ depth2--;
10733
+ if (depth2 === 0) {
10734
+ trySegment(segmentStart, i2);
10735
+ break;
10736
+ }
10737
+ i2++;
10738
+ continue;
10739
+ }
10740
+ if (ch === "," && depth2 === 1) {
10741
+ trySegment(segmentStart, i2);
10742
+ segmentStart = i2 + 1;
10743
+ i2++;
10744
+ continue;
10745
+ }
10746
+ i2++;
10747
+ }
10748
+ }
10749
+ if (nameMatchAbs < 0 || nameMatchLen <= 0) return null;
10750
+ const start = nameMatchAbs + nameMatchLen;
10751
+ let i = start;
10752
+ let depth = 0;
10753
+ let inSingle = false;
10754
+ let inDouble = false;
10755
+ let inBacktick = false;
10756
+ let inBracket = false;
10757
+ while (i < createSql.length) {
10758
+ const ch = createSql[i];
10759
+ if (inSingle) {
10760
+ if (ch === "'" && createSql[i + 1] === "'") {
10761
+ i += 2;
10762
+ continue;
10763
+ }
10764
+ if (ch === "'") inSingle = false;
10765
+ i++;
10766
+ continue;
10767
+ }
10768
+ if (inDouble) {
10769
+ if (ch === '"') inDouble = false;
10770
+ i++;
10771
+ continue;
10772
+ }
10773
+ if (inBacktick) {
10774
+ if (ch === "`") inBacktick = false;
10775
+ i++;
10776
+ continue;
10777
+ }
10778
+ if (inBracket) {
10779
+ if (ch === "]") inBracket = false;
10780
+ i++;
10781
+ continue;
10782
+ }
10783
+ if (ch === "'") {
10784
+ inSingle = true;
10785
+ i++;
10786
+ continue;
10787
+ }
10788
+ if (ch === '"') {
10789
+ inDouble = true;
10790
+ i++;
10791
+ continue;
10792
+ }
10793
+ if (ch === "`") {
10794
+ inBacktick = true;
10795
+ i++;
10796
+ continue;
10797
+ }
10798
+ if (ch === "[") {
10799
+ inBracket = true;
10800
+ i++;
10801
+ continue;
10802
+ }
10803
+ if (ch === "(") {
10804
+ depth++;
10805
+ i++;
10806
+ continue;
10807
+ }
10808
+ if (ch === ")") {
10809
+ if (depth === 0) {
10810
+ break;
10811
+ }
10812
+ depth--;
10813
+ i++;
10814
+ continue;
10815
+ }
10816
+ if (ch === "," && depth === 0) {
10817
+ break;
10818
+ }
10819
+ i++;
10820
+ }
10821
+ const colDef = createSql.slice(start, i);
10822
+ const collRe = /\bCOLLATE\s+("([^"]+)"|'([^']+)'|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][\w$]*))/i;
10823
+ const match = collRe.exec(colDef);
10824
+ if (!match) return null;
10825
+ return match[2] ?? match[3] ?? match[4] ?? match[5] ?? match[6] ?? match[1] ?? null;
10826
+ }
10827
+ async function indexCollationMatchesColumn(d1, table, tableSafe, indexSafe, columnName, session) {
10828
+ const xinfo = await executeD1Query(d1, {
10829
+ query: `PRAGMA index_xinfo("${indexSafe}")`,
10830
+ params: [],
10831
+ ...session
10832
+ });
10833
+ if (!xinfo.ok) {
10834
+ return false;
10835
+ }
10836
+ const xRows = xinfo.rows ?? [];
10837
+ const keyRows = xRows.filter((row) => {
10838
+ const isKey = row.key === 1 || row.key === true || Number(row.key) === 1;
10839
+ if (!isKey) return false;
10840
+ return typeof row.name === "string" && row.name === columnName;
10841
+ });
10842
+ if (keyRows.length === 0) {
10843
+ const byName = xRows.find(
10844
+ (row) => typeof row.name === "string" && row.name === columnName
10845
+ );
10846
+ if (!byName) return false;
10847
+ keyRows.push(byName);
10848
+ }
10849
+ const indexColl = normalizeSqliteCollation(keyRows[0]?.coll);
10850
+ const master = await executeD1Query(d1, {
10851
+ query: `SELECT sql AS create_sql FROM sqlite_master WHERE type = 'table' AND name = ?`,
10852
+ params: [table],
10853
+ ...session
10854
+ });
10855
+ let createSql = "";
10856
+ if (master.ok && Array.isArray(master.rows) && master.rows.length > 0) {
10857
+ createSql = String(
10858
+ master.rows[0]?.create_sql ?? ""
10859
+ );
10860
+ }
10861
+ const columnCollRaw = parseColumnCollationFromCreateSql(createSql, columnName);
10862
+ const columnColl = normalizeSqliteCollation(columnCollRaw);
10863
+ return indexColl === columnColl;
10864
+ }
10865
+ async function resolveD1BoundedIdentityColumn(d1, tableName, session) {
10866
+ const table = tableName.trim();
10867
+ if (!table) {
10868
+ throw new D1SqlCompileError("missing_table", "table_name is required for bounded mutation");
10869
+ }
10870
+ const safe = table.replace(/"/g, '""');
10871
+ const info = await executeD1Query(d1, {
10872
+ query: `PRAGMA table_info("${safe}")`,
10873
+ params: [],
10874
+ ...session
10875
+ });
10876
+ if (!info.ok) {
10877
+ throw new D1SqlCompileError(
10878
+ "bounded_mutation_no_unique_identity",
10879
+ `Unable to introspect table "${table}" for bounded mutation identity: ${info.message}`
10880
+ );
10881
+ }
10882
+ const cols = info.rows.filter(
10883
+ (row) => typeof row?.name === "string" && row.name.length > 0
10884
+ );
10885
+ const colByName = new Map(cols.map((col) => [col.name, col]));
10886
+ const isNotNullColumn = (name) => {
10887
+ const col = colByName.get(name);
10888
+ if (!col) return false;
10889
+ return col.notnull === 1 || col.notnull === true || Number(col.notnull) === 1;
10890
+ };
10891
+ const isIntegerPrimaryKeyType = (col) => {
10892
+ if (typeof col.pk !== "number" || col.pk <= 0) return false;
10893
+ const declared = String(col.type ?? "").trim().toUpperCase();
10894
+ return declared === "INTEGER";
10895
+ };
10896
+ const loadIndexList = async () => {
10897
+ const indexList = await executeD1Query(d1, {
10898
+ query: `PRAGMA index_list("${safe}")`,
10899
+ params: [],
10900
+ ...session
10901
+ });
10902
+ if (!indexList.ok) return null;
10903
+ return indexList.rows;
10904
+ };
10905
+ const isDescendingIntegerPrimaryKeyException = async (colName, indexes) => {
10906
+ if (indexes) {
10907
+ const hasPkOrigin = indexes.some(
10908
+ (index) => String(index.origin ?? "").toLowerCase() === "pk"
10909
+ );
10910
+ if (hasPkOrigin) return true;
10911
+ const originReported = indexes.some(
10912
+ (index) => index.origin !== void 0 && index.origin !== null && String(index.origin).length > 0
10913
+ );
10914
+ if (indexes.length === 0 || originReported) {
10915
+ return false;
10916
+ }
10917
+ }
10918
+ const master = await executeD1Query(d1, {
10919
+ query: `SELECT sql AS create_sql FROM sqlite_master WHERE type = 'table' AND name = ?`,
10920
+ params: [table],
10921
+ ...session
10922
+ });
10923
+ if (!master.ok || !Array.isArray(master.rows) || master.rows.length === 0) {
10924
+ return false;
10925
+ }
10926
+ const createSql = String(
10927
+ master.rows[0]?.create_sql ?? ""
10928
+ );
10929
+ if (!createSql) return false;
10930
+ const escaped = colName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10931
+ const inlineDesc = new RegExp(
10932
+ `(?:^|[^\\w])(?:"${escaped}"|${escaped})\\s+INTEGER\\s+PRIMARY\\s+KEY\\s+DESC\\b`,
10933
+ "i"
10934
+ );
10935
+ const tableDesc = new RegExp(
10936
+ `PRIMARY\\s+KEY\\s*\\(\\s*(?:"${escaped}"|${escaped})\\s+DESC\\b`,
10937
+ "i"
10938
+ );
10939
+ return inlineDesc.test(createSql) || tableDesc.test(createSql);
10940
+ };
10941
+ const pkCols = cols.filter((row) => typeof row.pk === "number" && row.pk > 0).sort((a, b) => (a.pk ?? 0) - (b.pk ?? 0));
10942
+ let indexRows;
10943
+ if (pkCols.length === 1 && pkCols[0]?.name) {
10944
+ if (isIntegerPrimaryKeyType(pkCols[0])) {
10945
+ indexRows = await loadIndexList();
10946
+ const isDescException = await isDescendingIntegerPrimaryKeyException(
10947
+ pkCols[0].name,
10948
+ indexRows
10949
+ );
10950
+ if (!isDescException) {
10951
+ return pkCols[0].name;
10952
+ }
10953
+ } else if (isNotNullColumn(pkCols[0].name)) {
10954
+ indexRows = await loadIndexList();
10955
+ const pkIndex = (indexRows ?? []).find(
10956
+ (index) => String(index.origin ?? "").toLowerCase() === "pk"
10957
+ );
10958
+ if (pkIndex && typeof pkIndex.name === "string" && pkIndex.name) {
10959
+ const indexSafe = pkIndex.name.replace(/"/g, '""');
10960
+ const collMatch = await indexCollationMatchesColumn(
10961
+ d1,
10962
+ table,
10963
+ safe,
10964
+ indexSafe,
10965
+ pkCols[0].name,
10966
+ session
10967
+ );
10968
+ if (collMatch) {
10969
+ return pkCols[0].name;
10970
+ }
10971
+ }
10972
+ }
10973
+ }
10974
+ if (indexRows === void 0) {
10975
+ indexRows = await loadIndexList();
10976
+ }
10977
+ if (indexRows) {
10978
+ for (const index of indexRows) {
10979
+ const unique = index.unique === 1 || index.unique === true || Number(index.unique) === 1;
10980
+ if (!unique || typeof index.name !== "string" || !index.name) continue;
10981
+ const isPartial = index.partial === 1 || index.partial === true || Number(index.partial) === 1;
10982
+ if (isPartial) {
10983
+ continue;
10984
+ }
10985
+ const indexSafe = index.name.replace(/"/g, '""');
10986
+ const indexInfo = await executeD1Query(d1, {
10987
+ query: `PRAGMA index_info("${indexSafe}")`,
10988
+ params: [],
10989
+ ...session
10990
+ });
10991
+ if (!indexInfo.ok) continue;
10992
+ const rawIndexCols = indexInfo.rows ?? [];
10993
+ const hasExpressionTerm = rawIndexCols.some((row) => {
10994
+ const nameOk = typeof row?.name === "string" && row.name.length > 0;
10995
+ if (!nameOk) return true;
10996
+ if (typeof row.cid === "number" && row.cid < 0) return true;
10997
+ return false;
10998
+ });
10999
+ if (hasExpressionTerm || rawIndexCols.length === 0) {
11000
+ continue;
11001
+ }
11002
+ const indexCols = rawIndexCols.filter(
11003
+ (row) => typeof row?.name === "string" && row.name.length > 0
11004
+ );
11005
+ if (indexCols.length === 1 && indexCols[0]?.name) {
11006
+ const identity = indexCols[0].name;
11007
+ if (!isNotNullColumn(identity)) {
11008
+ continue;
11009
+ }
11010
+ const collMatch = await indexCollationMatchesColumn(
11011
+ d1,
11012
+ table,
11013
+ safe,
11014
+ indexSafe,
11015
+ identity,
11016
+ session
11017
+ );
11018
+ if (!collMatch) {
11019
+ continue;
11020
+ }
11021
+ return identity;
11022
+ }
11023
+ }
11024
+ }
11025
+ throw new D1SqlCompileError(
11026
+ "bounded_mutation_no_unique_identity",
11027
+ `Bounded update/delete on "${table}" requires a proven single-column PRIMARY KEY or UNIQUE index`
11028
+ );
11029
+ }
11030
+ async function compileOptionsForBoundedMutation(d1, payload, session) {
11031
+ if (!hasPaginationBounds2(payload) && !payload.sort_by) {
11032
+ return void 0;
11033
+ }
11034
+ if (!hasPaginationBounds2(payload)) {
11035
+ return void 0;
11036
+ }
11037
+ const identityColumn = await resolveD1BoundedIdentityColumn(
11038
+ d1,
11039
+ payload.table_name ?? "",
11040
+ session
11041
+ );
11042
+ return { identityColumn };
11043
+ }
11044
+ function headerValue2(options, name) {
11045
+ const headers = options?.headers;
11046
+ if (!headers) return void 0;
11047
+ const lower = name.toLowerCase();
11048
+ for (const [key, value] of Object.entries(headers)) {
11049
+ if (key.toLowerCase() === lower && value?.trim()) {
11050
+ return value.trim();
11051
+ }
11052
+ }
11053
+ return void 0;
11054
+ }
11055
+ function sessionFromOptions(options, defaults) {
11056
+ return {
11057
+ bookmark: headerValue2(options, "x-athena-d1-bookmark") ?? null,
11058
+ sessionMode: headerValue2(options, "x-athena-d1-session-mode") ?? defaults.defaultSessionMode ?? null
11059
+ };
11060
+ }
11061
+ function resolveStripNulls(payloadStrip, callOptions, defaultValue = true) {
11062
+ if (typeof payloadStrip === "boolean") return payloadStrip;
11063
+ if (typeof callOptions?.stripNulls === "boolean") return callOptions.stripNulls;
11064
+ return defaultValue;
11065
+ }
11066
+ function stripNullPropertiesFromRows(rows) {
11067
+ return rows.map((row) => {
11068
+ if (row == null || typeof row !== "object" || Array.isArray(row)) {
11069
+ return row;
11070
+ }
11071
+ const out = {};
11072
+ for (const [key, value] of Object.entries(row)) {
11073
+ if (value !== null) {
11074
+ out[key] = value;
11075
+ }
11076
+ }
11077
+ return out;
11078
+ });
11079
+ }
11080
+ function maybeStripNullRows(rows, strip) {
11081
+ return strip ? stripNullPropertiesFromRows(rows) : rows;
11082
+ }
11083
+ function successResponse(data, count, raw, bookmark) {
11084
+ const response = {
11085
+ ok: true,
11086
+ status: 200,
11087
+ statusText: "OK",
11088
+ data,
11089
+ count: count ?? null,
11090
+ error: void 0,
11091
+ errorDetails: null,
11092
+ raw
11093
+ };
11094
+ if (bookmark) {
11095
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
11096
+ const rawRecord = raw;
11097
+ rawRecord.bookmark = bookmark;
11098
+ }
11099
+ }
11100
+ return response;
11101
+ }
11102
+ function errorResponse(status, code, message, endpoint, method, hint) {
11103
+ const error = new AthenaGatewayError({
11104
+ code,
11105
+ message,
11106
+ status,
11107
+ endpoint,
11108
+ method,
11109
+ hint
11110
+ });
11111
+ return {
11112
+ ok: false,
11113
+ status,
11114
+ statusText: null,
11115
+ data: null,
11116
+ error: error.message,
11117
+ errorDetails: error.toDetails(),
11118
+ raw: { error: message, code }
11119
+ };
11120
+ }
11121
+ function compileErrorResponse(error, endpoint, method) {
11122
+ if (error instanceof D1SqlCompileError) {
11123
+ return errorResponse(
11124
+ 400,
11125
+ "HTTP_ERROR",
11126
+ error.message,
11127
+ endpoint,
11128
+ method,
11129
+ `D1 SQL compile failed (${error.code})`
11130
+ );
11131
+ }
11132
+ const message = error instanceof Error ? error.message : String(error);
11133
+ return errorResponse(500, "UNKNOWN_ERROR", message, endpoint, method);
11134
+ }
11135
+ function createCloudflareD1GatewayTransport(options) {
11136
+ const { d1 } = options;
11137
+ async function runCompiled(compiled, callOptions, endpoint, method, mapResult, stripNulls = true) {
11138
+ try {
11139
+ const session = sessionFromOptions(callOptions, options);
11140
+ if (compiled.statements && compiled.statements.length > 1) {
11141
+ const batch = await executeD1Batch(d1, {
11142
+ statements: compiled.statements.map((statement) => ({
11143
+ query: statement.sql,
11144
+ params: statement.params
11145
+ })),
11146
+ ...session
11147
+ });
11148
+ if (!batch.ok) {
11149
+ return errorResponse(400, "HTTP_ERROR", batch.message, endpoint, method);
11150
+ }
11151
+ const rows2 = maybeStripNullRows(
11152
+ batch.results.flatMap(
11153
+ (item) => Array.isArray(item.results) ? item.results : []
11154
+ ),
11155
+ stripNulls
11156
+ );
11157
+ const changes = batch.results.reduce((sum2, item) => {
11158
+ const meta = item?.meta;
11159
+ const n = meta && typeof meta === "object" && typeof meta.changes === "number" ? meta.changes : 0;
11160
+ return sum2 + n;
11161
+ }, 0);
11162
+ const count = rows2.length > 0 ? rows2.length : changes;
11163
+ const mapped2 = mapResult?.(rows2, count) ?? {
11164
+ data: rows2,
11165
+ count
11166
+ };
11167
+ return successResponse(mapped2.data, mapped2.count, batch, batch.bookmark);
11168
+ }
11169
+ const result = await executeD1Query(d1, {
11170
+ query: compiled.sql,
11171
+ params: compiled.params,
11172
+ ...session
11173
+ });
11174
+ if (!result.ok) {
11175
+ return errorResponse(400, "HTTP_ERROR", result.message, endpoint, method);
11176
+ }
11177
+ const rows = maybeStripNullRows(result.rows, stripNulls);
11178
+ const mapped = mapResult?.(rows, result.count) ?? {
11179
+ data: rows,
11180
+ count: result.count
11181
+ };
11182
+ return successResponse(mapped.data, mapped.count, result, result.bookmark);
11183
+ } catch (error) {
11184
+ const message = error instanceof Error ? error.message : String(error);
11185
+ return errorResponse(500, "UNKNOWN_ERROR", message, endpoint, method);
11186
+ }
11187
+ }
11188
+ return {
11189
+ baseUrl: CLOUDFLARE_EDGE_BASE_URL,
11190
+ buildHeaders(callOptions) {
11191
+ return { ...callOptions?.headers ?? {} };
11192
+ },
11193
+ async resolveCallOptions(callOptions) {
11194
+ return callOptions;
11195
+ },
11196
+ async verifyConnection(connectionOptions) {
11197
+ const baseUrl = CLOUDFLARE_EDGE_BASE_URL;
11198
+ try {
11199
+ const result = await executeD1Query(d1, { query: "SELECT 1 AS ok" });
11200
+ if (!result.ok) {
11201
+ return {
11202
+ ok: false,
11203
+ reachable: false,
11204
+ status: 500,
11205
+ statusText: null,
11206
+ baseUrl,
11207
+ url: `${baseUrl}/d1`,
11208
+ error: result.message,
11209
+ errorDetails: null,
11210
+ raw: result
11211
+ };
11212
+ }
11213
+ return {
11214
+ ok: true,
11215
+ reachable: true,
11216
+ status: 200,
11217
+ statusText: "OK",
11218
+ baseUrl,
11219
+ url: `${baseUrl}/d1`,
11220
+ error: void 0,
11221
+ errorDetails: null,
11222
+ raw: result
11223
+ };
11224
+ } catch (error) {
11225
+ const message = error instanceof Error ? error.message : String(error);
11226
+ return {
11227
+ ok: false,
11228
+ reachable: false,
11229
+ status: 0,
11230
+ statusText: null,
11231
+ baseUrl,
11232
+ url: `${baseUrl}/d1`,
11233
+ error: message,
11234
+ errorDetails: null,
11235
+ raw: null
11236
+ };
11237
+ }
11238
+ },
11239
+ async fetchGateway(payload, callOptions) {
11240
+ try {
11241
+ if (payload && typeof payload === "object" && "operation" in payload) {
11242
+ return errorResponse(
11243
+ 400,
11244
+ "HTTP_ERROR",
11245
+ "Direct AST operation payloads are unsupported on D1 edge-local",
11246
+ "/gateway/fetch",
11247
+ "POST"
11248
+ );
11249
+ }
11250
+ const compiled = compileD1Fetch(payload);
11251
+ const stripNulls = resolveStripNulls(payload.strip_nulls, callOptions, true);
11252
+ if (payload.head === true) {
11253
+ return runCompiled(
11254
+ compiled,
11255
+ callOptions,
11256
+ "/gateway/fetch",
11257
+ "POST",
11258
+ (rows) => ({ data: [], count: extractAthenaCount(rows) }),
11259
+ // COUNT rows are meta, not user-facing object rows
11260
+ false
11261
+ );
11262
+ }
11263
+ const wantsTotalCount = payload.count === "exact" || payload.count === "planned" || payload.count === "estimated";
11264
+ if (wantsTotalCount) {
11265
+ const session = sessionFromOptions(callOptions, options);
11266
+ const countCompiled = compileD1Count(payload);
11267
+ const batch = await executeD1Batch(d1, {
11268
+ statements: [
11269
+ {
11270
+ query: compiled.sql,
11271
+ params: compiled.params
11272
+ },
11273
+ {
11274
+ query: countCompiled.sql,
11275
+ params: countCompiled.params
11276
+ }
11277
+ ],
11278
+ ...session
11279
+ });
11280
+ if (!batch.ok) {
11281
+ return errorResponse(400, "HTTP_ERROR", batch.message, "/gateway/fetch", "POST");
11282
+ }
11283
+ const dataItem = batch.results[0];
11284
+ const countItem = batch.results[1];
11285
+ if (!dataItem || dataItem.success === false) {
11286
+ const message = dataItem && typeof dataItem.error === "string" && dataItem.error.trim() ? dataItem.error : "D1 page query failed";
11287
+ return errorResponse(400, "HTTP_ERROR", message, "/gateway/fetch", "POST");
11288
+ }
11289
+ if (!countItem || countItem.success === false) {
11290
+ const message = countItem && typeof countItem.error === "string" && countItem.error.trim() ? countItem.error : "D1 count query failed";
11291
+ return errorResponse(400, "HTTP_ERROR", message, "/gateway/fetch", "POST");
11292
+ }
11293
+ const dataRows = Array.isArray(dataItem.results) ? dataItem.results : [];
11294
+ const countRows = Array.isArray(countItem.results) ? countItem.results : [];
11295
+ const total = extractAthenaCount(countRows);
11296
+ const rows = maybeStripNullRows(dataRows, stripNulls);
11297
+ return successResponse(
11298
+ rows,
11299
+ total,
11300
+ { data: dataItem, count: countItem, batch },
11301
+ batch.bookmark
11302
+ );
11303
+ }
11304
+ return runCompiled(compiled, callOptions, "/gateway/fetch", "POST", void 0, stripNulls);
11305
+ } catch (error) {
11306
+ return compileErrorResponse(error, "/gateway/fetch", "POST");
11307
+ }
11308
+ },
11309
+ async insertGateway(payload, callOptions) {
11310
+ try {
11311
+ const compiled = compileD1Insert(payload);
11312
+ const stripNulls = resolveStripNulls(void 0, callOptions, true);
11313
+ return runCompiled(compiled, callOptions, "/gateway/insert", "PUT", void 0, stripNulls);
11314
+ } catch (error) {
11315
+ return compileErrorResponse(error, "/gateway/insert", "PUT");
11316
+ }
11317
+ },
11318
+ async updateGateway(payload, callOptions) {
11319
+ try {
11320
+ const session = sessionFromOptions(callOptions, options);
11321
+ const compileOptions = await compileOptionsForBoundedMutation(d1, payload, session);
11322
+ const compiled = compileD1Update(payload, compileOptions);
11323
+ const stripNulls = resolveStripNulls(payload.strip_nulls, callOptions, true);
11324
+ return runCompiled(compiled, callOptions, "/gateway/update", "POST", void 0, stripNulls);
11325
+ } catch (error) {
11326
+ return compileErrorResponse(error, "/gateway/update", "POST");
11327
+ }
11328
+ },
11329
+ async deleteGateway(payload, callOptions) {
11330
+ try {
11331
+ const session = sessionFromOptions(callOptions, options);
11332
+ const compileOptions = await compileOptionsForBoundedMutation(d1, payload, session);
11333
+ const compiled = compileD1Delete(payload, compileOptions);
11334
+ const stripNulls = resolveStripNulls(void 0, callOptions, true);
11335
+ return runCompiled(compiled, callOptions, "/gateway/delete", "DELETE", void 0, stripNulls);
11336
+ } catch (error) {
11337
+ return compileErrorResponse(error, "/gateway/delete", "DELETE");
11338
+ }
11339
+ },
11340
+ async rpcGateway(payload, callOptions) {
11341
+ return errorResponse(
11342
+ 400,
11343
+ "HTTP_ERROR",
11344
+ "RPC is unsupported on D1 edge-local mode",
11345
+ "/gateway/rpc",
11346
+ "POST",
11347
+ "Use flat CRUD or raw query SQL instead"
11348
+ );
11349
+ },
11350
+ async queryGateway(payload, callOptions) {
11351
+ try {
11352
+ const params = payload.params ?? callOptions?.params;
11353
+ const session = sessionFromOptions(callOptions, options);
11354
+ const query = rewritePostgresSqlForSqlite(payload.query);
11355
+ const result = await executeD1Query(d1, {
11356
+ query,
11357
+ params: Array.isArray(params) ? params : [],
11358
+ ...session
11359
+ });
11360
+ if (!result.ok) {
11361
+ return errorResponse(400, "HTTP_ERROR", result.message, "/gateway/query", "POST");
11362
+ }
11363
+ const stripNulls = resolveStripNulls(void 0, callOptions, true);
11364
+ const rows = maybeStripNullRows(result.rows, stripNulls);
11365
+ return successResponse(
11366
+ rows,
11367
+ result.count,
11368
+ { ...result, query },
11369
+ result.bookmark
11370
+ );
11371
+ } catch (error) {
11372
+ const message = error instanceof Error ? error.message : String(error);
11373
+ return errorResponse(500, "UNKNOWN_ERROR", message, "/gateway/query", "POST");
11374
+ }
11375
+ }
11376
+ };
11377
+ }
11378
+
11379
+ // src/config/errors.ts
11380
+ var AthenaConfigurationError = class extends Error {
11381
+ code;
11382
+ service;
11383
+ constructor(code, message, service) {
11384
+ super(message);
11385
+ this.name = "AthenaConfigurationError";
11386
+ this.code = code;
11387
+ this.service = service;
11388
+ }
11389
+ };
11390
+
11391
+ // src/cloudflare/execution-mode.ts
11392
+ var ATHENA_EXECUTION_MODE_ENV_KEY = "ATHENA_EXECUTION_MODE";
11393
+ var ATHENA_EXECUTION_PREFER_ENV_KEY = "ATHENA_EXECUTION_PREFER";
11394
+ var MODE_ALIASES = {
11395
+ gateway: "gateway",
11396
+ server: "gateway",
11397
+ remote: "gateway",
11398
+ http: "gateway",
11399
+ edge: "edge",
11400
+ cloudflare: "edge",
11401
+ "cloudflare-edge": "edge",
11402
+ d1: "edge",
11403
+ local: "edge",
11404
+ auto: "auto"
11405
+ };
11406
+ function normalizeOptional(value) {
11407
+ const trimmed = value?.trim();
11408
+ return trimmed || void 0;
11409
+ }
11410
+ function normalizeModeString(value) {
11411
+ if (value == null) return void 0;
11412
+ const key = value.trim().toLowerCase();
11413
+ if (!key) return void 0;
11414
+ const mapped = MODE_ALIASES[key];
11415
+ if (!mapped) {
11416
+ throw new AthenaConfigurationError(
11417
+ "ATHENA_NO_SERVICE_CONFIGURED",
11418
+ `Unknown Athena execution mode "${value}". Use gateway | edge | auto (aliases: server, remote, cloudflare, d1).`,
11419
+ "db"
11420
+ );
11421
+ }
11422
+ return mapped;
11423
+ }
11424
+ function isD1Binding(value) {
11425
+ return Boolean(
11426
+ value && typeof value === "object" && typeof value.prepare === "function"
11427
+ );
11428
+ }
11429
+ var GATEWAY_URL_ENV_KEYS = [
11430
+ "ATHENA_URL",
11431
+ "NEXT_PUBLIC_ATHENA_URL",
11432
+ "ATHENA_DB_URL",
11433
+ "ATHENA_GATEWAY_URL",
11434
+ "NEXT_PUBLIC_ATHENA_DB_API_URL"
11435
+ ];
11436
+ function resolveGatewayUrl(url, env) {
11437
+ if (normalizeOptional(url)) {
11438
+ return normalizeOptional(url);
11439
+ }
11440
+ for (const key of GATEWAY_URL_ENV_KEYS) {
11441
+ const value = normalizeOptional(env[key]);
11442
+ if (value) return value;
11443
+ }
11444
+ return void 0;
11445
+ }
11446
+ function resolvePrefer(prefer, env) {
11447
+ const raw = normalizeOptional(typeof prefer === "string" ? prefer : prefer ?? void 0) ?? normalizeOptional(env[ATHENA_EXECUTION_PREFER_ENV_KEY]) ?? "edge";
11448
+ const key = raw.toLowerCase();
11449
+ if (key === "gateway" || key === "server" || key === "remote" || key === "http") {
11450
+ return "gateway";
11451
+ }
11452
+ if (key === "edge" || key === "d1" || key === "cloudflare" || key === "local") {
11453
+ return "edge";
11454
+ }
11455
+ throw new AthenaConfigurationError(
11456
+ "ATHENA_NO_SERVICE_CONFIGURED",
11457
+ `Unknown Athena execution prefer "${raw}". Use edge | gateway.`,
11458
+ "db"
11459
+ );
11460
+ }
11461
+ function resolveAthenaExecutionMode(input = {}) {
11462
+ const env = input.env ?? {};
11463
+ const fromEnv = normalizeModeString(env[ATHENA_EXECUTION_MODE_ENV_KEY]);
11464
+ const requested = normalizeModeString(input.mode) ?? fromEnv ?? "auto";
11465
+ const url = resolveGatewayUrl(input.url, env);
11466
+ const hasD1 = isD1Binding(input.d1);
11467
+ const hasGateway = Boolean(url);
11468
+ if (requested === "gateway") {
11469
+ if (!hasGateway) {
11470
+ throw new AthenaConfigurationError(
11471
+ "ATHENA_NO_SERVICE_CONFIGURED",
11472
+ 'Athena execution mode is "gateway" but no url / ATHENA_URL / ATHENA_DB_URL / ATHENA_GATEWAY_URL was provided.',
11473
+ "db"
11474
+ );
11475
+ }
11476
+ return "gateway";
11477
+ }
11478
+ if (requested === "edge") {
11479
+ if (!hasD1) {
11480
+ throw new AthenaConfigurationError(
11481
+ "ATHENA_NO_SERVICE_CONFIGURED",
11482
+ 'Athena execution mode is "edge" but no D1 binding was provided (db.d1 / config.d1 / env.DB).',
11483
+ "db"
11484
+ );
11485
+ }
11486
+ return "edge";
11487
+ }
11488
+ if (hasD1 && hasGateway) {
11489
+ return resolvePrefer(input.prefer, env);
11490
+ }
11491
+ if (hasD1) return "edge";
11492
+ if (hasGateway) return "gateway";
11493
+ throw new AthenaConfigurationError(
11494
+ "ATHENA_NO_SERVICE_CONFIGURED",
11495
+ '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).',
11496
+ "db"
11497
+ );
11498
+ }
11499
+
11500
+ // src/cloudflare/r2/storage.ts
11501
+ function normalizePrefix(prefix) {
11502
+ if (!prefix?.trim()) return "";
11503
+ const normalized = prefix.replace(/^\/+/, "").replace(/\/?$/, "/");
11504
+ if (normalized.includes("\0")) {
11505
+ throw new Error("storage prefix must not contain null bytes");
11506
+ }
11507
+ if (normalized.split("/").some((segment) => segment === "..")) {
11508
+ throw new Error('storage prefix must not contain ".." path segments');
11509
+ }
11510
+ return normalized;
11511
+ }
11512
+ function assertSafeObjectKey(key) {
11513
+ if (typeof key !== "string" || !key.trim()) {
11514
+ throw new Error("Object key is required");
11515
+ }
11516
+ if (key.includes("\0")) {
11517
+ throw new Error("Object key must not contain null bytes");
11518
+ }
11519
+ const cleaned = key.replace(/^\/+/, "");
11520
+ if (!cleaned) {
11521
+ throw new Error("Object key is required");
11522
+ }
11523
+ const segments = cleaned.split("/");
11524
+ if (segments.some((segment) => segment === "..")) {
11525
+ throw new Error('Object key must not contain ".." path segments');
11526
+ }
11527
+ return cleaned;
11528
+ }
11529
+ function joinKey(prefix, key) {
11530
+ return `${prefix}${assertSafeObjectKey(key)}`;
11531
+ }
11532
+ function toLogicalKey(prefix, physicalKey) {
11533
+ if (!prefix) return physicalKey;
11534
+ if (physicalKey.startsWith(prefix)) {
11535
+ return physicalKey.slice(prefix.length);
11536
+ }
11537
+ return physicalKey;
11538
+ }
11539
+ function toPhysicalKey(prefix, key) {
11540
+ return joinKey(prefix, key);
11541
+ }
11542
+ function unsupported(method) {
11543
+ throw new Error(
11544
+ `storage.${method} is not available in Cloudflare edge-local R2 object mode. Only putObject / getObject / deleteObject / listObjects are supported (L3a).`
11545
+ );
11546
+ }
11547
+ function createCloudflareR2StorageModule(options) {
11548
+ const prefix = normalizePrefix(options.prefix);
11549
+ const { r2 } = options;
11550
+ const putObject = async (input) => {
11551
+ const logical = assertSafeObjectKey(input.key);
11552
+ const physical = toPhysicalKey(prefix, logical);
11553
+ await r2.put(physical, input.body, {
11554
+ httpMetadata: input.contentType ? { contentType: input.contentType } : void 0,
11555
+ customMetadata: input.metadata
11556
+ });
11557
+ return { key: logical };
11558
+ };
11559
+ const getObject = async (input) => {
11560
+ const logical = assertSafeObjectKey(input.key);
11561
+ const physical = toPhysicalKey(prefix, logical);
11562
+ const object = await r2.get(physical);
11563
+ if (!object) return null;
11564
+ return {
11565
+ key: toLogicalKey(prefix, object.key),
11566
+ size: object.size,
11567
+ contentType: object.httpMetadata?.contentType,
11568
+ body: object
11569
+ };
11570
+ };
11571
+ const deleteObject = async (input) => {
11572
+ const logicalKeys = (Array.isArray(input.key) ? input.key : [input.key]).map(
11573
+ (key) => assertSafeObjectKey(key)
11574
+ );
11575
+ const physicalKeys = logicalKeys.map((key) => toPhysicalKey(prefix, key));
11576
+ await r2.delete(physicalKeys.length === 1 ? physicalKeys[0] : physicalKeys);
11577
+ return { deleted: logicalKeys };
11578
+ };
11579
+ const listObjects = async (input) => {
11580
+ const relative = input?.prefix?.trim() ? assertSafeObjectKey(input.prefix) : "";
11581
+ const listPrefix = `${prefix}${relative}`;
11582
+ const listed = await r2.list({
11583
+ prefix: listPrefix || void 0,
11584
+ limit: input?.limit,
11585
+ cursor: input?.cursor
11586
+ });
11587
+ return {
11588
+ objects: listed.objects.map((object) => ({
11589
+ key: toLogicalKey(prefix, object.key),
11590
+ size: object.size,
11591
+ etag: object.etag,
11592
+ uploaded: object.uploaded
11593
+ })),
11594
+ truncated: listed.truncated,
11595
+ cursor: listed.cursor
11596
+ };
11597
+ };
11598
+ const base = {
11599
+ putObject,
11600
+ getObject,
11601
+ deleteObject,
11602
+ listObjects
11603
+ };
11604
+ return new Proxy(base, {
11605
+ get(target, property, receiver) {
11606
+ if (property in target) {
11607
+ return Reflect.get(target, property, receiver);
11608
+ }
11609
+ if (typeof property === "string") {
11610
+ return (...args) => {
11611
+ return unsupported(property);
11612
+ };
11613
+ }
11614
+ return void 0;
11615
+ }
11616
+ });
11617
+ }
11618
+
11619
+ // src/billing/module.ts
11620
+ var SDK_NAME5 = "xylex-group/athena-billing";
11621
+ var SDK_HEADER_VALUE4 = buildSdkHeaderValue(SDK_NAME5);
11622
+ var AthenaBillingError = class extends Error {
11623
+ status;
11624
+ endpoint;
11625
+ method;
11626
+ body;
11627
+ constructor(input) {
11628
+ super(input.message);
11629
+ this.name = "AthenaBillingError";
11630
+ this.status = input.status;
11631
+ this.endpoint = input.endpoint;
11632
+ this.method = input.method;
11633
+ this.body = input.body;
11634
+ }
11635
+ };
11636
+ function withPathParam2(path, name, value) {
11637
+ return path.replace(`{${name}}`, encodeURIComponent(value));
11638
+ }
11639
+ function appendQuery3(path, query) {
11640
+ if (!query) return path;
11641
+ const params = new URLSearchParams();
11642
+ for (const [key, value] of Object.entries(query)) {
11643
+ if (value === void 0 || value === null) continue;
11644
+ params.set(key, String(value));
11645
+ }
11646
+ const serialized = params.toString();
11647
+ return serialized ? `${path}?${serialized}` : path;
11648
+ }
11649
+ function connectionQuery(input) {
11650
+ const query = {
11651
+ connectionId: input.connectionId
11652
+ };
11653
+ if (input.clientName) query.clientName = input.clientName;
11654
+ if ("cursor" in input && input.cursor) query.cursor = input.cursor;
11655
+ if ("source" in input && input.source) query.source = input.source;
11656
+ if ("limit" in input && input.limit !== void 0) query.limit = String(input.limit);
11657
+ if ("offset" in input && input.offset !== void 0) query.offset = String(input.offset);
11658
+ return query;
11659
+ }
11660
+ function parseEnvelopeData(body) {
11661
+ if (body && typeof body === "object" && "data" in body) {
11662
+ return body.data;
11663
+ }
11664
+ return body;
11665
+ }
11666
+ function createBillingModule(config) {
11667
+ const baseUrl = normalizeAthenaGatewayBaseUrl(config.baseUrl, {
11668
+ label: "Athena billing base URL"
11669
+ });
11670
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);
11671
+ async function call(method, path, body, options, responseType = "json") {
11672
+ const headers = buildAthenaRequestHeaders({
11673
+ profile: "gateway",
11674
+ sdkHeaderValue: SDK_HEADER_VALUE4,
11675
+ apiKey: options?.apiKey ?? config.apiKey,
11676
+ client: config.client,
11677
+ configHeaders: {
11678
+ ...config.headers ?? {}
11679
+ },
11680
+ callHeaders: options?.headers,
11681
+ contentType: "application/json"
11682
+ });
11683
+ let requestBody;
11684
+ if (body !== void 0 && body !== null) {
11685
+ if (typeof body === "string" || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof FormData || body instanceof URLSearchParams) {
11686
+ requestBody = body;
11687
+ } else {
11688
+ requestBody = JSON.stringify(body);
11689
+ if (!hasHeaderIgnoreCase(headers, "Content-Type")) {
11690
+ headers["Content-Type"] = "application/json";
11691
+ }
11692
+ }
11693
+ }
11694
+ const targetUrl = `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
11695
+ const response = await fetchImpl(targetUrl, {
11696
+ method,
11697
+ headers,
11698
+ body: requestBody,
11699
+ signal: options?.signal
11700
+ });
11701
+ if (responseType === "text") {
11702
+ const text = await response.text();
11703
+ if (!response.ok) {
11704
+ throw new AthenaBillingError({
11705
+ message: `Billing request failed (${response.status})`,
11706
+ status: response.status,
11707
+ endpoint: path,
11708
+ method,
11709
+ body: text
11710
+ });
11711
+ }
11712
+ return text;
11713
+ }
11714
+ const rawText = await response.text();
11715
+ let parsed = rawText;
11716
+ if (rawText) {
11717
+ try {
11718
+ parsed = JSON.parse(rawText);
11719
+ } catch {
11720
+ parsed = rawText;
11721
+ }
11722
+ } else {
11723
+ parsed = null;
11724
+ }
11725
+ if (!response.ok) {
11726
+ const message = parsed && typeof parsed === "object" && "message" in parsed && typeof parsed.message === "string" ? parsed.message : `Billing request failed (${response.status})`;
11727
+ throw new AthenaBillingError({
11728
+ message,
11729
+ status: response.status,
11730
+ endpoint: path,
11731
+ method,
11732
+ body: parsed
11733
+ });
11734
+ }
11735
+ return parseEnvelopeData(parsed);
11736
+ }
11737
+ return {
11738
+ getCapabilities(input, options) {
11739
+ return call(
11740
+ "GET",
11741
+ appendQuery3("/billing/v1/capabilities", connectionQuery(input)),
11742
+ void 0,
11743
+ options
11744
+ );
11745
+ },
11746
+ createCheckout(body, options) {
11747
+ return call("POST", "/billing/v1/checkouts", body, options);
11748
+ },
11749
+ listProducts(input, options) {
11750
+ return call(
11751
+ "GET",
11752
+ appendQuery3("/billing/v1/products", connectionQuery(input)),
11753
+ void 0,
11754
+ options
11755
+ );
11756
+ },
11757
+ listPrices(input, options) {
11758
+ return call(
11759
+ "GET",
11760
+ appendQuery3("/billing/v1/prices", {
11761
+ ...connectionQuery(input),
11762
+ ...input.productId ? { productId: input.productId } : {}
11763
+ }),
11764
+ void 0,
11765
+ options
11766
+ );
11767
+ },
11768
+ listCustomers(input, options) {
11769
+ return call(
11770
+ "GET",
11771
+ appendQuery3("/billing/v1/customers", connectionQuery(input)),
11772
+ void 0,
11773
+ options
11774
+ );
11775
+ },
11776
+ createCustomer(input, options) {
11777
+ return call(
11778
+ "POST",
11779
+ "/billing/v1/customers",
11780
+ {
11781
+ connectionId: input.connectionId,
11782
+ clientName: input.clientName,
11783
+ email: input.email,
11784
+ name: input.name,
11785
+ metadata: input.metadata ?? {},
11786
+ idempotencyKey: input.idempotencyKey
9123
11787
  },
9124
11788
  options
9125
11789
  );
@@ -9548,18 +12212,6 @@ function createBillingModule(config) {
9548
12212
  };
9549
12213
  }
9550
12214
 
9551
- // src/config/errors.ts
9552
- var AthenaConfigurationError = class extends Error {
9553
- code;
9554
- service;
9555
- constructor(code, message, service) {
9556
- super(message);
9557
- this.name = "AthenaConfigurationError";
9558
- this.code = code;
9559
- this.service = service;
9560
- }
9561
- };
9562
-
9563
12215
  // src/diagnostics.ts
9564
12216
  function readProcessEnv2() {
9565
12217
  try {
@@ -9659,14 +12311,30 @@ function readFirstEnv(env, keys) {
9659
12311
  }
9660
12312
  return void 0;
9661
12313
  }
9662
- function normalizeOptional(value) {
12314
+ function readFirstEnvHttpUrl(env, keys) {
12315
+ for (const key of keys) {
12316
+ const value = env?.[key]?.trim();
12317
+ if (value && isAbsoluteHttpUrl(value)) return value;
12318
+ }
12319
+ return void 0;
12320
+ }
12321
+ function normalizeOptional2(value) {
9663
12322
  const normalized = value?.trim();
9664
12323
  return normalized || void 0;
9665
12324
  }
12325
+ function isAbsoluteHttpUrl(value) {
12326
+ try {
12327
+ const url = new URL(value);
12328
+ return url.protocol === "http:" || url.protocol === "https:";
12329
+ } catch {
12330
+ return false;
12331
+ }
12332
+ }
9666
12333
  function appendPath(baseUrl, path) {
9667
12334
  return `${baseUrl.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
9668
12335
  }
9669
12336
  function toWebSocketUrl(baseUrl) {
12337
+ if (!isAbsoluteHttpUrl(baseUrl)) return void 0;
9670
12338
  const url = new URL(baseUrl);
9671
12339
  url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
9672
12340
  url.pathname = `${url.pathname.replace(/\/+$/, "")}/wss/gateway`;
@@ -9676,11 +12344,11 @@ function toWebSocketUrl(baseUrl) {
9676
12344
  }
9677
12345
  function resolveCore(config) {
9678
12346
  const env = config.env;
9679
- const explicitRoot = normalizeOptional(config.url);
9680
- const envRoot = readFirstEnv(env, ENV_URL_KEYS);
9681
- const root = explicitRoot ?? envRoot;
9682
- const explicitRootWinsOverEnvServices = explicitRoot !== void 0;
9683
- const resolveService = (explicit, envKeys, path) => normalizeOptional(explicit) ?? (explicitRootWinsOverEnvServices && root ? appendPath(root, path) : void 0) ?? readFirstEnv(env, envKeys) ?? (root ? appendPath(root, path) : void 0);
12347
+ const explicitRoot = normalizeOptional2(config.url);
12348
+ const envRoot = readFirstEnvHttpUrl(env, ENV_URL_KEYS);
12349
+ const root = explicitRoot && isAbsoluteHttpUrl(explicitRoot) ? explicitRoot : explicitRoot ? void 0 : envRoot;
12350
+ const explicitRootWinsOverEnvServices = Boolean(root && explicitRoot && isAbsoluteHttpUrl(explicitRoot));
12351
+ const resolveService = (explicit, envKeys, path) => normalizeOptional2(explicit) ?? (explicitRootWinsOverEnvServices && root ? appendPath(root, path) : void 0) ?? readFirstEnvHttpUrl(env, envKeys) ?? (root ? appendPath(root, path) : void 0);
9684
12352
  const dbUrl = resolveService(config.db?.url, ENV_DB_URL_KEYS, "db");
9685
12353
  const urls = {
9686
12354
  db: dbUrl,
@@ -9688,8 +12356,8 @@ function resolveCore(config) {
9688
12356
  chat: resolveService(config.chat?.url, ENV_CHAT_URL_KEYS, "chat"),
9689
12357
  storage: resolveService(config.storage?.url, ENV_STORAGE_URL_KEYS, "storage"),
9690
12358
  // Billing lives on the main Athena HTTP surface (same host as gateway/db).
9691
- billing: normalizeOptional(config.billing?.url) ?? dbUrl ?? root ?? void 0,
9692
- chatWs: normalizeOptional(config.chat?.wsUrl) ?? (explicitRootWinsOverEnvServices && root ? toWebSocketUrl(root) : void 0) ?? readFirstEnv(env, ENV_CHAT_WS_URL_KEYS) ?? (root ? toWebSocketUrl(root) : void 0)
12359
+ billing: normalizeOptional2(config.billing?.url) ?? dbUrl ?? root ?? void 0,
12360
+ chatWs: normalizeOptional2(config.chat?.wsUrl) ?? (explicitRootWinsOverEnvServices && root ? toWebSocketUrl(root) : void 0) ?? readFirstEnvHttpUrl(env, ENV_CHAT_WS_URL_KEYS) ?? (root ? toWebSocketUrl(root) : void 0)
9693
12361
  };
9694
12362
  if (!urls.db && !urls.auth && !urls.chat && !urls.storage && !urls.billing) {
9695
12363
  throw new AthenaConfigurationError(
@@ -9698,7 +12366,7 @@ function resolveCore(config) {
9698
12366
  "db"
9699
12367
  );
9700
12368
  }
9701
- const key = normalizeOptional(config.key) ?? readFirstEnv(env, ENV_KEY_KEYS);
12369
+ const key = normalizeOptional2(config.key) ?? readFirstEnv(env, ENV_KEY_KEYS);
9702
12370
  if (!key) {
9703
12371
  throw new AthenaConfigurationError(
9704
12372
  "ATHENA_API_KEY_REQUIRED",
@@ -9709,7 +12377,7 @@ function resolveCore(config) {
9709
12377
  config,
9710
12378
  urls,
9711
12379
  key,
9712
- client: normalizeOptional(config.client) ?? readFirstEnv(env, ENV_CLIENT_KEYS)
12380
+ client: normalizeOptional2(config.client) ?? readFirstEnv(env, ENV_CLIENT_KEYS)
9713
12381
  };
9714
12382
  return {
9715
12383
  ...base,
@@ -9724,7 +12392,13 @@ async function resolveConfiguredContext(core, viewContext) {
9724
12392
  function createInternalConfig(core) {
9725
12393
  const { config, urls } = core;
9726
12394
  const { url: _authUrl, ...authOptions } = config.auth ?? {};
9727
- const { url: _storageUrl, directUpload, ...storageOptions } = config.storage ?? {};
12395
+ const {
12396
+ url: _storageUrl,
12397
+ directUpload,
12398
+ r2: _r2,
12399
+ prefix: _r2Prefix,
12400
+ ...storageOptions
12401
+ } = config.storage ?? {};
9728
12402
  const diagnostics = resolveAthenaClientDiagnostics({
9729
12403
  diagnostics: config.diagnostics,
9730
12404
  debugAst: config.debugAst,
@@ -9755,7 +12429,8 @@ function createInternalConfig(core) {
9755
12429
  storage: {
9756
12430
  ...storageOptions,
9757
12431
  ...directUpload ? { directUpload } : {}
9758
- }
12432
+ },
12433
+ gatewayTransport: config.gatewayTransport
9759
12434
  };
9760
12435
  }
9761
12436
  function serviceGuard(urls, service) {
@@ -9778,6 +12453,232 @@ function createUnavailableNamespace(service, urls, path = []) {
9778
12453
  }
9779
12454
  });
9780
12455
  }
12456
+ function isD1Binding2(value) {
12457
+ return Boolean(
12458
+ value && typeof value === "object" && typeof value.prepare === "function"
12459
+ );
12460
+ }
12461
+ function isR2Binding(value) {
12462
+ return Boolean(
12463
+ value && typeof value === "object" && typeof value.put === "function" && typeof value.get === "function"
12464
+ );
12465
+ }
12466
+ function foldBindingAliases(config) {
12467
+ const d1 = config.db?.d1 ?? config.d1;
12468
+ const r2 = config.storage?.r2 ?? config.r2;
12469
+ const sessionMode = config.db?.sessionMode ?? config.sessionMode;
12470
+ const prefix = config.storage?.prefix ?? config.storagePrefix;
12471
+ let next = { ...config };
12472
+ if (d1 !== void 0 || sessionMode !== void 0) {
12473
+ next = {
12474
+ ...next,
12475
+ db: {
12476
+ ...next.db,
12477
+ ...d1 !== void 0 ? { d1 } : {},
12478
+ ...sessionMode !== void 0 ? { sessionMode } : {}
12479
+ }
12480
+ };
12481
+ }
12482
+ if (r2 !== void 0 || prefix !== void 0) {
12483
+ next = {
12484
+ ...next,
12485
+ storage: {
12486
+ ...next.storage,
12487
+ ...r2 !== void 0 ? { r2 } : {},
12488
+ ...prefix !== void 0 ? { prefix } : {}
12489
+ }
12490
+ };
12491
+ }
12492
+ const {
12493
+ d1: _d1,
12494
+ r2: _r2,
12495
+ storagePrefix: _storagePrefix,
12496
+ sessionMode: _sessionMode,
12497
+ ...rest
12498
+ } = next;
12499
+ return rest;
12500
+ }
12501
+ function applyExecutionMode(config) {
12502
+ const d1 = config.db?.d1;
12503
+ const hasD1 = isD1Binding2(d1);
12504
+ const hasUrl = Boolean(
12505
+ normalizeOptional2(config.url) ?? normalizeOptional2(config.db?.url) ?? (config.env ? normalizeOptional2(config.env.ATHENA_URL) ?? normalizeOptional2(config.env.NEXT_PUBLIC_ATHENA_URL) : void 0)
12506
+ );
12507
+ const hasModeHint = config.mode != null || config.prefer != null || Boolean(config.env?.ATHENA_EXECUTION_MODE) || Boolean(config.env?.ATHENA_EXECUTION_PREFER);
12508
+ if (!hasD1 && !hasModeHint) {
12509
+ return config;
12510
+ }
12511
+ if (hasD1 && !hasUrl && !hasModeHint) {
12512
+ return config;
12513
+ }
12514
+ let resolved;
12515
+ try {
12516
+ resolved = resolveAthenaExecutionMode({
12517
+ mode: config.mode,
12518
+ prefer: config.prefer,
12519
+ d1: hasD1 ? d1 : null,
12520
+ url: config.url ?? config.db?.url,
12521
+ env: config.env
12522
+ });
12523
+ } catch (error) {
12524
+ if (!hasModeHint) return config;
12525
+ throw error;
12526
+ }
12527
+ if (resolved === "gateway" && hasD1) {
12528
+ const { d1: _drop, sessionMode: _sm, ...dbRest } = config.db ?? {};
12529
+ return {
12530
+ ...config,
12531
+ db: Object.keys(dbRest).length > 0 ? dbRest : void 0,
12532
+ gatewayTransport: void 0
12533
+ };
12534
+ }
12535
+ return config;
12536
+ }
12537
+ function resolveUnifiedRemoteRoot(config) {
12538
+ return normalizeOptional2(config.url) ?? readFirstEnv(config.env, ENV_URL_KEYS);
12539
+ }
12540
+ function isEdgeLocalSentinelUrl(url) {
12541
+ if (!url) return false;
12542
+ return url === CLOUDFLARE_EDGE_BASE_URL || url.startsWith("https://athena.local/") || url.startsWith("http://athena.local/");
12543
+ }
12544
+ function hasRemoteDbGatewayUrl(config) {
12545
+ const dbUrl = normalizeOptional2(config.db?.url) ?? readFirstEnv(config.env, ENV_DB_URL_KEYS);
12546
+ return Boolean(dbUrl && !isEdgeLocalSentinelUrl(dbUrl));
12547
+ }
12548
+ function hasRemoteHttpServices(config) {
12549
+ return Boolean(
12550
+ 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)
12551
+ );
12552
+ }
12553
+ function hasRemoteHttpStorage(config) {
12554
+ return Boolean(
12555
+ normalizeOptional2(config.storage?.url) || readFirstEnv(config.env, ENV_STORAGE_URL_KEYS) || resolveUnifiedRemoteRoot(config)
12556
+ );
12557
+ }
12558
+ function hasRemoteAuthService(config) {
12559
+ return Boolean(
12560
+ normalizeOptional2(config.auth?.url) || readFirstEnv(config.env, ENV_AUTH_URL_KEYS) || resolveUnifiedRemoteRoot(config)
12561
+ );
12562
+ }
12563
+ function materializeEdgeBindings(config) {
12564
+ const d1 = config.db?.d1;
12565
+ const r2 = config.storage?.r2;
12566
+ const hasD1 = isD1Binding2(d1);
12567
+ const hasR2 = isR2Binding(r2);
12568
+ if (!hasD1 && !hasR2) {
12569
+ return config;
12570
+ }
12571
+ if (hasD1 && d1 && typeof d1.prepare !== "function") {
12572
+ throw new AthenaConfigurationError(
12573
+ "ATHENA_NO_SERVICE_CONFIGURED",
12574
+ "db.d1 must be a D1 binding with prepare().",
12575
+ "db"
12576
+ );
12577
+ }
12578
+ const remoteRoot = resolveUnifiedRemoteRoot(config);
12579
+ const remoteServices = hasRemoteHttpServices(config);
12580
+ const remoteStorage = hasRemoteHttpStorage(config);
12581
+ const remoteAuth = hasRemoteAuthService(config);
12582
+ const next = { ...config };
12583
+ if (hasD1 && d1) {
12584
+ if (!config.gatewayTransport) {
12585
+ next.gatewayTransport = createCloudflareD1GatewayTransport({
12586
+ d1,
12587
+ defaultSessionMode: config.db?.sessionMode
12588
+ });
12589
+ }
12590
+ const explicitDbUrl = normalizeOptional2(config.db?.url);
12591
+ const remoteDbGateway = hasRemoteDbGatewayUrl(config);
12592
+ next.db = {
12593
+ ...config.db,
12594
+ d1,
12595
+ url: explicitDbUrl ?? (remoteDbGateway ? void 0 : CLOUDFLARE_EDGE_BASE_URL)
12596
+ };
12597
+ const explicitKey = normalizeOptional2(config.key);
12598
+ if (explicitKey) {
12599
+ next.key = explicitKey;
12600
+ } else if (!remoteServices) {
12601
+ next.key = CLOUDFLARE_EDGE_API_KEY;
12602
+ } else {
12603
+ next.key = void 0;
12604
+ }
12605
+ if (remoteRoot) {
12606
+ next.billing = {
12607
+ ...config.billing ?? {},
12608
+ url: normalizeOptional2(config.billing?.url) ?? remoteRoot
12609
+ };
12610
+ }
12611
+ if (!config.capabilities) {
12612
+ next.capabilities = createCloudflareEdgeCapabilities({
12613
+ hasR2,
12614
+ // Explicit storage.url / env storage URL / unified remote root all count.
12615
+ hasRemoteStorage: remoteStorage,
12616
+ authRemote: remoteAuth,
12617
+ findManyAst: false
12618
+ });
12619
+ }
12620
+ } else if (hasR2 && r2) {
12621
+ if (!remoteRoot && !normalizeOptional2(config.db?.url) && !normalizeOptional2(config.storage?.url) && !readFirstEnv(config.env, ENV_STORAGE_URL_KEYS)) {
12622
+ next.storage = {
12623
+ ...config.storage,
12624
+ r2,
12625
+ // Local sentinel so resolveCore accepts a storage-only binding client.
12626
+ url: CLOUDFLARE_EDGE_BASE_URL
12627
+ };
12628
+ if (!remoteServices) {
12629
+ next.key = normalizeOptional2(config.key) ?? CLOUDFLARE_EDGE_API_KEY;
12630
+ } else if (normalizeOptional2(config.key)) {
12631
+ next.key = normalizeOptional2(config.key);
12632
+ } else {
12633
+ next.key = void 0;
12634
+ }
12635
+ }
12636
+ if (!config.capabilities) {
12637
+ if (remoteRoot || normalizeOptional2(config.db?.url) || readFirstEnv(config.env, ENV_DB_URL_KEYS)) {
12638
+ const base = createGatewayCapabilities({
12639
+ authRemote: remoteAuth,
12640
+ storageConfigured: true
12641
+ });
12642
+ next.capabilities = {
12643
+ ...base,
12644
+ storage: {
12645
+ ...base.storage,
12646
+ local: true,
12647
+ objects: true
12648
+ }
12649
+ };
12650
+ } else {
12651
+ next.capabilities = {
12652
+ mode: "cloudflare-edge",
12653
+ db: {
12654
+ engine: "unknown",
12655
+ local: false,
12656
+ layers: {
12657
+ query: false,
12658
+ flatCrud: false,
12659
+ findManyAst: false,
12660
+ rpc: false,
12661
+ relations: false
12662
+ }
12663
+ },
12664
+ storage: {
12665
+ local: true,
12666
+ objects: true,
12667
+ catalogs: false,
12668
+ backups: false
12669
+ },
12670
+ auth: {
12671
+ remote: remoteAuth
12672
+ }
12673
+ };
12674
+ }
12675
+ }
12676
+ }
12677
+ return next;
12678
+ }
12679
+ function normalizeCreateClientConfig(config) {
12680
+ return materializeEdgeBindings(applyExecutionMode(foldBindingAliases(config)));
12681
+ }
9781
12682
  function createClientView(core, viewContext) {
9782
12683
  const resolved = createInternalClientView(
9783
12684
  core.internalCore,
@@ -9795,12 +12696,23 @@ function createClientView(core, viewContext) {
9795
12696
  },
9796
12697
  ...billingOptions
9797
12698
  }) : createUnavailableNamespace("billing", core.urls);
12699
+ const capabilities = core.config.capabilities ?? createGatewayCapabilities({
12700
+ authRemote: Boolean(core.urls.auth),
12701
+ // Match unavailable storage proxy when no storage URL was resolved.
12702
+ storageConfigured: Boolean(core.urls.storage)
12703
+ });
12704
+ const r2 = core.config.storage?.r2;
12705
+ const storageModule = isR2Binding(r2) ? createCloudflareR2StorageModule({
12706
+ r2,
12707
+ prefix: core.config.storage?.prefix ?? void 0
12708
+ }) : core.urls.storage ? resolved.storage : createUnavailableNamespace("storage", core.urls);
9798
12709
  const client = {
9799
12710
  db: core.urls.db ? resolved.db : createUnavailableNamespace("db", core.urls),
9800
12711
  auth: core.urls.auth ? resolved.auth : createUnavailableNamespace("auth", core.urls),
9801
12712
  chat: core.urls.chat ? resolved.chat : createUnavailableNamespace("chat", core.urls),
9802
- storage: core.urls.storage ? resolved.storage : createUnavailableNamespace("storage", core.urls),
12713
+ storage: storageModule,
9803
12714
  billing: billingModule,
12715
+ capabilities,
9804
12716
  from: ((...args) => {
9805
12717
  requireDb();
9806
12718
  return Reflect.apply(resolved.from, resolved, args);
@@ -9841,7 +12753,8 @@ function normalizeOptionalContextString(value) {
9841
12753
  }
9842
12754
  function warnIfEmptyRequestContext(context) {
9843
12755
  if (!isEmptyAthenaRequestContext(context)) return;
9844
- if (typeof process !== "undefined" && process.env?.NODE_ENV === "production") {
12756
+ const nodeEnv = globalThis.process?.env?.NODE_ENV;
12757
+ if (nodeEnv === "production") {
9845
12758
  return;
9846
12759
  }
9847
12760
  console.warn(
@@ -9849,37 +12762,38 @@ function warnIfEmptyRequestContext(context) {
9849
12762
  );
9850
12763
  }
9851
12764
  function createClient(config) {
9852
- return createClientView(resolveCore(config));
12765
+ const normalized = normalizeCreateClientConfig(config);
12766
+ return createClientView(resolveCore(normalized));
9853
12767
  }
9854
12768
 
9855
12769
  // src/next/shared.ts
9856
- function normalizeOptional2(value) {
12770
+ function normalizeOptional3(value) {
9857
12771
  const normalized = value?.trim();
9858
12772
  return normalized || void 0;
9859
12773
  }
9860
12774
  function readHeader(headers, target) {
9861
12775
  if (!headers) return void 0;
9862
12776
  if (typeof headers.get === "function") {
9863
- return normalizeOptional2(headers.get(target));
12777
+ return normalizeOptional3(headers.get(target));
9864
12778
  }
9865
12779
  const normalizedTarget = target.toLowerCase();
9866
12780
  for (const [key, value] of Object.entries(headers)) {
9867
- if (key.toLowerCase() === normalizedTarget) return normalizeOptional2(value ?? void 0);
12781
+ if (key.toLowerCase() === normalizedTarget) return normalizeOptional3(value ?? void 0);
9868
12782
  }
9869
12783
  return void 0;
9870
12784
  }
9871
12785
  function serializeCookies(cookies) {
9872
- if (typeof cookies === "string") return normalizeOptional2(cookies);
12786
+ if (typeof cookies === "string") return normalizeOptional3(cookies);
9873
12787
  if (!cookies) return void 0;
9874
12788
  const values = cookies.getAll().map((cookie) => {
9875
- const name = normalizeOptional2(cookie.name);
12789
+ const name = normalizeOptional3(cookie.name);
9876
12790
  return name ? `${name}=${cookie.value}` : void 0;
9877
12791
  }).filter((value) => Boolean(value));
9878
12792
  return values.length ? values.join("; ") : void 0;
9879
12793
  }
9880
12794
  function resolveBearerToken(authorization) {
9881
12795
  const match = authorization?.match(/^Bearer\s+(.+)$/i);
9882
- return normalizeOptional2(match?.[1]);
12796
+ return normalizeOptional3(match?.[1]);
9883
12797
  }
9884
12798
  async function loadNextHeadersModule() {
9885
12799
  try {
@@ -11306,7 +14220,7 @@ function createAthenaTableSchemaHandlers(options) {
11306
14220
 
11307
14221
  // src/next/server.ts
11308
14222
  function warnEmptyServerScope() {
11309
- if (typeof process !== "undefined" && process.env?.NODE_ENV === "production") {
14223
+ if (isNodeProductionEnv()) {
11310
14224
  return;
11311
14225
  }
11312
14226
  console.warn(