@hot-updater/cloudflare 0.29.2 → 0.29.4

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.
@@ -1,6 +1,7 @@
1
1
  import type { DatabasePlugin } from "@hot-updater/plugin-core";
2
2
  import { setupBundleMethodsTestSuite } from "@hot-updater/test-utils";
3
- import { beforeEach, describe, vi } from "vitest";
3
+ import { beforeEach, describe, expect, it, vi } from "vitest";
4
+
4
5
  import { d1Database } from "./d1Database";
5
6
 
6
7
  type D1Row = {
@@ -40,6 +41,18 @@ const getFilteredRows = (sql: string, params: any[]) => {
40
41
  let filteredRows = Array.from(rows.values());
41
42
  let index = 0;
42
43
 
44
+ const consumeInValues = (pattern: RegExp) => {
45
+ const match = sql.match(pattern);
46
+ if (!match) {
47
+ return null;
48
+ }
49
+
50
+ const count = (match[1]?.match(/\?/g) ?? []).length;
51
+ const values = params.slice(index, index + count);
52
+ index += count;
53
+ return values;
54
+ };
55
+
43
56
  if (sql.includes("channel = ?")) {
44
57
  const channel = params[index++];
45
58
  filteredRows = filteredRows.filter((row) => row.channel === channel);
@@ -50,6 +63,78 @@ const getFilteredRows = (sql: string, params: any[]) => {
50
63
  filteredRows = filteredRows.filter((row) => row.platform === platform);
51
64
  }
52
65
 
66
+ if (sql.includes("enabled = ?")) {
67
+ const enabled = Number(params[index++]);
68
+ filteredRows = filteredRows.filter(
69
+ (row) => Number(row.enabled) === enabled,
70
+ );
71
+ }
72
+
73
+ const idInValues = consumeInValues(/id IN \(([^)]+)\)/);
74
+ if (idInValues) {
75
+ filteredRows = filteredRows.filter((row) => idInValues.includes(row.id));
76
+ }
77
+
78
+ if (sql.includes("id = ?")) {
79
+ const id = params[index++];
80
+ filteredRows = filteredRows.filter((row) => row.id === id);
81
+ }
82
+
83
+ if (sql.includes("id > ?")) {
84
+ const id = params[index++];
85
+ filteredRows = filteredRows.filter((row) => row.id.localeCompare(id) > 0);
86
+ }
87
+
88
+ if (sql.includes("id >= ?")) {
89
+ const id = params[index++];
90
+ filteredRows = filteredRows.filter((row) => row.id.localeCompare(id) >= 0);
91
+ }
92
+
93
+ if (sql.includes("id < ?")) {
94
+ const id = params[index++];
95
+ filteredRows = filteredRows.filter((row) => row.id.localeCompare(id) < 0);
96
+ }
97
+
98
+ if (sql.includes("id <= ?")) {
99
+ const id = params[index++];
100
+ filteredRows = filteredRows.filter((row) => row.id.localeCompare(id) <= 0);
101
+ }
102
+
103
+ if (sql.includes("target_app_version IS NOT NULL")) {
104
+ filteredRows = filteredRows.filter(
105
+ (row) => row.target_app_version !== null,
106
+ );
107
+ }
108
+
109
+ if (sql.includes("target_app_version IS NULL")) {
110
+ filteredRows = filteredRows.filter(
111
+ (row) => row.target_app_version === null,
112
+ );
113
+ } else if (sql.includes("target_app_version = ?")) {
114
+ const targetAppVersion = params[index++];
115
+ filteredRows = filteredRows.filter(
116
+ (row) => row.target_app_version === targetAppVersion,
117
+ );
118
+ }
119
+
120
+ const targetAppVersionInValues = consumeInValues(
121
+ /target_app_version IN \(([^)]+)\)/,
122
+ );
123
+ if (targetAppVersionInValues) {
124
+ filteredRows = filteredRows.filter((row) =>
125
+ targetAppVersionInValues.includes(row.target_app_version),
126
+ );
127
+ }
128
+
129
+ if (sql.includes("fingerprint_hash IS NULL")) {
130
+ filteredRows = filteredRows.filter((row) => row.fingerprint_hash === null);
131
+ } else if (sql.includes("fingerprint_hash = ?")) {
132
+ const fingerprintHash = params[index++];
133
+ filteredRows = filteredRows.filter(
134
+ (row) => row.fingerprint_hash === fingerprintHash,
135
+ );
136
+ }
137
+
53
138
  return { filteredRows, index };
54
139
  };
