@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.
- package/README.md +17 -1
- package/dist/{athena-request-headers-Lr_m8xCV.d.cts → athena-request-headers-BnFN2mbd.d.cts} +1 -1
- package/dist/{athena-request-headers-DzimbvOA.d.ts → athena-request-headers-Dwdkq2WR.d.ts} +1 -1
- package/dist/billing.cjs +1 -1
- package/dist/billing.cjs.map +1 -1
- package/dist/billing.js +1 -1
- package/dist/billing.js.map +1 -1
- package/dist/browser.cjs +3064 -163
- package/dist/browser.cjs.map +1 -1
- package/dist/browser.d.cts +10 -10
- package/dist/browser.d.ts +10 -10
- package/dist/browser.js +3064 -163
- package/dist/browser.js.map +1 -1
- package/dist/cli/index.cjs +2990 -83
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.d.cts +4 -4
- package/dist/cli/index.d.ts +4 -4
- package/dist/cli/index.js +2990 -83
- package/dist/cli/index.js.map +1 -1
- package/dist/cloudflare.cjs +12914 -0
- package/dist/cloudflare.cjs.map +1 -0
- package/dist/cloudflare.d.cts +368 -0
- package/dist/cloudflare.d.ts +368 -0
- package/dist/cloudflare.js +12885 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/cookies.cjs +4 -3
- package/dist/cookies.cjs.map +1 -1
- package/dist/cookies.js +4 -3
- package/dist/cookies.js.map +1 -1
- package/dist/env.cjs +1 -1
- package/dist/env.cjs.map +1 -1
- package/dist/env.js +1 -1
- package/dist/env.js.map +1 -1
- package/dist/index.cjs +2989 -86
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -10
- package/dist/index.d.ts +10 -10
- package/dist/index.js +2989 -87
- package/dist/index.js.map +1 -1
- package/dist/{model-form-3Gr8rkdT.d.cts → model-form-D0ykVVOs.d.cts} +3 -3
- package/dist/{model-form-CotpEL7z.d.ts → model-form-U8NVtfSA.d.ts} +3 -3
- package/dist/{module-CQmOaDzP.d.cts → module-CMWlJ1z3.d.cts} +4 -4
- package/dist/{module-CWkUTcUc.d.ts → module-CZ-wPcf2.d.ts} +4 -4
- package/dist/next/client.cjs +3025 -125
- package/dist/next/client.cjs.map +1 -1
- package/dist/next/client.d.cts +4 -4
- package/dist/next/client.d.ts +4 -4
- package/dist/next/client.js +3025 -125
- package/dist/next/client.js.map +1 -1
- package/dist/next/server.cjs +3108 -194
- package/dist/next/server.cjs.map +1 -1
- package/dist/next/server.d.cts +22 -9
- package/dist/next/server.d.ts +22 -9
- package/dist/next/server.js +3108 -194
- package/dist/next/server.js.map +1 -1
- package/dist/{pipeline-BnRKO_Pd.d.cts → pipeline-BCpb4BX1.d.cts} +1 -1
- package/dist/{pipeline-sWCmlFqu.d.ts → pipeline-CgmXwMeX.d.ts} +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +6 -6
- package/dist/react.d.ts +6 -6
- package/dist/react.js +1 -1
- package/dist/react.js.map +1 -1
- package/dist/{schema-handlers-VjFDhIMw.d.ts → schema-handlers-CvWqF-dW.d.ts} +1 -1
- package/dist/{schema-handlers-BtT_IQFi.d.cts → schema-handlers-Dr8h9Jg-.d.cts} +1 -1
- package/dist/social-providers.cjs +1 -1
- package/dist/social-providers.cjs.map +1 -1
- package/dist/social-providers.js +1 -1
- package/dist/social-providers.js.map +1 -1
- package/dist/{types-Bltx6iL6.d.cts → types-B2RZPivM.d.cts} +8 -1
- package/dist/{types-Bltx6iL6.d.ts → types-B2RZPivM.d.ts} +8 -1
- package/dist/{types-BDX8zS7w.d.ts → types-BKklrX4J.d.ts} +2 -2
- package/dist/{types-CgCv5o6R.d.cts → types-D5dj1v5Z.d.cts} +1 -1
- package/dist/{types-D-Am7YSd.d.cts → types-DqBFwfhn.d.cts} +2 -2
- package/dist/{types-B75PdABb.d.ts → types-S-bTMPiM.d.ts} +1 -1
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +2 -2
- package/dist/utils.d.ts +2 -2
- package/dist/utils.js.map +1 -1
- package/dist/{v3-client-G1SLeHRa.d.cts → v3-client-DP-qg82X.d.cts} +300 -4
- package/dist/{v3-client-ao8BWQ8v.d.ts → v3-client-OAai_JNs.d.ts} +300 -4
- package/package.json +10 -3
package/dist/browser.js
CHANGED
|
@@ -1838,6 +1838,8 @@ function buildUpdateDebugSql(payload) {
|
|
|
1838
1838
|
sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
|
|
1839
1839
|
}
|
|
1840
1840
|
const pagination = resolvePagination({
|
|
1841
|
+
limit: payload.limit,
|
|
1842
|
+
offset: payload.offset,
|
|
1841
1843
|
currentPage: payload.current_page,
|
|
1842
1844
|
pageSize: payload.page_size
|
|
1843
1845
|
});
|
|
@@ -1860,6 +1862,8 @@ function buildDeleteDebugSql(payload) {
|
|
|
1860
1862
|
sqlParts.push(`WHERE ${whereClauses.join(" AND ")}`);
|
|
1861
1863
|
}
|
|
1862
1864
|
const pagination = resolvePagination({
|
|
1865
|
+
limit: payload.limit,
|
|
1866
|
+
offset: payload.offset,
|
|
1863
1867
|
currentPage: payload.current_page,
|
|
1864
1868
|
pageSize: payload.page_size
|
|
1865
1869
|
});
|
|
@@ -2003,7 +2007,7 @@ function buildAthenaGatewayUrl(baseUrl, path) {
|
|
|
2003
2007
|
|
|
2004
2008
|
// package.json
|
|
2005
2009
|
var package_default = {
|
|
2006
|
-
version: "3.
|
|
2010
|
+
version: "3.5.1"
|
|
2007
2011
|
};
|
|
2008
2012
|
|
|
2009
2013
|
// src/sdk-version.ts
|
|
@@ -2300,13 +2304,14 @@ var LEGACY_COOKIE_PREFIX = "better-auth";
|
|
|
2300
2304
|
var DEFAULT_SESSION_MAX_AGE = 7 * 24 * 60 * 60;
|
|
2301
2305
|
var DEFAULT_CACHE_MAX_AGE = 60 * 5;
|
|
2302
2306
|
function isProductionRuntime() {
|
|
2303
|
-
return
|
|
2307
|
+
return globalThis.process?.env?.NODE_ENV === "production";
|
|
2304
2308
|
}
|
|
2305
2309
|
function getEnvironmentSecret() {
|
|
2306
|
-
|
|
2310
|
+
const env = globalThis.process?.env;
|
|
2311
|
+
if (!env) {
|
|
2307
2312
|
return void 0;
|
|
2308
2313
|
}
|
|
2309
|
-
return
|
|
2314
|
+
return env.ATHENA_AUTH_SECRET || env.BETTER_AUTH_SECRET || env.AUTH_SECRET;
|
|
2310
2315
|
}
|
|
2311
2316
|
function isDynamicBaseURLConfig(baseURL) {
|
|
2312
2317
|
return typeof baseURL === "object" && baseURL !== null && "allowedHosts" in baseURL && Array.isArray(baseURL.allowedHosts);
|
|
@@ -5876,9 +5881,9 @@ function readHeadersField(value) {
|
|
|
5876
5881
|
const headers = value.headers;
|
|
5877
5882
|
if (!isRecord8(headers)) return {};
|
|
5878
5883
|
const result = {};
|
|
5879
|
-
for (const [key,
|
|
5880
|
-
if (typeof
|
|
5881
|
-
result[key] =
|
|
5884
|
+
for (const [key, headerValue3] of Object.entries(headers)) {
|
|
5885
|
+
if (typeof headerValue3 === "string") {
|
|
5886
|
+
result[key] = headerValue3;
|
|
5882
5887
|
}
|
|
5883
5888
|
}
|
|
5884
5889
|
return result;
|
|
@@ -9556,6 +9561,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, beha
|
|
|
9556
9561
|
strip_nulls: mergedOptions?.stripNulls ?? true
|
|
9557
9562
|
};
|
|
9558
9563
|
if (executionState.order) payload.sort_by = executionState.order;
|
|
9564
|
+
if (executionState.limit !== void 0) payload.limit = executionState.limit;
|
|
9565
|
+
if (executionState.offset !== void 0) payload.offset = executionState.offset;
|
|
9559
9566
|
if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
|
|
9560
9567
|
if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
|
|
9561
9568
|
if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
|
|
@@ -9610,6 +9617,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, beha
|
|
|
9610
9617
|
conditions: filters
|
|
9611
9618
|
};
|
|
9612
9619
|
if (executionState.order) payload.sort_by = executionState.order;
|
|
9620
|
+
if (executionState.limit !== void 0) payload.limit = executionState.limit;
|
|
9621
|
+
if (executionState.offset !== void 0) payload.offset = executionState.offset;
|
|
9613
9622
|
if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
|
|
9614
9623
|
if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
|
|
9615
9624
|
if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
|
|
@@ -9661,7 +9670,11 @@ function createQueryBuilder(client, formatGatewayResult, behavior, tracer) {
|
|
|
9661
9670
|
if (!normalizedQuery) {
|
|
9662
9671
|
throw new Error("query requires a non-empty string");
|
|
9663
9672
|
}
|
|
9664
|
-
const
|
|
9673
|
+
const params = options?.params;
|
|
9674
|
+
const payload = {
|
|
9675
|
+
query: normalizedQuery,
|
|
9676
|
+
...Array.isArray(params) ? { params } : {}
|
|
9677
|
+
};
|
|
9665
9678
|
const callsite = captureTraceCallsite(tracer);
|
|
9666
9679
|
return executeRead(
|
|
9667
9680
|
behavior,
|
|
@@ -9710,7 +9723,7 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
|
|
|
9710
9723
|
}
|
|
9711
9724
|
function createInternalClientCore(config) {
|
|
9712
9725
|
const normalizedAuthConfig = normalizeAuthClientConfig(config.auth, config.authUrl);
|
|
9713
|
-
const gatewayTransport = createAthenaGatewayClient({
|
|
9726
|
+
const gatewayTransport = config.gatewayTransport ?? createAthenaGatewayClient({
|
|
9714
9727
|
baseUrl: config.baseUrl,
|
|
9715
9728
|
apiKey: config.apiKey,
|
|
9716
9729
|
client: config.client ?? void 0,
|
|
@@ -9727,142 +9740,2780 @@ function createInternalClientCore(config) {
|
|
|
9727
9740
|
normalizedAuthConfig
|
|
9728
9741
|
});
|
|
9729
9742
|
}
|
|
9730
|
-
function createInternalClientView(core, resolveContext) {
|
|
9731
|
-
const { config, formatGatewayResult, normalizedAuthConfig, queryTracer } = core;
|
|
9732
|
-
const gateway = createAthenaGatewayClientView(core.gatewayTransport, async () => {
|
|
9733
|
-
const context = await resolveContext();
|
|
9734
|
-
return context ? {
|
|
9735
|
-
headers: context.headers,
|
|
9736
|
-
userId: context.userId,
|
|
9737
|
-
organizationId: context.organizationId,
|
|
9738
|
-
bearerToken: context.bearerToken,
|
|
9739
|
-
cookie: context.cookie,
|
|
9740
|
-
sessionToken: context.sessionToken,
|
|
9741
|
-
forceNoCache: context.forceNoCache
|
|
9742
|
-
} : void 0;
|
|
9743
|
-
});
|
|
9744
|
-
const auth = createAuthModule({
|
|
9745
|
-
...normalizedAuthConfig ?? {}
|
|
9746
|
-
}, {
|
|
9747
|
-
async resolveCallOptions() {
|
|
9748
|
-
const context = await resolveContext();
|
|
9749
|
-
return context ? {
|
|
9750
|
-
headers: buildContextHeaders(context),
|
|
9751
|
-
bearerToken: context.bearerToken ?? void 0,
|
|
9752
|
-
cookie: context.cookie ?? void 0,
|
|
9753
|
-
sessionToken: context.sessionToken ?? void 0,
|
|
9754
|
-
forceNoCache: context.forceNoCache
|
|
9755
|
-
} : void 0;
|
|
9756
|
-
}
|
|
9757
|
-
});
|
|
9758
|
-
function from(tableOrModel, options) {
|
|
9759
|
-
if (isAthenaModelTarget(tableOrModel)) {
|
|
9760
|
-
if (options?.schema !== void 0) {
|
|
9761
|
-
throw new Error(
|
|
9762
|
-
"from(model) does not accept a schema override because the model already defines its target."
|
|
9763
|
-
);
|
|
9764
|
-
}
|
|
9765
|
-
return createTableBuilder(
|
|
9766
|
-
resolveAthenaModelTargetTableName(tableOrModel),
|
|
9767
|
-
gateway,
|
|
9768
|
-
formatGatewayResult,
|
|
9769
|
-
queryTracer,
|
|
9770
|
-
config.behavior
|
|
9743
|
+
function createInternalClientView(core, resolveContext) {
|
|
9744
|
+
const { config, formatGatewayResult, normalizedAuthConfig, queryTracer } = core;
|
|
9745
|
+
const gateway = createAthenaGatewayClientView(core.gatewayTransport, async () => {
|
|
9746
|
+
const context = await resolveContext();
|
|
9747
|
+
return context ? {
|
|
9748
|
+
headers: context.headers,
|
|
9749
|
+
userId: context.userId,
|
|
9750
|
+
organizationId: context.organizationId,
|
|
9751
|
+
bearerToken: context.bearerToken,
|
|
9752
|
+
cookie: context.cookie,
|
|
9753
|
+
sessionToken: context.sessionToken,
|
|
9754
|
+
forceNoCache: context.forceNoCache
|
|
9755
|
+
} : void 0;
|
|
9756
|
+
});
|
|
9757
|
+
const auth = createAuthModule({
|
|
9758
|
+
...normalizedAuthConfig ?? {}
|
|
9759
|
+
}, {
|
|
9760
|
+
async resolveCallOptions() {
|
|
9761
|
+
const context = await resolveContext();
|
|
9762
|
+
return context ? {
|
|
9763
|
+
headers: buildContextHeaders(context),
|
|
9764
|
+
bearerToken: context.bearerToken ?? void 0,
|
|
9765
|
+
cookie: context.cookie ?? void 0,
|
|
9766
|
+
sessionToken: context.sessionToken ?? void 0,
|
|
9767
|
+
forceNoCache: context.forceNoCache
|
|
9768
|
+
} : void 0;
|
|
9769
|
+
}
|
|
9770
|
+
});
|
|
9771
|
+
function from(tableOrModel, options) {
|
|
9772
|
+
if (isAthenaModelTarget(tableOrModel)) {
|
|
9773
|
+
if (options?.schema !== void 0) {
|
|
9774
|
+
throw new Error(
|
|
9775
|
+
"from(model) does not accept a schema override because the model already defines its target."
|
|
9776
|
+
);
|
|
9777
|
+
}
|
|
9778
|
+
return createTableBuilder(
|
|
9779
|
+
resolveAthenaModelTargetTableName(tableOrModel),
|
|
9780
|
+
gateway,
|
|
9781
|
+
formatGatewayResult,
|
|
9782
|
+
queryTracer,
|
|
9783
|
+
config.behavior
|
|
9784
|
+
);
|
|
9785
|
+
}
|
|
9786
|
+
const resolvedTableName = resolveTableNameForCall(tableOrModel, options?.schema);
|
|
9787
|
+
return createTableBuilder(
|
|
9788
|
+
resolvedTableName,
|
|
9789
|
+
gateway,
|
|
9790
|
+
formatGatewayResult,
|
|
9791
|
+
queryTracer,
|
|
9792
|
+
config.behavior
|
|
9793
|
+
);
|
|
9794
|
+
}
|
|
9795
|
+
const rpc = (fn, args, options) => {
|
|
9796
|
+
const normalizedFn = fn.trim();
|
|
9797
|
+
if (!normalizedFn) {
|
|
9798
|
+
throw new Error("rpc requires a function name");
|
|
9799
|
+
}
|
|
9800
|
+
return createRpcBuilder(
|
|
9801
|
+
normalizedFn,
|
|
9802
|
+
args,
|
|
9803
|
+
options,
|
|
9804
|
+
gateway,
|
|
9805
|
+
formatGatewayResult,
|
|
9806
|
+
queryTracer,
|
|
9807
|
+
captureTraceCallsite(queryTracer),
|
|
9808
|
+
Boolean(config.behavior?.debugAst)
|
|
9809
|
+
);
|
|
9810
|
+
};
|
|
9811
|
+
const query = createQueryBuilder(
|
|
9812
|
+
gateway,
|
|
9813
|
+
formatGatewayResult,
|
|
9814
|
+
config.behavior,
|
|
9815
|
+
queryTracer
|
|
9816
|
+
);
|
|
9817
|
+
const untypedDbFrom = from;
|
|
9818
|
+
const db = {
|
|
9819
|
+
from,
|
|
9820
|
+
select(table2, first, second) {
|
|
9821
|
+
if (first && typeof first === "object" && !Array.isArray(first)) {
|
|
9822
|
+
return untypedDbFrom(table2).select(void 0, first);
|
|
9823
|
+
}
|
|
9824
|
+
return untypedDbFrom(table2).select(first, second);
|
|
9825
|
+
},
|
|
9826
|
+
insert(table2, values, options) {
|
|
9827
|
+
return Array.isArray(values) ? untypedDbFrom(table2).insert(values, options) : untypedDbFrom(table2).insert(values, options);
|
|
9828
|
+
},
|
|
9829
|
+
upsert(table2, values, options) {
|
|
9830
|
+
return Array.isArray(values) ? untypedDbFrom(table2).upsert(values, options) : untypedDbFrom(table2).upsert(values, options);
|
|
9831
|
+
},
|
|
9832
|
+
update(table2, values, options) {
|
|
9833
|
+
return untypedDbFrom(table2).update(values, options);
|
|
9834
|
+
},
|
|
9835
|
+
delete(table2, options) {
|
|
9836
|
+
return untypedDbFrom(table2).delete(options);
|
|
9837
|
+
},
|
|
9838
|
+
rpc,
|
|
9839
|
+
query
|
|
9840
|
+
};
|
|
9841
|
+
const chat = createChatModule({
|
|
9842
|
+
baseUrl: config.chatUrl,
|
|
9843
|
+
apiKey: config.apiKey,
|
|
9844
|
+
client: config.client ?? void 0,
|
|
9845
|
+
headers: config.headers,
|
|
9846
|
+
wsUrl: config.chatWsUrl,
|
|
9847
|
+
webSocketFactory: config.chat?.webSocketFactory ?? void 0
|
|
9848
|
+
}, {
|
|
9849
|
+
async resolveCallOptions() {
|
|
9850
|
+
const context = await resolveContext();
|
|
9851
|
+
return context ? {
|
|
9852
|
+
headers: buildContextHeaders(context),
|
|
9853
|
+
bearerToken: context.bearerToken,
|
|
9854
|
+
cookie: context.cookie,
|
|
9855
|
+
sessionToken: context.sessionToken,
|
|
9856
|
+
forceNoCache: context.forceNoCache
|
|
9857
|
+
} : void 0;
|
|
9858
|
+
}
|
|
9859
|
+
});
|
|
9860
|
+
const request2 = createAthenaRequest(config, resolveContext);
|
|
9861
|
+
const storage = createStorageModule(gateway, {
|
|
9862
|
+
...config.storage,
|
|
9863
|
+
...config.storageUrl ? {
|
|
9864
|
+
baseUrl: config.storageUrl,
|
|
9865
|
+
stripBasePath: true
|
|
9866
|
+
} : {}
|
|
9867
|
+
});
|
|
9868
|
+
return {
|
|
9869
|
+
from,
|
|
9870
|
+
db,
|
|
9871
|
+
rpc,
|
|
9872
|
+
query,
|
|
9873
|
+
request: request2,
|
|
9874
|
+
verifyConnection: gateway.verifyConnection,
|
|
9875
|
+
auth: auth.auth,
|
|
9876
|
+
chat,
|
|
9877
|
+
storage
|
|
9878
|
+
};
|
|
9879
|
+
}
|
|
9880
|
+
|
|
9881
|
+
// src/cloudflare/types.ts
|
|
9882
|
+
var CLOUDFLARE_EDGE_BASE_URL = "https://athena.local/cloudflare-edge";
|
|
9883
|
+
var CLOUDFLARE_EDGE_API_KEY = "cloudflare-edge-local";
|
|
9884
|
+
|
|
9885
|
+
// src/cloudflare/capabilities.ts
|
|
9886
|
+
function createGatewayCapabilities(options) {
|
|
9887
|
+
const storageConfigured = options?.storageConfigured ?? true;
|
|
9888
|
+
return {
|
|
9889
|
+
mode: "gateway",
|
|
9890
|
+
db: {
|
|
9891
|
+
engine: options?.engine ?? "postgresql",
|
|
9892
|
+
local: false,
|
|
9893
|
+
layers: {
|
|
9894
|
+
query: true,
|
|
9895
|
+
flatCrud: true,
|
|
9896
|
+
findManyAst: true,
|
|
9897
|
+
rpc: true,
|
|
9898
|
+
relations: true
|
|
9899
|
+
}
|
|
9900
|
+
},
|
|
9901
|
+
storage: {
|
|
9902
|
+
local: false,
|
|
9903
|
+
objects: storageConfigured,
|
|
9904
|
+
catalogs: storageConfigured ? options?.storageCatalogs ?? true : false,
|
|
9905
|
+
backups: storageConfigured ? options?.storageBackups ?? true : false
|
|
9906
|
+
},
|
|
9907
|
+
auth: {
|
|
9908
|
+
remote: options?.authRemote ?? true
|
|
9909
|
+
}
|
|
9910
|
+
};
|
|
9911
|
+
}
|
|
9912
|
+
function createCloudflareEdgeCapabilities(options) {
|
|
9913
|
+
const hasObjects = options.hasR2 || Boolean(options.hasRemoteStorage);
|
|
9914
|
+
return {
|
|
9915
|
+
mode: "cloudflare-edge",
|
|
9916
|
+
db: {
|
|
9917
|
+
engine: "cloudflare-d1",
|
|
9918
|
+
local: true,
|
|
9919
|
+
layers: {
|
|
9920
|
+
query: true,
|
|
9921
|
+
flatCrud: true,
|
|
9922
|
+
findManyAst: options.findManyAst ?? false,
|
|
9923
|
+
rpc: false,
|
|
9924
|
+
relations: false
|
|
9925
|
+
}
|
|
9926
|
+
},
|
|
9927
|
+
storage: {
|
|
9928
|
+
// Local objects only when an R2 binding is present.
|
|
9929
|
+
local: options.hasR2,
|
|
9930
|
+
// Remote hybrid root can still expose storage.objects via the HTTP API.
|
|
9931
|
+
objects: hasObjects,
|
|
9932
|
+
catalogs: false,
|
|
9933
|
+
backups: false
|
|
9934
|
+
},
|
|
9935
|
+
auth: {
|
|
9936
|
+
remote: options.authRemote
|
|
9937
|
+
}
|
|
9938
|
+
};
|
|
9939
|
+
}
|
|
9940
|
+
|
|
9941
|
+
// src/cloudflare/d1/runner.ts
|
|
9942
|
+
function resultColumns(rows) {
|
|
9943
|
+
const first = rows.find((value) => value && typeof value === "object" && !Array.isArray(value));
|
|
9944
|
+
if (!first) return [];
|
|
9945
|
+
return Object.keys(first);
|
|
9946
|
+
}
|
|
9947
|
+
function isIdentChar(ch) {
|
|
9948
|
+
if (!ch) return false;
|
|
9949
|
+
return /[A-Za-z0-9_]/.test(ch);
|
|
9950
|
+
}
|
|
9951
|
+
function scanSqlKeywordsOutsideLiterals(sql, onKeyword) {
|
|
9952
|
+
let inSingle = false;
|
|
9953
|
+
let inDouble = false;
|
|
9954
|
+
let inBacktick = false;
|
|
9955
|
+
let inBracket = false;
|
|
9956
|
+
let inLineComment = false;
|
|
9957
|
+
let inBlockComment = false;
|
|
9958
|
+
for (let i = 0; i < sql.length; i += 1) {
|
|
9959
|
+
const ch = sql[i];
|
|
9960
|
+
const next = sql[i + 1];
|
|
9961
|
+
if (inLineComment) {
|
|
9962
|
+
if (ch === "\n" || ch === "\r") inLineComment = false;
|
|
9963
|
+
continue;
|
|
9964
|
+
}
|
|
9965
|
+
if (inBlockComment) {
|
|
9966
|
+
if (ch === "*" && next === "/") {
|
|
9967
|
+
i += 1;
|
|
9968
|
+
inBlockComment = false;
|
|
9969
|
+
}
|
|
9970
|
+
continue;
|
|
9971
|
+
}
|
|
9972
|
+
if (inSingle) {
|
|
9973
|
+
if (ch === "'" && next === "'") {
|
|
9974
|
+
i += 1;
|
|
9975
|
+
continue;
|
|
9976
|
+
}
|
|
9977
|
+
if (ch === "'") inSingle = false;
|
|
9978
|
+
continue;
|
|
9979
|
+
}
|
|
9980
|
+
if (inDouble) {
|
|
9981
|
+
if (ch === '"' && next === '"') {
|
|
9982
|
+
i += 1;
|
|
9983
|
+
continue;
|
|
9984
|
+
}
|
|
9985
|
+
if (ch === '"') inDouble = false;
|
|
9986
|
+
continue;
|
|
9987
|
+
}
|
|
9988
|
+
if (inBacktick) {
|
|
9989
|
+
if (ch === "`" && next === "`") {
|
|
9990
|
+
i += 1;
|
|
9991
|
+
continue;
|
|
9992
|
+
}
|
|
9993
|
+
if (ch === "`") inBacktick = false;
|
|
9994
|
+
continue;
|
|
9995
|
+
}
|
|
9996
|
+
if (inBracket) {
|
|
9997
|
+
if (ch === "]") inBracket = false;
|
|
9998
|
+
continue;
|
|
9999
|
+
}
|
|
10000
|
+
if (ch === "-" && next === "-") {
|
|
10001
|
+
inLineComment = true;
|
|
10002
|
+
i += 1;
|
|
10003
|
+
continue;
|
|
10004
|
+
}
|
|
10005
|
+
if (ch === "/" && next === "*") {
|
|
10006
|
+
inBlockComment = true;
|
|
10007
|
+
i += 1;
|
|
10008
|
+
continue;
|
|
10009
|
+
}
|
|
10010
|
+
if (ch === "'") {
|
|
10011
|
+
inSingle = true;
|
|
10012
|
+
continue;
|
|
10013
|
+
}
|
|
10014
|
+
if (ch === '"') {
|
|
10015
|
+
inDouble = true;
|
|
10016
|
+
continue;
|
|
10017
|
+
}
|
|
10018
|
+
if (ch === "`") {
|
|
10019
|
+
inBacktick = true;
|
|
10020
|
+
continue;
|
|
10021
|
+
}
|
|
10022
|
+
if (ch === "[") {
|
|
10023
|
+
inBracket = true;
|
|
10024
|
+
continue;
|
|
10025
|
+
}
|
|
10026
|
+
if (!isIdentChar(ch) || isIdentChar(sql[i - 1])) {
|
|
10027
|
+
continue;
|
|
10028
|
+
}
|
|
10029
|
+
let end = i + 1;
|
|
10030
|
+
while (end < sql.length && isIdentChar(sql[end])) {
|
|
10031
|
+
end += 1;
|
|
10032
|
+
}
|
|
10033
|
+
const keyword = sql.slice(i, end);
|
|
10034
|
+
if (onKeyword(keyword, i)) {
|
|
10035
|
+
return;
|
|
10036
|
+
}
|
|
10037
|
+
i = end - 1;
|
|
10038
|
+
}
|
|
10039
|
+
}
|
|
10040
|
+
function sqlContainsKeywordOutsideLiterals(sql, keyword) {
|
|
10041
|
+
const target = keyword.toUpperCase();
|
|
10042
|
+
let found = false;
|
|
10043
|
+
scanSqlKeywordsOutsideLiterals(sql, (token) => {
|
|
10044
|
+
if (token.toUpperCase() === target) {
|
|
10045
|
+
found = true;
|
|
10046
|
+
return true;
|
|
10047
|
+
}
|
|
10048
|
+
return false;
|
|
10049
|
+
});
|
|
10050
|
+
return found;
|
|
10051
|
+
}
|
|
10052
|
+
function sqlFirstKeywordOutsideLiterals(sql) {
|
|
10053
|
+
let first = null;
|
|
10054
|
+
scanSqlKeywordsOutsideLiterals(sql, (token) => {
|
|
10055
|
+
first = token;
|
|
10056
|
+
return true;
|
|
10057
|
+
});
|
|
10058
|
+
return first;
|
|
10059
|
+
}
|
|
10060
|
+
var ROW_PRODUCING_LEAD_KEYWORDS = /* @__PURE__ */ new Set(["SELECT", "PRAGMA", "EXPLAIN", "VALUES"]);
|
|
10061
|
+
var MUTATION_LEAD_KEYWORDS = /* @__PURE__ */ new Set(["INSERT", "UPDATE", "DELETE", "REPLACE"]);
|
|
10062
|
+
var WITH_TERMINAL_KEYWORDS = /* @__PURE__ */ new Set([
|
|
10063
|
+
"SELECT",
|
|
10064
|
+
"INSERT",
|
|
10065
|
+
"UPDATE",
|
|
10066
|
+
"DELETE",
|
|
10067
|
+
"REPLACE",
|
|
10068
|
+
"VALUES",
|
|
10069
|
+
"PRAGMA",
|
|
10070
|
+
"EXPLAIN"
|
|
10071
|
+
]);
|
|
10072
|
+
function sqlTerminalKeywordAfterWith(sql) {
|
|
10073
|
+
let inSingle = false;
|
|
10074
|
+
let inDouble = false;
|
|
10075
|
+
let inBacktick = false;
|
|
10076
|
+
let inBracket = false;
|
|
10077
|
+
let inLineComment = false;
|
|
10078
|
+
let inBlockComment = false;
|
|
10079
|
+
let depth = 0;
|
|
10080
|
+
let sawWith = false;
|
|
10081
|
+
for (let i = 0; i < sql.length; i += 1) {
|
|
10082
|
+
const ch = sql[i];
|
|
10083
|
+
const next = sql[i + 1];
|
|
10084
|
+
if (inLineComment) {
|
|
10085
|
+
if (ch === "\n" || ch === "\r") inLineComment = false;
|
|
10086
|
+
continue;
|
|
10087
|
+
}
|
|
10088
|
+
if (inBlockComment) {
|
|
10089
|
+
if (ch === "*" && next === "/") {
|
|
10090
|
+
i += 1;
|
|
10091
|
+
inBlockComment = false;
|
|
10092
|
+
}
|
|
10093
|
+
continue;
|
|
10094
|
+
}
|
|
10095
|
+
if (inSingle) {
|
|
10096
|
+
if (ch === "'" && next === "'") {
|
|
10097
|
+
i += 1;
|
|
10098
|
+
continue;
|
|
10099
|
+
}
|
|
10100
|
+
if (ch === "'") inSingle = false;
|
|
10101
|
+
continue;
|
|
10102
|
+
}
|
|
10103
|
+
if (inDouble) {
|
|
10104
|
+
if (ch === '"' && next === '"') {
|
|
10105
|
+
i += 1;
|
|
10106
|
+
continue;
|
|
10107
|
+
}
|
|
10108
|
+
if (ch === '"') inDouble = false;
|
|
10109
|
+
continue;
|
|
10110
|
+
}
|
|
10111
|
+
if (inBacktick) {
|
|
10112
|
+
if (ch === "`" && next === "`") {
|
|
10113
|
+
i += 1;
|
|
10114
|
+
continue;
|
|
10115
|
+
}
|
|
10116
|
+
if (ch === "`") inBacktick = false;
|
|
10117
|
+
continue;
|
|
10118
|
+
}
|
|
10119
|
+
if (inBracket) {
|
|
10120
|
+
if (ch === "]") inBracket = false;
|
|
10121
|
+
continue;
|
|
10122
|
+
}
|
|
10123
|
+
if (ch === "-" && next === "-") {
|
|
10124
|
+
inLineComment = true;
|
|
10125
|
+
i += 1;
|
|
10126
|
+
continue;
|
|
10127
|
+
}
|
|
10128
|
+
if (ch === "/" && next === "*") {
|
|
10129
|
+
inBlockComment = true;
|
|
10130
|
+
i += 1;
|
|
10131
|
+
continue;
|
|
10132
|
+
}
|
|
10133
|
+
if (ch === "'") {
|
|
10134
|
+
inSingle = true;
|
|
10135
|
+
continue;
|
|
10136
|
+
}
|
|
10137
|
+
if (ch === '"') {
|
|
10138
|
+
inDouble = true;
|
|
10139
|
+
continue;
|
|
10140
|
+
}
|
|
10141
|
+
if (ch === "`") {
|
|
10142
|
+
inBacktick = true;
|
|
10143
|
+
continue;
|
|
10144
|
+
}
|
|
10145
|
+
if (ch === "[") {
|
|
10146
|
+
inBracket = true;
|
|
10147
|
+
continue;
|
|
10148
|
+
}
|
|
10149
|
+
if (ch === "(") {
|
|
10150
|
+
depth += 1;
|
|
10151
|
+
continue;
|
|
10152
|
+
}
|
|
10153
|
+
if (ch === ")") {
|
|
10154
|
+
if (depth > 0) depth -= 1;
|
|
10155
|
+
continue;
|
|
10156
|
+
}
|
|
10157
|
+
if (depth !== 0 || !isIdentChar(ch) || isIdentChar(sql[i - 1])) {
|
|
10158
|
+
continue;
|
|
10159
|
+
}
|
|
10160
|
+
let end = i + 1;
|
|
10161
|
+
while (end < sql.length && isIdentChar(sql[end])) {
|
|
10162
|
+
end += 1;
|
|
10163
|
+
}
|
|
10164
|
+
const keyword = sql.slice(i, end);
|
|
10165
|
+
const upper = keyword.toUpperCase();
|
|
10166
|
+
if (!sawWith) {
|
|
10167
|
+
if (upper === "WITH") {
|
|
10168
|
+
sawWith = true;
|
|
10169
|
+
}
|
|
10170
|
+
i = end - 1;
|
|
10171
|
+
continue;
|
|
10172
|
+
}
|
|
10173
|
+
if (WITH_TERMINAL_KEYWORDS.has(upper)) {
|
|
10174
|
+
return keyword;
|
|
10175
|
+
}
|
|
10176
|
+
i = end - 1;
|
|
10177
|
+
}
|
|
10178
|
+
return null;
|
|
10179
|
+
}
|
|
10180
|
+
function sqlLeadStatementKeyword(sql) {
|
|
10181
|
+
const first = sqlFirstKeywordOutsideLiterals(sql);
|
|
10182
|
+
if (!first) return null;
|
|
10183
|
+
if (first.toUpperCase() !== "WITH") return first;
|
|
10184
|
+
return sqlTerminalKeywordAfterWith(sql) ?? first;
|
|
10185
|
+
}
|
|
10186
|
+
function statementExpectsResultRows(sql) {
|
|
10187
|
+
const lead = sqlLeadStatementKeyword(sql);
|
|
10188
|
+
if (lead) {
|
|
10189
|
+
const upper = lead.toUpperCase();
|
|
10190
|
+
if (ROW_PRODUCING_LEAD_KEYWORDS.has(upper)) {
|
|
10191
|
+
return true;
|
|
10192
|
+
}
|
|
10193
|
+
if (MUTATION_LEAD_KEYWORDS.has(upper)) {
|
|
10194
|
+
return sqlContainsKeywordOutsideLiterals(sql, "RETURNING");
|
|
10195
|
+
}
|
|
10196
|
+
}
|
|
10197
|
+
return sqlContainsKeywordOutsideLiterals(sql, "RETURNING");
|
|
10198
|
+
}
|
|
10199
|
+
function collectRowsFromBatchResults(results) {
|
|
10200
|
+
const rows = [];
|
|
10201
|
+
for (const item of results) {
|
|
10202
|
+
if (Array.isArray(item.results) && item.results.length > 0) {
|
|
10203
|
+
rows.push(...item.results);
|
|
10204
|
+
}
|
|
10205
|
+
}
|
|
10206
|
+
return rows;
|
|
10207
|
+
}
|
|
10208
|
+
function sumBatchAffectedRows(results, statementCount) {
|
|
10209
|
+
let sum2 = 0;
|
|
10210
|
+
let sawChanges = false;
|
|
10211
|
+
for (const item of results) {
|
|
10212
|
+
const changes = item.meta?.changes;
|
|
10213
|
+
if (typeof changes === "number") {
|
|
10214
|
+
sum2 += changes;
|
|
10215
|
+
sawChanges = true;
|
|
10216
|
+
}
|
|
10217
|
+
}
|
|
10218
|
+
return sawChanges ? sum2 : statementCount;
|
|
10219
|
+
}
|
|
10220
|
+
function matchSqlKeywordAt(query, index, keyword) {
|
|
10221
|
+
const len = keyword.length;
|
|
10222
|
+
if (index + len > query.length) {
|
|
10223
|
+
return null;
|
|
10224
|
+
}
|
|
10225
|
+
const slice = query.slice(index, index + len);
|
|
10226
|
+
if (slice.toLowerCase() !== keyword.toLowerCase()) {
|
|
10227
|
+
return null;
|
|
10228
|
+
}
|
|
10229
|
+
const before = index === 0 ? "" : query[index - 1];
|
|
10230
|
+
const after = index + len >= query.length ? "" : query[index + len];
|
|
10231
|
+
const isIdent = (c) => /[A-Za-z0-9_]/.test(c);
|
|
10232
|
+
if (before && isIdent(before)) {
|
|
10233
|
+
return null;
|
|
10234
|
+
}
|
|
10235
|
+
if (after && isIdent(after)) {
|
|
10236
|
+
return null;
|
|
10237
|
+
}
|
|
10238
|
+
return len;
|
|
10239
|
+
}
|
|
10240
|
+
function splitSqlStatements(query) {
|
|
10241
|
+
const statements = [];
|
|
10242
|
+
let inSingle = false;
|
|
10243
|
+
let inDouble = false;
|
|
10244
|
+
let inBacktick = false;
|
|
10245
|
+
let inBracket = false;
|
|
10246
|
+
let inLineComment = false;
|
|
10247
|
+
let inBlockComment = false;
|
|
10248
|
+
let segmentStart = 0;
|
|
10249
|
+
let segmentHasContent = false;
|
|
10250
|
+
let awaitTriggerBegin = false;
|
|
10251
|
+
let triggerBodyDepth = 0;
|
|
10252
|
+
let caseDepth = 0;
|
|
10253
|
+
const flushSegment = (end) => {
|
|
10254
|
+
if (!segmentHasContent) {
|
|
10255
|
+
segmentStart = end + 1;
|
|
10256
|
+
return;
|
|
10257
|
+
}
|
|
10258
|
+
const sql = query.slice(segmentStart, end).trim();
|
|
10259
|
+
if (sql) {
|
|
10260
|
+
statements.push(sql);
|
|
10261
|
+
}
|
|
10262
|
+
segmentHasContent = false;
|
|
10263
|
+
segmentStart = end + 1;
|
|
10264
|
+
awaitTriggerBegin = false;
|
|
10265
|
+
triggerBodyDepth = 0;
|
|
10266
|
+
caseDepth = 0;
|
|
10267
|
+
};
|
|
10268
|
+
for (let i = 0; i < query.length; i += 1) {
|
|
10269
|
+
const ch = query[i];
|
|
10270
|
+
const next = query[i + 1];
|
|
10271
|
+
if (inLineComment) {
|
|
10272
|
+
if (ch === "\n" || ch === "\r") {
|
|
10273
|
+
inLineComment = false;
|
|
10274
|
+
}
|
|
10275
|
+
continue;
|
|
10276
|
+
}
|
|
10277
|
+
if (inBlockComment) {
|
|
10278
|
+
if (ch === "*" && next === "/") {
|
|
10279
|
+
inBlockComment = false;
|
|
10280
|
+
i += 1;
|
|
10281
|
+
}
|
|
10282
|
+
continue;
|
|
10283
|
+
}
|
|
10284
|
+
if (inSingle) {
|
|
10285
|
+
if (ch === "'" && next === "'") {
|
|
10286
|
+
i += 1;
|
|
10287
|
+
continue;
|
|
10288
|
+
}
|
|
10289
|
+
if (ch === "'") {
|
|
10290
|
+
inSingle = false;
|
|
10291
|
+
}
|
|
10292
|
+
continue;
|
|
10293
|
+
}
|
|
10294
|
+
if (inDouble) {
|
|
10295
|
+
if (ch === '"' && next === '"') {
|
|
10296
|
+
i += 1;
|
|
10297
|
+
continue;
|
|
10298
|
+
}
|
|
10299
|
+
if (ch === '"') {
|
|
10300
|
+
inDouble = false;
|
|
10301
|
+
}
|
|
10302
|
+
continue;
|
|
10303
|
+
}
|
|
10304
|
+
if (inBacktick) {
|
|
10305
|
+
if (ch === "`" && next === "`") {
|
|
10306
|
+
i += 1;
|
|
10307
|
+
continue;
|
|
10308
|
+
}
|
|
10309
|
+
if (ch === "`") {
|
|
10310
|
+
inBacktick = false;
|
|
10311
|
+
}
|
|
10312
|
+
continue;
|
|
10313
|
+
}
|
|
10314
|
+
if (inBracket) {
|
|
10315
|
+
if (ch === "]") {
|
|
10316
|
+
inBracket = false;
|
|
10317
|
+
}
|
|
10318
|
+
continue;
|
|
10319
|
+
}
|
|
10320
|
+
if (ch === "-" && next === "-") {
|
|
10321
|
+
inLineComment = true;
|
|
10322
|
+
i += 1;
|
|
10323
|
+
continue;
|
|
10324
|
+
}
|
|
10325
|
+
if (ch === "/" && next === "*") {
|
|
10326
|
+
inBlockComment = true;
|
|
10327
|
+
i += 1;
|
|
10328
|
+
continue;
|
|
10329
|
+
}
|
|
10330
|
+
if (ch === "'") {
|
|
10331
|
+
inSingle = true;
|
|
10332
|
+
segmentHasContent = true;
|
|
10333
|
+
continue;
|
|
10334
|
+
}
|
|
10335
|
+
if (ch === '"') {
|
|
10336
|
+
inDouble = true;
|
|
10337
|
+
segmentHasContent = true;
|
|
10338
|
+
continue;
|
|
10339
|
+
}
|
|
10340
|
+
if (ch === "`") {
|
|
10341
|
+
inBacktick = true;
|
|
10342
|
+
segmentHasContent = true;
|
|
10343
|
+
continue;
|
|
10344
|
+
}
|
|
10345
|
+
if (ch === "[") {
|
|
10346
|
+
inBracket = true;
|
|
10347
|
+
segmentHasContent = true;
|
|
10348
|
+
continue;
|
|
10349
|
+
}
|
|
10350
|
+
if (/[A-Za-z_]/.test(ch)) {
|
|
10351
|
+
const createLen = matchSqlKeywordAt(query, i, "CREATE");
|
|
10352
|
+
if (createLen != null) {
|
|
10353
|
+
let j2 = i + createLen;
|
|
10354
|
+
const skipWsAndComments = () => {
|
|
10355
|
+
while (j2 < query.length) {
|
|
10356
|
+
const c = query[j2];
|
|
10357
|
+
const n = query[j2 + 1];
|
|
10358
|
+
if (/\s/.test(c)) {
|
|
10359
|
+
j2 += 1;
|
|
10360
|
+
continue;
|
|
10361
|
+
}
|
|
10362
|
+
if (c === "-" && n === "-") {
|
|
10363
|
+
j2 += 2;
|
|
10364
|
+
while (j2 < query.length && query[j2] !== "\n" && query[j2] !== "\r") {
|
|
10365
|
+
j2 += 1;
|
|
10366
|
+
}
|
|
10367
|
+
continue;
|
|
10368
|
+
}
|
|
10369
|
+
if (c === "/" && n === "*") {
|
|
10370
|
+
j2 += 2;
|
|
10371
|
+
while (j2 < query.length) {
|
|
10372
|
+
if (query[j2] === "*" && query[j2 + 1] === "/") {
|
|
10373
|
+
j2 += 2;
|
|
10374
|
+
break;
|
|
10375
|
+
}
|
|
10376
|
+
j2 += 1;
|
|
10377
|
+
}
|
|
10378
|
+
continue;
|
|
10379
|
+
}
|
|
10380
|
+
break;
|
|
10381
|
+
}
|
|
10382
|
+
};
|
|
10383
|
+
skipWsAndComments();
|
|
10384
|
+
const tempLen = matchSqlKeywordAt(query, j2, "TEMPORARY") ?? matchSqlKeywordAt(query, j2, "TEMP");
|
|
10385
|
+
if (tempLen != null) {
|
|
10386
|
+
j2 += tempLen;
|
|
10387
|
+
skipWsAndComments();
|
|
10388
|
+
}
|
|
10389
|
+
const triggerLen = matchSqlKeywordAt(query, j2, "TRIGGER");
|
|
10390
|
+
if (triggerLen != null) {
|
|
10391
|
+
awaitTriggerBegin = true;
|
|
10392
|
+
segmentHasContent = true;
|
|
10393
|
+
i += createLen - 1;
|
|
10394
|
+
continue;
|
|
10395
|
+
}
|
|
10396
|
+
segmentHasContent = true;
|
|
10397
|
+
i += createLen - 1;
|
|
10398
|
+
continue;
|
|
10399
|
+
}
|
|
10400
|
+
const caseLen = matchSqlKeywordAt(query, i, "CASE");
|
|
10401
|
+
if (caseLen != null) {
|
|
10402
|
+
caseDepth += 1;
|
|
10403
|
+
segmentHasContent = true;
|
|
10404
|
+
i += caseLen - 1;
|
|
10405
|
+
continue;
|
|
10406
|
+
}
|
|
10407
|
+
const beginLen = matchSqlKeywordAt(query, i, "BEGIN");
|
|
10408
|
+
if (beginLen != null) {
|
|
10409
|
+
if (awaitTriggerBegin) {
|
|
10410
|
+
triggerBodyDepth += 1;
|
|
10411
|
+
awaitTriggerBegin = false;
|
|
10412
|
+
}
|
|
10413
|
+
segmentHasContent = true;
|
|
10414
|
+
i += beginLen - 1;
|
|
10415
|
+
continue;
|
|
10416
|
+
}
|
|
10417
|
+
const endLen = matchSqlKeywordAt(query, i, "END");
|
|
10418
|
+
if (endLen != null) {
|
|
10419
|
+
if (caseDepth > 0) {
|
|
10420
|
+
caseDepth -= 1;
|
|
10421
|
+
} else if (triggerBodyDepth > 0) {
|
|
10422
|
+
triggerBodyDepth -= 1;
|
|
10423
|
+
}
|
|
10424
|
+
segmentHasContent = true;
|
|
10425
|
+
i += endLen - 1;
|
|
10426
|
+
continue;
|
|
10427
|
+
}
|
|
10428
|
+
let j = i + 1;
|
|
10429
|
+
while (j < query.length && /[A-Za-z0-9_]/.test(query[j])) {
|
|
10430
|
+
j += 1;
|
|
10431
|
+
}
|
|
10432
|
+
segmentHasContent = true;
|
|
10433
|
+
i = j - 1;
|
|
10434
|
+
continue;
|
|
10435
|
+
}
|
|
10436
|
+
if (ch === ";") {
|
|
10437
|
+
if (triggerBodyDepth > 0 || caseDepth > 0) {
|
|
10438
|
+
segmentHasContent = true;
|
|
10439
|
+
continue;
|
|
10440
|
+
}
|
|
10441
|
+
flushSegment(i);
|
|
10442
|
+
continue;
|
|
10443
|
+
}
|
|
10444
|
+
if (!/\s/.test(ch)) {
|
|
10445
|
+
segmentHasContent = true;
|
|
10446
|
+
}
|
|
10447
|
+
}
|
|
10448
|
+
flushSegment(query.length);
|
|
10449
|
+
return statements;
|
|
10450
|
+
}
|
|
10451
|
+
function isMultiStatement(query) {
|
|
10452
|
+
return splitSqlStatements(query).length > 1;
|
|
10453
|
+
}
|
|
10454
|
+
function resolveSessionTarget(db, input) {
|
|
10455
|
+
const sessionValue = input.bookmark?.trim() || input.sessionMode?.trim();
|
|
10456
|
+
if (!sessionValue) {
|
|
10457
|
+
return { target: db, session: null };
|
|
10458
|
+
}
|
|
10459
|
+
if (typeof db.withSession !== "function") {
|
|
10460
|
+
throw new Error("D1 session mode/bookmark requested but withSession is not available");
|
|
10461
|
+
}
|
|
10462
|
+
const session = db.withSession(sessionValue);
|
|
10463
|
+
return { target: session, session };
|
|
10464
|
+
}
|
|
10465
|
+
function normalizeD1BindParams(params) {
|
|
10466
|
+
return params.map((value) => {
|
|
10467
|
+
if (typeof value === "boolean") {
|
|
10468
|
+
return value ? 1 : 0;
|
|
10469
|
+
}
|
|
10470
|
+
return value;
|
|
10471
|
+
});
|
|
10472
|
+
}
|
|
10473
|
+
async function executeD1Query(db, input) {
|
|
10474
|
+
const query = input.query?.trim();
|
|
10475
|
+
if (!query) {
|
|
10476
|
+
return { ok: false, error: "invalid_query", message: "query is required" };
|
|
10477
|
+
}
|
|
10478
|
+
const params = normalizeD1BindParams(Array.isArray(input.params) ? input.params : []);
|
|
10479
|
+
const { target, session } = resolveSessionTarget(db, input);
|
|
10480
|
+
if (isMultiStatement(query)) {
|
|
10481
|
+
if (params.length > 0) {
|
|
10482
|
+
return {
|
|
10483
|
+
ok: false,
|
|
10484
|
+
error: "invalid_query",
|
|
10485
|
+
message: "params are only supported for single prepared statements"
|
|
10486
|
+
};
|
|
10487
|
+
}
|
|
10488
|
+
const resolveBookmark = () => session?.getBookmark() ?? null;
|
|
10489
|
+
const parts = splitSqlStatements(query);
|
|
10490
|
+
if (typeof target.batch === "function") {
|
|
10491
|
+
const prepared = parts.map((part) => target.prepare(part));
|
|
10492
|
+
const results = await target.batch(prepared);
|
|
10493
|
+
const rows2 = collectRowsFromBatchResults(results);
|
|
10494
|
+
return {
|
|
10495
|
+
ok: true,
|
|
10496
|
+
rows: rows2,
|
|
10497
|
+
columns: resultColumns(rows2),
|
|
10498
|
+
// Prefer returned rows; otherwise sum mutation meta.changes (not statement count).
|
|
10499
|
+
count: rows2.length > 0 ? rows2.length : sumBatchAffectedRows(results, parts.length),
|
|
10500
|
+
bookmark: resolveBookmark(),
|
|
10501
|
+
meta: { statementCount: parts.length, results },
|
|
10502
|
+
statementCount: parts.length
|
|
10503
|
+
};
|
|
10504
|
+
}
|
|
10505
|
+
const canExec = typeof target.exec === "function" && !session;
|
|
10506
|
+
if (canExec) {
|
|
10507
|
+
const execResult = await target.exec(query);
|
|
10508
|
+
return {
|
|
10509
|
+
ok: true,
|
|
10510
|
+
rows: [],
|
|
10511
|
+
columns: [],
|
|
10512
|
+
durationMs: execResult.duration,
|
|
10513
|
+
count: execResult.count,
|
|
10514
|
+
bookmark: resolveBookmark(),
|
|
10515
|
+
meta: { statementCount: execResult.count },
|
|
10516
|
+
statementCount: execResult.count
|
|
10517
|
+
};
|
|
10518
|
+
}
|
|
10519
|
+
return {
|
|
10520
|
+
ok: false,
|
|
10521
|
+
error: "invalid_query",
|
|
10522
|
+
message: "multi-statement query requires D1 batch() or exec() support"
|
|
10523
|
+
};
|
|
10524
|
+
}
|
|
10525
|
+
let statement = target.prepare(query);
|
|
10526
|
+
if (params.length > 0) {
|
|
10527
|
+
statement = statement.bind(...params);
|
|
10528
|
+
}
|
|
10529
|
+
const expectsRows = statementExpectsResultRows(query);
|
|
10530
|
+
const result = expectsRows ? await statement.all() : await statement.run();
|
|
10531
|
+
if (result.success === false) {
|
|
10532
|
+
const errorField = result.error;
|
|
10533
|
+
const message = typeof errorField === "string" && errorField.trim() ? errorField : "D1 query failed";
|
|
10534
|
+
return {
|
|
10535
|
+
ok: false,
|
|
10536
|
+
error: "query_failed",
|
|
10537
|
+
message
|
|
10538
|
+
};
|
|
10539
|
+
}
|
|
10540
|
+
const rows = Array.isArray(result.results) ? result.results : [];
|
|
10541
|
+
const bookmark = session?.getBookmark() ?? null;
|
|
10542
|
+
const meta = result.meta ?? {};
|
|
10543
|
+
const changes = typeof meta.changes === "number" ? meta.changes : typeof result.meta?.changes === "number" ? result.meta.changes : void 0;
|
|
10544
|
+
return {
|
|
10545
|
+
ok: true,
|
|
10546
|
+
rows,
|
|
10547
|
+
columns: resultColumns(rows),
|
|
10548
|
+
durationMs: typeof result.meta?.duration === "number" ? result.meta.duration : void 0,
|
|
10549
|
+
count: expectsRows ? rows.length : changes ?? rows.length,
|
|
10550
|
+
bookmark,
|
|
10551
|
+
meta
|
|
10552
|
+
};
|
|
10553
|
+
}
|
|
10554
|
+
async function executeD1Batch(db, input) {
|
|
10555
|
+
const statements = Array.isArray(input.statements) ? input.statements : [];
|
|
10556
|
+
if (statements.length === 0) {
|
|
10557
|
+
return {
|
|
10558
|
+
ok: false,
|
|
10559
|
+
error: "invalid_batch",
|
|
10560
|
+
message: "statements must contain at least one item"
|
|
10561
|
+
};
|
|
10562
|
+
}
|
|
10563
|
+
const { target, session } = resolveSessionTarget(db, input);
|
|
10564
|
+
const prepared = statements.map((item) => {
|
|
10565
|
+
const query = item.query?.trim();
|
|
10566
|
+
if (!query) {
|
|
10567
|
+
throw new Error("statements[].query is required");
|
|
10568
|
+
}
|
|
10569
|
+
const params = normalizeD1BindParams(Array.isArray(item.params) ? item.params : []);
|
|
10570
|
+
let statement = target.prepare(query);
|
|
10571
|
+
if (params.length > 0) {
|
|
10572
|
+
statement = statement.bind(...params);
|
|
10573
|
+
}
|
|
10574
|
+
return statement;
|
|
10575
|
+
});
|
|
10576
|
+
const results = await target.batch(prepared);
|
|
10577
|
+
const bookmark = session?.getBookmark() ?? null;
|
|
10578
|
+
return {
|
|
10579
|
+
ok: true,
|
|
10580
|
+
results,
|
|
10581
|
+
bookmark
|
|
10582
|
+
};
|
|
10583
|
+
}
|
|
10584
|
+
|
|
10585
|
+
// src/cloudflare/d1/sql.ts
|
|
10586
|
+
function asSingle(sql, params) {
|
|
10587
|
+
return { sql, params };
|
|
10588
|
+
}
|
|
10589
|
+
function asBatch(statements) {
|
|
10590
|
+
if (statements.length === 0) {
|
|
10591
|
+
throw new D1SqlCompileError("empty_insert", "batch requires at least one statement");
|
|
10592
|
+
}
|
|
10593
|
+
return {
|
|
10594
|
+
sql: statements[0].sql,
|
|
10595
|
+
params: statements[0].params,
|
|
10596
|
+
statements
|
|
10597
|
+
};
|
|
10598
|
+
}
|
|
10599
|
+
function hasPaginationBounds(payload) {
|
|
10600
|
+
return payload.limit !== void 0 || payload.offset !== void 0 || payload.page_size !== void 0 || payload.current_page !== void 0;
|
|
10601
|
+
}
|
|
10602
|
+
function assertEffectiveMutationBounds(payload) {
|
|
10603
|
+
if (payload.current_page !== void 0 && payload.page_size === void 0 && payload.limit === void 0) {
|
|
10604
|
+
throw new D1SqlCompileError(
|
|
10605
|
+
"page_without_size",
|
|
10606
|
+
"current_page requires page_size (or limit) for bounded update/delete on D1 edge-local"
|
|
10607
|
+
);
|
|
10608
|
+
}
|
|
10609
|
+
const clause = limitOffsetClause(payload);
|
|
10610
|
+
if (!clause.trim()) {
|
|
10611
|
+
throw new D1SqlCompileError(
|
|
10612
|
+
"invalid_pagination_bounds",
|
|
10613
|
+
"Bounded update/delete requires limit, offset, and/or page_size on D1 edge-local"
|
|
10614
|
+
);
|
|
10615
|
+
}
|
|
10616
|
+
}
|
|
10617
|
+
var SQLITE_ROWID_ALIASES = /* @__PURE__ */ new Set(["rowid", "oid", "_rowid_"]);
|
|
10618
|
+
function referencedMutationColumns(payload) {
|
|
10619
|
+
const names = [];
|
|
10620
|
+
for (const condition of payload.conditions ?? []) {
|
|
10621
|
+
const column = (condition.column ?? condition.eq_column ?? "").trim();
|
|
10622
|
+
if (column) names.push(column);
|
|
10623
|
+
}
|
|
10624
|
+
if (payload.sort_by?.field?.trim()) {
|
|
10625
|
+
names.push(payload.sort_by.field.trim());
|
|
10626
|
+
}
|
|
10627
|
+
return names;
|
|
10628
|
+
}
|
|
10629
|
+
function resolveBoundedIdentityColumn(payload, options) {
|
|
10630
|
+
const refs = referencedMutationColumns(payload);
|
|
10631
|
+
const lower = refs.map((name) => name.toLowerCase());
|
|
10632
|
+
if (lower.some((name) => SQLITE_ROWID_ALIASES.has(name))) {
|
|
10633
|
+
throw new D1SqlCompileError(
|
|
10634
|
+
"bounded_mutation_unsafe_identity",
|
|
10635
|
+
"Bounded update/delete cannot use rowid/oid/_rowid_ in filters or order \u2014 those names may be user columns that shadow SQLite row identity. Resolve the table primary key (or a single-column unique index) instead."
|
|
10636
|
+
);
|
|
10637
|
+
}
|
|
10638
|
+
const identity = options?.identityColumn?.trim();
|
|
10639
|
+
if (!identity) {
|
|
10640
|
+
throw new D1SqlCompileError(
|
|
10641
|
+
"bounded_mutation_no_unique_identity",
|
|
10642
|
+
"Bounded update/delete requires a proven unique identity column from the table schema (single-column PRIMARY KEY or UNIQUE index). Cannot assume a column named id."
|
|
10643
|
+
);
|
|
10644
|
+
}
|
|
10645
|
+
if (SQLITE_ROWID_ALIASES.has(identity.toLowerCase())) {
|
|
10646
|
+
throw new D1SqlCompileError(
|
|
10647
|
+
"bounded_mutation_unsafe_identity",
|
|
10648
|
+
`Bounded update/delete cannot use identity column "${identity}" \u2014 it may shadow SQLite row identity.`
|
|
10649
|
+
);
|
|
10650
|
+
}
|
|
10651
|
+
return identity;
|
|
10652
|
+
}
|
|
10653
|
+
function boundedRowidInClause(table2, whereSql, whereParams, payload, options) {
|
|
10654
|
+
assertEffectiveMutationBounds(payload);
|
|
10655
|
+
const identity = resolveBoundedIdentityColumn(payload, options);
|
|
10656
|
+
const identitySql = quoteIdent(identity);
|
|
10657
|
+
const innerWhere = whereSql.replace(/^WHERE\s+/i, "");
|
|
10658
|
+
const parts = [
|
|
10659
|
+
`SELECT ${identitySql} FROM ${quoteIdent(table2)}`,
|
|
10660
|
+
innerWhere ? `WHERE ${innerWhere}` : "",
|
|
10661
|
+
orderClause(payload.sort_by),
|
|
10662
|
+
limitOffsetClause(payload)
|
|
10663
|
+
].filter(Boolean);
|
|
10664
|
+
return {
|
|
10665
|
+
sql: `${identitySql} IN (${parts.join(" ")})`,
|
|
10666
|
+
params: [...whereParams]
|
|
10667
|
+
};
|
|
10668
|
+
}
|
|
10669
|
+
var D1SqlCompileError = class extends Error {
|
|
10670
|
+
code;
|
|
10671
|
+
constructor(code, message) {
|
|
10672
|
+
super(message);
|
|
10673
|
+
this.name = "D1SqlCompileError";
|
|
10674
|
+
this.code = code;
|
|
10675
|
+
}
|
|
10676
|
+
};
|
|
10677
|
+
var SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
10678
|
+
function quoteIdent(name) {
|
|
10679
|
+
const trimmed = name.trim();
|
|
10680
|
+
if (!trimmed) {
|
|
10681
|
+
throw new D1SqlCompileError("invalid_identifier", "Identifier is required");
|
|
10682
|
+
}
|
|
10683
|
+
if (trimmed.includes(".")) {
|
|
10684
|
+
throw new D1SqlCompileError(
|
|
10685
|
+
"schema_qualified_name",
|
|
10686
|
+
`Schema-qualified names are unsupported on D1 edge-local: ${trimmed}`
|
|
10687
|
+
);
|
|
10688
|
+
}
|
|
10689
|
+
if (!SAFE_IDENTIFIER.test(trimmed)) {
|
|
10690
|
+
throw new D1SqlCompileError(
|
|
10691
|
+
"invalid_identifier",
|
|
10692
|
+
`Invalid SQL identifier for D1 edge-local: ${trimmed}`
|
|
10693
|
+
);
|
|
10694
|
+
}
|
|
10695
|
+
return quoteQualifiedIdentifier(trimmed);
|
|
10696
|
+
}
|
|
10697
|
+
var RESPONSE_ALIAS_PATTERN2 = /^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*([A-Za-z_][A-Za-z0-9_]*)$/;
|
|
10698
|
+
var SQL_ALIAS_PATTERN2 = /^([A-Za-z_][A-Za-z0-9_]*)\s+(?:as\s+)?([A-Za-z_][A-Za-z0-9_]*)$/i;
|
|
10699
|
+
function quoteSelectTokenStrict(token) {
|
|
10700
|
+
const trimmed = token.trim();
|
|
10701
|
+
if (!trimmed || trimmed === "*") return trimmed || "*";
|
|
10702
|
+
if (SAFE_IDENTIFIER.test(trimmed)) {
|
|
10703
|
+
return quoteQualifiedIdentifier(trimmed);
|
|
10704
|
+
}
|
|
10705
|
+
const responseAlias = RESPONSE_ALIAS_PATTERN2.exec(trimmed);
|
|
10706
|
+
if (responseAlias) {
|
|
10707
|
+
const [, aliasIdentifier, baseIdentifier] = responseAlias;
|
|
10708
|
+
return `${quoteQualifiedIdentifier(baseIdentifier)} AS ${quoteQualifiedIdentifier(aliasIdentifier)}`;
|
|
10709
|
+
}
|
|
10710
|
+
const sqlAlias = SQL_ALIAS_PATTERN2.exec(trimmed);
|
|
10711
|
+
if (sqlAlias) {
|
|
10712
|
+
const [, baseIdentifier, aliasIdentifier] = sqlAlias;
|
|
10713
|
+
return `${quoteQualifiedIdentifier(baseIdentifier)} AS ${quoteQualifiedIdentifier(aliasIdentifier)}`;
|
|
10714
|
+
}
|
|
10715
|
+
throw new D1SqlCompileError(
|
|
10716
|
+
"unsafe_select",
|
|
10717
|
+
`SELECT/RETURNING expressions are not supported on D1 edge-local; use column names or aliases only: ${token}`
|
|
10718
|
+
);
|
|
10719
|
+
}
|
|
10720
|
+
function selectClause(columns) {
|
|
10721
|
+
if (columns === void 0 || columns === "*" || columns === "") return "*";
|
|
10722
|
+
if (typeof columns === "string") {
|
|
10723
|
+
const trimmed = columns.trim();
|
|
10724
|
+
if (!trimmed || trimmed === "*") return "*";
|
|
10725
|
+
return trimmed.split(",").map((part) => quoteSelectTokenStrict(part)).join(", ");
|
|
10726
|
+
}
|
|
10727
|
+
if (columns.length === 0) return "*";
|
|
10728
|
+
return columns.map((column) => quoteSelectTokenStrict(column)).join(", ");
|
|
10729
|
+
}
|
|
10730
|
+
function wantsReturning(payload) {
|
|
10731
|
+
return Boolean(payload.columns) && payload.head !== true;
|
|
10732
|
+
}
|
|
10733
|
+
function conditionToWhere(condition) {
|
|
10734
|
+
const column = condition.column?.trim() || condition.eq_column?.trim() || "";
|
|
10735
|
+
if (!column) {
|
|
10736
|
+
throw new D1SqlCompileError("invalid_condition", "Condition requires a column");
|
|
10737
|
+
}
|
|
10738
|
+
const col = quoteIdent(column);
|
|
10739
|
+
const operator = (condition.operator || "eq").toLowerCase();
|
|
10740
|
+
const value = condition.value !== void 0 ? condition.value : condition.eq_value;
|
|
10741
|
+
switch (operator) {
|
|
10742
|
+
case "eq": {
|
|
10743
|
+
if (Array.isArray(value)) {
|
|
10744
|
+
if (value.length === 0) {
|
|
10745
|
+
return { sql: "1 = 0", params: [] };
|
|
10746
|
+
}
|
|
10747
|
+
const placeholders = value.map(() => "?").join(", ");
|
|
10748
|
+
return { sql: `${col} IN (${placeholders})`, params: [...value] };
|
|
10749
|
+
}
|
|
10750
|
+
if (value === null) {
|
|
10751
|
+
return { sql: `${col} IS NULL`, params: [] };
|
|
10752
|
+
}
|
|
10753
|
+
return { sql: `${col} = ?`, params: [value ?? null] };
|
|
10754
|
+
}
|
|
10755
|
+
case "neq":
|
|
10756
|
+
if (value === null) {
|
|
10757
|
+
return { sql: `${col} IS NOT NULL`, params: [] };
|
|
10758
|
+
}
|
|
10759
|
+
return { sql: `${col} != ?`, params: [value ?? null] };
|
|
10760
|
+
case "gt":
|
|
10761
|
+
return { sql: `${col} > ?`, params: [value ?? null] };
|
|
10762
|
+
case "gte":
|
|
10763
|
+
return { sql: `${col} >= ?`, params: [value ?? null] };
|
|
10764
|
+
case "lt":
|
|
10765
|
+
return { sql: `${col} < ?`, params: [value ?? null] };
|
|
10766
|
+
case "lte":
|
|
10767
|
+
return { sql: `${col} <= ?`, params: [value ?? null] };
|
|
10768
|
+
case "like":
|
|
10769
|
+
return { sql: `${col} LIKE ?`, params: [value ?? null] };
|
|
10770
|
+
case "ilike":
|
|
10771
|
+
return { sql: `${col} LIKE ? COLLATE NOCASE`, params: [value ?? null] };
|
|
10772
|
+
case "in": {
|
|
10773
|
+
const items = Array.isArray(value) ? value : value === void 0 ? [] : [value];
|
|
10774
|
+
if (items.length === 0) {
|
|
10775
|
+
return { sql: "1 = 0", params: [] };
|
|
10776
|
+
}
|
|
10777
|
+
const placeholders = items.map(() => "?").join(", ");
|
|
10778
|
+
return { sql: `${col} IN (${placeholders})`, params: [...items] };
|
|
10779
|
+
}
|
|
10780
|
+
case "is": {
|
|
10781
|
+
if (value === null || value === "null") {
|
|
10782
|
+
return { sql: `${col} IS NULL`, params: [] };
|
|
10783
|
+
}
|
|
10784
|
+
if (value === true || value === "true") {
|
|
10785
|
+
return { sql: `${col} IS TRUE`, params: [] };
|
|
10786
|
+
}
|
|
10787
|
+
if (value === false || value === "false") {
|
|
10788
|
+
return { sql: `${col} IS FALSE`, params: [] };
|
|
10789
|
+
}
|
|
10790
|
+
return { sql: `${col} IS ?`, params: [value] };
|
|
10791
|
+
}
|
|
10792
|
+
case "not":
|
|
10793
|
+
case "or":
|
|
10794
|
+
case "contains":
|
|
10795
|
+
case "containedby":
|
|
10796
|
+
throw new D1SqlCompileError(
|
|
10797
|
+
"unsupported_operator",
|
|
10798
|
+
`Condition operator "${operator}" is not supported on D1 edge-local L1`
|
|
10799
|
+
);
|
|
10800
|
+
default:
|
|
10801
|
+
throw new D1SqlCompileError(
|
|
10802
|
+
"unsupported_operator",
|
|
10803
|
+
`Unknown condition operator "${operator}"`
|
|
10804
|
+
);
|
|
10805
|
+
}
|
|
10806
|
+
}
|
|
10807
|
+
function buildWhere(conditions) {
|
|
10808
|
+
if (!conditions?.length) {
|
|
10809
|
+
return { sql: "", params: [] };
|
|
10810
|
+
}
|
|
10811
|
+
const parts = [];
|
|
10812
|
+
const params = [];
|
|
10813
|
+
for (const condition of conditions) {
|
|
10814
|
+
if (!condition.operator && condition.eq_column) {
|
|
10815
|
+
const clause2 = conditionToWhere({
|
|
10816
|
+
...condition,
|
|
10817
|
+
operator: "eq",
|
|
10818
|
+
column: condition.eq_column,
|
|
10819
|
+
value: condition.eq_value
|
|
10820
|
+
});
|
|
10821
|
+
parts.push(clause2.sql);
|
|
10822
|
+
params.push(...clause2.params);
|
|
10823
|
+
continue;
|
|
10824
|
+
}
|
|
10825
|
+
const clause = conditionToWhere(condition);
|
|
10826
|
+
parts.push(clause.sql);
|
|
10827
|
+
params.push(...clause.params);
|
|
10828
|
+
}
|
|
10829
|
+
return {
|
|
10830
|
+
sql: parts.length ? `WHERE ${parts.join(" AND ")}` : "",
|
|
10831
|
+
params
|
|
10832
|
+
};
|
|
10833
|
+
}
|
|
10834
|
+
function orderClause(order) {
|
|
10835
|
+
if (!order?.field?.trim()) return "";
|
|
10836
|
+
const direction = order.direction === "descending" ? "DESC" : "ASC";
|
|
10837
|
+
return `ORDER BY ${quoteIdent(order.field)} ${direction}`;
|
|
10838
|
+
}
|
|
10839
|
+
function limitOffsetClause(payload) {
|
|
10840
|
+
let limit = payload.limit;
|
|
10841
|
+
let offset = payload.offset;
|
|
10842
|
+
if (limit === void 0 && payload.page_size !== void 0) {
|
|
10843
|
+
limit = payload.page_size;
|
|
10844
|
+
}
|
|
10845
|
+
if (payload.current_page !== void 0 && offset === void 0) {
|
|
10846
|
+
const pageSize = payload.page_size ?? payload.limit;
|
|
10847
|
+
if (pageSize !== void 0) {
|
|
10848
|
+
offset = Math.max(0, (payload.current_page - 1) * pageSize);
|
|
10849
|
+
}
|
|
10850
|
+
}
|
|
10851
|
+
const parts = [];
|
|
10852
|
+
if (offset !== void 0 && limit === void 0) {
|
|
10853
|
+
parts.push("LIMIT -1");
|
|
10854
|
+
parts.push(`OFFSET ${Math.max(0, Math.trunc(offset))}`);
|
|
10855
|
+
} else {
|
|
10856
|
+
if (limit !== void 0) {
|
|
10857
|
+
parts.push(`LIMIT ${Math.max(0, Math.trunc(limit))}`);
|
|
10858
|
+
}
|
|
10859
|
+
if (offset !== void 0) {
|
|
10860
|
+
parts.push(`OFFSET ${Math.max(0, Math.trunc(offset))}`);
|
|
10861
|
+
}
|
|
10862
|
+
}
|
|
10863
|
+
return parts.join(" ");
|
|
10864
|
+
}
|
|
10865
|
+
function rejectStructuredRelations(payload) {
|
|
10866
|
+
const select = payload.select;
|
|
10867
|
+
if (select && typeof select === "object" && !Array.isArray(select)) {
|
|
10868
|
+
for (const value of Object.values(select)) {
|
|
10869
|
+
if (value && typeof value === "object") {
|
|
10870
|
+
throw new D1SqlCompileError(
|
|
10871
|
+
"relations_unsupported",
|
|
10872
|
+
"Nested relation selects are unsupported on D1 edge-local"
|
|
10873
|
+
);
|
|
10874
|
+
}
|
|
10875
|
+
}
|
|
10876
|
+
}
|
|
10877
|
+
if (payload.view_name) {
|
|
10878
|
+
throw new D1SqlCompileError(
|
|
10879
|
+
"view_unsupported",
|
|
10880
|
+
"view_name is unsupported on D1 edge-local L1"
|
|
10881
|
+
);
|
|
10882
|
+
}
|
|
10883
|
+
}
|
|
10884
|
+
function jsonValue(value) {
|
|
10885
|
+
if (value === void 0) return null;
|
|
10886
|
+
if (value !== null && typeof value === "object") {
|
|
10887
|
+
return JSON.stringify(value);
|
|
10888
|
+
}
|
|
10889
|
+
return value;
|
|
10890
|
+
}
|
|
10891
|
+
function compileD1Fetch(payload) {
|
|
10892
|
+
rejectStructuredRelations(payload);
|
|
10893
|
+
const table2 = payload.table_name?.trim();
|
|
10894
|
+
if (!table2) {
|
|
10895
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for fetch");
|
|
10896
|
+
}
|
|
10897
|
+
let columns = payload.columns;
|
|
10898
|
+
if (payload.select && typeof payload.select === "object" && !Array.isArray(payload.select)) {
|
|
10899
|
+
const keys = Object.entries(payload.select).filter(([, enabled]) => enabled === true || enabled === 1).map(([key]) => key);
|
|
10900
|
+
if (keys.length > 0) {
|
|
10901
|
+
columns = keys;
|
|
10902
|
+
}
|
|
10903
|
+
} else if (typeof payload.select === "string" && payload.select.trim()) {
|
|
10904
|
+
columns = payload.select;
|
|
10905
|
+
}
|
|
10906
|
+
let where = buildWhere(payload.conditions);
|
|
10907
|
+
if (!where.sql && payload.where && typeof payload.where === "object") {
|
|
10908
|
+
const eqConditions = Object.entries(
|
|
10909
|
+
payload.where
|
|
10910
|
+
).map(([column, value]) => ({
|
|
10911
|
+
column,
|
|
10912
|
+
operator: "eq",
|
|
10913
|
+
value
|
|
10914
|
+
}));
|
|
10915
|
+
where = buildWhere(eqConditions);
|
|
10916
|
+
}
|
|
10917
|
+
if (payload.head === true) {
|
|
10918
|
+
return compileD1CountFromWhere(table2, where);
|
|
10919
|
+
}
|
|
10920
|
+
const parts = [
|
|
10921
|
+
`SELECT ${selectClause(columns)} FROM ${quoteIdent(table2)}`,
|
|
10922
|
+
where.sql,
|
|
10923
|
+
orderClause(payload.sort_by),
|
|
10924
|
+
limitOffsetClause(payload)
|
|
10925
|
+
].filter(Boolean);
|
|
10926
|
+
return asSingle(parts.join(" "), where.params);
|
|
10927
|
+
}
|
|
10928
|
+
function compileD1Count(payload) {
|
|
10929
|
+
rejectStructuredRelations(payload);
|
|
10930
|
+
const table2 = payload.table_name?.trim();
|
|
10931
|
+
if (!table2) {
|
|
10932
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for count");
|
|
10933
|
+
}
|
|
10934
|
+
let where = buildWhere(payload.conditions);
|
|
10935
|
+
if (!where.sql && payload.where && typeof payload.where === "object") {
|
|
10936
|
+
const eqConditions = Object.entries(
|
|
10937
|
+
payload.where
|
|
10938
|
+
).map(([column, value]) => ({
|
|
10939
|
+
column,
|
|
10940
|
+
operator: "eq",
|
|
10941
|
+
value
|
|
10942
|
+
}));
|
|
10943
|
+
where = buildWhere(eqConditions);
|
|
10944
|
+
}
|
|
10945
|
+
return compileD1CountFromWhere(table2, where);
|
|
10946
|
+
}
|
|
10947
|
+
function compileD1CountFromWhere(table2, where) {
|
|
10948
|
+
const parts = [
|
|
10949
|
+
`SELECT COUNT(*) AS __athena_count FROM ${quoteIdent(table2)}`,
|
|
10950
|
+
where.sql
|
|
10951
|
+
].filter(Boolean);
|
|
10952
|
+
return asSingle(parts.join(" "), where.params);
|
|
10953
|
+
}
|
|
10954
|
+
function extractAthenaCount(rows) {
|
|
10955
|
+
const first = rows[0];
|
|
10956
|
+
const rawCount = first && typeof first === "object" && !Array.isArray(first) ? first.__athena_count : void 0;
|
|
10957
|
+
const count = typeof rawCount === "number" ? rawCount : typeof rawCount === "bigint" ? Number(rawCount) : Number(rawCount ?? 0);
|
|
10958
|
+
return Number.isFinite(count) ? count : 0;
|
|
10959
|
+
}
|
|
10960
|
+
function compileSingleRowInsert(table2, row, payload) {
|
|
10961
|
+
const columns = Object.keys(row);
|
|
10962
|
+
if (columns.length === 0) {
|
|
10963
|
+
if (payload.on_conflict) {
|
|
10964
|
+
throw new D1SqlCompileError(
|
|
10965
|
+
"default_values_upsert_unsupported",
|
|
10966
|
+
"DEFAULT VALUES upsert is unsupported on D1 edge-local; provide insert columns or omit onConflict"
|
|
10967
|
+
);
|
|
10968
|
+
}
|
|
10969
|
+
const parts2 = [`INSERT INTO ${quoteIdent(table2)} DEFAULT VALUES`];
|
|
10970
|
+
if (wantsReturning(payload)) {
|
|
10971
|
+
parts2.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
10972
|
+
}
|
|
10973
|
+
return { sql: parts2.join(" "), params: [] };
|
|
10974
|
+
}
|
|
10975
|
+
const params = columns.map((column) => jsonValue(row[column]));
|
|
10976
|
+
const parts = [
|
|
10977
|
+
`INSERT INTO ${quoteIdent(table2)} (${columns.map(quoteIdent).join(", ")})`,
|
|
10978
|
+
`VALUES (${columns.map(() => "?").join(", ")})`
|
|
10979
|
+
];
|
|
10980
|
+
appendOnConflict(parts, params, payload, columns);
|
|
10981
|
+
if (wantsReturning(payload)) {
|
|
10982
|
+
parts.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
10983
|
+
}
|
|
10984
|
+
return { sql: parts.join(" "), params };
|
|
10985
|
+
}
|
|
10986
|
+
function parseOnConflictColumns(onConflict) {
|
|
10987
|
+
const raw = Array.isArray(onConflict) ? onConflict : [onConflict];
|
|
10988
|
+
const columns = [];
|
|
10989
|
+
for (const item of raw) {
|
|
10990
|
+
for (const part of String(item).split(",")) {
|
|
10991
|
+
const trimmed = part.trim();
|
|
10992
|
+
if (trimmed) columns.push(trimmed);
|
|
10993
|
+
}
|
|
10994
|
+
}
|
|
10995
|
+
if (columns.length === 0) {
|
|
10996
|
+
throw new D1SqlCompileError(
|
|
10997
|
+
"invalid_on_conflict",
|
|
10998
|
+
"on_conflict requires at least one column"
|
|
10999
|
+
);
|
|
11000
|
+
}
|
|
11001
|
+
return columns;
|
|
11002
|
+
}
|
|
11003
|
+
function appendOnConflict(parts, params, payload, insertColumns) {
|
|
11004
|
+
if (!payload.on_conflict) return;
|
|
11005
|
+
const conflictCols = parseOnConflictColumns(payload.on_conflict);
|
|
11006
|
+
const conflictSql = conflictCols.map(quoteIdent).join(", ");
|
|
11007
|
+
if (payload.update_body !== void 0 && payload.update_body !== null) {
|
|
11008
|
+
const entries = Object.entries(payload.update_body);
|
|
11009
|
+
if (entries.length === 0) {
|
|
11010
|
+
parts.push(`ON CONFLICT (${conflictSql}) DO NOTHING`);
|
|
11011
|
+
return;
|
|
11012
|
+
}
|
|
11013
|
+
const assignments2 = entries.map(([column, value]) => {
|
|
11014
|
+
params.push(jsonValue(value));
|
|
11015
|
+
return `${quoteIdent(column)} = ?`;
|
|
11016
|
+
});
|
|
11017
|
+
parts.push(`ON CONFLICT (${conflictSql}) DO UPDATE SET ${assignments2.join(", ")}`);
|
|
11018
|
+
return;
|
|
11019
|
+
}
|
|
11020
|
+
const conflictSet = new Set(conflictCols);
|
|
11021
|
+
const assignments = insertColumns.filter((column) => !conflictSet.has(column)).map((column) => {
|
|
11022
|
+
const quoted = quoteIdent(column);
|
|
11023
|
+
return `${quoted} = excluded.${quoted}`;
|
|
11024
|
+
});
|
|
11025
|
+
if (assignments.length === 0) {
|
|
11026
|
+
parts.push(`ON CONFLICT (${conflictSql}) DO NOTHING`);
|
|
11027
|
+
} else {
|
|
11028
|
+
parts.push(`ON CONFLICT (${conflictSql}) DO UPDATE SET ${assignments.join(", ")}`);
|
|
11029
|
+
}
|
|
11030
|
+
}
|
|
11031
|
+
function compileD1Insert(payload) {
|
|
11032
|
+
const table2 = payload.table_name?.trim();
|
|
11033
|
+
if (!table2) {
|
|
11034
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for insert");
|
|
11035
|
+
}
|
|
11036
|
+
const rows = Array.isArray(payload.insert_body) ? payload.insert_body : [payload.insert_body];
|
|
11037
|
+
if (rows.length === 0) {
|
|
11038
|
+
throw new D1SqlCompileError("empty_insert", "insert_body must not be empty");
|
|
11039
|
+
}
|
|
11040
|
+
const columns = [];
|
|
11041
|
+
const seen = /* @__PURE__ */ new Set();
|
|
11042
|
+
for (const row of rows) {
|
|
11043
|
+
for (const key of Object.keys(row ?? {})) {
|
|
11044
|
+
if (seen.has(key)) continue;
|
|
11045
|
+
seen.add(key);
|
|
11046
|
+
columns.push(key);
|
|
11047
|
+
}
|
|
11048
|
+
}
|
|
11049
|
+
if (columns.length === 0) {
|
|
11050
|
+
if (rows.length === 1) {
|
|
11051
|
+
const compiled = compileSingleRowInsert(table2, {}, payload);
|
|
11052
|
+
return asSingle(compiled.sql, compiled.params);
|
|
11053
|
+
}
|
|
11054
|
+
throw new D1SqlCompileError(
|
|
11055
|
+
"empty_insert",
|
|
11056
|
+
"Multi-row insert_body cannot be empty objects; use a single {} for DEFAULT VALUES"
|
|
11057
|
+
);
|
|
11058
|
+
}
|
|
11059
|
+
const forceNullForMissing = payload.default_to_null === true;
|
|
11060
|
+
const isSparse = rows.some(
|
|
11061
|
+
(row) => columns.some((column) => !Object.prototype.hasOwnProperty.call(row, column))
|
|
11062
|
+
);
|
|
11063
|
+
if (isSparse && !forceNullForMissing && rows.length > 1) {
|
|
11064
|
+
return asBatch(
|
|
11065
|
+
rows.map((row) => compileSingleRowInsert(table2, row, payload))
|
|
11066
|
+
);
|
|
11067
|
+
}
|
|
11068
|
+
if (isSparse && !forceNullForMissing && rows.length === 1) {
|
|
11069
|
+
const compiled = compileSingleRowInsert(table2, rows[0], payload);
|
|
11070
|
+
return asSingle(compiled.sql, compiled.params);
|
|
11071
|
+
}
|
|
11072
|
+
const params = [];
|
|
11073
|
+
const valueGroups = rows.map((row) => {
|
|
11074
|
+
const placeholders = columns.map((column) => {
|
|
11075
|
+
const has = Object.prototype.hasOwnProperty.call(row, column);
|
|
11076
|
+
if (!has) {
|
|
11077
|
+
params.push(null);
|
|
11078
|
+
return "?";
|
|
11079
|
+
}
|
|
11080
|
+
params.push(jsonValue(row[column]));
|
|
11081
|
+
return "?";
|
|
11082
|
+
});
|
|
11083
|
+
return `(${placeholders.join(", ")})`;
|
|
11084
|
+
});
|
|
11085
|
+
const parts = [
|
|
11086
|
+
`INSERT INTO ${quoteIdent(table2)} (${columns.map(quoteIdent).join(", ")})`,
|
|
11087
|
+
`VALUES ${valueGroups.join(", ")}`
|
|
11088
|
+
];
|
|
11089
|
+
appendOnConflict(parts, params, payload, columns);
|
|
11090
|
+
if (wantsReturning(payload)) {
|
|
11091
|
+
parts.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
11092
|
+
}
|
|
11093
|
+
return asSingle(parts.join(" "), params);
|
|
11094
|
+
}
|
|
11095
|
+
function compileD1Update(payload, options) {
|
|
11096
|
+
const table2 = payload.table_name?.trim();
|
|
11097
|
+
if (!table2) {
|
|
11098
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for update");
|
|
11099
|
+
}
|
|
11100
|
+
const entries = Object.entries(payload.update_body ?? {});
|
|
11101
|
+
if (entries.length === 0) {
|
|
11102
|
+
throw new D1SqlCompileError("empty_update", "update_body must not be empty");
|
|
11103
|
+
}
|
|
11104
|
+
const params = [];
|
|
11105
|
+
const assignments = entries.map(([column, value]) => {
|
|
11106
|
+
params.push(jsonValue(value));
|
|
11107
|
+
return `${quoteIdent(column)} = ?`;
|
|
11108
|
+
});
|
|
11109
|
+
const where = buildWhere(payload.conditions);
|
|
11110
|
+
if (!where.sql) {
|
|
11111
|
+
throw new D1SqlCompileError(
|
|
11112
|
+
"unfiltered_update",
|
|
11113
|
+
"UPDATE requires at least one condition on D1 edge-local"
|
|
11114
|
+
);
|
|
11115
|
+
}
|
|
11116
|
+
if (hasPaginationBounds(payload) || payload.sort_by) {
|
|
11117
|
+
if (!hasPaginationBounds(payload)) {
|
|
11118
|
+
throw new D1SqlCompileError(
|
|
11119
|
+
"order_without_bounds",
|
|
11120
|
+
"UPDATE with sort_by requires limit/offset or page_size/current_page on D1 edge-local"
|
|
11121
|
+
);
|
|
11122
|
+
}
|
|
11123
|
+
const bounded = boundedRowidInClause(
|
|
11124
|
+
table2,
|
|
11125
|
+
where.sql,
|
|
11126
|
+
where.params,
|
|
11127
|
+
{
|
|
11128
|
+
...payload,
|
|
11129
|
+
conditions: payload.conditions
|
|
11130
|
+
},
|
|
11131
|
+
options
|
|
11132
|
+
);
|
|
11133
|
+
params.push(...bounded.params);
|
|
11134
|
+
const parts2 = [
|
|
11135
|
+
`UPDATE ${quoteIdent(table2)} SET ${assignments.join(", ")}`,
|
|
11136
|
+
`WHERE ${bounded.sql}`
|
|
11137
|
+
];
|
|
11138
|
+
if (wantsReturning(payload)) {
|
|
11139
|
+
parts2.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
11140
|
+
}
|
|
11141
|
+
return asSingle(parts2.join(" "), params);
|
|
11142
|
+
}
|
|
11143
|
+
params.push(...where.params);
|
|
11144
|
+
const parts = [
|
|
11145
|
+
`UPDATE ${quoteIdent(table2)} SET ${assignments.join(", ")}`,
|
|
11146
|
+
where.sql
|
|
11147
|
+
];
|
|
11148
|
+
if (wantsReturning(payload)) {
|
|
11149
|
+
parts.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
11150
|
+
}
|
|
11151
|
+
return asSingle(parts.join(" "), params);
|
|
11152
|
+
}
|
|
11153
|
+
function compileD1Delete(payload, options) {
|
|
11154
|
+
const table2 = payload.table_name?.trim();
|
|
11155
|
+
if (!table2) {
|
|
11156
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for delete");
|
|
11157
|
+
}
|
|
11158
|
+
const conditions = [...payload.conditions ?? []];
|
|
11159
|
+
if (payload.resource_id !== void 0 && payload.resource_id !== null) {
|
|
11160
|
+
const hasResourceIdFilter = conditions.some((condition) => {
|
|
11161
|
+
const column = (condition.column ?? condition.eq_column ?? "").trim();
|
|
11162
|
+
return column === "resource_id";
|
|
11163
|
+
});
|
|
11164
|
+
const hasIdFilter = conditions.some((condition) => {
|
|
11165
|
+
const column = (condition.column ?? condition.eq_column ?? "").trim();
|
|
11166
|
+
return column === "id";
|
|
11167
|
+
});
|
|
11168
|
+
if (!hasResourceIdFilter && !hasIdFilter) {
|
|
11169
|
+
conditions.unshift({
|
|
11170
|
+
column: "id",
|
|
11171
|
+
operator: "eq",
|
|
11172
|
+
value: payload.resource_id
|
|
11173
|
+
});
|
|
11174
|
+
}
|
|
11175
|
+
}
|
|
11176
|
+
const where = buildWhere(conditions);
|
|
11177
|
+
if (!where.sql) {
|
|
11178
|
+
throw new D1SqlCompileError(
|
|
11179
|
+
"unfiltered_delete",
|
|
11180
|
+
"DELETE requires at least one condition or resource_id on D1 edge-local"
|
|
11181
|
+
);
|
|
11182
|
+
}
|
|
11183
|
+
if (hasPaginationBounds(payload) || payload.sort_by) {
|
|
11184
|
+
if (!hasPaginationBounds(payload)) {
|
|
11185
|
+
throw new D1SqlCompileError(
|
|
11186
|
+
"order_without_bounds",
|
|
11187
|
+
"DELETE with sort_by requires limit/offset or page_size/current_page on D1 edge-local"
|
|
11188
|
+
);
|
|
11189
|
+
}
|
|
11190
|
+
const bounded = boundedRowidInClause(
|
|
11191
|
+
table2,
|
|
11192
|
+
where.sql,
|
|
11193
|
+
where.params,
|
|
11194
|
+
{
|
|
11195
|
+
...payload,
|
|
11196
|
+
conditions
|
|
11197
|
+
},
|
|
11198
|
+
options
|
|
11199
|
+
);
|
|
11200
|
+
const parts2 = [`DELETE FROM ${quoteIdent(table2)}`, `WHERE ${bounded.sql}`];
|
|
11201
|
+
if (wantsReturning(payload)) {
|
|
11202
|
+
parts2.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
11203
|
+
}
|
|
11204
|
+
return asSingle(parts2.join(" "), bounded.params);
|
|
11205
|
+
}
|
|
11206
|
+
const parts = [`DELETE FROM ${quoteIdent(table2)}`, where.sql];
|
|
11207
|
+
if (wantsReturning(payload)) {
|
|
11208
|
+
parts.push(`RETURNING ${selectClause(payload.columns)}`);
|
|
11209
|
+
}
|
|
11210
|
+
return asSingle(parts.join(" "), where.params);
|
|
11211
|
+
}
|
|
11212
|
+
|
|
11213
|
+
// src/cloudflare/d1/sql-rewrite.ts
|
|
11214
|
+
var PG_CAST_TYPES = "text|uuid|citext|varchar|bpchar|char|integer|int4|int8|bigint|smallint|boolean|bool|jsonb|json|numeric|decimal|real|float|double precision|timestamptz|timestamp|date|bytea";
|
|
11215
|
+
function mapSqlOutsideLiterals(sql, transform) {
|
|
11216
|
+
let out = "";
|
|
11217
|
+
let buffer = "";
|
|
11218
|
+
let inSingle = false;
|
|
11219
|
+
let inDouble = false;
|
|
11220
|
+
let inBacktick = false;
|
|
11221
|
+
let inBracket = false;
|
|
11222
|
+
let inLineComment = false;
|
|
11223
|
+
let inBlockComment = false;
|
|
11224
|
+
const flushCode = () => {
|
|
11225
|
+
if (buffer) {
|
|
11226
|
+
out += transform(buffer);
|
|
11227
|
+
buffer = "";
|
|
11228
|
+
}
|
|
11229
|
+
};
|
|
11230
|
+
for (let i = 0; i < sql.length; i += 1) {
|
|
11231
|
+
const ch = sql[i];
|
|
11232
|
+
const next = sql[i + 1];
|
|
11233
|
+
if (inLineComment) {
|
|
11234
|
+
out += ch;
|
|
11235
|
+
if (ch === "\n" || ch === "\r") inLineComment = false;
|
|
11236
|
+
continue;
|
|
11237
|
+
}
|
|
11238
|
+
if (inBlockComment) {
|
|
11239
|
+
out += ch;
|
|
11240
|
+
if (ch === "*" && next === "/") {
|
|
11241
|
+
out += next;
|
|
11242
|
+
i += 1;
|
|
11243
|
+
inBlockComment = false;
|
|
11244
|
+
}
|
|
11245
|
+
continue;
|
|
11246
|
+
}
|
|
11247
|
+
if (inSingle) {
|
|
11248
|
+
out += ch;
|
|
11249
|
+
if (ch === "'" && next === "'") {
|
|
11250
|
+
out += next;
|
|
11251
|
+
i += 1;
|
|
11252
|
+
continue;
|
|
11253
|
+
}
|
|
11254
|
+
if (ch === "'") inSingle = false;
|
|
11255
|
+
continue;
|
|
11256
|
+
}
|
|
11257
|
+
if (inDouble) {
|
|
11258
|
+
out += ch;
|
|
11259
|
+
if (ch === '"' && next === '"') {
|
|
11260
|
+
out += next;
|
|
11261
|
+
i += 1;
|
|
11262
|
+
continue;
|
|
11263
|
+
}
|
|
11264
|
+
if (ch === '"') inDouble = false;
|
|
11265
|
+
continue;
|
|
11266
|
+
}
|
|
11267
|
+
if (inBacktick) {
|
|
11268
|
+
out += ch;
|
|
11269
|
+
if (ch === "`" && next === "`") {
|
|
11270
|
+
out += next;
|
|
11271
|
+
i += 1;
|
|
11272
|
+
continue;
|
|
11273
|
+
}
|
|
11274
|
+
if (ch === "`") inBacktick = false;
|
|
11275
|
+
continue;
|
|
11276
|
+
}
|
|
11277
|
+
if (inBracket) {
|
|
11278
|
+
out += ch;
|
|
11279
|
+
if (ch === "]") inBracket = false;
|
|
11280
|
+
continue;
|
|
11281
|
+
}
|
|
11282
|
+
if (ch === "-" && next === "-") {
|
|
11283
|
+
flushCode();
|
|
11284
|
+
out += ch;
|
|
11285
|
+
out += next;
|
|
11286
|
+
i += 1;
|
|
11287
|
+
inLineComment = true;
|
|
11288
|
+
continue;
|
|
11289
|
+
}
|
|
11290
|
+
if (ch === "/" && next === "*") {
|
|
11291
|
+
flushCode();
|
|
11292
|
+
out += ch;
|
|
11293
|
+
out += next;
|
|
11294
|
+
i += 1;
|
|
11295
|
+
inBlockComment = true;
|
|
11296
|
+
continue;
|
|
11297
|
+
}
|
|
11298
|
+
if (ch === "'") {
|
|
11299
|
+
flushCode();
|
|
11300
|
+
out += ch;
|
|
11301
|
+
inSingle = true;
|
|
11302
|
+
continue;
|
|
11303
|
+
}
|
|
11304
|
+
if (ch === '"') {
|
|
11305
|
+
flushCode();
|
|
11306
|
+
out += ch;
|
|
11307
|
+
inDouble = true;
|
|
11308
|
+
continue;
|
|
11309
|
+
}
|
|
11310
|
+
if (ch === "`") {
|
|
11311
|
+
flushCode();
|
|
11312
|
+
out += ch;
|
|
11313
|
+
inBacktick = true;
|
|
11314
|
+
continue;
|
|
11315
|
+
}
|
|
11316
|
+
if (ch === "[") {
|
|
11317
|
+
flushCode();
|
|
11318
|
+
out += ch;
|
|
11319
|
+
inBracket = true;
|
|
11320
|
+
continue;
|
|
11321
|
+
}
|
|
11322
|
+
buffer += ch;
|
|
11323
|
+
}
|
|
11324
|
+
flushCode();
|
|
11325
|
+
return out;
|
|
11326
|
+
}
|
|
11327
|
+
function isIdentChar2(ch) {
|
|
11328
|
+
if (!ch) return false;
|
|
11329
|
+
return /[A-Za-z0-9_]/.test(ch);
|
|
11330
|
+
}
|
|
11331
|
+
function collectLimitOffsetKeywords(sql) {
|
|
11332
|
+
const hits = [];
|
|
11333
|
+
let depth = 0;
|
|
11334
|
+
let statement = 0;
|
|
11335
|
+
let inSingle = false;
|
|
11336
|
+
let inDouble = false;
|
|
11337
|
+
let inBacktick = false;
|
|
11338
|
+
let inBracket = false;
|
|
11339
|
+
let inLineComment = false;
|
|
11340
|
+
let inBlockComment = false;
|
|
11341
|
+
for (let i = 0; i < sql.length; i += 1) {
|
|
11342
|
+
const ch = sql[i];
|
|
11343
|
+
const next = sql[i + 1];
|
|
11344
|
+
if (inLineComment) {
|
|
11345
|
+
if (ch === "\n" || ch === "\r") inLineComment = false;
|
|
11346
|
+
continue;
|
|
11347
|
+
}
|
|
11348
|
+
if (inBlockComment) {
|
|
11349
|
+
if (ch === "*" && next === "/") {
|
|
11350
|
+
i += 1;
|
|
11351
|
+
inBlockComment = false;
|
|
11352
|
+
}
|
|
11353
|
+
continue;
|
|
11354
|
+
}
|
|
11355
|
+
if (inSingle) {
|
|
11356
|
+
if (ch === "'" && next === "'") {
|
|
11357
|
+
i += 1;
|
|
11358
|
+
continue;
|
|
11359
|
+
}
|
|
11360
|
+
if (ch === "'") inSingle = false;
|
|
11361
|
+
continue;
|
|
11362
|
+
}
|
|
11363
|
+
if (inDouble) {
|
|
11364
|
+
if (ch === '"' && next === '"') {
|
|
11365
|
+
i += 1;
|
|
11366
|
+
continue;
|
|
11367
|
+
}
|
|
11368
|
+
if (ch === '"') inDouble = false;
|
|
11369
|
+
continue;
|
|
11370
|
+
}
|
|
11371
|
+
if (inBacktick) {
|
|
11372
|
+
if (ch === "`" && next === "`") {
|
|
11373
|
+
i += 1;
|
|
11374
|
+
continue;
|
|
11375
|
+
}
|
|
11376
|
+
if (ch === "`") inBacktick = false;
|
|
11377
|
+
continue;
|
|
11378
|
+
}
|
|
11379
|
+
if (inBracket) {
|
|
11380
|
+
if (ch === "]") inBracket = false;
|
|
11381
|
+
continue;
|
|
11382
|
+
}
|
|
11383
|
+
if (ch === "-" && next === "-") {
|
|
11384
|
+
inLineComment = true;
|
|
11385
|
+
i += 1;
|
|
11386
|
+
continue;
|
|
11387
|
+
}
|
|
11388
|
+
if (ch === "/" && next === "*") {
|
|
11389
|
+
inBlockComment = true;
|
|
11390
|
+
i += 1;
|
|
11391
|
+
continue;
|
|
11392
|
+
}
|
|
11393
|
+
if (ch === "'") {
|
|
11394
|
+
inSingle = true;
|
|
11395
|
+
continue;
|
|
11396
|
+
}
|
|
11397
|
+
if (ch === '"') {
|
|
11398
|
+
inDouble = true;
|
|
11399
|
+
continue;
|
|
11400
|
+
}
|
|
11401
|
+
if (ch === "`") {
|
|
11402
|
+
inBacktick = true;
|
|
11403
|
+
continue;
|
|
11404
|
+
}
|
|
11405
|
+
if (ch === "[") {
|
|
11406
|
+
inBracket = true;
|
|
11407
|
+
continue;
|
|
11408
|
+
}
|
|
11409
|
+
if (ch === "(") {
|
|
11410
|
+
depth += 1;
|
|
11411
|
+
continue;
|
|
11412
|
+
}
|
|
11413
|
+
if (ch === ")") {
|
|
11414
|
+
depth = Math.max(0, depth - 1);
|
|
11415
|
+
continue;
|
|
11416
|
+
}
|
|
11417
|
+
if (ch === ";" && depth === 0) {
|
|
11418
|
+
statement += 1;
|
|
11419
|
+
continue;
|
|
11420
|
+
}
|
|
11421
|
+
if (!isIdentChar2(ch) || isIdentChar2(sql[i - 1])) {
|
|
11422
|
+
continue;
|
|
11423
|
+
}
|
|
11424
|
+
const rest = sql.slice(i);
|
|
11425
|
+
if (/^LIMIT\b/i.test(rest)) {
|
|
11426
|
+
hits.push({ kind: "limit", start: i, depth, statement });
|
|
11427
|
+
i += 4;
|
|
11428
|
+
continue;
|
|
11429
|
+
}
|
|
11430
|
+
if (/^OFFSET\b/i.test(rest)) {
|
|
11431
|
+
hits.push({ kind: "offset", start: i, depth, statement });
|
|
11432
|
+
i += 5;
|
|
11433
|
+
}
|
|
11434
|
+
}
|
|
11435
|
+
return hits;
|
|
11436
|
+
}
|
|
11437
|
+
function injectLimitBeforeBareOffsets(sql) {
|
|
11438
|
+
const hits = collectLimitOffsetKeywords(sql);
|
|
11439
|
+
if (hits.length === 0) return sql;
|
|
11440
|
+
const injectAt = [];
|
|
11441
|
+
for (const hit of hits) {
|
|
11442
|
+
if (hit.kind !== "offset") continue;
|
|
11443
|
+
let hasLimit = false;
|
|
11444
|
+
for (let i = hits.length - 1; i >= 0; i -= 1) {
|
|
11445
|
+
const prev = hits[i];
|
|
11446
|
+
if (prev.start >= hit.start) continue;
|
|
11447
|
+
if (prev.statement !== hit.statement) continue;
|
|
11448
|
+
if (prev.depth !== hit.depth) continue;
|
|
11449
|
+
if (prev.kind === "limit") {
|
|
11450
|
+
hasLimit = true;
|
|
11451
|
+
break;
|
|
11452
|
+
}
|
|
11453
|
+
if (prev.kind === "offset") {
|
|
11454
|
+
break;
|
|
11455
|
+
}
|
|
11456
|
+
}
|
|
11457
|
+
if (!hasLimit) {
|
|
11458
|
+
injectAt.push(hit.start);
|
|
11459
|
+
}
|
|
11460
|
+
}
|
|
11461
|
+
if (injectAt.length === 0) return sql;
|
|
11462
|
+
let out = sql;
|
|
11463
|
+
for (let i = injectAt.length - 1; i >= 0; i -= 1) {
|
|
11464
|
+
const at = injectAt[i];
|
|
11465
|
+
out = `${out.slice(0, at)}LIMIT -1 ${out.slice(at)}`;
|
|
11466
|
+
}
|
|
11467
|
+
return out;
|
|
11468
|
+
}
|
|
11469
|
+
function rewritePostgresSqlForSqlite(sql) {
|
|
11470
|
+
const castPattern = new RegExp(`::(?:${PG_CAST_TYPES})\\b`, "gi");
|
|
11471
|
+
const withoutCastsAndIlike = mapSqlOutsideLiterals(sql, (chunk) => {
|
|
11472
|
+
let rewritten = chunk.replace(castPattern, "");
|
|
11473
|
+
rewritten = rewritten.replace(/\bILIKE\b/gi, "LIKE");
|
|
11474
|
+
return rewritten;
|
|
11475
|
+
});
|
|
11476
|
+
return injectLimitBeforeBareOffsets(withoutCastsAndIlike);
|
|
11477
|
+
}
|
|
11478
|
+
|
|
11479
|
+
// src/cloudflare/d1/transport.ts
|
|
11480
|
+
function hasPaginationBounds2(payload) {
|
|
11481
|
+
return payload.limit !== void 0 || payload.offset !== void 0 || payload.page_size !== void 0 || payload.current_page !== void 0;
|
|
11482
|
+
}
|
|
11483
|
+
function normalizeSqliteCollation(name) {
|
|
11484
|
+
const raw = String(name ?? "").trim().replace(/^["'`[]|["'`\]]$/g, "");
|
|
11485
|
+
if (!raw) return "BINARY";
|
|
11486
|
+
return raw.toUpperCase();
|
|
11487
|
+
}
|
|
11488
|
+
function findCreateTableColumnListOpen(createSql) {
|
|
11489
|
+
const m = /\bCREATE\s+(?:(?:TEMP|TEMPORARY|VIRTUAL)\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?/i.exec(
|
|
11490
|
+
createSql
|
|
11491
|
+
);
|
|
11492
|
+
if (!m) return -1;
|
|
11493
|
+
let i = m.index + m[0].length;
|
|
11494
|
+
let inSingle = false;
|
|
11495
|
+
let inDouble = false;
|
|
11496
|
+
let inBacktick = false;
|
|
11497
|
+
let inBracket = false;
|
|
11498
|
+
while (i < createSql.length) {
|
|
11499
|
+
const ch = createSql[i];
|
|
11500
|
+
if (inSingle) {
|
|
11501
|
+
if (ch === "'" && createSql[i + 1] === "'") {
|
|
11502
|
+
i += 2;
|
|
11503
|
+
continue;
|
|
11504
|
+
}
|
|
11505
|
+
if (ch === "'") inSingle = false;
|
|
11506
|
+
i++;
|
|
11507
|
+
continue;
|
|
11508
|
+
}
|
|
11509
|
+
if (inDouble) {
|
|
11510
|
+
if (ch === '"') inDouble = false;
|
|
11511
|
+
i++;
|
|
11512
|
+
continue;
|
|
11513
|
+
}
|
|
11514
|
+
if (inBacktick) {
|
|
11515
|
+
if (ch === "`") inBacktick = false;
|
|
11516
|
+
i++;
|
|
11517
|
+
continue;
|
|
11518
|
+
}
|
|
11519
|
+
if (inBracket) {
|
|
11520
|
+
if (ch === "]") inBracket = false;
|
|
11521
|
+
i++;
|
|
11522
|
+
continue;
|
|
11523
|
+
}
|
|
11524
|
+
if (ch === "'") {
|
|
11525
|
+
inSingle = true;
|
|
11526
|
+
i++;
|
|
11527
|
+
continue;
|
|
11528
|
+
}
|
|
11529
|
+
if (ch === '"') {
|
|
11530
|
+
inDouble = true;
|
|
11531
|
+
i++;
|
|
11532
|
+
continue;
|
|
11533
|
+
}
|
|
11534
|
+
if (ch === "`") {
|
|
11535
|
+
inBacktick = true;
|
|
11536
|
+
i++;
|
|
11537
|
+
continue;
|
|
11538
|
+
}
|
|
11539
|
+
if (ch === "[") {
|
|
11540
|
+
inBracket = true;
|
|
11541
|
+
i++;
|
|
11542
|
+
continue;
|
|
11543
|
+
}
|
|
11544
|
+
if (ch === "(") return i;
|
|
11545
|
+
i++;
|
|
11546
|
+
}
|
|
11547
|
+
return -1;
|
|
11548
|
+
}
|
|
11549
|
+
function parseColumnCollationFromCreateSql(createSql, columnName) {
|
|
11550
|
+
if (!createSql || !columnName) return null;
|
|
11551
|
+
const listOpen = findCreateTableColumnListOpen(createSql);
|
|
11552
|
+
if (listOpen < 0) return null;
|
|
11553
|
+
const listStart = listOpen + 1;
|
|
11554
|
+
const escaped = columnName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
11555
|
+
const nameRe = new RegExp(
|
|
11556
|
+
`(?:^|[^\\w])(?:"${escaped}"|\`${escaped}\`|\\[${escaped}\\]|${escaped})\\s+`,
|
|
11557
|
+
"i"
|
|
11558
|
+
);
|
|
11559
|
+
const listSlice = createSql.slice(listStart);
|
|
11560
|
+
let nameMatchAbs = -1;
|
|
11561
|
+
let nameMatchLen = 0;
|
|
11562
|
+
{
|
|
11563
|
+
let i2 = 0;
|
|
11564
|
+
let depth2 = 1;
|
|
11565
|
+
let inSingle2 = false;
|
|
11566
|
+
let inDouble2 = false;
|
|
11567
|
+
let inBacktick2 = false;
|
|
11568
|
+
let inBracket2 = false;
|
|
11569
|
+
let segmentStart = 0;
|
|
11570
|
+
const trySegment = (from, to) => {
|
|
11571
|
+
if (nameMatchAbs >= 0) return;
|
|
11572
|
+
const segment = listSlice.slice(from, to);
|
|
11573
|
+
const m = nameRe.exec(segment);
|
|
11574
|
+
if (!m) return;
|
|
11575
|
+
const leading = segment.slice(0, m.index).trim();
|
|
11576
|
+
if (leading.length > 0) return;
|
|
11577
|
+
nameMatchAbs = listStart + from + m.index;
|
|
11578
|
+
nameMatchLen = m[0].length;
|
|
11579
|
+
};
|
|
11580
|
+
while (i2 < listSlice.length && depth2 > 0) {
|
|
11581
|
+
const ch = listSlice[i2];
|
|
11582
|
+
if (inSingle2) {
|
|
11583
|
+
if (ch === "'" && listSlice[i2 + 1] === "'") {
|
|
11584
|
+
i2 += 2;
|
|
11585
|
+
continue;
|
|
11586
|
+
}
|
|
11587
|
+
if (ch === "'") inSingle2 = false;
|
|
11588
|
+
i2++;
|
|
11589
|
+
continue;
|
|
11590
|
+
}
|
|
11591
|
+
if (inDouble2) {
|
|
11592
|
+
if (ch === '"') inDouble2 = false;
|
|
11593
|
+
i2++;
|
|
11594
|
+
continue;
|
|
11595
|
+
}
|
|
11596
|
+
if (inBacktick2) {
|
|
11597
|
+
if (ch === "`") inBacktick2 = false;
|
|
11598
|
+
i2++;
|
|
11599
|
+
continue;
|
|
11600
|
+
}
|
|
11601
|
+
if (inBracket2) {
|
|
11602
|
+
if (ch === "]") inBracket2 = false;
|
|
11603
|
+
i2++;
|
|
11604
|
+
continue;
|
|
11605
|
+
}
|
|
11606
|
+
if (ch === "'") {
|
|
11607
|
+
inSingle2 = true;
|
|
11608
|
+
i2++;
|
|
11609
|
+
continue;
|
|
11610
|
+
}
|
|
11611
|
+
if (ch === '"') {
|
|
11612
|
+
inDouble2 = true;
|
|
11613
|
+
i2++;
|
|
11614
|
+
continue;
|
|
11615
|
+
}
|
|
11616
|
+
if (ch === "`") {
|
|
11617
|
+
inBacktick2 = true;
|
|
11618
|
+
i2++;
|
|
11619
|
+
continue;
|
|
11620
|
+
}
|
|
11621
|
+
if (ch === "[") {
|
|
11622
|
+
inBracket2 = true;
|
|
11623
|
+
i2++;
|
|
11624
|
+
continue;
|
|
11625
|
+
}
|
|
11626
|
+
if (ch === "(") {
|
|
11627
|
+
depth2++;
|
|
11628
|
+
i2++;
|
|
11629
|
+
continue;
|
|
11630
|
+
}
|
|
11631
|
+
if (ch === ")") {
|
|
11632
|
+
depth2--;
|
|
11633
|
+
if (depth2 === 0) {
|
|
11634
|
+
trySegment(segmentStart, i2);
|
|
11635
|
+
break;
|
|
11636
|
+
}
|
|
11637
|
+
i2++;
|
|
11638
|
+
continue;
|
|
11639
|
+
}
|
|
11640
|
+
if (ch === "," && depth2 === 1) {
|
|
11641
|
+
trySegment(segmentStart, i2);
|
|
11642
|
+
segmentStart = i2 + 1;
|
|
11643
|
+
i2++;
|
|
11644
|
+
continue;
|
|
11645
|
+
}
|
|
11646
|
+
i2++;
|
|
11647
|
+
}
|
|
11648
|
+
}
|
|
11649
|
+
if (nameMatchAbs < 0 || nameMatchLen <= 0) return null;
|
|
11650
|
+
const start = nameMatchAbs + nameMatchLen;
|
|
11651
|
+
let i = start;
|
|
11652
|
+
let depth = 0;
|
|
11653
|
+
let inSingle = false;
|
|
11654
|
+
let inDouble = false;
|
|
11655
|
+
let inBacktick = false;
|
|
11656
|
+
let inBracket = false;
|
|
11657
|
+
while (i < createSql.length) {
|
|
11658
|
+
const ch = createSql[i];
|
|
11659
|
+
if (inSingle) {
|
|
11660
|
+
if (ch === "'" && createSql[i + 1] === "'") {
|
|
11661
|
+
i += 2;
|
|
11662
|
+
continue;
|
|
11663
|
+
}
|
|
11664
|
+
if (ch === "'") inSingle = false;
|
|
11665
|
+
i++;
|
|
11666
|
+
continue;
|
|
11667
|
+
}
|
|
11668
|
+
if (inDouble) {
|
|
11669
|
+
if (ch === '"') inDouble = false;
|
|
11670
|
+
i++;
|
|
11671
|
+
continue;
|
|
11672
|
+
}
|
|
11673
|
+
if (inBacktick) {
|
|
11674
|
+
if (ch === "`") inBacktick = false;
|
|
11675
|
+
i++;
|
|
11676
|
+
continue;
|
|
11677
|
+
}
|
|
11678
|
+
if (inBracket) {
|
|
11679
|
+
if (ch === "]") inBracket = false;
|
|
11680
|
+
i++;
|
|
11681
|
+
continue;
|
|
11682
|
+
}
|
|
11683
|
+
if (ch === "'") {
|
|
11684
|
+
inSingle = true;
|
|
11685
|
+
i++;
|
|
11686
|
+
continue;
|
|
11687
|
+
}
|
|
11688
|
+
if (ch === '"') {
|
|
11689
|
+
inDouble = true;
|
|
11690
|
+
i++;
|
|
11691
|
+
continue;
|
|
11692
|
+
}
|
|
11693
|
+
if (ch === "`") {
|
|
11694
|
+
inBacktick = true;
|
|
11695
|
+
i++;
|
|
11696
|
+
continue;
|
|
11697
|
+
}
|
|
11698
|
+
if (ch === "[") {
|
|
11699
|
+
inBracket = true;
|
|
11700
|
+
i++;
|
|
11701
|
+
continue;
|
|
11702
|
+
}
|
|
11703
|
+
if (ch === "(") {
|
|
11704
|
+
depth++;
|
|
11705
|
+
i++;
|
|
11706
|
+
continue;
|
|
11707
|
+
}
|
|
11708
|
+
if (ch === ")") {
|
|
11709
|
+
if (depth === 0) {
|
|
11710
|
+
break;
|
|
11711
|
+
}
|
|
11712
|
+
depth--;
|
|
11713
|
+
i++;
|
|
11714
|
+
continue;
|
|
11715
|
+
}
|
|
11716
|
+
if (ch === "," && depth === 0) {
|
|
11717
|
+
break;
|
|
11718
|
+
}
|
|
11719
|
+
i++;
|
|
11720
|
+
}
|
|
11721
|
+
const colDef = createSql.slice(start, i);
|
|
11722
|
+
const collRe = /\bCOLLATE\s+("([^"]+)"|'([^']+)'|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][\w$]*))/i;
|
|
11723
|
+
const match = collRe.exec(colDef);
|
|
11724
|
+
if (!match) return null;
|
|
11725
|
+
return match[2] ?? match[3] ?? match[4] ?? match[5] ?? match[6] ?? match[1] ?? null;
|
|
11726
|
+
}
|
|
11727
|
+
async function indexCollationMatchesColumn(d1, table2, tableSafe, indexSafe, columnName, session) {
|
|
11728
|
+
const xinfo = await executeD1Query(d1, {
|
|
11729
|
+
query: `PRAGMA index_xinfo("${indexSafe}")`,
|
|
11730
|
+
params: [],
|
|
11731
|
+
...session
|
|
11732
|
+
});
|
|
11733
|
+
if (!xinfo.ok) {
|
|
11734
|
+
return false;
|
|
11735
|
+
}
|
|
11736
|
+
const xRows = xinfo.rows ?? [];
|
|
11737
|
+
const keyRows = xRows.filter((row) => {
|
|
11738
|
+
const isKey = row.key === 1 || row.key === true || Number(row.key) === 1;
|
|
11739
|
+
if (!isKey) return false;
|
|
11740
|
+
return typeof row.name === "string" && row.name === columnName;
|
|
11741
|
+
});
|
|
11742
|
+
if (keyRows.length === 0) {
|
|
11743
|
+
const byName = xRows.find(
|
|
11744
|
+
(row) => typeof row.name === "string" && row.name === columnName
|
|
11745
|
+
);
|
|
11746
|
+
if (!byName) return false;
|
|
11747
|
+
keyRows.push(byName);
|
|
11748
|
+
}
|
|
11749
|
+
const indexColl = normalizeSqliteCollation(keyRows[0]?.coll);
|
|
11750
|
+
const master = await executeD1Query(d1, {
|
|
11751
|
+
query: `SELECT sql AS create_sql FROM sqlite_master WHERE type = 'table' AND name = ?`,
|
|
11752
|
+
params: [table2],
|
|
11753
|
+
...session
|
|
11754
|
+
});
|
|
11755
|
+
let createSql = "";
|
|
11756
|
+
if (master.ok && Array.isArray(master.rows) && master.rows.length > 0) {
|
|
11757
|
+
createSql = String(
|
|
11758
|
+
master.rows[0]?.create_sql ?? ""
|
|
11759
|
+
);
|
|
11760
|
+
}
|
|
11761
|
+
const columnCollRaw = parseColumnCollationFromCreateSql(createSql, columnName);
|
|
11762
|
+
const columnColl = normalizeSqliteCollation(columnCollRaw);
|
|
11763
|
+
return indexColl === columnColl;
|
|
11764
|
+
}
|
|
11765
|
+
async function resolveD1BoundedIdentityColumn(d1, tableName, session) {
|
|
11766
|
+
const table2 = tableName.trim();
|
|
11767
|
+
if (!table2) {
|
|
11768
|
+
throw new D1SqlCompileError("missing_table", "table_name is required for bounded mutation");
|
|
11769
|
+
}
|
|
11770
|
+
const safe = table2.replace(/"/g, '""');
|
|
11771
|
+
const info = await executeD1Query(d1, {
|
|
11772
|
+
query: `PRAGMA table_info("${safe}")`,
|
|
11773
|
+
params: [],
|
|
11774
|
+
...session
|
|
11775
|
+
});
|
|
11776
|
+
if (!info.ok) {
|
|
11777
|
+
throw new D1SqlCompileError(
|
|
11778
|
+
"bounded_mutation_no_unique_identity",
|
|
11779
|
+
`Unable to introspect table "${table2}" for bounded mutation identity: ${info.message}`
|
|
11780
|
+
);
|
|
11781
|
+
}
|
|
11782
|
+
const cols = info.rows.filter(
|
|
11783
|
+
(row) => typeof row?.name === "string" && row.name.length > 0
|
|
11784
|
+
);
|
|
11785
|
+
const colByName = new Map(cols.map((col) => [col.name, col]));
|
|
11786
|
+
const isNotNullColumn = (name) => {
|
|
11787
|
+
const col = colByName.get(name);
|
|
11788
|
+
if (!col) return false;
|
|
11789
|
+
return col.notnull === 1 || col.notnull === true || Number(col.notnull) === 1;
|
|
11790
|
+
};
|
|
11791
|
+
const isIntegerPrimaryKeyType = (col) => {
|
|
11792
|
+
if (typeof col.pk !== "number" || col.pk <= 0) return false;
|
|
11793
|
+
const declared = String(col.type ?? "").trim().toUpperCase();
|
|
11794
|
+
return declared === "INTEGER";
|
|
11795
|
+
};
|
|
11796
|
+
const loadIndexList = async () => {
|
|
11797
|
+
const indexList = await executeD1Query(d1, {
|
|
11798
|
+
query: `PRAGMA index_list("${safe}")`,
|
|
11799
|
+
params: [],
|
|
11800
|
+
...session
|
|
11801
|
+
});
|
|
11802
|
+
if (!indexList.ok) return null;
|
|
11803
|
+
return indexList.rows;
|
|
11804
|
+
};
|
|
11805
|
+
const isDescendingIntegerPrimaryKeyException = async (colName, indexes) => {
|
|
11806
|
+
if (indexes) {
|
|
11807
|
+
const hasPkOrigin = indexes.some(
|
|
11808
|
+
(index) => String(index.origin ?? "").toLowerCase() === "pk"
|
|
11809
|
+
);
|
|
11810
|
+
if (hasPkOrigin) return true;
|
|
11811
|
+
const originReported = indexes.some(
|
|
11812
|
+
(index) => index.origin !== void 0 && index.origin !== null && String(index.origin).length > 0
|
|
11813
|
+
);
|
|
11814
|
+
if (indexes.length === 0 || originReported) {
|
|
11815
|
+
return false;
|
|
11816
|
+
}
|
|
11817
|
+
}
|
|
11818
|
+
const master = await executeD1Query(d1, {
|
|
11819
|
+
query: `SELECT sql AS create_sql FROM sqlite_master WHERE type = 'table' AND name = ?`,
|
|
11820
|
+
params: [table2],
|
|
11821
|
+
...session
|
|
11822
|
+
});
|
|
11823
|
+
if (!master.ok || !Array.isArray(master.rows) || master.rows.length === 0) {
|
|
11824
|
+
return false;
|
|
11825
|
+
}
|
|
11826
|
+
const createSql = String(
|
|
11827
|
+
master.rows[0]?.create_sql ?? ""
|
|
11828
|
+
);
|
|
11829
|
+
if (!createSql) return false;
|
|
11830
|
+
const escaped = colName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
11831
|
+
const inlineDesc = new RegExp(
|
|
11832
|
+
`(?:^|[^\\w])(?:"${escaped}"|${escaped})\\s+INTEGER\\s+PRIMARY\\s+KEY\\s+DESC\\b`,
|
|
11833
|
+
"i"
|
|
11834
|
+
);
|
|
11835
|
+
const tableDesc = new RegExp(
|
|
11836
|
+
`PRIMARY\\s+KEY\\s*\\(\\s*(?:"${escaped}"|${escaped})\\s+DESC\\b`,
|
|
11837
|
+
"i"
|
|
11838
|
+
);
|
|
11839
|
+
return inlineDesc.test(createSql) || tableDesc.test(createSql);
|
|
11840
|
+
};
|
|
11841
|
+
const pkCols = cols.filter((row) => typeof row.pk === "number" && row.pk > 0).sort((a, b) => (a.pk ?? 0) - (b.pk ?? 0));
|
|
11842
|
+
let indexRows;
|
|
11843
|
+
if (pkCols.length === 1 && pkCols[0]?.name) {
|
|
11844
|
+
if (isIntegerPrimaryKeyType(pkCols[0])) {
|
|
11845
|
+
indexRows = await loadIndexList();
|
|
11846
|
+
const isDescException = await isDescendingIntegerPrimaryKeyException(
|
|
11847
|
+
pkCols[0].name,
|
|
11848
|
+
indexRows
|
|
11849
|
+
);
|
|
11850
|
+
if (!isDescException) {
|
|
11851
|
+
return pkCols[0].name;
|
|
11852
|
+
}
|
|
11853
|
+
} else if (isNotNullColumn(pkCols[0].name)) {
|
|
11854
|
+
indexRows = await loadIndexList();
|
|
11855
|
+
const pkIndex = (indexRows ?? []).find(
|
|
11856
|
+
(index) => String(index.origin ?? "").toLowerCase() === "pk"
|
|
11857
|
+
);
|
|
11858
|
+
if (pkIndex && typeof pkIndex.name === "string" && pkIndex.name) {
|
|
11859
|
+
const indexSafe = pkIndex.name.replace(/"/g, '""');
|
|
11860
|
+
const collMatch = await indexCollationMatchesColumn(
|
|
11861
|
+
d1,
|
|
11862
|
+
table2,
|
|
11863
|
+
safe,
|
|
11864
|
+
indexSafe,
|
|
11865
|
+
pkCols[0].name,
|
|
11866
|
+
session
|
|
11867
|
+
);
|
|
11868
|
+
if (collMatch) {
|
|
11869
|
+
return pkCols[0].name;
|
|
11870
|
+
}
|
|
11871
|
+
}
|
|
11872
|
+
}
|
|
11873
|
+
}
|
|
11874
|
+
if (indexRows === void 0) {
|
|
11875
|
+
indexRows = await loadIndexList();
|
|
11876
|
+
}
|
|
11877
|
+
if (indexRows) {
|
|
11878
|
+
for (const index of indexRows) {
|
|
11879
|
+
const unique = index.unique === 1 || index.unique === true || Number(index.unique) === 1;
|
|
11880
|
+
if (!unique || typeof index.name !== "string" || !index.name) continue;
|
|
11881
|
+
const isPartial = index.partial === 1 || index.partial === true || Number(index.partial) === 1;
|
|
11882
|
+
if (isPartial) {
|
|
11883
|
+
continue;
|
|
11884
|
+
}
|
|
11885
|
+
const indexSafe = index.name.replace(/"/g, '""');
|
|
11886
|
+
const indexInfo = await executeD1Query(d1, {
|
|
11887
|
+
query: `PRAGMA index_info("${indexSafe}")`,
|
|
11888
|
+
params: [],
|
|
11889
|
+
...session
|
|
11890
|
+
});
|
|
11891
|
+
if (!indexInfo.ok) continue;
|
|
11892
|
+
const rawIndexCols = indexInfo.rows ?? [];
|
|
11893
|
+
const hasExpressionTerm = rawIndexCols.some((row) => {
|
|
11894
|
+
const nameOk = typeof row?.name === "string" && row.name.length > 0;
|
|
11895
|
+
if (!nameOk) return true;
|
|
11896
|
+
if (typeof row.cid === "number" && row.cid < 0) return true;
|
|
11897
|
+
return false;
|
|
11898
|
+
});
|
|
11899
|
+
if (hasExpressionTerm || rawIndexCols.length === 0) {
|
|
11900
|
+
continue;
|
|
11901
|
+
}
|
|
11902
|
+
const indexCols = rawIndexCols.filter(
|
|
11903
|
+
(row) => typeof row?.name === "string" && row.name.length > 0
|
|
11904
|
+
);
|
|
11905
|
+
if (indexCols.length === 1 && indexCols[0]?.name) {
|
|
11906
|
+
const identity = indexCols[0].name;
|
|
11907
|
+
if (!isNotNullColumn(identity)) {
|
|
11908
|
+
continue;
|
|
11909
|
+
}
|
|
11910
|
+
const collMatch = await indexCollationMatchesColumn(
|
|
11911
|
+
d1,
|
|
11912
|
+
table2,
|
|
11913
|
+
safe,
|
|
11914
|
+
indexSafe,
|
|
11915
|
+
identity,
|
|
11916
|
+
session
|
|
11917
|
+
);
|
|
11918
|
+
if (!collMatch) {
|
|
11919
|
+
continue;
|
|
11920
|
+
}
|
|
11921
|
+
return identity;
|
|
11922
|
+
}
|
|
11923
|
+
}
|
|
11924
|
+
}
|
|
11925
|
+
throw new D1SqlCompileError(
|
|
11926
|
+
"bounded_mutation_no_unique_identity",
|
|
11927
|
+
`Bounded update/delete on "${table2}" requires a proven single-column PRIMARY KEY or UNIQUE index`
|
|
11928
|
+
);
|
|
11929
|
+
}
|
|
11930
|
+
async function compileOptionsForBoundedMutation(d1, payload, session) {
|
|
11931
|
+
if (!hasPaginationBounds2(payload) && !payload.sort_by) {
|
|
11932
|
+
return void 0;
|
|
11933
|
+
}
|
|
11934
|
+
if (!hasPaginationBounds2(payload)) {
|
|
11935
|
+
return void 0;
|
|
11936
|
+
}
|
|
11937
|
+
const identityColumn = await resolveD1BoundedIdentityColumn(
|
|
11938
|
+
d1,
|
|
11939
|
+
payload.table_name ?? "",
|
|
11940
|
+
session
|
|
11941
|
+
);
|
|
11942
|
+
return { identityColumn };
|
|
11943
|
+
}
|
|
11944
|
+
function headerValue2(options, name) {
|
|
11945
|
+
const headers = options?.headers;
|
|
11946
|
+
if (!headers) return void 0;
|
|
11947
|
+
const lower = name.toLowerCase();
|
|
11948
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
11949
|
+
if (key.toLowerCase() === lower && value?.trim()) {
|
|
11950
|
+
return value.trim();
|
|
11951
|
+
}
|
|
11952
|
+
}
|
|
11953
|
+
return void 0;
|
|
11954
|
+
}
|
|
11955
|
+
function sessionFromOptions(options, defaults) {
|
|
11956
|
+
return {
|
|
11957
|
+
bookmark: headerValue2(options, "x-athena-d1-bookmark") ?? null,
|
|
11958
|
+
sessionMode: headerValue2(options, "x-athena-d1-session-mode") ?? defaults.defaultSessionMode ?? null
|
|
11959
|
+
};
|
|
11960
|
+
}
|
|
11961
|
+
function resolveStripNulls(payloadStrip, callOptions, defaultValue = true) {
|
|
11962
|
+
if (typeof payloadStrip === "boolean") return payloadStrip;
|
|
11963
|
+
if (typeof callOptions?.stripNulls === "boolean") return callOptions.stripNulls;
|
|
11964
|
+
return defaultValue;
|
|
11965
|
+
}
|
|
11966
|
+
function stripNullPropertiesFromRows(rows) {
|
|
11967
|
+
return rows.map((row) => {
|
|
11968
|
+
if (row == null || typeof row !== "object" || Array.isArray(row)) {
|
|
11969
|
+
return row;
|
|
11970
|
+
}
|
|
11971
|
+
const out = {};
|
|
11972
|
+
for (const [key, value] of Object.entries(row)) {
|
|
11973
|
+
if (value !== null) {
|
|
11974
|
+
out[key] = value;
|
|
11975
|
+
}
|
|
11976
|
+
}
|
|
11977
|
+
return out;
|
|
11978
|
+
});
|
|
11979
|
+
}
|
|
11980
|
+
function maybeStripNullRows(rows, strip) {
|
|
11981
|
+
return strip ? stripNullPropertiesFromRows(rows) : rows;
|
|
11982
|
+
}
|
|
11983
|
+
function successResponse(data, count, raw, bookmark) {
|
|
11984
|
+
const response = {
|
|
11985
|
+
ok: true,
|
|
11986
|
+
status: 200,
|
|
11987
|
+
statusText: "OK",
|
|
11988
|
+
data,
|
|
11989
|
+
count: count ?? null,
|
|
11990
|
+
error: void 0,
|
|
11991
|
+
errorDetails: null,
|
|
11992
|
+
raw
|
|
11993
|
+
};
|
|
11994
|
+
if (bookmark) {
|
|
11995
|
+
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
|
11996
|
+
const rawRecord = raw;
|
|
11997
|
+
rawRecord.bookmark = bookmark;
|
|
11998
|
+
}
|
|
11999
|
+
}
|
|
12000
|
+
return response;
|
|
12001
|
+
}
|
|
12002
|
+
function errorResponse(status, code, message, endpoint, method, hint) {
|
|
12003
|
+
const error = new AthenaGatewayError({
|
|
12004
|
+
code,
|
|
12005
|
+
message,
|
|
12006
|
+
status,
|
|
12007
|
+
endpoint,
|
|
12008
|
+
method,
|
|
12009
|
+
hint
|
|
12010
|
+
});
|
|
12011
|
+
return {
|
|
12012
|
+
ok: false,
|
|
12013
|
+
status,
|
|
12014
|
+
statusText: null,
|
|
12015
|
+
data: null,
|
|
12016
|
+
error: error.message,
|
|
12017
|
+
errorDetails: error.toDetails(),
|
|
12018
|
+
raw: { error: message, code }
|
|
12019
|
+
};
|
|
12020
|
+
}
|
|
12021
|
+
function compileErrorResponse(error, endpoint, method) {
|
|
12022
|
+
if (error instanceof D1SqlCompileError) {
|
|
12023
|
+
return errorResponse(
|
|
12024
|
+
400,
|
|
12025
|
+
"HTTP_ERROR",
|
|
12026
|
+
error.message,
|
|
12027
|
+
endpoint,
|
|
12028
|
+
method,
|
|
12029
|
+
`D1 SQL compile failed (${error.code})`
|
|
12030
|
+
);
|
|
12031
|
+
}
|
|
12032
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
12033
|
+
return errorResponse(500, "UNKNOWN_ERROR", message, endpoint, method);
|
|
12034
|
+
}
|
|
12035
|
+
function createCloudflareD1GatewayTransport(options) {
|
|
12036
|
+
const { d1 } = options;
|
|
12037
|
+
async function runCompiled(compiled, callOptions, endpoint, method, mapResult, stripNulls = true) {
|
|
12038
|
+
try {
|
|
12039
|
+
const session = sessionFromOptions(callOptions, options);
|
|
12040
|
+
if (compiled.statements && compiled.statements.length > 1) {
|
|
12041
|
+
const batch = await executeD1Batch(d1, {
|
|
12042
|
+
statements: compiled.statements.map((statement) => ({
|
|
12043
|
+
query: statement.sql,
|
|
12044
|
+
params: statement.params
|
|
12045
|
+
})),
|
|
12046
|
+
...session
|
|
12047
|
+
});
|
|
12048
|
+
if (!batch.ok) {
|
|
12049
|
+
return errorResponse(400, "HTTP_ERROR", batch.message, endpoint, method);
|
|
12050
|
+
}
|
|
12051
|
+
const rows2 = maybeStripNullRows(
|
|
12052
|
+
batch.results.flatMap(
|
|
12053
|
+
(item) => Array.isArray(item.results) ? item.results : []
|
|
12054
|
+
),
|
|
12055
|
+
stripNulls
|
|
12056
|
+
);
|
|
12057
|
+
const changes = batch.results.reduce((sum2, item) => {
|
|
12058
|
+
const meta = item?.meta;
|
|
12059
|
+
const n = meta && typeof meta === "object" && typeof meta.changes === "number" ? meta.changes : 0;
|
|
12060
|
+
return sum2 + n;
|
|
12061
|
+
}, 0);
|
|
12062
|
+
const count = rows2.length > 0 ? rows2.length : changes;
|
|
12063
|
+
const mapped2 = mapResult?.(rows2, count) ?? {
|
|
12064
|
+
data: rows2,
|
|
12065
|
+
count
|
|
12066
|
+
};
|
|
12067
|
+
return successResponse(mapped2.data, mapped2.count, batch, batch.bookmark);
|
|
12068
|
+
}
|
|
12069
|
+
const result = await executeD1Query(d1, {
|
|
12070
|
+
query: compiled.sql,
|
|
12071
|
+
params: compiled.params,
|
|
12072
|
+
...session
|
|
12073
|
+
});
|
|
12074
|
+
if (!result.ok) {
|
|
12075
|
+
return errorResponse(400, "HTTP_ERROR", result.message, endpoint, method);
|
|
12076
|
+
}
|
|
12077
|
+
const rows = maybeStripNullRows(result.rows, stripNulls);
|
|
12078
|
+
const mapped = mapResult?.(rows, result.count) ?? {
|
|
12079
|
+
data: rows,
|
|
12080
|
+
count: result.count
|
|
12081
|
+
};
|
|
12082
|
+
return successResponse(mapped.data, mapped.count, result, result.bookmark);
|
|
12083
|
+
} catch (error) {
|
|
12084
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
12085
|
+
return errorResponse(500, "UNKNOWN_ERROR", message, endpoint, method);
|
|
12086
|
+
}
|
|
12087
|
+
}
|
|
12088
|
+
return {
|
|
12089
|
+
baseUrl: CLOUDFLARE_EDGE_BASE_URL,
|
|
12090
|
+
buildHeaders(callOptions) {
|
|
12091
|
+
return { ...callOptions?.headers ?? {} };
|
|
12092
|
+
},
|
|
12093
|
+
async resolveCallOptions(callOptions) {
|
|
12094
|
+
return callOptions;
|
|
12095
|
+
},
|
|
12096
|
+
async verifyConnection(connectionOptions) {
|
|
12097
|
+
const baseUrl = CLOUDFLARE_EDGE_BASE_URL;
|
|
12098
|
+
try {
|
|
12099
|
+
const result = await executeD1Query(d1, { query: "SELECT 1 AS ok" });
|
|
12100
|
+
if (!result.ok) {
|
|
12101
|
+
return {
|
|
12102
|
+
ok: false,
|
|
12103
|
+
reachable: false,
|
|
12104
|
+
status: 500,
|
|
12105
|
+
statusText: null,
|
|
12106
|
+
baseUrl,
|
|
12107
|
+
url: `${baseUrl}/d1`,
|
|
12108
|
+
error: result.message,
|
|
12109
|
+
errorDetails: null,
|
|
12110
|
+
raw: result
|
|
12111
|
+
};
|
|
12112
|
+
}
|
|
12113
|
+
return {
|
|
12114
|
+
ok: true,
|
|
12115
|
+
reachable: true,
|
|
12116
|
+
status: 200,
|
|
12117
|
+
statusText: "OK",
|
|
12118
|
+
baseUrl,
|
|
12119
|
+
url: `${baseUrl}/d1`,
|
|
12120
|
+
error: void 0,
|
|
12121
|
+
errorDetails: null,
|
|
12122
|
+
raw: result
|
|
12123
|
+
};
|
|
12124
|
+
} catch (error) {
|
|
12125
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
12126
|
+
return {
|
|
12127
|
+
ok: false,
|
|
12128
|
+
reachable: false,
|
|
12129
|
+
status: 0,
|
|
12130
|
+
statusText: null,
|
|
12131
|
+
baseUrl,
|
|
12132
|
+
url: `${baseUrl}/d1`,
|
|
12133
|
+
error: message,
|
|
12134
|
+
errorDetails: null,
|
|
12135
|
+
raw: null
|
|
12136
|
+
};
|
|
12137
|
+
}
|
|
12138
|
+
},
|
|
12139
|
+
async fetchGateway(payload, callOptions) {
|
|
12140
|
+
try {
|
|
12141
|
+
if (payload && typeof payload === "object" && "operation" in payload) {
|
|
12142
|
+
return errorResponse(
|
|
12143
|
+
400,
|
|
12144
|
+
"HTTP_ERROR",
|
|
12145
|
+
"Direct AST operation payloads are unsupported on D1 edge-local",
|
|
12146
|
+
"/gateway/fetch",
|
|
12147
|
+
"POST"
|
|
12148
|
+
);
|
|
12149
|
+
}
|
|
12150
|
+
const compiled = compileD1Fetch(payload);
|
|
12151
|
+
const stripNulls = resolveStripNulls(payload.strip_nulls, callOptions, true);
|
|
12152
|
+
if (payload.head === true) {
|
|
12153
|
+
return runCompiled(
|
|
12154
|
+
compiled,
|
|
12155
|
+
callOptions,
|
|
12156
|
+
"/gateway/fetch",
|
|
12157
|
+
"POST",
|
|
12158
|
+
(rows) => ({ data: [], count: extractAthenaCount(rows) }),
|
|
12159
|
+
// COUNT rows are meta, not user-facing object rows
|
|
12160
|
+
false
|
|
12161
|
+
);
|
|
12162
|
+
}
|
|
12163
|
+
const wantsTotalCount = payload.count === "exact" || payload.count === "planned" || payload.count === "estimated";
|
|
12164
|
+
if (wantsTotalCount) {
|
|
12165
|
+
const session = sessionFromOptions(callOptions, options);
|
|
12166
|
+
const countCompiled = compileD1Count(payload);
|
|
12167
|
+
const batch = await executeD1Batch(d1, {
|
|
12168
|
+
statements: [
|
|
12169
|
+
{
|
|
12170
|
+
query: compiled.sql,
|
|
12171
|
+
params: compiled.params
|
|
12172
|
+
},
|
|
12173
|
+
{
|
|
12174
|
+
query: countCompiled.sql,
|
|
12175
|
+
params: countCompiled.params
|
|
12176
|
+
}
|
|
12177
|
+
],
|
|
12178
|
+
...session
|
|
12179
|
+
});
|
|
12180
|
+
if (!batch.ok) {
|
|
12181
|
+
return errorResponse(400, "HTTP_ERROR", batch.message, "/gateway/fetch", "POST");
|
|
12182
|
+
}
|
|
12183
|
+
const dataItem = batch.results[0];
|
|
12184
|
+
const countItem = batch.results[1];
|
|
12185
|
+
if (!dataItem || dataItem.success === false) {
|
|
12186
|
+
const message = dataItem && typeof dataItem.error === "string" && dataItem.error.trim() ? dataItem.error : "D1 page query failed";
|
|
12187
|
+
return errorResponse(400, "HTTP_ERROR", message, "/gateway/fetch", "POST");
|
|
12188
|
+
}
|
|
12189
|
+
if (!countItem || countItem.success === false) {
|
|
12190
|
+
const message = countItem && typeof countItem.error === "string" && countItem.error.trim() ? countItem.error : "D1 count query failed";
|
|
12191
|
+
return errorResponse(400, "HTTP_ERROR", message, "/gateway/fetch", "POST");
|
|
12192
|
+
}
|
|
12193
|
+
const dataRows = Array.isArray(dataItem.results) ? dataItem.results : [];
|
|
12194
|
+
const countRows = Array.isArray(countItem.results) ? countItem.results : [];
|
|
12195
|
+
const total = extractAthenaCount(countRows);
|
|
12196
|
+
const rows = maybeStripNullRows(dataRows, stripNulls);
|
|
12197
|
+
return successResponse(
|
|
12198
|
+
rows,
|
|
12199
|
+
total,
|
|
12200
|
+
{ data: dataItem, count: countItem, batch },
|
|
12201
|
+
batch.bookmark
|
|
12202
|
+
);
|
|
12203
|
+
}
|
|
12204
|
+
return runCompiled(compiled, callOptions, "/gateway/fetch", "POST", void 0, stripNulls);
|
|
12205
|
+
} catch (error) {
|
|
12206
|
+
return compileErrorResponse(error, "/gateway/fetch", "POST");
|
|
12207
|
+
}
|
|
12208
|
+
},
|
|
12209
|
+
async insertGateway(payload, callOptions) {
|
|
12210
|
+
try {
|
|
12211
|
+
const compiled = compileD1Insert(payload);
|
|
12212
|
+
const stripNulls = resolveStripNulls(void 0, callOptions, true);
|
|
12213
|
+
return runCompiled(compiled, callOptions, "/gateway/insert", "PUT", void 0, stripNulls);
|
|
12214
|
+
} catch (error) {
|
|
12215
|
+
return compileErrorResponse(error, "/gateway/insert", "PUT");
|
|
12216
|
+
}
|
|
12217
|
+
},
|
|
12218
|
+
async updateGateway(payload, callOptions) {
|
|
12219
|
+
try {
|
|
12220
|
+
const session = sessionFromOptions(callOptions, options);
|
|
12221
|
+
const compileOptions = await compileOptionsForBoundedMutation(d1, payload, session);
|
|
12222
|
+
const compiled = compileD1Update(payload, compileOptions);
|
|
12223
|
+
const stripNulls = resolveStripNulls(payload.strip_nulls, callOptions, true);
|
|
12224
|
+
return runCompiled(compiled, callOptions, "/gateway/update", "POST", void 0, stripNulls);
|
|
12225
|
+
} catch (error) {
|
|
12226
|
+
return compileErrorResponse(error, "/gateway/update", "POST");
|
|
12227
|
+
}
|
|
12228
|
+
},
|
|
12229
|
+
async deleteGateway(payload, callOptions) {
|
|
12230
|
+
try {
|
|
12231
|
+
const session = sessionFromOptions(callOptions, options);
|
|
12232
|
+
const compileOptions = await compileOptionsForBoundedMutation(d1, payload, session);
|
|
12233
|
+
const compiled = compileD1Delete(payload, compileOptions);
|
|
12234
|
+
const stripNulls = resolveStripNulls(void 0, callOptions, true);
|
|
12235
|
+
return runCompiled(compiled, callOptions, "/gateway/delete", "DELETE", void 0, stripNulls);
|
|
12236
|
+
} catch (error) {
|
|
12237
|
+
return compileErrorResponse(error, "/gateway/delete", "DELETE");
|
|
12238
|
+
}
|
|
12239
|
+
},
|
|
12240
|
+
async rpcGateway(payload, callOptions) {
|
|
12241
|
+
return errorResponse(
|
|
12242
|
+
400,
|
|
12243
|
+
"HTTP_ERROR",
|
|
12244
|
+
"RPC is unsupported on D1 edge-local mode",
|
|
12245
|
+
"/gateway/rpc",
|
|
12246
|
+
"POST",
|
|
12247
|
+
"Use flat CRUD or raw query SQL instead"
|
|
12248
|
+
);
|
|
12249
|
+
},
|
|
12250
|
+
async queryGateway(payload, callOptions) {
|
|
12251
|
+
try {
|
|
12252
|
+
const params = payload.params ?? callOptions?.params;
|
|
12253
|
+
const session = sessionFromOptions(callOptions, options);
|
|
12254
|
+
const query = rewritePostgresSqlForSqlite(payload.query);
|
|
12255
|
+
const result = await executeD1Query(d1, {
|
|
12256
|
+
query,
|
|
12257
|
+
params: Array.isArray(params) ? params : [],
|
|
12258
|
+
...session
|
|
12259
|
+
});
|
|
12260
|
+
if (!result.ok) {
|
|
12261
|
+
return errorResponse(400, "HTTP_ERROR", result.message, "/gateway/query", "POST");
|
|
12262
|
+
}
|
|
12263
|
+
const stripNulls = resolveStripNulls(void 0, callOptions, true);
|
|
12264
|
+
const rows = maybeStripNullRows(result.rows, stripNulls);
|
|
12265
|
+
return successResponse(
|
|
12266
|
+
rows,
|
|
12267
|
+
result.count,
|
|
12268
|
+
{ ...result, query },
|
|
12269
|
+
result.bookmark
|
|
12270
|
+
);
|
|
12271
|
+
} catch (error) {
|
|
12272
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
12273
|
+
return errorResponse(500, "UNKNOWN_ERROR", message, "/gateway/query", "POST");
|
|
12274
|
+
}
|
|
12275
|
+
}
|
|
12276
|
+
};
|
|
12277
|
+
}
|
|
12278
|
+
|
|
12279
|
+
// src/config/errors.ts
|
|
12280
|
+
var AthenaConfigurationError = class extends Error {
|
|
12281
|
+
code;
|
|
12282
|
+
service;
|
|
12283
|
+
constructor(code, message, service) {
|
|
12284
|
+
super(message);
|
|
12285
|
+
this.name = "AthenaConfigurationError";
|
|
12286
|
+
this.code = code;
|
|
12287
|
+
this.service = service;
|
|
12288
|
+
}
|
|
12289
|
+
};
|
|
12290
|
+
|
|
12291
|
+
// src/cloudflare/execution-mode.ts
|
|
12292
|
+
var ATHENA_EXECUTION_MODE_ENV_KEY = "ATHENA_EXECUTION_MODE";
|
|
12293
|
+
var ATHENA_EXECUTION_PREFER_ENV_KEY = "ATHENA_EXECUTION_PREFER";
|
|
12294
|
+
var MODE_ALIASES = {
|
|
12295
|
+
gateway: "gateway",
|
|
12296
|
+
server: "gateway",
|
|
12297
|
+
remote: "gateway",
|
|
12298
|
+
http: "gateway",
|
|
12299
|
+
edge: "edge",
|
|
12300
|
+
cloudflare: "edge",
|
|
12301
|
+
"cloudflare-edge": "edge",
|
|
12302
|
+
d1: "edge",
|
|
12303
|
+
local: "edge",
|
|
12304
|
+
auto: "auto"
|
|
12305
|
+
};
|
|
12306
|
+
function normalizeOptional(value) {
|
|
12307
|
+
const trimmed = value?.trim();
|
|
12308
|
+
return trimmed || void 0;
|
|
12309
|
+
}
|
|
12310
|
+
function normalizeModeString(value) {
|
|
12311
|
+
if (value == null) return void 0;
|
|
12312
|
+
const key = value.trim().toLowerCase();
|
|
12313
|
+
if (!key) return void 0;
|
|
12314
|
+
const mapped = MODE_ALIASES[key];
|
|
12315
|
+
if (!mapped) {
|
|
12316
|
+
throw new AthenaConfigurationError(
|
|
12317
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
12318
|
+
`Unknown Athena execution mode "${value}". Use gateway | edge | auto (aliases: server, remote, cloudflare, d1).`,
|
|
12319
|
+
"db"
|
|
12320
|
+
);
|
|
12321
|
+
}
|
|
12322
|
+
return mapped;
|
|
12323
|
+
}
|
|
12324
|
+
function isD1Binding(value) {
|
|
12325
|
+
return Boolean(
|
|
12326
|
+
value && typeof value === "object" && typeof value.prepare === "function"
|
|
12327
|
+
);
|
|
12328
|
+
}
|
|
12329
|
+
var GATEWAY_URL_ENV_KEYS = [
|
|
12330
|
+
"ATHENA_URL",
|
|
12331
|
+
"NEXT_PUBLIC_ATHENA_URL",
|
|
12332
|
+
"ATHENA_DB_URL",
|
|
12333
|
+
"ATHENA_GATEWAY_URL",
|
|
12334
|
+
"NEXT_PUBLIC_ATHENA_DB_API_URL"
|
|
12335
|
+
];
|
|
12336
|
+
function resolveGatewayUrl(url, env) {
|
|
12337
|
+
if (normalizeOptional(url)) {
|
|
12338
|
+
return normalizeOptional(url);
|
|
12339
|
+
}
|
|
12340
|
+
for (const key of GATEWAY_URL_ENV_KEYS) {
|
|
12341
|
+
const value = normalizeOptional(env[key]);
|
|
12342
|
+
if (value) return value;
|
|
12343
|
+
}
|
|
12344
|
+
return void 0;
|
|
12345
|
+
}
|
|
12346
|
+
function resolvePrefer(prefer, env) {
|
|
12347
|
+
const raw = normalizeOptional(typeof prefer === "string" ? prefer : prefer ?? void 0) ?? normalizeOptional(env[ATHENA_EXECUTION_PREFER_ENV_KEY]) ?? "edge";
|
|
12348
|
+
const key = raw.toLowerCase();
|
|
12349
|
+
if (key === "gateway" || key === "server" || key === "remote" || key === "http") {
|
|
12350
|
+
return "gateway";
|
|
12351
|
+
}
|
|
12352
|
+
if (key === "edge" || key === "d1" || key === "cloudflare" || key === "local") {
|
|
12353
|
+
return "edge";
|
|
12354
|
+
}
|
|
12355
|
+
throw new AthenaConfigurationError(
|
|
12356
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
12357
|
+
`Unknown Athena execution prefer "${raw}". Use edge | gateway.`,
|
|
12358
|
+
"db"
|
|
12359
|
+
);
|
|
12360
|
+
}
|
|
12361
|
+
function resolveAthenaExecutionMode(input = {}) {
|
|
12362
|
+
const env = input.env ?? {};
|
|
12363
|
+
const fromEnv = normalizeModeString(env[ATHENA_EXECUTION_MODE_ENV_KEY]);
|
|
12364
|
+
const requested = normalizeModeString(input.mode) ?? fromEnv ?? "auto";
|
|
12365
|
+
const url = resolveGatewayUrl(input.url, env);
|
|
12366
|
+
const hasD1 = isD1Binding(input.d1);
|
|
12367
|
+
const hasGateway = Boolean(url);
|
|
12368
|
+
if (requested === "gateway") {
|
|
12369
|
+
if (!hasGateway) {
|
|
12370
|
+
throw new AthenaConfigurationError(
|
|
12371
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
12372
|
+
'Athena execution mode is "gateway" but no url / ATHENA_URL / ATHENA_DB_URL / ATHENA_GATEWAY_URL was provided.',
|
|
12373
|
+
"db"
|
|
9771
12374
|
);
|
|
9772
12375
|
}
|
|
9773
|
-
|
|
9774
|
-
return createTableBuilder(
|
|
9775
|
-
resolvedTableName,
|
|
9776
|
-
gateway,
|
|
9777
|
-
formatGatewayResult,
|
|
9778
|
-
queryTracer,
|
|
9779
|
-
config.behavior
|
|
9780
|
-
);
|
|
12376
|
+
return "gateway";
|
|
9781
12377
|
}
|
|
9782
|
-
|
|
9783
|
-
|
|
9784
|
-
|
|
9785
|
-
|
|
12378
|
+
if (requested === "edge") {
|
|
12379
|
+
if (!hasD1) {
|
|
12380
|
+
throw new AthenaConfigurationError(
|
|
12381
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
12382
|
+
'Athena execution mode is "edge" but no D1 binding was provided (db.d1 / config.d1 / env.DB).',
|
|
12383
|
+
"db"
|
|
12384
|
+
);
|
|
9786
12385
|
}
|
|
9787
|
-
return
|
|
9788
|
-
|
|
9789
|
-
|
|
9790
|
-
|
|
9791
|
-
|
|
9792
|
-
|
|
9793
|
-
|
|
9794
|
-
|
|
9795
|
-
|
|
12386
|
+
return "edge";
|
|
12387
|
+
}
|
|
12388
|
+
if (hasD1 && hasGateway) {
|
|
12389
|
+
return resolvePrefer(input.prefer, env);
|
|
12390
|
+
}
|
|
12391
|
+
if (hasD1) return "edge";
|
|
12392
|
+
if (hasGateway) return "gateway";
|
|
12393
|
+
throw new AthenaConfigurationError(
|
|
12394
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
12395
|
+
'Cannot resolve Athena execution mode: provide mode "gateway" with url/key, mode "edge" with d1, or mode "auto" with either a D1 binding or a gateway URL (ATHENA_URL / ATHENA_DB_URL / ATHENA_GATEWAY_URL).',
|
|
12396
|
+
"db"
|
|
12397
|
+
);
|
|
12398
|
+
}
|
|
12399
|
+
|
|
12400
|
+
// src/cloudflare/r2/storage.ts
|
|
12401
|
+
function normalizePrefix(prefix) {
|
|
12402
|
+
if (!prefix?.trim()) return "";
|
|
12403
|
+
const normalized = prefix.replace(/^\/+/, "").replace(/\/?$/, "/");
|
|
12404
|
+
if (normalized.includes("\0")) {
|
|
12405
|
+
throw new Error("storage prefix must not contain null bytes");
|
|
12406
|
+
}
|
|
12407
|
+
if (normalized.split("/").some((segment) => segment === "..")) {
|
|
12408
|
+
throw new Error('storage prefix must not contain ".." path segments');
|
|
12409
|
+
}
|
|
12410
|
+
return normalized;
|
|
12411
|
+
}
|
|
12412
|
+
function assertSafeObjectKey(key) {
|
|
12413
|
+
if (typeof key !== "string" || !key.trim()) {
|
|
12414
|
+
throw new Error("Object key is required");
|
|
12415
|
+
}
|
|
12416
|
+
if (key.includes("\0")) {
|
|
12417
|
+
throw new Error("Object key must not contain null bytes");
|
|
12418
|
+
}
|
|
12419
|
+
const cleaned = key.replace(/^\/+/, "");
|
|
12420
|
+
if (!cleaned) {
|
|
12421
|
+
throw new Error("Object key is required");
|
|
12422
|
+
}
|
|
12423
|
+
const segments = cleaned.split("/");
|
|
12424
|
+
if (segments.some((segment) => segment === "..")) {
|
|
12425
|
+
throw new Error('Object key must not contain ".." path segments');
|
|
12426
|
+
}
|
|
12427
|
+
return cleaned;
|
|
12428
|
+
}
|
|
12429
|
+
function joinKey(prefix, key) {
|
|
12430
|
+
return `${prefix}${assertSafeObjectKey(key)}`;
|
|
12431
|
+
}
|
|
12432
|
+
function toLogicalKey(prefix, physicalKey) {
|
|
12433
|
+
if (!prefix) return physicalKey;
|
|
12434
|
+
if (physicalKey.startsWith(prefix)) {
|
|
12435
|
+
return physicalKey.slice(prefix.length);
|
|
12436
|
+
}
|
|
12437
|
+
return physicalKey;
|
|
12438
|
+
}
|
|
12439
|
+
function toPhysicalKey(prefix, key) {
|
|
12440
|
+
return joinKey(prefix, key);
|
|
12441
|
+
}
|
|
12442
|
+
function unsupported(method) {
|
|
12443
|
+
throw new Error(
|
|
12444
|
+
`storage.${method} is not available in Cloudflare edge-local R2 object mode. Only putObject / getObject / deleteObject / listObjects are supported (L3a).`
|
|
12445
|
+
);
|
|
12446
|
+
}
|
|
12447
|
+
function createCloudflareR2StorageModule(options) {
|
|
12448
|
+
const prefix = normalizePrefix(options.prefix);
|
|
12449
|
+
const { r2 } = options;
|
|
12450
|
+
const putObject = async (input) => {
|
|
12451
|
+
const logical = assertSafeObjectKey(input.key);
|
|
12452
|
+
const physical = toPhysicalKey(prefix, logical);
|
|
12453
|
+
await r2.put(physical, input.body, {
|
|
12454
|
+
httpMetadata: input.contentType ? { contentType: input.contentType } : void 0,
|
|
12455
|
+
customMetadata: input.metadata
|
|
12456
|
+
});
|
|
12457
|
+
return { key: logical };
|
|
12458
|
+
};
|
|
12459
|
+
const getObject = async (input) => {
|
|
12460
|
+
const logical = assertSafeObjectKey(input.key);
|
|
12461
|
+
const physical = toPhysicalKey(prefix, logical);
|
|
12462
|
+
const object = await r2.get(physical);
|
|
12463
|
+
if (!object) return null;
|
|
12464
|
+
return {
|
|
12465
|
+
key: toLogicalKey(prefix, object.key),
|
|
12466
|
+
size: object.size,
|
|
12467
|
+
contentType: object.httpMetadata?.contentType,
|
|
12468
|
+
body: object
|
|
12469
|
+
};
|
|
12470
|
+
};
|
|
12471
|
+
const deleteObject = async (input) => {
|
|
12472
|
+
const logicalKeys = (Array.isArray(input.key) ? input.key : [input.key]).map(
|
|
12473
|
+
(key) => assertSafeObjectKey(key)
|
|
9796
12474
|
);
|
|
12475
|
+
const physicalKeys = logicalKeys.map((key) => toPhysicalKey(prefix, key));
|
|
12476
|
+
await r2.delete(physicalKeys.length === 1 ? physicalKeys[0] : physicalKeys);
|
|
12477
|
+
return { deleted: logicalKeys };
|
|
12478
|
+
};
|
|
12479
|
+
const listObjects = async (input) => {
|
|
12480
|
+
const relative = input?.prefix?.trim() ? assertSafeObjectKey(input.prefix) : "";
|
|
12481
|
+
const listPrefix = `${prefix}${relative}`;
|
|
12482
|
+
const listed = await r2.list({
|
|
12483
|
+
prefix: listPrefix || void 0,
|
|
12484
|
+
limit: input?.limit,
|
|
12485
|
+
cursor: input?.cursor
|
|
12486
|
+
});
|
|
12487
|
+
return {
|
|
12488
|
+
objects: listed.objects.map((object) => ({
|
|
12489
|
+
key: toLogicalKey(prefix, object.key),
|
|
12490
|
+
size: object.size,
|
|
12491
|
+
etag: object.etag,
|
|
12492
|
+
uploaded: object.uploaded
|
|
12493
|
+
})),
|
|
12494
|
+
truncated: listed.truncated,
|
|
12495
|
+
cursor: listed.cursor
|
|
12496
|
+
};
|
|
9797
12497
|
};
|
|
9798
|
-
const
|
|
9799
|
-
|
|
9800
|
-
|
|
9801
|
-
|
|
9802
|
-
|
|
9803
|
-
|
|
9804
|
-
|
|
9805
|
-
|
|
9806
|
-
|
|
9807
|
-
|
|
9808
|
-
if (first && typeof first === "object" && !Array.isArray(first)) {
|
|
9809
|
-
return untypedDbFrom(table2).select(void 0, first);
|
|
12498
|
+
const base = {
|
|
12499
|
+
putObject,
|
|
12500
|
+
getObject,
|
|
12501
|
+
deleteObject,
|
|
12502
|
+
listObjects
|
|
12503
|
+
};
|
|
12504
|
+
return new Proxy(base, {
|
|
12505
|
+
get(target, property, receiver) {
|
|
12506
|
+
if (property in target) {
|
|
12507
|
+
return Reflect.get(target, property, receiver);
|
|
9810
12508
|
}
|
|
9811
|
-
|
|
9812
|
-
|
|
9813
|
-
|
|
9814
|
-
|
|
9815
|
-
|
|
9816
|
-
|
|
9817
|
-
return Array.isArray(values) ? untypedDbFrom(table2).upsert(values, options) : untypedDbFrom(table2).upsert(values, options);
|
|
9818
|
-
},
|
|
9819
|
-
update(table2, values, options) {
|
|
9820
|
-
return untypedDbFrom(table2).update(values, options);
|
|
9821
|
-
},
|
|
9822
|
-
delete(table2, options) {
|
|
9823
|
-
return untypedDbFrom(table2).delete(options);
|
|
9824
|
-
},
|
|
9825
|
-
rpc,
|
|
9826
|
-
query
|
|
9827
|
-
};
|
|
9828
|
-
const chat = createChatModule({
|
|
9829
|
-
baseUrl: config.chatUrl,
|
|
9830
|
-
apiKey: config.apiKey,
|
|
9831
|
-
client: config.client ?? void 0,
|
|
9832
|
-
headers: config.headers,
|
|
9833
|
-
wsUrl: config.chatWsUrl,
|
|
9834
|
-
webSocketFactory: config.chat?.webSocketFactory ?? void 0
|
|
9835
|
-
}, {
|
|
9836
|
-
async resolveCallOptions() {
|
|
9837
|
-
const context = await resolveContext();
|
|
9838
|
-
return context ? {
|
|
9839
|
-
headers: buildContextHeaders(context),
|
|
9840
|
-
bearerToken: context.bearerToken,
|
|
9841
|
-
cookie: context.cookie,
|
|
9842
|
-
sessionToken: context.sessionToken,
|
|
9843
|
-
forceNoCache: context.forceNoCache
|
|
9844
|
-
} : void 0;
|
|
12509
|
+
if (typeof property === "string") {
|
|
12510
|
+
return (...args) => {
|
|
12511
|
+
return unsupported(property);
|
|
12512
|
+
};
|
|
12513
|
+
}
|
|
12514
|
+
return void 0;
|
|
9845
12515
|
}
|
|
9846
12516
|
});
|
|
9847
|
-
const request2 = createAthenaRequest(config, resolveContext);
|
|
9848
|
-
const storage = createStorageModule(gateway, {
|
|
9849
|
-
...config.storage,
|
|
9850
|
-
...config.storageUrl ? {
|
|
9851
|
-
baseUrl: config.storageUrl,
|
|
9852
|
-
stripBasePath: true
|
|
9853
|
-
} : {}
|
|
9854
|
-
});
|
|
9855
|
-
return {
|
|
9856
|
-
from,
|
|
9857
|
-
db,
|
|
9858
|
-
rpc,
|
|
9859
|
-
query,
|
|
9860
|
-
request: request2,
|
|
9861
|
-
verifyConnection: gateway.verifyConnection,
|
|
9862
|
-
auth: auth.auth,
|
|
9863
|
-
chat,
|
|
9864
|
-
storage
|
|
9865
|
-
};
|
|
9866
12517
|
}
|
|
9867
12518
|
|
|
9868
12519
|
// src/billing/module.ts
|
|
@@ -10555,18 +13206,6 @@ function createBillingModule(config) {
|
|
|
10555
13206
|
};
|
|
10556
13207
|
}
|
|
10557
13208
|
|
|
10558
|
-
// src/config/errors.ts
|
|
10559
|
-
var AthenaConfigurationError = class extends Error {
|
|
10560
|
-
code;
|
|
10561
|
-
service;
|
|
10562
|
-
constructor(code, message, service) {
|
|
10563
|
-
super(message);
|
|
10564
|
-
this.name = "AthenaConfigurationError";
|
|
10565
|
-
this.code = code;
|
|
10566
|
-
this.service = service;
|
|
10567
|
-
}
|
|
10568
|
-
};
|
|
10569
|
-
|
|
10570
13209
|
// src/context/merge.ts
|
|
10571
13210
|
function mergeAthenaRequestContexts(base, override) {
|
|
10572
13211
|
if (!base && !override) return void 0;
|
|
@@ -10679,14 +13318,30 @@ function readFirstEnv(env, keys) {
|
|
|
10679
13318
|
}
|
|
10680
13319
|
return void 0;
|
|
10681
13320
|
}
|
|
10682
|
-
function
|
|
13321
|
+
function readFirstEnvHttpUrl(env, keys) {
|
|
13322
|
+
for (const key of keys) {
|
|
13323
|
+
const value = env?.[key]?.trim();
|
|
13324
|
+
if (value && isAbsoluteHttpUrl(value)) return value;
|
|
13325
|
+
}
|
|
13326
|
+
return void 0;
|
|
13327
|
+
}
|
|
13328
|
+
function normalizeOptional2(value) {
|
|
10683
13329
|
const normalized = value?.trim();
|
|
10684
13330
|
return normalized || void 0;
|
|
10685
13331
|
}
|
|
13332
|
+
function isAbsoluteHttpUrl(value) {
|
|
13333
|
+
try {
|
|
13334
|
+
const url = new URL(value);
|
|
13335
|
+
return url.protocol === "http:" || url.protocol === "https:";
|
|
13336
|
+
} catch {
|
|
13337
|
+
return false;
|
|
13338
|
+
}
|
|
13339
|
+
}
|
|
10686
13340
|
function appendPath(baseUrl, path) {
|
|
10687
13341
|
return `${baseUrl.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
10688
13342
|
}
|
|
10689
13343
|
function toWebSocketUrl(baseUrl) {
|
|
13344
|
+
if (!isAbsoluteHttpUrl(baseUrl)) return void 0;
|
|
10690
13345
|
const url = new URL(baseUrl);
|
|
10691
13346
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
10692
13347
|
url.pathname = `${url.pathname.replace(/\/+$/, "")}/wss/gateway`;
|
|
@@ -10696,11 +13351,11 @@ function toWebSocketUrl(baseUrl) {
|
|
|
10696
13351
|
}
|
|
10697
13352
|
function resolveCore(config) {
|
|
10698
13353
|
const env = config.env;
|
|
10699
|
-
const explicitRoot =
|
|
10700
|
-
const envRoot =
|
|
10701
|
-
const root = explicitRoot
|
|
10702
|
-
const explicitRootWinsOverEnvServices = explicitRoot
|
|
10703
|
-
const resolveService = (explicit, envKeys, path) =>
|
|
13354
|
+
const explicitRoot = normalizeOptional2(config.url);
|
|
13355
|
+
const envRoot = readFirstEnvHttpUrl(env, ENV_URL_KEYS);
|
|
13356
|
+
const root = explicitRoot && isAbsoluteHttpUrl(explicitRoot) ? explicitRoot : explicitRoot ? void 0 : envRoot;
|
|
13357
|
+
const explicitRootWinsOverEnvServices = Boolean(root && explicitRoot && isAbsoluteHttpUrl(explicitRoot));
|
|
13358
|
+
const resolveService = (explicit, envKeys, path) => normalizeOptional2(explicit) ?? (explicitRootWinsOverEnvServices && root ? appendPath(root, path) : void 0) ?? readFirstEnvHttpUrl(env, envKeys) ?? (root ? appendPath(root, path) : void 0);
|
|
10704
13359
|
const dbUrl = resolveService(config.db?.url, ENV_DB_URL_KEYS, "db");
|
|
10705
13360
|
const urls = {
|
|
10706
13361
|
db: dbUrl,
|
|
@@ -10708,8 +13363,8 @@ function resolveCore(config) {
|
|
|
10708
13363
|
chat: resolveService(config.chat?.url, ENV_CHAT_URL_KEYS, "chat"),
|
|
10709
13364
|
storage: resolveService(config.storage?.url, ENV_STORAGE_URL_KEYS, "storage"),
|
|
10710
13365
|
// Billing lives on the main Athena HTTP surface (same host as gateway/db).
|
|
10711
|
-
billing:
|
|
10712
|
-
chatWs:
|
|
13366
|
+
billing: normalizeOptional2(config.billing?.url) ?? dbUrl ?? root ?? void 0,
|
|
13367
|
+
chatWs: normalizeOptional2(config.chat?.wsUrl) ?? (explicitRootWinsOverEnvServices && root ? toWebSocketUrl(root) : void 0) ?? readFirstEnvHttpUrl(env, ENV_CHAT_WS_URL_KEYS) ?? (root ? toWebSocketUrl(root) : void 0)
|
|
10713
13368
|
};
|
|
10714
13369
|
if (!urls.db && !urls.auth && !urls.chat && !urls.storage && !urls.billing) {
|
|
10715
13370
|
throw new AthenaConfigurationError(
|
|
@@ -10718,7 +13373,7 @@ function resolveCore(config) {
|
|
|
10718
13373
|
"db"
|
|
10719
13374
|
);
|
|
10720
13375
|
}
|
|
10721
|
-
const key =
|
|
13376
|
+
const key = normalizeOptional2(config.key) ?? readFirstEnv(env, ENV_KEY_KEYS);
|
|
10722
13377
|
if (!key) {
|
|
10723
13378
|
throw new AthenaConfigurationError(
|
|
10724
13379
|
"ATHENA_API_KEY_REQUIRED",
|
|
@@ -10729,7 +13384,7 @@ function resolveCore(config) {
|
|
|
10729
13384
|
config,
|
|
10730
13385
|
urls,
|
|
10731
13386
|
key,
|
|
10732
|
-
client:
|
|
13387
|
+
client: normalizeOptional2(config.client) ?? readFirstEnv(env, ENV_CLIENT_KEYS)
|
|
10733
13388
|
};
|
|
10734
13389
|
return {
|
|
10735
13390
|
...base,
|
|
@@ -10744,7 +13399,13 @@ async function resolveConfiguredContext(core, viewContext) {
|
|
|
10744
13399
|
function createInternalConfig(core) {
|
|
10745
13400
|
const { config, urls } = core;
|
|
10746
13401
|
const { url: _authUrl, ...authOptions } = config.auth ?? {};
|
|
10747
|
-
const {
|
|
13402
|
+
const {
|
|
13403
|
+
url: _storageUrl,
|
|
13404
|
+
directUpload,
|
|
13405
|
+
r2: _r2,
|
|
13406
|
+
prefix: _r2Prefix,
|
|
13407
|
+
...storageOptions
|
|
13408
|
+
} = config.storage ?? {};
|
|
10748
13409
|
const diagnostics = resolveAthenaClientDiagnostics({
|
|
10749
13410
|
diagnostics: config.diagnostics,
|
|
10750
13411
|
debugAst: config.debugAst,
|
|
@@ -10775,7 +13436,8 @@ function createInternalConfig(core) {
|
|
|
10775
13436
|
storage: {
|
|
10776
13437
|
...storageOptions,
|
|
10777
13438
|
...directUpload ? { directUpload } : {}
|
|
10778
|
-
}
|
|
13439
|
+
},
|
|
13440
|
+
gatewayTransport: config.gatewayTransport
|
|
10779
13441
|
};
|
|
10780
13442
|
}
|
|
10781
13443
|
function serviceGuard(urls, service) {
|
|
@@ -10798,6 +13460,232 @@ function createUnavailableNamespace(service, urls, path = []) {
|
|
|
10798
13460
|
}
|
|
10799
13461
|
});
|
|
10800
13462
|
}
|
|
13463
|
+
function isD1Binding2(value) {
|
|
13464
|
+
return Boolean(
|
|
13465
|
+
value && typeof value === "object" && typeof value.prepare === "function"
|
|
13466
|
+
);
|
|
13467
|
+
}
|
|
13468
|
+
function isR2Binding(value) {
|
|
13469
|
+
return Boolean(
|
|
13470
|
+
value && typeof value === "object" && typeof value.put === "function" && typeof value.get === "function"
|
|
13471
|
+
);
|
|
13472
|
+
}
|
|
13473
|
+
function foldBindingAliases(config) {
|
|
13474
|
+
const d1 = config.db?.d1 ?? config.d1;
|
|
13475
|
+
const r2 = config.storage?.r2 ?? config.r2;
|
|
13476
|
+
const sessionMode = config.db?.sessionMode ?? config.sessionMode;
|
|
13477
|
+
const prefix = config.storage?.prefix ?? config.storagePrefix;
|
|
13478
|
+
let next = { ...config };
|
|
13479
|
+
if (d1 !== void 0 || sessionMode !== void 0) {
|
|
13480
|
+
next = {
|
|
13481
|
+
...next,
|
|
13482
|
+
db: {
|
|
13483
|
+
...next.db,
|
|
13484
|
+
...d1 !== void 0 ? { d1 } : {},
|
|
13485
|
+
...sessionMode !== void 0 ? { sessionMode } : {}
|
|
13486
|
+
}
|
|
13487
|
+
};
|
|
13488
|
+
}
|
|
13489
|
+
if (r2 !== void 0 || prefix !== void 0) {
|
|
13490
|
+
next = {
|
|
13491
|
+
...next,
|
|
13492
|
+
storage: {
|
|
13493
|
+
...next.storage,
|
|
13494
|
+
...r2 !== void 0 ? { r2 } : {},
|
|
13495
|
+
...prefix !== void 0 ? { prefix } : {}
|
|
13496
|
+
}
|
|
13497
|
+
};
|
|
13498
|
+
}
|
|
13499
|
+
const {
|
|
13500
|
+
d1: _d1,
|
|
13501
|
+
r2: _r2,
|
|
13502
|
+
storagePrefix: _storagePrefix,
|
|
13503
|
+
sessionMode: _sessionMode,
|
|
13504
|
+
...rest
|
|
13505
|
+
} = next;
|
|
13506
|
+
return rest;
|
|
13507
|
+
}
|
|
13508
|
+
function applyExecutionMode(config) {
|
|
13509
|
+
const d1 = config.db?.d1;
|
|
13510
|
+
const hasD1 = isD1Binding2(d1);
|
|
13511
|
+
const hasUrl = Boolean(
|
|
13512
|
+
normalizeOptional2(config.url) ?? normalizeOptional2(config.db?.url) ?? (config.env ? normalizeOptional2(config.env.ATHENA_URL) ?? normalizeOptional2(config.env.NEXT_PUBLIC_ATHENA_URL) : void 0)
|
|
13513
|
+
);
|
|
13514
|
+
const hasModeHint = config.mode != null || config.prefer != null || Boolean(config.env?.ATHENA_EXECUTION_MODE) || Boolean(config.env?.ATHENA_EXECUTION_PREFER);
|
|
13515
|
+
if (!hasD1 && !hasModeHint) {
|
|
13516
|
+
return config;
|
|
13517
|
+
}
|
|
13518
|
+
if (hasD1 && !hasUrl && !hasModeHint) {
|
|
13519
|
+
return config;
|
|
13520
|
+
}
|
|
13521
|
+
let resolved;
|
|
13522
|
+
try {
|
|
13523
|
+
resolved = resolveAthenaExecutionMode({
|
|
13524
|
+
mode: config.mode,
|
|
13525
|
+
prefer: config.prefer,
|
|
13526
|
+
d1: hasD1 ? d1 : null,
|
|
13527
|
+
url: config.url ?? config.db?.url,
|
|
13528
|
+
env: config.env
|
|
13529
|
+
});
|
|
13530
|
+
} catch (error) {
|
|
13531
|
+
if (!hasModeHint) return config;
|
|
13532
|
+
throw error;
|
|
13533
|
+
}
|
|
13534
|
+
if (resolved === "gateway" && hasD1) {
|
|
13535
|
+
const { d1: _drop, sessionMode: _sm, ...dbRest } = config.db ?? {};
|
|
13536
|
+
return {
|
|
13537
|
+
...config,
|
|
13538
|
+
db: Object.keys(dbRest).length > 0 ? dbRest : void 0,
|
|
13539
|
+
gatewayTransport: void 0
|
|
13540
|
+
};
|
|
13541
|
+
}
|
|
13542
|
+
return config;
|
|
13543
|
+
}
|
|
13544
|
+
function resolveUnifiedRemoteRoot(config) {
|
|
13545
|
+
return normalizeOptional2(config.url) ?? readFirstEnv(config.env, ENV_URL_KEYS);
|
|
13546
|
+
}
|
|
13547
|
+
function isEdgeLocalSentinelUrl(url) {
|
|
13548
|
+
if (!url) return false;
|
|
13549
|
+
return url === CLOUDFLARE_EDGE_BASE_URL || url.startsWith("https://athena.local/") || url.startsWith("http://athena.local/");
|
|
13550
|
+
}
|
|
13551
|
+
function hasRemoteDbGatewayUrl(config) {
|
|
13552
|
+
const dbUrl = normalizeOptional2(config.db?.url) ?? readFirstEnv(config.env, ENV_DB_URL_KEYS);
|
|
13553
|
+
return Boolean(dbUrl && !isEdgeLocalSentinelUrl(dbUrl));
|
|
13554
|
+
}
|
|
13555
|
+
function hasRemoteHttpServices(config) {
|
|
13556
|
+
return Boolean(
|
|
13557
|
+
resolveUnifiedRemoteRoot(config) || hasRemoteDbGatewayUrl(config) || normalizeOptional2(config.auth?.url) || readFirstEnv(config.env, ENV_AUTH_URL_KEYS) || normalizeOptional2(config.storage?.url) || readFirstEnv(config.env, ENV_STORAGE_URL_KEYS) || normalizeOptional2(config.chat?.url) || readFirstEnv(config.env, ENV_CHAT_URL_KEYS) || normalizeOptional2(config.billing?.url)
|
|
13558
|
+
);
|
|
13559
|
+
}
|
|
13560
|
+
function hasRemoteHttpStorage(config) {
|
|
13561
|
+
return Boolean(
|
|
13562
|
+
normalizeOptional2(config.storage?.url) || readFirstEnv(config.env, ENV_STORAGE_URL_KEYS) || resolveUnifiedRemoteRoot(config)
|
|
13563
|
+
);
|
|
13564
|
+
}
|
|
13565
|
+
function hasRemoteAuthService(config) {
|
|
13566
|
+
return Boolean(
|
|
13567
|
+
normalizeOptional2(config.auth?.url) || readFirstEnv(config.env, ENV_AUTH_URL_KEYS) || resolveUnifiedRemoteRoot(config)
|
|
13568
|
+
);
|
|
13569
|
+
}
|
|
13570
|
+
function materializeEdgeBindings(config) {
|
|
13571
|
+
const d1 = config.db?.d1;
|
|
13572
|
+
const r2 = config.storage?.r2;
|
|
13573
|
+
const hasD1 = isD1Binding2(d1);
|
|
13574
|
+
const hasR2 = isR2Binding(r2);
|
|
13575
|
+
if (!hasD1 && !hasR2) {
|
|
13576
|
+
return config;
|
|
13577
|
+
}
|
|
13578
|
+
if (hasD1 && d1 && typeof d1.prepare !== "function") {
|
|
13579
|
+
throw new AthenaConfigurationError(
|
|
13580
|
+
"ATHENA_NO_SERVICE_CONFIGURED",
|
|
13581
|
+
"db.d1 must be a D1 binding with prepare().",
|
|
13582
|
+
"db"
|
|
13583
|
+
);
|
|
13584
|
+
}
|
|
13585
|
+
const remoteRoot = resolveUnifiedRemoteRoot(config);
|
|
13586
|
+
const remoteServices = hasRemoteHttpServices(config);
|
|
13587
|
+
const remoteStorage = hasRemoteHttpStorage(config);
|
|
13588
|
+
const remoteAuth = hasRemoteAuthService(config);
|
|
13589
|
+
const next = { ...config };
|
|
13590
|
+
if (hasD1 && d1) {
|
|
13591
|
+
if (!config.gatewayTransport) {
|
|
13592
|
+
next.gatewayTransport = createCloudflareD1GatewayTransport({
|
|
13593
|
+
d1,
|
|
13594
|
+
defaultSessionMode: config.db?.sessionMode
|
|
13595
|
+
});
|
|
13596
|
+
}
|
|
13597
|
+
const explicitDbUrl = normalizeOptional2(config.db?.url);
|
|
13598
|
+
const remoteDbGateway = hasRemoteDbGatewayUrl(config);
|
|
13599
|
+
next.db = {
|
|
13600
|
+
...config.db,
|
|
13601
|
+
d1,
|
|
13602
|
+
url: explicitDbUrl ?? (remoteDbGateway ? void 0 : CLOUDFLARE_EDGE_BASE_URL)
|
|
13603
|
+
};
|
|
13604
|
+
const explicitKey = normalizeOptional2(config.key);
|
|
13605
|
+
if (explicitKey) {
|
|
13606
|
+
next.key = explicitKey;
|
|
13607
|
+
} else if (!remoteServices) {
|
|
13608
|
+
next.key = CLOUDFLARE_EDGE_API_KEY;
|
|
13609
|
+
} else {
|
|
13610
|
+
next.key = void 0;
|
|
13611
|
+
}
|
|
13612
|
+
if (remoteRoot) {
|
|
13613
|
+
next.billing = {
|
|
13614
|
+
...config.billing ?? {},
|
|
13615
|
+
url: normalizeOptional2(config.billing?.url) ?? remoteRoot
|
|
13616
|
+
};
|
|
13617
|
+
}
|
|
13618
|
+
if (!config.capabilities) {
|
|
13619
|
+
next.capabilities = createCloudflareEdgeCapabilities({
|
|
13620
|
+
hasR2,
|
|
13621
|
+
// Explicit storage.url / env storage URL / unified remote root all count.
|
|
13622
|
+
hasRemoteStorage: remoteStorage,
|
|
13623
|
+
authRemote: remoteAuth,
|
|
13624
|
+
findManyAst: false
|
|
13625
|
+
});
|
|
13626
|
+
}
|
|
13627
|
+
} else if (hasR2 && r2) {
|
|
13628
|
+
if (!remoteRoot && !normalizeOptional2(config.db?.url) && !normalizeOptional2(config.storage?.url) && !readFirstEnv(config.env, ENV_STORAGE_URL_KEYS)) {
|
|
13629
|
+
next.storage = {
|
|
13630
|
+
...config.storage,
|
|
13631
|
+
r2,
|
|
13632
|
+
// Local sentinel so resolveCore accepts a storage-only binding client.
|
|
13633
|
+
url: CLOUDFLARE_EDGE_BASE_URL
|
|
13634
|
+
};
|
|
13635
|
+
if (!remoteServices) {
|
|
13636
|
+
next.key = normalizeOptional2(config.key) ?? CLOUDFLARE_EDGE_API_KEY;
|
|
13637
|
+
} else if (normalizeOptional2(config.key)) {
|
|
13638
|
+
next.key = normalizeOptional2(config.key);
|
|
13639
|
+
} else {
|
|
13640
|
+
next.key = void 0;
|
|
13641
|
+
}
|
|
13642
|
+
}
|
|
13643
|
+
if (!config.capabilities) {
|
|
13644
|
+
if (remoteRoot || normalizeOptional2(config.db?.url) || readFirstEnv(config.env, ENV_DB_URL_KEYS)) {
|
|
13645
|
+
const base = createGatewayCapabilities({
|
|
13646
|
+
authRemote: remoteAuth,
|
|
13647
|
+
storageConfigured: true
|
|
13648
|
+
});
|
|
13649
|
+
next.capabilities = {
|
|
13650
|
+
...base,
|
|
13651
|
+
storage: {
|
|
13652
|
+
...base.storage,
|
|
13653
|
+
local: true,
|
|
13654
|
+
objects: true
|
|
13655
|
+
}
|
|
13656
|
+
};
|
|
13657
|
+
} else {
|
|
13658
|
+
next.capabilities = {
|
|
13659
|
+
mode: "cloudflare-edge",
|
|
13660
|
+
db: {
|
|
13661
|
+
engine: "unknown",
|
|
13662
|
+
local: false,
|
|
13663
|
+
layers: {
|
|
13664
|
+
query: false,
|
|
13665
|
+
flatCrud: false,
|
|
13666
|
+
findManyAst: false,
|
|
13667
|
+
rpc: false,
|
|
13668
|
+
relations: false
|
|
13669
|
+
}
|
|
13670
|
+
},
|
|
13671
|
+
storage: {
|
|
13672
|
+
local: true,
|
|
13673
|
+
objects: true,
|
|
13674
|
+
catalogs: false,
|
|
13675
|
+
backups: false
|
|
13676
|
+
},
|
|
13677
|
+
auth: {
|
|
13678
|
+
remote: remoteAuth
|
|
13679
|
+
}
|
|
13680
|
+
};
|
|
13681
|
+
}
|
|
13682
|
+
}
|
|
13683
|
+
}
|
|
13684
|
+
return next;
|
|
13685
|
+
}
|
|
13686
|
+
function normalizeCreateClientConfig(config) {
|
|
13687
|
+
return materializeEdgeBindings(applyExecutionMode(foldBindingAliases(config)));
|
|
13688
|
+
}
|
|
10801
13689
|
function createClientView(core, viewContext) {
|
|
10802
13690
|
const resolved = createInternalClientView(
|
|
10803
13691
|
core.internalCore,
|
|
@@ -10815,12 +13703,23 @@ function createClientView(core, viewContext) {
|
|
|
10815
13703
|
},
|
|
10816
13704
|
...billingOptions
|
|
10817
13705
|
}) : createUnavailableNamespace("billing", core.urls);
|
|
13706
|
+
const capabilities = core.config.capabilities ?? createGatewayCapabilities({
|
|
13707
|
+
authRemote: Boolean(core.urls.auth),
|
|
13708
|
+
// Match unavailable storage proxy when no storage URL was resolved.
|
|
13709
|
+
storageConfigured: Boolean(core.urls.storage)
|
|
13710
|
+
});
|
|
13711
|
+
const r2 = core.config.storage?.r2;
|
|
13712
|
+
const storageModule = isR2Binding(r2) ? createCloudflareR2StorageModule({
|
|
13713
|
+
r2,
|
|
13714
|
+
prefix: core.config.storage?.prefix ?? void 0
|
|
13715
|
+
}) : core.urls.storage ? resolved.storage : createUnavailableNamespace("storage", core.urls);
|
|
10818
13716
|
const client = {
|
|
10819
13717
|
db: core.urls.db ? resolved.db : createUnavailableNamespace("db", core.urls),
|
|
10820
13718
|
auth: core.urls.auth ? resolved.auth : createUnavailableNamespace("auth", core.urls),
|
|
10821
13719
|
chat: core.urls.chat ? resolved.chat : createUnavailableNamespace("chat", core.urls),
|
|
10822
|
-
storage:
|
|
13720
|
+
storage: storageModule,
|
|
10823
13721
|
billing: billingModule,
|
|
13722
|
+
capabilities,
|
|
10824
13723
|
from: ((...args) => {
|
|
10825
13724
|
requireDb();
|
|
10826
13725
|
return Reflect.apply(resolved.from, resolved, args);
|
|
@@ -10861,7 +13760,8 @@ function normalizeOptionalContextString(value) {
|
|
|
10861
13760
|
}
|
|
10862
13761
|
function warnIfEmptyRequestContext(context) {
|
|
10863
13762
|
if (!isEmptyAthenaRequestContext(context)) return;
|
|
10864
|
-
|
|
13763
|
+
const nodeEnv = globalThis.process?.env?.NODE_ENV;
|
|
13764
|
+
if (nodeEnv === "production") {
|
|
10865
13765
|
return;
|
|
10866
13766
|
}
|
|
10867
13767
|
console.warn(
|
|
@@ -10869,7 +13769,8 @@ function warnIfEmptyRequestContext(context) {
|
|
|
10869
13769
|
);
|
|
10870
13770
|
}
|
|
10871
13771
|
function createClient(config) {
|
|
10872
|
-
|
|
13772
|
+
const normalized = normalizeCreateClientConfig(config);
|
|
13773
|
+
return createClientView(resolveCore(normalized));
|
|
10873
13774
|
}
|
|
10874
13775
|
|
|
10875
13776
|
// src/gateway/types.ts
|