@hot-updater/cloudflare 1.0.0-rc.4 → 1.0.0-rc.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/index.cjs +88 -918
  2. package/dist/index.d.cts +794 -4
  3. package/dist/index.d.mts +794 -4
  4. package/dist/index.mjs +88 -920
  5. package/dist/init/index.cjs +11768 -0
  6. package/dist/init/index.d.cts +5 -1
  7. package/dist/init/index.d.mts +5 -1
  8. package/dist/init/index.mjs +11761 -1
  9. package/dist/worker/index.cjs +55 -911
  10. package/dist/worker/index.d.cts +794 -9
  11. package/dist/worker/index.d.mts +794 -9
  12. package/dist/worker/index.mjs +56 -913
  13. package/package.json +8 -12
  14. package/sql/bundles.sql +115 -212
  15. package/src/d1Database.ts +58 -43
  16. package/src/d1Executor.ts +84 -0
  17. package/src/d1Schema.ts +26 -0
  18. package/src/index.ts +1 -0
  19. package/src/plugins.ts +8 -0
  20. package/src/r2S3Storage.ts +4 -4
  21. package/src/r2Storage.ts +2 -2
  22. package/src/r2WorkerStorage.ts +4 -4
  23. package/src/worker/d1Database.ts +21 -35
  24. package/src/worker/index.ts +1 -0
  25. package/worker/dist/README.md +1 -1
  26. package/worker/dist/index.js +9538 -6210
  27. package/worker/dist/index.js.map +4 -4
  28. package/worker/migrations/0001_hot-updater_1.0.0.sql +115 -222
  29. package/worker/src/index.ts +2 -2
  30. package/dist/iac/index.cjs +0 -12688
  31. package/dist/iac/index.d.cts +0 -5
  32. package/dist/iac/index.d.mts +0 -5
  33. package/dist/iac/index.mjs +0 -12680
  34. package/src/d1Database.spec.ts +0 -277
  35. package/src/d1Implementation.spec.ts +0 -342
  36. package/src/d1Implementation.ts +0 -781
  37. package/src/d1Query.spec.ts +0 -46
  38. package/src/d1Query.ts +0 -92
  39. package/src/d1Rows.spec.ts +0 -143
  40. package/src/d1Rows.ts +0 -361
  41. package/src/d1Sql.spec.ts +0 -30
  42. package/src/d1Sql.ts +0 -175
  43. package/src/r2Storage.spec.ts +0 -346
  44. package/src/r2WorkerStorage.spec.ts +0 -184
  45. package/src/utils/createWrangler.spec.ts +0 -75
  46. package/src/worker/d1Database.spec.ts +0 -69
  47. package/worker/src/databaseMigration.integration.spec.ts +0 -191
  48. package/worker/src/databasePlugins.integration.spec.ts +0 -326
  49. package/worker/src/index.integration.spec.ts +0 -190
  50. package/worker/src/insightsMovement.integration.spec.ts +0 -73
  51. package/worker/src/storagePlugin.integration.spec.ts +0 -59
  52. package/worker/src/testWorker.ts +0 -5
package/dist/index.cjs CHANGED
@@ -22,953 +22,114 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
22
22
  }) : target, mod));
23
23
  //#endregion
24
24
  let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
25
- let _hot_updater_plugin_core_internal = require("@hot-updater/plugin-core/internal");
26
25
  let cloudflare = require("cloudflare");
27
26
  cloudflare = __toESM(cloudflare, 1);
28
27
  let _aws_sdk_client_s3 = require("@aws-sdk/client-s3");
29
28
  let _aws_sdk_lib_storage = require("@aws-sdk/lib-storage");