55
140
 
@@ -170,4 +255,44 @@ describe("d1Database plugin", () => {
170
255
  await plugin.commitBundle();
171
256
  },
172
257
  });
258
+
259
+ it("refreshes bundle data before merging an update after a previous list request", async () => {
260
+ const bundleId = "bundle-stale-cache";
261
+ const initialRow: D1Row = {
262
+ id: bundleId,
263
+ channel: "production",
264
+ enabled: 1,
265
+ should_force_update: 0,
266
+ file_hash: "hash-1",
267
+ git_commit_hash: "commit-1",
268
+ message: "stale message",
269
+ platform: "ios",
270
+ target_app_version: "1.0.0",
271
+ storage_uri: "s3://bucket/stale.zip",
272
+ fingerprint_hash: null,
273
+ metadata: JSON.stringify({ source: "initial" }),
274
+ rollout_cohort_count: 1000,
275
+ target_cohorts: null,
276
+ };
277
+ rows.set(bundleId, initialRow);
278
+
279
+ await plugin.getBundles({ limit: 20, offset: 0 });
280
+
281
+ rows.set(bundleId, {
282
+ ...initialRow,
283
+ message: "fresh message",
284
+ metadata: JSON.stringify({ source: "fresh" }),
285
+ });
286
+
287
+ await plugin.updateBundle(bundleId, { enabled: false });
288
+ await plugin.commitBundle();
289
+
290
+ expect(rows.get(bundleId)).toEqual(
291
+ expect.objectContaining({
292
+ enabled: 0,
293
+ message: "fresh message",
294
+ metadata: JSON.stringify({ source: "fresh" }),
295
+ }),
296
+ );
297
+ });
173
298
  });
