@hot-updater/cloudflare 1.0.0-rc.5 → 1.0.0

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