30
- //#region src/d1Rows.ts
31
- var InvalidD1RowError = class extends Error {
32
- name = "InvalidD1RowError";
33
- model;
34
- constructor(model) {
35
- super(`D1 returned an invalid ${model} row`);
36
- this.model = model;
37
- }
38
- };
39
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
40
- const stringValue = (row, field, model) => {
41
- const value = row[field];
42
- if (typeof value !== "string") throw new InvalidD1RowError(model);
43
- return value;
44
- };
45
- const nullableString = (row, field, model) => {
46
- const value = row[field];
47
- if (value === null) return null;
48
- if (typeof value !== "string") throw new InvalidD1RowError(model);
49
- return value;
50
- };
51
- const numberValue = (row, field, model) => {
52
- const value = row[field];
53
- if (typeof value !== "number") throw new InvalidD1RowError(model);
54
- return value;
55
- };
56
- const byteSizeValue = (row, field, model) => {
57
- const value = row[field];
58
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new InvalidD1RowError(model);
59
- return value;
60
- };
61
- const booleanValue = (row, field, model) => {
62
- const value = row[field];
63
- if (value === true || value === 1) return true;
64
- if (value === false || value === 0) return false;
65
- throw new InvalidD1RowError(model);
66
- };
67
- const jsonValue = (value, model) => {
68
- if (typeof value !== "string") throw new InvalidD1RowError(model);
69
- try {
70
- return JSON.parse(value);
71
- } catch (error) {
72
- if (error instanceof SyntaxError) throw new InvalidD1RowError(model);
73
- throw error;
74
- }
75
- };
76
- const metadata = (row) => {
77
- const value = jsonValue(row["metadata"], "bundles");
78
- if (!(0, _hot_updater_plugin_core.isDatabaseMetadataObject)(value)) throw new InvalidD1RowError("bundles");
79
- return value;
80
- };
81
- const bundleRow = (row) => {
82
- const platform = stringValue(row, "platform", "bundles");
83
- if (platform !== "ios" && platform !== "android") throw new InvalidD1RowError("bundles");
84
- return {
85
- id: stringValue(row, "id", "bundles"),
86
- platform,
87
- file_hash: stringValue(row, "file_hash", "bundles"),
88
- git_commit_hash: nullableString(row, "git_commit_hash", "bundles"),
89
- storage_uri: stringValue(row, "storage_uri", "bundles"),
90
- archive_byte_size: row["archive_byte_size"] === void 0 ? 0 : byteSizeValue(row, "archive_byte_size", "bundles"),
91
- metadata: metadata(row),
92
- manifest_storage_uri: nullableString(row, "manifest_storage_uri", "bundles"),
93
- manifest_file_hash: nullableString(row, "manifest_file_hash", "bundles"),
94
- asset_base_storage_uri: nullableString(row, "asset_base_storage_uri", "bundles")
95
- };
96
- };
97
- const patchRow = (row) => ({
98
- id: stringValue(row, "id", "bundle_patches"),
99
- bundle_id: stringValue(row, "bundle_id", "bundle_patches"),
100
- base_bundle_id: stringValue(row, "base_bundle_id", "bundle_patches"),
101
- base_file_hash: stringValue(row, "base_file_hash", "bundle_patches"),
102
- patch_file_hash: stringValue(row, "patch_file_hash", "bundle_patches"),
103
- patch_storage_uri: stringValue(row, "patch_storage_uri", "bundle_patches"),
104
- byte_size: byteSizeValue(row, "byte_size", "bundle_patches"),
105
- order_index: numberValue(row, "order_index", "bundle_patches")
106
- });
107
- const channelRow = (row) => ({
108
- id: stringValue(row, "id", "channels"),
109
- name: stringValue(row, "name", "channels")
110
- });
111
- const eventRow = (row) => {
112
- const type = stringValue(row, "type", "bundle_events");
113
- const platform = stringValue(row, "platform", "bundle_events");
114
- const fromBundleId = nullableString(row, "from_bundle_id", "bundle_events");
115
- const updateStrategy = nullableString(row, "update_strategy", "bundle_events");
116
- if (platform !== "ios" && platform !== "android" || !((type === "UPDATE_APPLIED" || type === "RECOVERED" || type === "RELEASE_ADOPTED") && typeof fromBundleId === "string" && (updateStrategy === "fingerprint" || updateStrategy === "appVersion") || type === "UNCHANGED" && fromBundleId === null && updateStrategy === null)) throw new InvalidD1RowError("bundle_events");
117
- return {
118
- id: stringValue(row, "id", "bundle_events"),
119
- type,
120
- install_id: stringValue(row, "install_id", "bundle_events"),
121
- user_id: nullableString(row, "user_id", "bundle_events"),
122
- username: nullableString(row, "username", "bundle_events"),
123
- from_release_id: nullableString(row, "from_release_id", "bundle_events"),
124
- from_bundle_id: fromBundleId,
125
- to_release_id: nullableString(row, "to_release_id", "bundle_events"),
126
- to_bundle_id: stringValue(row, "to_bundle_id", "bundle_events"),
127
- platform,
128
- app_version: stringValue(row, "app_version", "bundle_events"),
129
- channel: stringValue(row, "channel", "bundle_events"),
130
- cohort: stringValue(row, "cohort", "bundle_events"),
131
- update_strategy: updateStrategy,
132
- fingerprint_hash: nullableString(row, "fingerprint_hash", "bundle_events"),
133
- sdk_version: nullableString(row, "sdk_version", "bundle_events"),
134
- received_at_ms: numberValue(row, "received_at_ms", "bundle_events")
135
- };
136
- };
137
- const installationRow = (row) => {
138
- const type = stringValue(row, "type", "bundle_installations");
139
- const platform = stringValue(row, "platform", "bundle_installations");
140
- if (![
141
- "UPDATE_APPLIED",
142
- "RECOVERED",
143
- "RELEASE_ADOPTED",
144
- "UNCHANGED"
145
- ].includes(type) || platform !== "ios" && platform !== "android") throw new InvalidD1RowError("bundle_installations");
146
- return {
147
- id: stringValue(row, "id", "bundle_installations"),
148
- install_id: stringValue(row, "install_id", "bundle_installations"),
149
- user_id: nullableString(row, "user_id", "bundle_installations"),
150
- username: nullableString(row, "username", "bundle_installations"),
151
- to_bundle_id: stringValue(row, "to_bundle_id", "bundle_installations"),
152
- type,
153
- platform,
154
- app_version: stringValue(row, "app_version", "bundle_installations"),
155
- channel: stringValue(row, "channel", "bundle_installations"),
156
- cohort: stringValue(row, "cohort", "bundle_installations"),
157
- received_at_ms: numberValue(row, "received_at_ms", "bundle_installations")
158
- };
159
- };
160
- const apiKeyRow = (row) => {
161
- const role = stringValue(row, "role", "api_keys");
162
- if (role !== "client") throw new InvalidD1RowError("api_keys");
163
- const revokedAt = row["revoked_at_ms"];
164
- return {
165
- id: stringValue(row, "id", "api_keys"),
166
- hash: stringValue(row, "hash", "api_keys"),
167
- name: stringValue(row, "name", "api_keys"),
168
- prefix: stringValue(row, "prefix", "api_keys"),
169
- role,
170
- created_at_ms: numberValue(row, "created_at_ms", "api_keys"),
171
- revoked_at_ms: revokedAt === null ? null : numberValue(row, "revoked_at_ms", "api_keys")
172
- };
173
- };
174
- const releaseTargetCohorts = (row) => {
175
- const value = jsonValue(row["target_cohorts"], "releases");
176
- if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) throw new InvalidD1RowError("releases");
177
- return value.filter((item) => typeof item === "string");
178
- };
179
- const releaseRow = (row) => {
180
- const platform = stringValue(row, "platform", "releases");
181
- const kind = stringValue(row, "kind", "releases");
182
- const strategy = stringValue(row, "strategy", "releases");
183
- const operation = stringValue(row, "operation", "releases");
184
- if (platform !== "ios" && platform !== "android" || kind !== "BUNDLE" && kind !== "EMBEDDED" || strategy !== "APP_VERSION" && strategy !== "FINGERPRINT" || operation !== "DEPLOY" && operation !== "PROMOTE" && operation !== "ROLLBACK") throw new InvalidD1RowError("releases");
185
- return {
186
- id: stringValue(row, "id", "releases"),
187
- revision: numberValue(row, "revision", "releases"),
188
- scope_key: stringValue(row, "scope_key", "releases"),
189
- channel_id: stringValue(row, "channel_id", "releases"),
190
- platform,
191
- kind,
192
- bundle_id: nullableString(row, "bundle_id", "releases"),
193
- strategy,
194
- target_app_version: nullableString(row, "target_app_version", "releases"),
195
- fingerprint_hash: nullableString(row, "fingerprint_hash", "releases"),
196
- enabled: booleanValue(row, "enabled", "releases"),
197
- should_force_update: booleanValue(row, "should_force_update", "releases"),
198
- message: nullableString(row, "message", "releases"),
199
- rollout_cohort_count: numberValue(row, "rollout_cohort_count", "releases"),
200
- target_cohorts: releaseTargetCohorts(row),
201
- operation,
202
- source_release_id: nullableString(row, "source_release_id", "releases"),
203
- created_at_ms: numberValue(row, "created_at_ms", "releases"),
204
- updated_at_ms: numberValue(row, "updated_at_ms", "releases")
205
- };
206
- };
207
- const releaseCatalogRow = (row) => {
208
- const platform = stringValue(row, "platform", "release_catalogs");
209
- const strategy = stringValue(row, "strategy", "release_catalogs");
210
- if (platform !== "ios" && platform !== "android" || strategy !== "APP_VERSION" && strategy !== "FINGERPRINT") throw new InvalidD1RowError("release_catalogs");
211
- return {
212
- scope_key: stringValue(row, "scope_key", "release_catalogs"),
213
- catalog_id: stringValue(row, "catalog_id", "release_catalogs"),
214
- strategy,
215
- channel_id: stringValue(row, "channel_id", "release_catalogs"),
216
- channel_key: stringValue(row, "channel_key", "release_catalogs"),
217
- platform,
218
- fingerprint_hash: nullableString(row, "fingerprint_hash", "release_catalogs"),
219
- generation: numberValue(row, "generation", "release_catalogs"),
220
- payload: stringValue(row, "payload", "release_catalogs"),
221
- catalog_hash: stringValue(row, "catalog_hash", "release_catalogs"),
222
- byte_size: numberValue(row, "byte_size", "release_catalogs"),
223
- is_tombstone: booleanValue(row, "is_tombstone", "release_catalogs"),
224
- updated_at_ms: numberValue(row, "updated_at_ms", "release_catalogs")
225
- };
226
- };
227
- function parseD1Row(model, value) {
228
- if (!isRecord(value)) throw new InvalidD1RowError(model);
229
- switch (model) {
230
- case "bundles": return bundleRow(value);
231
- case "bundle_patches": return patchRow(value);
232
- case "channels": return channelRow(value);
233
- case "bundle_events": return eventRow(value);
234
- case "bundle_installations": return installationRow(value);
235
- case "api_keys": return apiKeyRow(value);
236
- case "releases": return releaseRow(value);
237
- case "release_catalogs": return releaseCatalogRow(value);
238
- }
239
- }
240
- //#endregion
241
- //#region src/d1Sql.ts
242
- var InvalidD1PredicateError = class extends Error {
243
- name = "InvalidD1PredicateError";
244
- };
245
- const encodeD1Value = (value) => {
246
- const encoded = JSON.stringify(value);
247
- if (encoded === void 0) throw new TypeError("D1 values must be JSON-serializable.");
248
- return encoded;
249
- };
250
- const bind = (value) => ({
251
- sql: "json_extract(?, '$')",
252
- params: [encodeD1Value(value)]
253
- });
254
- const escapeLikePattern = (value) => value.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_");
255
- const stringPredicate = (condition, operator) => {
256
- if (typeof condition.value !== "string") throw new InvalidD1PredicateError();
257
- if (condition.mode !== "insensitive") {
258
- const parameter = bind(condition.value);
259
- const column = `${condition.field} COLLATE BINARY`;
260
- const value = `${parameter.sql} COLLATE BINARY`;
261
- if (operator === "contains" || operator === "starts_with") return {
262
- sql: `instr(${column}, ${value}) ${operator === "contains" ? "> 0" : "= 1"}`,
263
- params: parameter.params
264
- };
265
- return {
266
- sql: `substr(${column}, length(${condition.field}) - length(${parameter.sql}) + 1) = ${value}`,
267
- params: [...parameter.params, ...parameter.params]
268
- };
269
- }
270
- const literal = escapeLikePattern(condition.value);
271
- const pattern = operator === "contains" ? `%${literal}%` : operator === "starts_with" ? `${literal}%` : `%${literal}`;
272
- const parameter = bind(pattern);
273
- return {
274
- sql: `lower(${condition.field}) LIKE lower(${parameter.sql}) ESCAPE '\\'`,
275
- params: parameter.params
276
- };
277
- };
278
- const predicate = (condition) => {
279
- const operator = condition.operator ?? "eq";
280
- switch (operator) {
281
- case "eq":
282
- case "ne": {
283
- if (condition.value === null) return {
284
- sql: `${condition.field} IS ${operator === "ne" ? "NOT " : ""}NULL`,
285
- params: []
286
- };
287
- const parameter = bind(condition.value);
288
- const insensitive = "mode" in condition && condition.mode === "insensitive";
289
- const column = insensitive ? `lower(${condition.field})` : condition.field;
290
- const value = insensitive ? `lower(${parameter.sql})` : parameter.sql;
291
- return {
292
- sql: `${column} ${operator === "eq" ? "=" : "<>"} ${value}`,
293
- params: parameter.params
294
- };
295
- }
296
- case "gt":
297
- case "gte":
298
- case "lt":
299
- case "lte": {
300
- const sqlOperator = {
301
- gt: ">",
302
- gte: ">=",
303
- lt: "<",
304
- lte: "<="
305
- }[operator];
306
- const parameter = bind(condition.value);
307
- return {
308
- sql: `${condition.field} ${sqlOperator} ${parameter.sql}`,
309
- params: parameter.params
310
- };
311
- }
312
- case "in":
313
- case "not_in":
314
- if (!Array.isArray(condition.value)) throw new InvalidD1PredicateError();
315
- if (condition.value.length === 0) return {
316
- sql: operator === "not_in" ? "1 = 1" : "1 = 0",
317
- params: []
318
- };
319
- return {
320
- sql: `${condition.field} ${operator === "not_in" ? "NOT " : ""}IN (SELECT value FROM json_each(?))`,
321
- params: [encodeD1Value(condition.value)]
322
- };
323
- case "contains":
324
- case "starts_with":
325
- case "ends_with": return stringPredicate(condition, operator);
326
- }
327
- };
328
- const buildD1Where = (where) => {
329
- const [first, ...rest] = where ?? [];
330
- if (first === void 0) return {
331
- sql: "",
332
- params: []
333
- };
334
- const initial = predicate(first);
335
- let sql = initial.sql;
336
- const params = [...initial.params];
337
- for (const condition of rest) {
338
- const next = predicate(condition);
339
- sql = `(${sql} ${condition.connector === "OR" ? "OR" : "AND"} ${next.sql})`;
340
- params.push(...next.params);
341
- }
342
- return {
343
- sql: ` WHERE ${sql}`,
344
- params
345
- };
346
- };
347
- const buildD1Order = (orderBy) => orderBy === void 0 ? "" : ` ORDER BY ${orderBy.map((clause) => `${clause.field} ${clause.direction.toUpperCase()}${clause.nulls ? ` NULLS ${clause.nulls.toUpperCase()}` : ""}`).join(", ")}`;
348
- const d1Placeholders = (count) => Array.from({ length: count }, () => "json_extract(?, '$')").join(", ");
349
- const encodeD1Values = (values) => values.map(encodeD1Value);
350
- //#endregion
351
- //#region src/d1Query.ts
352
- const d1TableNames = {
353
- bundles: "bundles",
354
- bundle_patches: "bundle_patches",
355
- channels: "channels",
356
- bundle_events: "bundle_events",
357
- bundle_installations: "bundle_installations",
358
- api_keys: "api_keys",
359
- release_catalogs: "release_catalogs",
360
- releases: "releases"
361
- };
362
- var D1QueryResultError = class extends Error {
363
- result;
364
- name = "D1QueryResultError";
365
- operation = "count";
366
- constructor(result) {
367
- super("D1 count query returned a malformed first row");
368
- this.result = result;
369
- }
370
- };
371
- const countD1Rows = async (executor, input) => {
372
- const where = buildD1Where(input.where);
373
- const table = d1TableNames[input.model];
374
- const source = input.distinct === void 0 ? `${table}${where.sql}` : `(SELECT DISTINCT ${input.distinct.join(", ")} FROM ${table}${where.sql}) AS distinct_rows`;
375
- const row = (await executor.query(`SELECT COUNT(*) AS count FROM ${source}`, where.params))[0];
376
- if (typeof row !== "object" || row === null || Array.isArray(row)) throw new D1QueryResultError(row);
377
- const count = Reflect.get(row, "count");
378
- if (typeof count !== "number" || !Number.isFinite(count)) throw new D1QueryResultError(row);
379
- return count;
380
- };
381
- const findManyD1Rows = async (executor, input) => {
382
- const where = buildD1Where(input.where);
383
- const orderBy = input.orderBy;
384
- const order = buildD1Order(orderBy);
385
- const table = d1TableNames[input.model];
386
- const source = input.distinctOn === void 0 ? `SELECT * FROM ${table}${where.sql}${order}` : `SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${input.distinctOn.fields.join(", ")}${order}) AS __hot_updater_rank FROM ${table}${where.sql}) AS distinct_rows WHERE __hot_updater_rank = 1${order}`;
387
- const pageParams = encodeD1Values([input.limit, input.offset]);
388
- const rows = await executor.query(`${source} LIMIT json_extract(?, '$') OFFSET json_extract(?, '$')`, [...where.params, ...pageParams]);
389
- switch (input.model) {
390
- case "bundles": return rows.map((row) => parseD1Row("bundles", row));
391
- case "bundle_patches": return rows.map((row) => parseD1Row("bundle_patches", row));
392
- case "channels": return rows.map((row) => parseD1Row("channels", row));
393
- case "bundle_events": return rows.map((row) => parseD1Row("bundle_events", row));
394
- case "bundle_installations": return rows.map((row) => parseD1Row("bundle_installations", row));
395
- case "api_keys": return rows.map((row) => parseD1Row("api_keys", row));
396
- case "releases": return rows.map((row) => parseD1Row("releases", row));
397
- case "release_catalogs": return rows.map((row) => parseD1Row("release_catalogs", row));
398
- }
399
- };
400
- //#endregion
401
- //#region src/d1Implementation.ts
29
+ let _hot_updater_server_plugins_api_keys = require("@hot-updater/server/plugins/api-keys");
30
+ let _hot_updater_server_plugins_insights = require("@hot-updater/server/plugins/insights");
31
+ //#region src/d1Executor.ts
402
32
  var D1ExecutionError = class extends Error {
403
33
  name = "D1ExecutionError";
404
34
  constructor() {
405
35
  super("D1 did not successfully execute every requested statement");
406
36
  }
407
37
  };