package/src/d1Database.ts CHANGED
@@ -176,7 +176,6 @@ function transformRowToBundle(row: SnakeCaseBundle): Bundle {
176
176
  export const d1Database = createDatabasePlugin<D1DatabaseConfig>({
177
177
  name: "d1Database",
178
178
  factory: (config) => {
179
- let bundles: Bundle[] = [];
180
179
  const cf = new Cloudflare({
181
180
  apiToken: config.cloudflareApiToken,
182
181
  });
@@ -233,11 +232,6 @@ export const d1Database = createDatabasePlugin<D1DatabaseConfig>({
233
232
 
234
233
  return {
235
234
  async getBundleById(bundleId) {
236
- const found = bundles.find((b) => b.id === bundleId);
237
- if (found) {
238
- return found;
239
- }
240
-
241
235
  const sql = minify(/* sql */ `
242
236
  SELECT * FROM bundles WHERE id = ? LIMIT 1`);
243
237
  const singlePage = await cf.d1.database.query(config.databaseId, {
@@ -262,7 +256,12 @@ export const d1Database = createDatabasePlugin<D1DatabaseConfig>({
262
256
  const totalCount = await getTotalCount(where);
263
257
 
264
258
  // 2. Get paginated bundles
265
- bundles = await getPaginatedBundles(where, limit, offset, orderBy);
259
+ const bundles = await getPaginatedBundles(
260
+ where,
261
+ limit,
262
+ offset,
263
+ orderBy,
264
+ );
266
265
 
267
266
  // 3. Calculate pagination metadata
268
267
  const paginationOptions: PaginationOptions = { limit, offset };
@@ -306,9 +305,6 @@ export const d1Database = createDatabasePlugin<D1DatabaseConfig>({
306
305
  sql: deleteSql,
307
306
  params: [op.data.id],
308
307
  });
309
-
310
- // Update local bundles array
311
- bundles = bundles.filter((b) => b.id !== op.data.id);
312
308
  } else if (op.operation === "insert" || op.operation === "update") {
313
309
  // Handle insert and update operations
314
310
  const bundle = op.data;
package/src/r2Storage.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import path from "path";
2
+
1
3
  import {
2
4
  createStorageKeyBuilder,
3
5
  createStoragePlugin,
@@ -6,7 +8,6 @@ import {
6
8
  } from "@hot-updater/plugin-core";
7
9
  import { ExecaError } from "execa";
8
10
 
9
- import path from "path";
10
11
  import { createWrangler } from "./utils/createWrangler";
11
12
 
12
13
  export interface R2StorageConfig {
@@ -44,8 +44,8 @@ const resolveJwtSecretFromContext = (
44
44
  };
45
45
 
46
46
  export const r2WorkerStorage = <
47
- TContext extends
48
- RequestEnvContext<CloudflareWorkerStorageEnv> = RequestEnvContext<CloudflareWorkerStorageEnv>,
47
+ TContext extends RequestEnvContext<CloudflareWorkerStorageEnv> =
48
+ RequestEnvContext<CloudflareWorkerStorageEnv>,
49
49
  >(
50
50
  config: CloudflareWorkerStorageConfig<TContext>,
51
51
  ) => {
@@ -1,6 +1,7 @@
1
1
  export { verifyJwtSignedUrl } from "@hot-updater/js";
2
2
 
3
3
  import type { RequestEnvContext as BaseRequestEnvContext } from "@hot-updater/plugin-core";
4
+
4
5
  import {
5
6
  type CloudflareWorkerDatabaseEnv,
6
7
  d1WorkerDatabase,
@@ -14,20 +15,19 @@ import {
14
15
  export type { CloudflareWorkerDatabaseEnv, CloudflareWorkerStorageEnv };
15
16
 
16
17
  export interface CloudflareWorkerRuntimeEnv
17
- extends CloudflareWorkerDatabaseEnv,
18
- CloudflareWorkerStorageEnv {}
18
+ extends CloudflareWorkerDatabaseEnv, CloudflareWorkerStorageEnv {}
19
19
 
20
20
  export type RequestEnvContext<TEnv = CloudflareWorkerRuntimeEnv> =
21
21
  BaseRequestEnvContext<TEnv>;
22
22
 
23
23
  export const d1Database = <
24
- TContext extends
25
- RequestEnvContext<CloudflareWorkerRuntimeEnv> = RequestEnvContext<CloudflareWorkerRuntimeEnv>,
24
+ TContext extends RequestEnvContext<CloudflareWorkerRuntimeEnv> =
25
+ RequestEnvContext<CloudflareWorkerRuntimeEnv>,
26
26
  >() => d1WorkerDatabase<TContext>();
27
27
 
28
28
  export const r2Storage = <
29
- TContext extends
30
- RequestEnvContext<CloudflareWorkerRuntimeEnv> = RequestEnvContext<CloudflareWorkerRuntimeEnv>,
29
+ TContext extends RequestEnvContext<CloudflareWorkerRuntimeEnv> =
30
+ RequestEnvContext<CloudflareWorkerRuntimeEnv>,
31
31
  >(
32
32
  config: CloudflareWorkerStorageConfig<TContext>,
33
33
  ) => r2WorkerStorage<TContext>(config);
@@ -1 +1 @@
1
- This folder contains the built output assets for the worker "hot-updater" generated at 2026-04-03T14:22:57.023Z.
1
+ This folder contains the built output assets for the worker "hot-updater" generated at 2026-04-07T10:08:43.621Z.
@@ -3326,12 +3326,12 @@ function mergeBundleUpdate(baseBundle, patch) {
3326
3326
  __name(mergeBundleUpdate, "mergeBundleUpdate");
3327
3327
  function createDatabasePlugin(options) {
3328
3328
  return (config2, hooks) => {
3329
+ let cachedMethods = null;
3330
+ const getMethods = /* @__PURE__ */ __name(() => {
3331
+ if (!cachedMethods) cachedMethods = options.factory(config2);
3332
+ return cachedMethods;
3333
+ }, "getMethods");
3329
3334
  return () => {
3330
- let cachedMethods = null;
3331
- const getMethods = /* @__PURE__ */ __name(() => {
3332
- if (!cachedMethods) cachedMethods = options.factory(config2);
3333
- return cachedMethods;
3334
- }, "getMethods");
3335
3335
  const changedMap = /* @__PURE__ */ new Map();
3336
3336
  const markChanged = /* @__PURE__ */ __name((operation, data) => {
3337
3337
  changedMap.set(data.id, {
@@ -3362,8 +3362,8 @@ function createDatabasePlugin(options) {
3362
3362
  const params = { changedSets: Array.from(changedMap.values()) };
3363
3363
  if (context2 === void 0) await methods.commitBundle(params);
3364
3364
  else await methods.commitBundle(params, context2);
3365
- await hooks?.onDatabaseUpdated?.();
3366
3365
  changedMap.clear();
3366
+ await hooks?.onDatabaseUpdated?.();
3367
3367
  },
3368
3368
  async updateBundle(targetBundleId, newBundle, context2) {
3369
3369
  const pendingChange = changedMap.get(targetBundleId);
@@ -3460,18 +3460,28 @@ var INIT_BUNDLE_ROLLBACK_UPDATE_INFO = {
3460
3460
  storageUri: null,
3461
3461
  fileHash: null
3462
3462
  };
3463
- function createPluginDatabaseCore(plugin, resolveFileUrl) {
3464
- const getSortedBundlePage = /* @__PURE__ */ __name(async (options, context2) => {
3465
- const result = await plugin.getBundles(
3463
+ function createPluginDatabaseCore(getPlugin, resolveFileUrl, options) {
3464
+ const runWithMutationPlugin = /* @__PURE__ */ __name(async (operation) => {
3465
+ const plugin = options?.createMutationPlugin?.() ?? getPlugin();
3466
+ try {
3467
+ return await operation(plugin);
3468
+ } finally {
3469
+ if (options?.createMutationPlugin) {
3470
+ await options.cleanupMutationPlugin?.(plugin);
3471
+ }
3472
+ }
3473
+ }, "runWithMutationPlugin");
3474
+ const getSortedBundlePage = /* @__PURE__ */ __name(async (options2, context2) => {
3475
+ const result = await getPlugin().getBundles(
3466
3476
  {
3467
- ...options,
3468
- orderBy: options.orderBy ?? DESC_ORDER
3477
+ ...options2,
3478
+ orderBy: options2.orderBy ?? DESC_ORDER
3469
3479
  },
3470
3480
  context2
3471
3481
  );
3472
3482
  return {
3473
3483
  ...result,
3474
- data: sortBundles(result.data, options.orderBy ?? DESC_ORDER)
3484
+ data: sortBundles(result.data, options2.orderBy ?? DESC_ORDER)
3475
3485
  };
3476
3486
  }, "getSortedBundlePage");
3477
3487
  const isEligibleForUpdate = /* @__PURE__ */ __name((bundle, cohort) => {
@@ -3551,7 +3561,7 @@ function createPluginDatabaseCore(plugin, resolveFileUrl) {
3551
3561
  }), "getBaseWhere");
3552
3562
  const api = {
3553
3563
  async getBundleById(id, context2) {
3554
- return plugin.getBundleById(id, context2);
3564
+ return getPlugin().getBundleById(id, context2);
3555
3565
  },
3556
3566
  async getUpdateInfo(args, context2) {
3557
3567
  const channel2 = args.channel ?? "production";
@@ -3595,31 +3605,37 @@ function createPluginDatabaseCore(plugin, resolveFileUrl) {
3595
3605
  return { ...rest, fileUrl };
3596
3606
  },
3597
3607
  async getChannels(context2) {
3598
- return plugin.getChannels(context2);
3608
+ return getPlugin().getChannels(context2);
3599
3609
  },
3600
- async getBundles(options, context2) {
3601
- return plugin.getBundles(options, context2);
3610
+ async getBundles(options2, context2) {
3611
+ return getPlugin().getBundles(options2, context2);
3602
3612
  },
3603
3613
  async insertBundle(bundle, context2) {
3604
- await plugin.appendBundle(bundle, context2);
3605
- await plugin.commitBundle(context2);
3614
+ await runWithMutationPlugin(async (plugin) => {
3615
+ await plugin.appendBundle(bundle, context2);
3616
+ await plugin.commitBundle(context2);
3617
+ });
3606
3618
  },
3607
3619
  async updateBundleById(bundleId, newBundle, context2) {
3608
- await plugin.updateBundle(bundleId, newBundle, context2);
3609
- await plugin.commitBundle(context2);
3620
+ await runWithMutationPlugin(async (plugin) => {
3621
+ await plugin.updateBundle(bundleId, newBundle, context2);
3622
+ await plugin.commitBundle(context2);
3623
+ });
3610
3624
  },
3611
3625
  async deleteBundleById(bundleId, context2) {
3612
- const bundle = await plugin.getBundleById(bundleId, context2);
3613
- if (!bundle) {
3614
- return;
3615
- }
3616
- await plugin.deleteBundle(bundle, context2);
3617
- await plugin.commitBundle(context2);
3626
+ await runWithMutationPlugin(async (plugin) => {
3627
+ const bundle = await plugin.getBundleById(bundleId, context2);
3628
+ if (!bundle) {
3629
+ return;
3630
+ }
3631
+ await plugin.deleteBundle(bundle, context2);
3632
+ await plugin.commitBundle(context2);
3633
+ });
3618
3634
  }
3619
3635
  };
3620
3636
  return {
3621
3637
  api,
3622
- adapterName: plugin.name,
3638
+ adapterName: getPlugin().name,
3623
3639
  createMigrator: /* @__PURE__ */ __name(() => {
3624
3640
  throw new Error(
3625
3641
  "createMigrator is only available for Kysely/Prisma/Drizzle database adapters."
@@ -3856,7 +3872,7 @@ var handleGetBundles = /* @__PURE__ */ __name(async (_params, request, api, cont
3856
3872
  },
3857
3873
  context2
3858
3874
  );
3859
- return new Response(JSON.stringify(result.data), {
3875
+ return new Response(JSON.stringify(result), {
3860
3876
  status: 200,
3861
3877
  headers: { "Content-Type": "application/json" }
3862
3878
  });
@@ -3893,7 +3909,12 @@ var handleDeleteBundle = /* @__PURE__ */ __name(async (params, _request, api, co
3893
3909
  }, "handleDeleteBundle");
3894
3910
  var handleGetChannels = /* @__PURE__ */ __name(async (_params, _request, api, context2) => {
3895
3911
  const channels = await api.getChannels(context2);
3896
- return new Response(JSON.stringify({ channels }), {
3912
+ const response = {
3913
+ data: {
3914
+ channels
3915
+ }
3916
+ };
3917
+ return new Response(JSON.stringify(response), {
3897
3918
  status: 200,
3898
3919
  headers: { "Content-Type": "application/json" }
3899
3920
  });
@@ -4006,6 +4027,7 @@ var normalizeBasePath = /* @__PURE__ */ __name((basePath) => {
4006
4027
 
4007
4028
  // ../../packages/server/src/runtime.ts
4008
4029
  function createHotUpdater(options) {
4030
+ const database = options.database;
4009
4031
  const basePath = normalizeBasePath(options.basePath ?? "/api");
4010
4032
  const storagePlugins = (options.storages ?? options.storagePlugins ?? []).map(
4011
4033
  (plugin2) => typeof plugin2 === "function" ? plugin2() : plugin2
@@ -4031,15 +4053,18 @@ function createHotUpdater(options) {
4031
4053
  }
4032
4054
  return fileUrl;
4033
4055
  }, "resolveStoragePluginUrl");
4034
- if (!isDatabasePluginFactory(options.database) && !isDatabasePlugin(options.database)) {
4056
+ if (!isDatabasePluginFactory(database) && !isDatabasePlugin(database)) {
4035
4057
  throw new Error(
4036
4058
  "@hot-updater/server/runtime only supports database plugins."
4037
4059
  );
4038
4060
  }
4039
- const plugin = isDatabasePluginFactory(options.database) ? options.database() : options.database;
4061
+ const plugin = isDatabasePluginFactory(database) ? database() : database;
4040
4062
  const core = createPluginDatabaseCore(
4041
- plugin,
4042
- resolveStoragePluginUrl
4063
+ () => plugin,
4064
+ resolveStoragePluginUrl,
4065
+ isDatabasePluginFactory(database) ? {
4066
+ createMutationPlugin: /* @__PURE__ */ __name(() => database(), "createMutationPlugin")
4067
+ } : void 0
4043
4068
  );
4044
4069
  const api = {
4045
4070
  ...core.api,
@@ -8828,7 +8853,6 @@ var resolveDbFromContext = /* @__PURE__ */ __name((context2) => {
8828
8853
  var d1WorkerDatabase = /* @__PURE__ */ __name(() => createDatabasePlugin({
8829
8854
  name: "d1WorkerDatabase",
8830
8855
  factory: /* @__PURE__ */ __name((config2) => {
8831
- let bundles = [];
8832
8856
  const queryAll = /* @__PURE__ */ __name(async (sql, params = [], context2) => {
8833
8857
  const result = await config2.getDb(context2).prepare(sql).bind(...params).all();
8834
8858
  return result.results ?? [];
@@ -8839,10 +8863,6 @@ var d1WorkerDatabase = /* @__PURE__ */ __name(() => createDatabasePlugin({
8839
8863
  }, "queryFirst");
8840
8864
  return {
8841
8865
  async getBundleById(bundleId, context2) {
8842
- const found = bundles.find((bundle) => bundle.id === bundleId);
8843
- if (found) {
8844
- return found;
8845
- }
8846
8866
  const row = await queryFirst(
8847
8867
  "SELECT * FROM bundles WHERE id = ? LIMIT 1",
8848
8868
  [bundleId],
@@ -8865,7 +8885,7 @@ var d1WorkerDatabase = /* @__PURE__ */ __name(() => createDatabasePlugin({
8865
8885
  [...params, limit, offset],
8866
8886
  context2
8867
8887
  );
8868
- bundles = rows.map(transformRowToBundle);
8888
+ const bundles = rows.map(transformRowToBundle);
8869
8889
  const paginationOptions = { limit, offset };
8870
8890
  return {
8871
8891
  data: bundles,
@@ -8888,9 +8908,6 @@ var d1WorkerDatabase = /* @__PURE__ */ __name(() => createDatabasePlugin({
8888
8908
  for (const operation of changedSets) {
8889
8909
  if (operation.operation === "delete") {
8890
8910
  await db.prepare("DELETE FROM bundles WHERE id = ?").bind(operation.data.id).run();
8891
- bundles = bundles.filter(
8892
- (bundle2) => bundle2.id !== operation.data.id
8893
- );
8894
8911
  continue;
8895
8912
  }
8896
8913
  const bundle = operation.data;