408
- const EXPECTATION_CONFLICT_MARKER = "HOT_UPDATER_COMMIT_EXPECTATION_CONFLICT";
409
- const expectationGuard = (expectations) => {
410
- const clauses = [];
411
- const params = [];
412
- for (const expectation of expectations) {
413
- const isRelease = expectation.model === "releases";
414
- const table = isRelease ? "releases" : "release_catalogs";
415
- const keyField = isRelease ? "id" : "scope_key";
416
- const versionField = isRelease ? "revision" : "generation";
417
- const key = isRelease ? expectation.id : expectation.scopeKey;
418
- const version = isRelease ? expectation.revision : expectation.generation;
419
- if (version === null) {
420
- clauses.push(`NOT EXISTS (SELECT 1 FROM ${table} WHERE ${keyField} = json_extract(?, '$'))`);
421
- params.push(...encodeD1Values([key]));
422
- } else {
423
- clauses.push(`EXISTS (SELECT 1 FROM ${table} WHERE ${keyField} = json_extract(?, '$') AND ${versionField} = json_extract(?, '$'))`);
424
- params.push(...encodeD1Values([key, version]));
425
- }
426
- }
38
+ const toSqlResult = (result) => {
39
+ if (result.success === false) throw new D1ExecutionError();
427
40
  return {
428
- sql: clauses.join(" AND ") || "1",
429
- params
41
+ rows: result.results ?? [],
42
+ changes: result.meta?.changes ?? 0
430
43
  };
431
44
  };
432
- const readVersion = (row, field) => {
433
- if (typeof row !== "object" || row === null) return null;
434
- const value = Reflect.get(row, field);
435
- return typeof value === "number" ? value : null;
436
- };
437
- const expectationConflict = async (executor, expectations) => {
438
- for (const expectation of expectations) {
439
- const isRelease = expectation.model === "releases";
440
- const table = isRelease ? "releases" : "release_catalogs";
441
- const keyField = isRelease ? "id" : "scope_key";
442
- const versionField = isRelease ? "revision" : "generation";
443
- const key = isRelease ? expectation.id : expectation.scopeKey;
444
- const expectedVersion = isRelease ? expectation.revision : expectation.generation;
445
- const rows = await executor.query(`SELECT ${versionField} FROM ${table} WHERE ${keyField} = json_extract(?, '$') LIMIT 1`, encodeD1Values([key]));
446
- const actualVersion = readVersion(rows[0], versionField);
447
- if (actualVersion !== expectedVersion) return {
448
- committed: false,
449
- conflict: {
450
- actualVersion,
451
- changeIndex: -1,
452
- expectedVersion,
453
- key,
454
- model: expectation.model,
455
- reason: "version_conflict"
456
- }
457
- };
458
- }
459
- return null;
460
- };
461
- const isExpectationConflictError = (error) => {
45
+ /** D1 reports SQLite errors in the message; the SQL core classifies codes. */
46
+ const withSqliteCode = (error) => {
462
47
  const message = error instanceof Error ? error.message : String(error);
463
- return message.includes(EXPECTATION_CONFLICT_MARKER) || message.toLowerCase().includes("malformed json");
464
- };
465
- const bundleValues = (row) => [
466
- row.id,
467
- row.platform,
468
- row.file_hash,
469
- row.git_commit_hash,
470
- row.storage_uri,
471
- row.archive_byte_size,
472
- row.metadata,
473
- row.manifest_storage_uri,
474
- row.manifest_file_hash,
475
- row.asset_base_storage_uri
476
- ];
477
- const patchValues = (row) => [
478
- row.id,
479
- row.bundle_id,
480
- row.base_bundle_id,
481
- row.base_file_hash,
482
- row.patch_file_hash,
483
- row.patch_storage_uri,
484
- row.byte_size,
485
- row.order_index
486
- ];
487
- const channelValues = (row) => [row.id, row.name];
488
- const insertQuery = (input, guard, conflictMode = "returnExisting") => {
489
- let columns;
490
- let values;
491
- switch (input.model) {
492
- case "bundles":
493
- columns = [
494
- "id",
495
- "platform",
496
- "file_hash",
497
- "git_commit_hash",
498
- "storage_uri",
499
- "archive_byte_size",
500
- "metadata",
501
- "manifest_storage_uri",
502
- "manifest_file_hash",
503
- "asset_base_storage_uri"
504
- ];
505
- values = bundleValues(input.data);
506
- break;
507
- case "bundle_patches":
508
- columns = [
509
- "id",
510
- "bundle_id",
511
- "base_bundle_id",
512
- "base_file_hash",
513
- "patch_file_hash",
514
- "patch_storage_uri",
515
- "byte_size",
516
- "order_index"
517
- ];
518
- values = patchValues(input.data);
519
- break;
520
- case "channels":
521
- columns = ["id", "name"];
522
- values = channelValues(input.data);
523
- break;
524
- case "bundle_events":
525
- case "bundle_installations":
526
- case "api_keys":
527
- case "release_catalogs":
528
- case "releases":
529
- columns = Object.keys(input.data);
530
- values = Object.values(input.data);
531
- }
532
- const conflict = input.onConflict !== "ignore" ? "" : input.model === "channels" ? conflictMode === "ignore" ? " ON CONFLICT(name) DO NOTHING" : " ON CONFLICT(name) DO UPDATE SET name = excluded.name" : input.model === "api_keys" ? conflictMode === "ignore" ? " ON CONFLICT(hash) DO NOTHING" : " ON CONFLICT(hash) DO UPDATE SET hash = excluded.hash" : " ON CONFLICT(install_id) DO UPDATE SET install_id = excluded.install_id";
533
- return {
534
- sql: `INSERT INTO ${d1TableNames[input.model]} (${columns.join(", ")}) ${guard === void 0 ? `VALUES (${d1Placeholders(values.length)})` : `SELECT ${d1Placeholders(values.length)} WHERE ${guard.sql}`}${conflict} RETURNING *`,
535
- params: [...encodeD1Values(values), ...guard?.params ?? []]
536
- };
537
- };
538
- const updateEntries = (update) => Object.entries(update);
539
- const updateQuery = (input, guard) => {
540
- const entries = updateEntries(input.update);
541
- const where = buildD1Where(input.where);
542
- if (entries.length === 0) return {
543
- sql: `SELECT * FROM ${d1TableNames[input.model]}${where.sql}${guard ? ` AND ${guard.sql}` : ""} LIMIT 1`,
544
- params: [...where.params, ...guard?.params ?? []]
545
- };
546
- const assignments = entries.map(([field]) => `${field} = json_extract(?, '$')`).join(", ");
547
- return {
548
- sql: `UPDATE ${d1TableNames[input.model]} SET ${assignments}${where.sql}${guard ? ` AND ${guard.sql}` : ""} RETURNING *`,
549
- params: [
550
- ...encodeD1Values(entries.map(([, value]) => value)),
551
- ...where.params,
552
- ...guard?.params ?? []
553
- ]
554
- };
555
- };
556
- const deleteQuery = (input, guard) => {
557
- const where = buildD1Where(input.where);
558
- return {
559
- sql: `DELETE FROM ${d1TableNames[input.model]}${where.sql}${guard ? ` AND ${guard.sql}` : ""}`,
560
- params: [...where.params, ...guard?.params ?? []]
561
- };
562
- };
563
- const insertedKey = (change) => {
564
- if (change.operation !== "insert") return void 0;
565
- if (change.model === "bundles") return `bundles:${change.row.id}`;
566
- if (change.model === "apiKeys") return `api_keys:${change.row.id}`;
567
- if (change.model === "releases") return `releases:${change.row.id}`;
568
- };
569
- const requiredRow = (change, changeIndex) => {
570
- if (change.operation !== "update") return void 0;
571
- if (change.model === "bundles") return {
572
- model: "bundles",
573
- id: change.where.id,
574
- changeIndex
575
- };
576
- if (change.model === "apiKeys") return {
577
- model: "api_keys",
578
- id: change.where.id,
579
- changeIndex
580
- };
581
- if (change.model === "releases") return {
582
- model: "releases",
583
- id: change.where.id,
584
- changeIndex
585
- };
586
- };
587
- const channelDeletePrecondition = (changes, changeIndex, channelId) => {
588
- const releaseEffects = /* @__PURE__ */ new Map();
589
- for (const change of changes.slice(0, changeIndex)) {
590
- if (change.model !== "releases") continue;
591
- switch (change.operation) {
592
- case "insert":
593
- releaseEffects.set(change.row.id, change.row.channel_id);
594
- break;
595
- case "update": break;
596
- case "delete": releaseEffects.set(change.where.id, null);
597
- }
598
- }
599
- return {
600
- id: channelId,
601
- excludedReleaseIds: [...releaseEffects.keys()],
602
- addedReferenceReleaseIds: [...releaseEffects].filter(([, finalChannelId]) => finalChannelId === channelId).map(([releaseId]) => releaseId)
603
- };
604
- };
605
- const changeQuery = (change, guard) => {
606
- switch (change.model) {
607
- case "bundles": switch (change.operation) {
608
- case "insert": return insertQuery({
609
- model: "bundles",
610
- data: change.row
611
- }, guard);
612
- case "update": return updateQuery({
613
- model: "bundles",
614
- where: [{
615
- field: "id",
616
- value: change.where.id
617
- }],
618
- update: change.update
619
- }, guard);
620
- case "delete": return deleteQuery({
621
- model: "bundles",
622
- where: [{
623
- field: "id",
624
- value: change.where.id
625
- }]
626
- }, guard);
627
- }
628
- case "bundlePatches": return change.operation === "insert" ? insertQuery({
629
- model: "bundle_patches",
630
- data: change.row
631
- }, guard) : deleteQuery({
632
- model: "bundle_patches",
633
- where: [{
634
- field: "bundle_id",
635
- value: change.where.bundleId
636
- }]
637
- }, guard);
638
- case "releases": switch (change.operation) {
639
- case "insert": return insertQuery({
640
- model: "releases",
641
- data: change.row
642
- }, guard);
643
- case "update": return updateQuery({
644
- model: "releases",
645
- where: [{
646
- field: "id",
647
- value: change.where.id
648
- }],
649
- update: change.update
650
- }, guard);
651
- case "delete": return deleteQuery({
652
- model: "releases",
653
- where: [{
654
- field: "id",
655
- value: change.where.id
656
- }]
657
- }, guard);
658
- }
659
- case "releaseCatalogs": return {
660
- sql: `INSERT INTO release_catalogs (${Object.keys(change.row).join(", ")}) SELECT ${d1Placeholders(Object.keys(change.row).length)} WHERE ${guard.sql} ON CONFLICT(scope_key) DO UPDATE SET ${Object.keys(change.row).filter((field) => field !== "scope_key").map((field) => `${field} = excluded.${field}`).join(", ")} RETURNING *`,
661
- params: [...encodeD1Values(Object.values(change.row)), ...guard.params]
662
- };
663
- case "channels": return change.operation === "insert" ? insertQuery({
664
- model: "channels",
665
- data: change.row,
666
- onConflict: change.onConflict
667
- }, guard, "ignore") : {
668
- sql: `DELETE FROM channels WHERE id = json_extract(?, '$') AND NOT EXISTS (SELECT 1 FROM releases WHERE channel_id = json_extract(?, '$')) AND ${guard.sql}`,
669
- params: [...encodeD1Values([change.where.id, change.where.id]), ...guard.params]
670
- };
671
- case "apiKeys": return change.operation === "insert" ? insertQuery({
672
- model: "api_keys",
673
- data: change.row,
674
- onConflict: change.onConflict
675
- }, guard, "ignore") : updateQuery({
676
- model: "api_keys",
677
- where: [{
678
- field: "id",
679
- value: change.where.id
680
- }],
681
- update: { revoked_at_ms: change.update.revokedAtMs }
682
- }, guard);
683
- }
684
- };
685
- const createCommitPlan = (input) => {
686
- const checks = [];
687
- const statements = [];
688
- const expectations = input.expectations ?? [];
689
- if (expectations.length > 0) {
690
- const guard = expectationGuard(expectations);
691
- statements.push({
692
- sql: `SELECT CASE WHEN ${guard.sql} THEN 1 ELSE json_extract('${EXPECTATION_CONFLICT_MARKER}', '$') END AS expectation_guard`,
693
- params: guard.params
694
- });
695
- }
696
- const requiredRows = [];
697
- const channelDeletes = [];
698
- const inserted = /* @__PURE__ */ new Set();
699
- for (const [changeIndex, change] of input.changes.entries()) {
700
- const required = requiredRow(change, changeIndex);
701
- if (required !== void 0) {
702
- if (!inserted.has(`${required.model}:${required.id}`)) {
703
- requiredRows.push(required);
704
- checks.push({
705
- changeIndex,
706
- resultIndex: statements.length,
707
- conflictWhen: "empty",
708
- reason: "not_found"
709
- });
710
- statements.push({
711
- sql: `SELECT id FROM ${d1TableNames[required.model]} WHERE id = json_extract(?, '$') LIMIT 1`,
712
- params: encodeD1Values([required.id])
713
- });
714
- }
715
- }
716
- if (change.model === "channels" && change.operation === "delete") {
717
- const precondition = channelDeletePrecondition(input.changes, changeIndex, change.where.id);
718
- channelDeletes.push(precondition);
719
- checks.push({
720
- changeIndex,
721
- resultIndex: statements.length,
722
- conflictWhen: "nonempty",
723
- reason: "referenced"
724
- });
725
- statements.push({
726
- sql: "SELECT id FROM releases WHERE channel_id = json_extract(?, '$') AND id NOT IN (SELECT value FROM json_each(?)) UNION ALL SELECT value AS id FROM json_each(?) LIMIT 1",
727
- params: encodeD1Values([
728
- precondition.id,
729
- precondition.excludedReleaseIds,
730
- precondition.addedReferenceReleaseIds
731
- ])
732
- });
733
- }
734
- const key = insertedKey(change);
735
- if (key !== void 0) inserted.add(key);
736
- }
737
- const guard = {
738
- sql: `NOT EXISTS (
739
- SELECT 1 FROM json_each(?) AS required
740
- WHERE NOT EXISTS (
741
- SELECT 1 FROM bundles
742
- WHERE json_extract(required.value, '$.model') = 'bundles'
743
- AND bundles.id = json_extract(required.value, '$.id')
744
- UNION ALL
745
- SELECT 1 FROM api_keys
746
- WHERE json_extract(required.value, '$.model') = 'api_keys'
747
- AND api_keys.id = json_extract(required.value, '$.id')
748
- UNION ALL
749
- SELECT 1 FROM channels
750
- WHERE json_extract(required.value, '$.model') = 'channels'
751
- AND channels.id = json_extract(required.value, '$.id')
752
- UNION ALL
753
- SELECT 1 FROM releases
754
- WHERE json_extract(required.value, '$.model') = 'releases'
755
- AND releases.id = json_extract(required.value, '$.id')
756
- )
757
- ) AND NOT EXISTS (
758
- SELECT 1 FROM json_each(?) AS channel_delete
759
- WHERE EXISTS (
760
- SELECT 1 FROM releases
761
- WHERE releases.channel_id = json_extract(channel_delete.value, '$.id')
762
- AND releases.id NOT IN (
763
- SELECT value FROM json_each(
764
- json_extract(channel_delete.value, '$.excludedReleaseIds')
765
- )
766
- )
767
- UNION ALL
768
- SELECT value FROM json_each(
769
- json_extract(channel_delete.value, '$.addedReferenceReleaseIds')
770
- )
771
- )
772
- )`,
773
- params: encodeD1Values([requiredRows.map(({ model, id }) => ({
774
- model,
775
- id
776
- })), channelDeletes])
777
- };
778
- statements.push(...input.changes.map((change) => changeQuery(change, guard)));
779
- return {
780
- checks,
781
- statements
782
- };
783
- };
784
- const resultForPlan = (plan, results) => {
785
- const missing = plan.checks.find(({ conflictWhen, resultIndex }) => conflictWhen === "empty" ? (results[resultIndex]?.length ?? 0) === 0 : (results[resultIndex]?.length ?? 0) > 0);
786
- return missing === void 0 ? { committed: true } : {
787
- committed: false,
788
- conflict: {
789
- changeIndex: missing.changeIndex,
790
- reason: missing.reason
791
- }
792
- };
793
- };
794
- const insertChannel = async (executor, input) => {
795
- const insert = insertQuery({
796
- model: "channels",
797
- data: input.row,
798
- onConflict: "ignore"
799
- }, void 0, "ignore");
800
- const select = {
801
- sql: "SELECT id, name FROM channels WHERE name = json_extract(?, '$') LIMIT 1",
802
- params: encodeD1Values([input.row.name])
803
- };
804
- const [insertedRows = [], canonicalRows = []] = await executor.batch([insert, select]);
805
- return {
806
- row: parseD1Row("channels", canonicalRows[0]),
807
- inserted: insertedRows.length > 0
808
- };
809
- };
810
- const deleteChannel = async (executor, input) => {
811
- const [channelRows = [], referenceRows = [], deletedRows = []] = await executor.batch([
812
- {
813
- sql: "SELECT id FROM channels WHERE id = json_extract(?, '$') LIMIT 1",
814
- params: encodeD1Values([input.id])
815
- },
816
- {
817
- sql: "SELECT id FROM releases WHERE channel_id = json_extract(?, '$') LIMIT 1",
818
- params: encodeD1Values([input.id])
819
- },
820
- {
821
- sql: "DELETE FROM channels WHERE id = json_extract(?, '$') AND NOT EXISTS (SELECT 1 FROM releases WHERE channel_id = json_extract(?, '$')) RETURNING id",
822
- params: encodeD1Values([input.id, input.id])
823
- }
824
- ]);
825
- if (channelRows.length === 0) return {
826
- deleted: false,
827
- reason: "not_found"
828
- };
829
- if (referenceRows.length > 0) return {
830
- deleted: false,
831
- reason: "not_empty"
832
- };
833
- return deletedRows.length > 0 ? { deleted: true } : {
834
- deleted: false,
835
- reason: "not_empty"
836
- };
837
- };
838
- const createD1Implementation = (executor) => ({
839
- async recordInsights({ event, installation }) {
840
- const columns = Object.keys(installation);
841
- const eventInsert = insertQuery({
842
- model: "bundle_events",
843
- data: event
844
- });
845
- await executor.batch([{
846
- sql: `INSERT INTO bundle_installations (${columns.join(", ")})
847
- SELECT ${d1Placeholders(columns.length)}
848
- WHERE NOT EXISTS (SELECT 1 FROM bundle_events WHERE id = json_extract(?, '$'))
849
- ON CONFLICT(install_id) DO UPDATE SET ${columns.filter((column) => column !== "install_id").map((column) => `${column} = excluded.${column}`).join(", ")}
850
- WHERE (excluded.received_at_ms, excluded.id) >
851
- (bundle_installations.received_at_ms, bundle_installations.id)`,
852
- params: encodeD1Values([...Object.values(installation), event.id])
853
- }, {
854
- ...eventInsert,
855
- sql: eventInsert.sql.replace(" RETURNING *", " ON CONFLICT(id) DO NOTHING")
856
- }]);
857
- },
858
- async create(input) {
859
- const query = insertQuery(input);
860
- const rows = await executor.query(query.sql, query.params);
861
- switch (input.model) {
862
- case "bundles": return parseD1Row("bundles", rows[0]);
863
- case "bundle_patches": return parseD1Row("bundle_patches", rows[0]);
864
- case "channels": return parseD1Row("channels", rows[0]);
865
- case "bundle_events": return parseD1Row("bundle_events", rows[0]);
866
- case "bundle_installations": return parseD1Row("bundle_installations", rows[0]);
867
- case "api_keys": return parseD1Row("api_keys", rows[0]);
868
- case "releases": return parseD1Row("releases", rows[0]);
869
- case "release_catalogs": return parseD1Row("release_catalogs", rows[0]);
870
- }
871
- },
872
- async update(input) {
873
- const query = updateQuery(input);
874
- const rows = await executor.query(query.sql, query.params);
875
- if (rows[0] === void 0) return null;
876
- switch (input.model) {
877
- case "bundles": return parseD1Row("bundles", rows[0]);
878
- case "api_keys": return parseD1Row("api_keys", rows[0]);
879
- case "releases": return parseD1Row("releases", rows[0]);
880
- case "release_catalogs": return parseD1Row("release_catalogs", rows[0]);
881
- case "bundle_installations": return parseD1Row("bundle_installations", rows[0]);
882
- }
883
- },
884
- async delete(input) {
885
- const query = deleteQuery(input);
886
- await executor.query(query.sql, query.params);
887
- },
888
- count: (input) => countD1Rows(executor, input),
889
- async findOne(input) {
890
- const where = buildD1Where(input.where);
891
- const rows = await executor.query(`SELECT * FROM ${d1TableNames[input.model]}${where.sql} LIMIT 1`, where.params);
892
- if (rows[0] === void 0) return null;
893
- switch (input.model) {
894
- case "bundles": return parseD1Row("bundles", rows[0]);
895
- case "bundle_patches": return parseD1Row("bundle_patches", rows[0]);
896
- case "channels": return parseD1Row("channels", rows[0]);
897
- case "api_keys": return parseD1Row("api_keys", rows[0]);
898
- case "releases": return parseD1Row("releases", rows[0]);
899
- case "release_catalogs": return parseD1Row("release_catalogs", rows[0]);
900
- case "bundle_installations": return parseD1Row("bundle_installations", rows[0]);
901
- }
902
- },
903
- findMany: (input) => findManyD1Rows(executor, input),
904
- insertChannel: (input) => insertChannel(executor, input),
905
- deleteChannel: (input) => deleteChannel(executor, input),
906
- async commit(input) {
907
- if (input.changes.length === 0) return { committed: true };
908
- const expectations = input.expectations ?? [];
909
- const conflict = await expectationConflict(executor, expectations);
910
- if (conflict !== null) return conflict;
911
- const plan = createCommitPlan(input);
912
- try {
913
- return resultForPlan(plan, await executor.batch(plan.statements));
914
- } catch (error) {
915
- if (expectations.length === 0 || !isExpectationConflictError(error)) throw error;
916
- return await expectationConflict(executor, expectations) ?? {
917
- committed: false,
918
- conflict: {
919
- actualVersion: expectations[0].model === "releases" ? expectations[0].revision : expectations[0].generation,
920
- changeIndex: -1,
921
- expectedVersion: expectations[0].model === "releases" ? expectations[0].revision : expectations[0].generation,
922
- key: expectations[0].model === "releases" ? expectations[0].id : expectations[0].scopeKey,
923
- model: expectations[0].model,
924
- reason: "version_conflict"
48
+ const code = /UNIQUE constraint failed|constraint failed: .*PRIMARY/iu.test(message) ? "SQLITE_CONSTRAINT_UNIQUE" : /SQLITE_BUSY|database is locked/iu.test(message) ? "SQLITE_BUSY" : void 0;
49
+ return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
50
+ };
51
+ /**
52
+ * Hot Updater's database on D1: the storage engine through the shared SQL
53
+ * core, fenced by the schema settings. D1 has no interactive transactions,
54
+ * so each write is one atomic batch that evaluates its guards first
55
+ * (`_hu_write`).
56
+ */
57
+ const createD1Database = (runner) => {
58
+ return (0, _hot_updater_plugin_core.createEngineDatabase)({
59
+ name: "d1Database",
60
+ adapter: (0, _hot_updater_plugin_core.createSqlAdapter)({
61
+ executor: {
62
+ dialect: "sqlite",
63
+ execute: (statement) => runner.query(statement).catch((error) => {
64
+ throw withSqliteCode(error);
65
+ }),
66
+ batch: (statements) => runner.batch(statements).catch((error) => {
67
+ throw withSqliteCode(error);
68
+ }),
69
+ transaction: () => {
70
+ throw new Error("D1 has no interactive transactions; writes are batches.");
925
71
  }
926
- };
927
- }
928
- }
929
- });
72
+ },
73
+ maxOps: 450,
74
+ maxParams: 100
75
+ })
76
+ });
77
+ };
78
+ //#endregion
79
+ //#region src/d1Schema.ts
80
+ /**
81
+ * D1's schema: the guard table batch writes need, then the shared SQL
82
+ * schema of core and the target's plugins, settings last. Every statement can
83
+ * run again, so a migration for a server's plugin tables repeats core's.
84
+ */
85
+ const d1SchemaStatements = ({ schema, settings } = _hot_updater_plugin_core.coreTarget) => [...(0, _hot_updater_plugin_core.createTableStatements)("sqlite", [_hot_updater_plugin_core.WRITE_GUARD_TABLE]), ...(0, _hot_updater_plugin_core.generateEngineSql)("sqlite", schema, settings)];
86
+ /** The schema as a D1 migration, which `wrangler d1 migrations apply` runs. */
87
+ const d1SchemaSql = (target) => `-- HotUpdater.schema\n\n${d1SchemaStatements(target).map((statement) => `${statement};`).join("\n\n")}\n`;
930
88
  //#endregion
931
89
  //#region src/d1Database.ts
90
+ /** The REST API binds text: each value goes as JSON and is read back with `json_extract`. */
91
+ const encode = ({ sql, params }) => ({
92
+ sql: sql.replaceAll("?", () => "json_extract(?, '$')"),
93
+ params: params.map((value) => JSON.stringify(value ?? null))
94
+ });
95
+ /**
96
+ * Hot Updater's database on D1 through the Cloudflare REST API, for the CLI
97
+ * and console. `hot-updater db generate` writes a D1 migration of the built-in
98
+ * tables and the server's plugin tables to `migrations`, and
99
+ * `hot-updater db migrate` applies them through the API.
100
+ */
932
101
  const d1Database = (config) => {
933
102
  const cloudflare$1 = new cloudflare.default({ apiToken: config.cloudflareApiToken });
934
103
  const execute = async (statements) => {
935
- const first = statements[0];
104
+ const [first] = statements;
936
105
  if (first === void 0) return [];
937
106
  const body = statements.length === 1 ? {
938
107
  account_id: config.accountId,
939
- sql: first.sql,
940
- params: [...first.params]
108
+ ...encode(first)
941
109
  } : {
942
110
  account_id: config.accountId,
943
- batch: statements.map(({ sql, params }) => ({
944
- sql,
945
- params: [...params]
946
- }))
111
+ batch: statements.map(encode)
947
112
  };
948
- const page = await cloudflare$1.d1.database.query(config.databaseId, { ...body });
113
+ const page = await cloudflare$1.d1.database.query(config.databaseId, body);
949
114
  const results = [];
950
- for await (const resultPage of page.iterPages()) for (const result of resultPage.result) {
951
- if (result.success === false) throw new D1ExecutionError();
952
- results.push(result.results ?? []);
953
- }
115
+ for await (const resultPage of page.iterPages()) for (const result of resultPage.result) results.push(toSqlResult(result));
954
116
  if (results.length !== statements.length) throw new D1ExecutionError();
955
117
  return results;
956
118
  };
957
- const adapter = (0, _hot_updater_plugin_core_internal.createDatabasePluginAdapter)("d1Database", createD1Implementation({
958
- async query(sql, params) {
959
- return (await execute([{
960
- sql,
961
- params
962
- }])).flat();
963
- },
964
- batch: execute
965
- }));
966
- return (0, _hot_updater_plugin_core.createDatabasePlugin)({
967
- name: "d1Database",
968
- models: adapter.models,
969
- commit: adapter.commit,
970
- ...adapter.dispose ? { dispose: adapter.dispose } : {}
971
- });
119
+ return {
120
+ ...createD1Database({
121
+ query: async (statement) => (await execute([statement]))[0],
122
+ batch: execute
123
+ }),
124
+ generateSchema: ((version, _name, target = _hot_updater_plugin_core.coreTarget) => {
125
+ if (version !== "latest" && version !== _hot_updater_plugin_core.coreSettings["schema.core"]) throw new Error(`Invalid version ${version}`);
126
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14);
127
+ return {
128
+ code: d1SchemaSql(target),
129
+ path: `migrations/${timestamp}_hot-updater.sql`
130
+ };
131
+ })
132
+ };
972
133
  };
973
134
  //#endregion
974
135
  //#region src/r2S3Storage.ts
@@ -991,7 +152,7 @@ const createR2S3Storage = (config) => {
991
152
  if (parsed.bucket !== bucketName) throw new Error(`Bucket name mismatch: expected "${bucketName}", but found "${parsed.bucket}".`);
992
153
  return parsed;
993
154
  };
994
- return (0, _hot_updater_plugin_core.createStoragePlugin)({
155
+ return (0, _hot_updater_plugin_core.createStorageAdapter)({
995
156
  name: "r2Storage",
996
157
  protocol: "r2",
997
158
  async put({ key, body, contentLength, contentType }) {
@@ -1064,5 +225,14 @@ const r2Storage = (config) => {
1064
225
  return createR2S3Storage(config);
1065
226
  };
1066
227
  //#endregion
228
+ //#region src/plugins.ts
229
+ /**
230
+ * The plugins the managed Cloudflare server runs: Insights, and API keys on every
231
+ * client route. Its Worker imports this list.
232
+ */
233
+ const plugins = [(0, _hot_updater_server_plugins_insights.insights)(), (0, _hot_updater_server_plugins_api_keys.apiKeys)()];
234
+ //#endregion
235
+ exports.D1ExecutionError = D1ExecutionError;
1067
236
  exports.d1Database = d1Database;
237
+ exports.plugins = plugins;
1068
238
  exports.r2Storage = r2Storage;