@hot-updater/server 1.0.0-rc.2 → 1.0.0-rc.21

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 (328) hide show
  1. package/LICENSE +12 -14
  2. package/dist/adapters/drizzle.cjs +32 -75
  3. package/dist/adapters/drizzle.d.cts +13 -5
  4. package/dist/adapters/drizzle.d.mts +13 -5
  5. package/dist/adapters/drizzle.mjs +32 -77
  6. package/dist/adapters/drizzleExecutor.cjs +114 -0
  7. package/dist/adapters/drizzleExecutor.d.cts +9 -0
  8. package/dist/adapters/drizzleExecutor.d.mts +9 -0
  9. package/dist/adapters/drizzleExecutor.mjs +112 -0
  10. package/dist/adapters/kysely.cjs +22 -31
  11. package/dist/adapters/kysely.d.cts +10 -6
  12. package/dist/adapters/kysely.d.mts +10 -6
  13. package/dist/adapters/kysely.mjs +23 -33
  14. package/dist/adapters/kyselyExecutor.cjs +32 -0
  15. package/dist/adapters/kyselyExecutor.d.cts +11 -0
  16. package/dist/adapters/kyselyExecutor.d.mts +11 -0
  17. package/dist/adapters/kyselyExecutor.mjs +32 -0
  18. package/dist/adapters/mongodb.cjs +18 -54
  19. package/dist/adapters/mongodb.d.cts +10 -5
  20. package/dist/adapters/mongodb.d.mts +10 -5
  21. package/dist/adapters/mongodb.mjs +19 -56
  22. package/dist/adapters/mongodbAdapter.cjs +192 -0
  23. package/dist/adapters/mongodbAdapter.d.cts +9 -0
  24. package/dist/adapters/mongodbAdapter.d.mts +9 -0
  25. package/dist/adapters/mongodbAdapter.mjs +191 -0
  26. package/dist/adapters/prisma.cjs +35 -267
  27. package/dist/adapters/prisma.d.cts +12 -7
  28. package/dist/adapters/prisma.d.mts +12 -7
  29. package/dist/adapters/prisma.mjs +36 -268
  30. package/dist/adapters/prismaExecutor.cjs +63 -0
  31. package/dist/adapters/prismaExecutor.mjs +63 -0
  32. package/dist/adapters/sqlProviders.cjs +14 -0
  33. package/dist/adapters/sqlProviders.mjs +14 -0
  34. package/dist/assembly/assemblePlugins.cjs +144 -0
  35. package/dist/assembly/assemblePlugins.d.cts +5 -0
  36. package/dist/assembly/assemblePlugins.d.mts +5 -0
  37. package/dist/assembly/assemblePlugins.mjs +139 -0
  38. package/dist/assembly/clientPlugins.cjs +88 -0
  39. package/dist/assembly/clientPlugins.mjs +88 -0
  40. package/dist/assembly/configError.d.cts +2 -0
  41. package/dist/assembly/configError.d.mts +2 -0
  42. package/dist/assembly/configError.mjs +2 -0
  43. package/dist/core/api.cjs +51 -0
  44. package/dist/core/api.d.cts +54 -0
  45. package/dist/core/api.d.mts +54 -0
  46. package/dist/core/api.mjs +51 -0
  47. package/dist/core/baseCandidates.cjs +28 -0
  48. package/dist/core/baseCandidates.mjs +28 -0
  49. package/dist/core/operations.cjs +351 -0
  50. package/dist/core/operations.mjs +351 -0
  51. package/dist/core/reads.cjs +273 -0
  52. package/dist/core/reads.d.cts +9 -0
  53. package/dist/core/reads.d.mts +9 -0
  54. package/dist/core/reads.mjs +267 -0
  55. package/dist/core/releases.cjs +193 -0
  56. package/dist/core/releases.mjs +190 -0
  57. package/dist/core/writes.cjs +96 -0
  58. package/dist/core/writes.mjs +91 -0
  59. package/dist/createHotUpdaterCore.cjs +72 -91
  60. package/dist/createHotUpdaterCore.d.cts +106 -38
  61. package/dist/createHotUpdaterCore.d.mts +106 -38
  62. package/dist/createHotUpdaterCore.mjs +74 -89
  63. package/dist/db/engineDrizzleSchema.cjs +53 -0
  64. package/dist/db/engineDrizzleSchema.mjs +53 -0
  65. package/dist/db/enginePrismaSchema.cjs +84 -0
  66. package/dist/db/enginePrismaSchema.d.cts +5 -0
  67. package/dist/db/enginePrismaSchema.d.mts +5 -0
  68. package/dist/db/enginePrismaSchema.mjs +83 -0
  69. package/dist/db/releaseCatalog.cjs +24 -47
  70. package/dist/db/releaseCatalog.mjs +20 -44
  71. package/dist/db/updateArtifacts.cjs +43 -72
  72. package/dist/db/updateArtifacts.mjs +40 -69
  73. package/dist/handler.cjs +59 -43
  74. package/dist/handler.d.cts +3 -5
  75. package/dist/handler.d.mts +3 -5
  76. package/dist/handler.mjs +61 -43
  77. package/dist/handlerAdminRoutes.cjs +374 -0
  78. package/dist/handlerAdminRoutes.mjs +372 -0
  79. package/dist/handlerParameters.cjs +6 -11
  80. package/dist/handlerParameters.mjs +6 -10
  81. package/dist/handlerReleaseCatalogRoutes.cjs +32 -15
  82. package/dist/handlerReleaseCatalogRoutes.mjs +32 -15
  83. package/dist/handlerTypes.d.cts +2 -55
  84. package/dist/handlerTypes.d.mts +2 -55
  85. package/dist/handlerVersionRoutes.cjs +20 -4
  86. package/dist/handlerVersionRoutes.mjs +20 -4
  87. package/dist/index.cjs +9 -9
  88. package/dist/index.d.cts +8 -9
  89. package/dist/index.d.mts +8 -9
  90. package/dist/index.mjs +3 -4
  91. package/dist/node.cjs +3 -6
  92. package/dist/node.d.cts +2 -2
  93. package/dist/node.d.mts +2 -2
  94. package/dist/node.mjs +4 -4
  95. package/dist/package.cjs +1 -1
  96. package/dist/package.mjs +1 -1
  97. package/dist/plugins/api-keys/index.cjs +9 -0
  98. package/dist/plugins/api-keys/index.d.cts +1 -0
  99. package/dist/plugins/api-keys/index.d.mts +1 -0
  100. package/dist/plugins/api-keys/index.mjs +2 -0
  101. package/dist/plugins/definePlugin.d.cts +2 -0
  102. package/dist/plugins/definePlugin.d.mts +2 -0
  103. package/dist/plugins/insights/index.cjs +9 -0
  104. package/dist/plugins/insights/index.d.cts +1 -0
  105. package/dist/plugins/insights/index.d.mts +1 -0
  106. package/dist/plugins/insights/index.mjs +2 -0
  107. package/dist/plugins/official.cjs +30 -0
  108. package/dist/plugins/official.mjs +29 -0
  109. package/dist/storageAccess.cjs +13 -10
  110. package/dist/storageAccess.mjs +13 -10
  111. package/dist/types/index.d.cts +2 -28
  112. package/dist/types/index.d.mts +2 -28
  113. package/package.json +26 -14
  114. package/dist/_virtual/_rolldown/runtime.cjs +0 -23
  115. package/dist/adapters/databaseConstraintErrors.cjs +0 -22
  116. package/dist/adapters/databaseConstraintErrors.mjs +0 -21
  117. package/dist/adapters/databasePluginUtils.cjs +0 -116
  118. package/dist/adapters/databasePluginUtils.mjs +0 -106
  119. package/dist/adapters/drizzleCrud.cjs +0 -311
  120. package/dist/adapters/drizzleCrud.mjs +0 -308
  121. package/dist/adapters/drizzleLazyDB.cjs +0 -106
  122. package/dist/adapters/drizzleLazyDB.mjs +0 -106
  123. package/dist/adapters/drizzleQuery.cjs +0 -69
  124. package/dist/adapters/drizzleQuery.mjs +0 -69
  125. package/dist/adapters/insightsTransaction.cjs +0 -22
  126. package/dist/adapters/insightsTransaction.mjs +0 -22
  127. package/dist/adapters/kyselyCrud.cjs +0 -305
  128. package/dist/adapters/kyselyCrud.mjs +0 -304
  129. package/dist/adapters/kyselyQuery.cjs +0 -56
  130. package/dist/adapters/kyselyQuery.mjs +0 -56
  131. package/dist/adapters/mongodbCollections.cjs +0 -38
  132. package/dist/adapters/mongodbCollections.mjs +0 -32
  133. package/dist/adapters/mongodbQuery.cjs +0 -94
  134. package/dist/adapters/mongodbQuery.mjs +0 -86
  135. package/dist/adapters/mongodbReads.cjs +0 -210
  136. package/dist/adapters/mongodbReads.mjs +0 -210
  137. package/dist/adapters/mongodbWrites.cjs +0 -148
  138. package/dist/adapters/mongodbWrites.mjs +0 -148
  139. package/dist/adapters/prismaQuery.cjs +0 -57
  140. package/dist/adapters/prismaQuery.mjs +0 -56
  141. package/dist/adapters/prismaRows.cjs +0 -219
  142. package/dist/adapters/prismaRows.mjs +0 -209
  143. package/dist/apiKeys.cjs +0 -143
  144. package/dist/apiKeys.d.cts +0 -49
  145. package/dist/apiKeys.d.mts +0 -49
  146. package/dist/apiKeys.mjs +0 -133
  147. package/dist/db/createBundleDiff.cjs +0 -144
  148. package/dist/db/createBundleDiff.d.cts +0 -16
  149. package/dist/db/createBundleDiff.d.mts +0 -16
  150. package/dist/db/createBundleDiff.mjs +0 -141
  151. package/dist/db/databasePluginCore.cjs +0 -137
  152. package/dist/db/databasePluginCore.mjs +0 -137
  153. package/dist/db/fixedMigrator.cjs +0 -79
  154. package/dist/db/fixedMigrator.mjs +0 -78
  155. package/dist/db/fixedMigratorMongo.cjs +0 -321
  156. package/dist/db/fixedMigratorMongo.mjs +0 -321
  157. package/dist/db/fixedMigratorShared.cjs +0 -23
  158. package/dist/db/fixedMigratorShared.mjs +0 -18
  159. package/dist/db/index.cjs +0 -27
  160. package/dist/db/index.d.cts +0 -12
  161. package/dist/db/index.d.mts +0 -12
  162. package/dist/db/index.mjs +0 -22
  163. package/dist/db/mongoMigrationExecution.cjs +0 -11
  164. package/dist/db/mongoMigrationExecution.mjs +0 -11
  165. package/dist/db/releaseCatalog.d.cts +0 -16
  166. package/dist/db/releaseCatalog.d.mts +0 -16
  167. package/dist/db/schema/insightsCollation.cjs +0 -14
  168. package/dist/db/schema/insightsCollation.mjs +0 -14
  169. package/dist/db/schema/mongodb.cjs +0 -25
  170. package/dist/db/schema/mongodb.mjs +0 -25
  171. package/dist/db/schema/registry.cjs +0 -21
  172. package/dist/db/schema/registry.mjs +0 -17
  173. package/dist/db/schema/sql.cjs +0 -105
  174. package/dist/db/schema/sql.mjs +0 -97
  175. package/dist/db/schema/sqlOperations.cjs +0 -27
  176. package/dist/db/schema/sqlOperations.mjs +0 -26
  177. package/dist/db/schemaGenerators.cjs +0 -275
  178. package/dist/db/schemaGenerators.mjs +0 -273
  179. package/dist/db/schemaReadiness.cjs +0 -26
  180. package/dist/db/schemaReadiness.d.cts +0 -9
  181. package/dist/db/schemaReadiness.d.mts +0 -9
  182. package/dist/db/schemaReadiness.mjs +0 -25
  183. package/dist/db/sqlMigrationExecution.cjs +0 -67
  184. package/dist/db/sqlMigrationExecution.mjs +0 -67
  185. package/dist/db/types.cjs +0 -22
  186. package/dist/db/types.d.cts +0 -118
  187. package/dist/db/types.d.mts +0 -118
  188. package/dist/db/types.mjs +0 -19
  189. package/dist/handlerBundleRoutes.cjs +0 -155
  190. package/dist/handlerBundleRoutes.mjs +0 -155
  191. package/dist/handlerReleaseManagementRoutes.cjs +0 -124
  192. package/dist/handlerReleaseManagementRoutes.mjs +0 -124
  193. package/dist/insights/domain.d.cts +0 -89
  194. package/dist/insights/domain.d.mts +0 -89
  195. package/dist/insights/errors.cjs +0 -15
  196. package/dist/insights/errors.mjs +0 -14
  197. package/dist/insights/eventInput.cjs +0 -155
  198. package/dist/insights/eventInput.mjs +0 -153
  199. package/dist/insights/provider.cjs +0 -314
  200. package/dist/insights/provider.d.cts +0 -6
  201. package/dist/insights/provider.d.mts +0 -6
  202. package/dist/insights/provider.mjs +0 -314
  203. package/dist/insights/queryInput.cjs +0 -93
  204. package/dist/insights/queryInput.mjs +0 -91
  205. package/dist/insights/routes.cjs +0 -58
  206. package/dist/insights/routes.mjs +0 -56
  207. package/dist/insights/types.d.cts +0 -32
  208. package/dist/insights/types.d.mts +0 -32
  209. package/dist/schema/dsl.cjs +0 -103
  210. package/dist/schema/dsl.mjs +0 -87
  211. package/dist/schema/index.cjs +0 -20
  212. package/dist/schema/index.mjs +0 -7
  213. package/dist/schema/settings.cjs +0 -9
  214. package/dist/schema/settings.mjs +0 -9
  215. package/dist/schema/types.cjs +0 -8
  216. package/dist/schema/types.mjs +0 -6
  217. package/dist/schema/v1_0_0.cjs +0 -406
  218. package/dist/schema/v1_0_0.mjs +0 -398
  219. package/src/adapters/databaseConstraintErrors.ts +0 -25
  220. package/src/adapters/databasePluginTestDatabase.ts +0 -120
  221. package/src/adapters/databasePluginUtils.spec.ts +0 -29
  222. package/src/adapters/databasePluginUtils.ts +0 -214
  223. package/src/adapters/drizzle.spec.ts +0 -336
  224. package/src/adapters/drizzle.ts +0 -162
  225. package/src/adapters/drizzleCrud.ts +0 -571
  226. package/src/adapters/drizzleLazyDB.ts +0 -271
  227. package/src/adapters/drizzleQuery.ts +0 -164
  228. package/src/adapters/insightsTransaction.ts +0 -32
  229. package/src/adapters/kysely.spec.ts +0 -174
  230. package/src/adapters/kysely.ts +0 -110
  231. package/src/adapters/kyselyCrud.ts +0 -709
  232. package/src/adapters/kyselyQuery.ts +0 -128
  233. package/src/adapters/mongodb.integration.spec.ts +0 -210
  234. package/src/adapters/mongodb.spec.ts +0 -209
  235. package/src/adapters/mongodb.ts +0 -138
  236. package/src/adapters/mongodbCollections.ts +0 -67
  237. package/src/adapters/mongodbQuery.ts +0 -255
  238. package/src/adapters/mongodbReads.ts +0 -380
  239. package/src/adapters/mongodbRows.spec.ts +0 -64
  240. package/src/adapters/mongodbRows.ts +0 -118
  241. package/src/adapters/mongodbTestClient.ts +0 -377
  242. package/src/adapters/mongodbTestFilter.ts +0 -169
  243. package/src/adapters/mongodbWrites.ts +0 -287
  244. package/src/adapters/prisma.spec.ts +0 -293
  245. package/src/adapters/prisma.ts +0 -565
  246. package/src/adapters/prismaQuery.ts +0 -129
  247. package/src/adapters/prismaRows.spec.ts +0 -98
  248. package/src/adapters/prismaRows.ts +0 -337
  249. package/src/adapters/prismaTestClient.ts +0 -413
  250. package/src/apiKeys.integration.spec.ts +0 -192
  251. package/src/apiKeys.spec.ts +0 -162
  252. package/src/apiKeys.ts +0 -220
  253. package/src/calculatePagination.ts +0 -34
  254. package/src/createHotUpdaterCore.ts +0 -246
  255. package/src/db/bundleRows.spec.ts +0 -164
  256. package/src/db/bundleRows.ts +0 -10
  257. package/src/db/createBundleDiff.spec.ts +0 -450
  258. package/src/db/createBundleDiff.ts +0 -364
  259. package/src/db/databasePluginCore.spec.ts +0 -62
  260. package/src/db/databasePluginCore.testFixtures.ts +0 -76
  261. package/src/db/databasePluginCore.ts +0 -185
  262. package/src/db/databasePluginUpdateCheck.bench.ts +0 -110
  263. package/src/db/fixedMigrator.spec.ts +0 -296
  264. package/src/db/fixedMigrator.ts +0 -147
  265. package/src/db/fixedMigratorMongo.spec.ts +0 -239
  266. package/src/db/fixedMigratorMongo.ts +0 -425
  267. package/src/db/fixedMigratorShared.ts +0 -36
  268. package/src/db/hotUpdaterSchema.ts +0 -5
  269. package/src/db/index.spec.ts +0 -1269
  270. package/src/db/index.ts +0 -47
  271. package/src/db/mongoMigrationExecution.ts +0 -23
  272. package/src/db/node-sqlite.d.ts +0 -25
  273. package/src/db/releaseCatalog.ts +0 -148
  274. package/src/db/schema/definitions.ts +0 -1
  275. package/src/db/schema/insightsCollation.ts +0 -21
  276. package/src/db/schema/mongodb.ts +0 -40
  277. package/src/db/schema/registry.ts +0 -55
  278. package/src/db/schema/sql.ts +0 -244
  279. package/src/db/schema/sqlOperations.ts +0 -63
  280. package/src/db/schema/types.ts +0 -1
  281. package/src/db/schemaGenerators.ts +0 -494
  282. package/src/db/schemaReadiness.ts +0 -34
  283. package/src/db/sqlMigrationExecution.spec.ts +0 -65
  284. package/src/db/sqlMigrationExecution.ts +0 -108
  285. package/src/db/types.spec.ts +0 -63
  286. package/src/db/types.ts +0 -228
  287. package/src/db/updateArtifacts.spec.ts +0 -359
  288. package/src/db/updateArtifacts.ts +0 -541
  289. package/src/handler-standalone.integration.spec.ts +0 -528
  290. package/src/handler.spec.ts +0 -190
  291. package/src/handler.testFixtures.ts +0 -30
  292. package/src/handler.ts +0 -245
  293. package/src/handlerAuth.integration.spec.ts +0 -33
  294. package/src/handlerBundleRoutes.ts +0 -259
  295. package/src/handlerErrors.ts +0 -7
  296. package/src/handlerManagement.spec.ts +0 -262
  297. package/src/handlerParameters.ts +0 -105
  298. package/src/handlerReleaseCatalogRoutes.ts +0 -154
  299. package/src/handlerReleaseManagementRoutes.ts +0 -213
  300. package/src/handlerTypes.ts +0 -96
  301. package/src/handlerVersionRoutes.ts +0 -12
  302. package/src/index.ts +0 -30
  303. package/src/insights/domain.ts +0 -103
  304. package/src/insights/errors.ts +0 -11
  305. package/src/insights/eventInput.ts +0 -225
  306. package/src/insights/insights.integration.spec.ts +0 -381
  307. package/src/insights/provider.spec.ts +0 -385
  308. package/src/insights/provider.ts +0 -591
  309. package/src/insights/queryInput.ts +0 -141
  310. package/src/insights/routes.ts +0 -104
  311. package/src/insights/types.ts +0 -55
  312. package/src/internalRouter.ts +0 -104
  313. package/src/node.spec.ts +0 -119
  314. package/src/node.ts +0 -111
  315. package/src/releaseCatalogRoutes.integration.spec.ts +0 -238
  316. package/src/runtime.spec.ts +0 -194
  317. package/src/runtime.testFixtures.ts +0 -71
  318. package/src/schema/dsl-all-versions.spec.ts +0 -37
  319. package/src/schema/dsl.ts +0 -187
  320. package/src/schema/index.ts +0 -10
  321. package/src/schema/settings.ts +0 -15
  322. package/src/schema/types.ts +0 -79
  323. package/src/schema/v1_0_0.spec.ts +0 -220
  324. package/src/schema/v1_0_0.ts +0 -529
  325. package/src/storageAccess.spec.ts +0 -152
  326. package/src/storageAccess.ts +0 -141
  327. package/src/types/index.ts +0 -34
  328. package/src/version.ts +0 -3
@@ -1,1269 +0,0 @@
1
- import { PGlite } from "@electric-sql/pglite";
2
- import type { Bundle } from "@hot-updater/core";
3
- import { NIL_UUID } from "@hot-updater/core";
4
- import { createStoragePlugin } from "@hot-updater/plugin-core";
5
- import { sql } from "drizzle-orm";
6
- import { Kysely } from "kysely";
7
- import { PGliteDialect } from "kysely-pglite-dialect";
8
- import { type ClientSession, MongoClient } from "mongodb";
9
- import {
10
- afterAll,
11
- afterEach,
12
- beforeAll,
13
- beforeEach,
14
- describe,
15
- expect,
16
- it,
17
- vi,
18
- } from "vitest";
19
-
20
- import { createInMemoryDatabasePlugin } from "../../../test-utils/test/inMemoryDatabasePlugin";
21
- import { drizzleAdapter } from "../adapters/drizzle";
22
- import { kyselyAdapter } from "../adapters/kysely";
23
- import { mongoAdapter } from "../adapters/mongodb";
24
- import { prismaAdapter } from "../adapters/prisma";
25
- import {
26
- createHotUpdater as createRuntimeHotUpdater,
27
- type CreateHotUpdaterOptions,
28
- } from "../index";
29
- import { bundleToRow } from "./bundleRows";
30
- import { createTableSql, hotUpdaterSchemaVersions } from "./hotUpdaterSchema";
31
- import { createMigrator, generateSchema } from "./index";
32
- import { generateDrizzleSchema } from "./schemaGenerators";
33
- import type { DatabasePlugin, ORMProvider } from "./types";
34
-
35
- const createHotUpdater = (
36
- options: Omit<CreateHotUpdaterOptions, "clientAccess">,
37
- ) =>
38
- createRuntimeHotUpdater({
39
- ...options,
40
- clientAccess: { type: "public" },
41
- });
42
-
43
- const RAW_PRISMA_SCHEMA = `model bundles {
44
- id String @id
45
- platform String
46
- should_force_update Boolean
47
- enabled Boolean
48
- file_hash String
49
- git_commit_hash String?
50
- message String?
51
- channel String @default("production")
52
- storage_uri String
53
- target_app_version String?
54
- fingerprint_hash String?
55
- metadata Json
56
- manifest_storage_uri String?
57
- manifest_file_hash String?
58
- asset_base_storage_uri String?
59
- rollout_cohort_count Int @default(1000)
60
- target_cohorts Json?
61
- }
62
- model bundle_patches {
63
- id String @id
64
- bundle_id String
65
- base_bundle_id String
66
- base_file_hash String
67
- patch_file_hash String
68
- patch_storage_uri String
69
- order_index Int @default(0)
70
- bundle bundles @relation("bundle_patches_bundles_patches", fields: [bundle_id], references: [id], onUpdate: Restrict, onDelete: Cascade)
71
- baseBundle bundles @relation("bundle_patches_bundles_baseForPatches", fields: [base_bundle_id], references: [id], onUpdate: Restrict, onDelete: Cascade)
72
- }
73
- model private_hot_updater_settings {
74
- key String @id
75
- value String @default("0.36.0")
76
- }`;
77
-
78
- const RAW_DRIZZLE_SCHEMA = `import { relations } from "drizzle-orm";
79
- import {
80
- pgTable,
81
- uuid,
82
- text,
83
- boolean,
84
- json,
85
- integer,
86
- varchar,
87
- foreignKey,
88
- } from "drizzle-orm/pg-core";
89
-
90
- export const bundles = pgTable("bundles", {
91
- id: uuid("id").primaryKey().notNull(),
92
- platform: text("platform").notNull(),
93
- should_force_update: boolean("should_force_update").notNull(),
94
- enabled: boolean("enabled").notNull(),
95
- file_hash: text("file_hash").notNull(),
96
- git_commit_hash: text("git_commit_hash"),
97
- message: text("message"),
98
- channel: text("channel").notNull().default("production"),
99
- storage_uri: text("storage_uri").notNull(),
100
- target_app_version: text("target_app_version"),
101
- fingerprint_hash: text("fingerprint_hash"),
102
- metadata: json("metadata").notNull(),
103
- manifest_storage_uri: text("manifest_storage_uri"),
104
- manifest_file_hash: text("manifest_file_hash"),
105
- asset_base_storage_uri: text("asset_base_storage_uri"),
106
- rollout_cohort_count: integer("rollout_cohort_count")
107
- .notNull()
108
- .default(1000),
109
- target_cohorts: json("target_cohorts"),
110
- })
111
-
112
- export const bundle_patches = pgTable(
113
- "bundle_patches",
114
- {
115
- id: varchar("id", { length: 255 }).primaryKey().notNull(),
116
- bundle_id: uuid("bundle_id").notNull(),
117
- base_bundle_id: uuid("base_bundle_id").notNull(),
118
- base_file_hash: text("base_file_hash").notNull(),
119
- patch_file_hash: text("patch_file_hash").notNull(),
120
- patch_storage_uri: text("patch_storage_uri").notNull(),
121
- order_index: integer("order_index").notNull().default(0),
122
- }, (table) => [
123
- foreignKey({
124
- columns: [table.bundle_id],
125
- foreignColumns: [bundles.id],
126
- name: "bundle_patches_bundle_id_fk",
127
- })
128
- .onUpdate("restrict")
129
- .onDelete("cascade"),
130
- foreignKey({
131
- columns: [table.base_bundle_id],
132
- foreignColumns: [bundles.id],
133
- name: "bundle_patches_base_bundle_id_fk",
134
- })
135
- .onUpdate("restrict")
136
- .onDelete("cascade"),
137
- ])
138
-
139
- export const private_hot_updater_settings = pgTable("private_hot_updater_settings", {
140
- key: varchar("key", { length: 255 }).primaryKey().notNull(),
141
- version: varchar("version", { length: 255 }).notNull().default("0.36.0"),
142
- })
143
-
144
- export const bundle_patchesRelations = relations(bundle_patches, ({ one, many }) => ({
145
- bundle: one(bundles, {
146
- relationName: "bundle_patches_bundles_patches",
147
- fields: [bundle_patches.bundle_id],
148
- references: [bundles.id],
149
- }),
150
- baseBundle: one(bundles, {
151
- relationName: "bundle_patches_bundles_baseForPatches",
152
- fields: [bundle_patches.base_bundle_id],
153
- references: [bundles.id],
154
- }),
155
- }));`;
156
-
157
- function createTestStoragePlugin(
158
- protocol: string,
159
- readText: (storageUri: string) => Promise<string | null> = async () => null,
160
- ) {
161
- return createStoragePlugin({
162
- name: `${protocol}TestStorage`,
163
- protocol,
164
- async get({ storageUri }) {
165
- const text = await readText(storageUri);
166
- return { response: text === null ? null : new Response(text) };
167
- },
168
- async getDownloadUrl({ storageUri }) {
169
- const prefixes: Record<string, string> = {
170
- gs: "https://firebase.example.com/",
171
- r2: "https://r2.example.com/",
172
- s3: "https://s3.example.com/",
173
- "supabase-storage":
174
- "https://supabase.example.com/storage/v1/object/sign/",
175
- };
176
- return {
177
- url: storageUri
178
- .replace(`${protocol}://`, prefixes[protocol] ?? "")
179
- .replace(/([^:]\/)\/+/g, "$1"),
180
- };
181
- },
182
- });
183
- }
184
-
185
- function createSchemaOnlyAdapter({
186
- code,
187
- name,
188
- provider,
189
- path,
190
- }: {
191
- code: string;
192
- name: string;
193
- provider: ORMProvider;
194
- path: string;
195
- }): DatabasePlugin {
196
- return {
197
- ...createInMemoryDatabasePlugin(),
198
- adapterName: name,
199
- provider,
200
- generateSchema: (_version, schemaName = name) => ({
201
- code,
202
- path: path || schemaName,
203
- }),
204
- };
205
- }
206
-
207
- const transactionBundle: Bundle = {
208
- archiveByteSize: 1_024,
209
- id: "00000000-0000-0000-0000-000000000777",
210
- platform: "ios",
211
- fileHash: "transaction-hash",
212
- gitCommitHash: null,
213
- storageUri: "s3://test-bucket/transaction.zip",
214
- };
215
- const transactionChannelId = "00000000-0000-0000-0000-000000000700";
216
-
217
- describe("server/db hotUpdater (PGlite + Kysely)", async () => {
218
- const db = new PGlite();
219
-
220
- const kysely = new Kysely<object>({ dialect: new PGliteDialect(db) });
221
- const storageTexts = new Map<string, string | Error>();
222
- const readStoredText = async (storageUri: string) => {
223
- const text = storageTexts.get(storageUri);
224
- if (text instanceof Error) {
225
- throw text;
226
- }
227
- return text ?? null;
228
- };
229
-
230
- const hotUpdater = createHotUpdater({
231
- database: kyselyAdapter({
232
- db: kysely,
233
- provider: "postgresql",
234
- }),
235
- storage: [
236
- createTestStoragePlugin("s3", readStoredText),
237
- createTestStoragePlugin("r2", readStoredText),
238
- createTestStoragePlugin("supabase-storage", readStoredText),
239
- createTestStoragePlugin("gs", readStoredText),
240
- ],
241
- });
242
- const prismaSchemaHotUpdater = createHotUpdater({
243
- database: createSchemaOnlyAdapter({
244
- code: RAW_PRISMA_SCHEMA,
245
- name: "prisma",
246
- path: "schema.prisma",
247
- provider: "postgresql",
248
- }),
249
- });
250
- const sqlitePrismaSchemaHotUpdater = createHotUpdater({
251
- database: createSchemaOnlyAdapter({
252
- code: RAW_PRISMA_SCHEMA,
253
- name: "prisma",
254
- path: "schema.prisma",
255
- provider: "sqlite",
256
- }),
257
- });
258
- const drizzleSchemaHotUpdater = createHotUpdater({
259
- database: createSchemaOnlyAdapter({
260
- code: RAW_DRIZZLE_SCHEMA,
261
- name: "drizzle",
262
- path: "hot-updater-schema.ts",
263
- provider: "postgresql",
264
- }),
265
- });
266
-
267
- it("uses the default generated schema artifact path for Drizzle", () => {
268
- const adapter = drizzleAdapter({
269
- db: {
270
- _: {
271
- fullSchema: {
272
- bundle_patches: {},
273
- bundles: {},
274
- },
275
- },
276
- $count: vi.fn(),
277
- delete: vi.fn(),
278
- insert: vi.fn(),
279
- query: {
280
- bundle_patches: { findFirst: vi.fn(), findMany: vi.fn() },
281
- bundles: { findFirst: vi.fn(), findMany: vi.fn() },
282
- },
283
- update: vi.fn(),
284
- },
285
- provider: "sqlite",
286
- });
287
-
288
- expect(adapter.generateSchema?.("latest").path).toBe(
289
- "hot-updater-schema.ts",
290
- );
291
- });
292
-
293
- beforeAll(async () => {
294
- const migrator = createMigrator(hotUpdater);
295
- const result = await migrator.migrateToLatest({
296
- mode: "from-schema",
297
- updateSettings: true,
298
- });
299
- await result.execute();
300
- });
301
-
302
- beforeEach(async () => {
303
- storageTexts.clear();
304
- await db.exec("DELETE FROM release_catalogs");
305
- await db.exec("DELETE FROM releases");
306
- await db.exec("DELETE FROM bundle_patches");
307
- await db.exec("DELETE FROM bundles");
308
- await db.exec("DELETE FROM channels");
309
- });
310
-
311
- afterAll(async () => {
312
- await kysely.destroy();
313
- await db.close();
314
- });
315
-
316
- describe("schema generation", () => {
317
- it("includes relations, defaults, and indexes in Prisma output", () => {
318
- const code = generateSchema(prismaSchemaHotUpdater, "latest").code;
319
-
320
- expect(code).toContain('metadata Json @default("{}")');
321
- expect(code).toContain('value String @default("1.0.0")');
322
- expect(code).toContain("model channels {");
323
- expect(code).toContain("id String @db.VarChar(255) @id");
324
- expect(code).toContain("name String @db.VarChar(255)");
325
- expect(code).toContain('@@unique([name], map: "channels_name_key")');
326
- expect(code).toContain("channel_id String @db.VarChar(255)");
327
- expect(code).toContain(
328
- 'channelRecord channels @relation("releases_channels", fields: [channel_id], references: [id], onUpdate: Restrict, onDelete: Restrict)',
329
- );
330
- expect(code).toContain(
331
- 'patches bundle_patches[] @relation("bundle_patches_bundles_patches")',
332
- );
333
- expect(code).toContain(
334
- 'baseForPatches bundle_patches[] @relation("bundle_patches_bundles_baseForPatches")',
335
- );
336
- expect(code).toContain(
337
- 'bundle bundles @relation("bundle_patches_bundles_patches"',
338
- );
339
- expect(code).toContain(
340
- 'baseBundle bundles @relation("bundle_patches_bundles_baseForPatches"',
341
- );
342
- expect(code).not.toContain(
343
- '@@index([channel], map: "bundles_channel_idx")',
344
- );
345
- expect(code).toContain(
346
- '@@index([scope_key, id], map: "releases_scope_order_idx")',
347
- );
348
- expect(code).toContain("scope_key String @db.VarChar(2048) @id");
349
- expect(code).not.toContain("bundles_platform_idx");
350
- expect(code).toContain(
351
- '@@index([bundle_id], map: "bundle_patches_bundle_id_idx")',
352
- );
353
- });
354
-
355
- it("omits the metadata JSON default for SQLite Prisma output", () => {
356
- const code = generateSchema(sqlitePrismaSchemaHotUpdater, "latest").code;
357
-
358
- expect(code).toContain("metadata Json");
359
- expect(code).not.toContain('metadata Json @default("{}")');
360
- });
361
-
362
- it("rejects generating a retired schema snapshot", () => {
363
- expect(() => generateSchema(prismaSchemaHotUpdater, "0.21.0")).toThrow(
364
- "Unsupported Hot Updater schema version: 0.21.0",
365
- );
366
- });
367
-
368
- it("includes foreign keys and indexes in Drizzle output", () => {
369
- const code = generateSchema(drizzleSchemaHotUpdater, "latest").code;
370
- const bundlesBlock = code.match(
371
- /export const bundles = [\s\S]*?(?=\n\nexport const bundle_patches = )/,
372
- )?.[0];
373
- const bundlePatchesBlock = code.match(
374
- /export const bundle_patches = [\s\S]*?(?=\n\nexport const bundle_patchesRelations = )/,
375
- )?.[0];
376
-
377
- expect(code).toContain(
378
- 'metadata: json("metadata").notNull().default({})',
379
- );
380
- expect(code).toContain('name: "bundle_patches_bundle_id_fk"');
381
- expect(code).toContain('name: "bundle_patches_base_bundle_id_fk"');
382
- expect(code).toContain('.onDelete("cascade")');
383
- expect(bundlesBlock).not.toContain("bundles_channel_idx");
384
- expect(bundlesBlock).not.toContain("bundles_platform_idx");
385
- expect(bundlesBlock).not.toContain("target_app_version");
386
- expect(bundlesBlock).not.toContain(
387
- 'index("bundle_patches_bundle_id_idx").on(table.bundle_id)',
388
- );
389
- expect(bundlePatchesBlock).toContain(
390
- 'index("bundle_patches_bundle_id_idx").on(table.bundle_id)',
391
- );
392
- expect(code).toContain(
393
- 'index("releases_scope_order_idx").on(table.scope_key, table.id)',
394
- );
395
- expect(code).toContain(
396
- 'scope_key: varchar("scope_key", { length: 2048 }).primaryKey().notNull()',
397
- );
398
- const generatedCode = generateDrizzleSchema("postgresql");
399
- expect(generatedCode).toContain(
400
- 'id: varchar("id", { length: 255 }).primaryKey().notNull()',
401
- );
402
- expect(generatedCode).toContain(
403
- 'version: varchar("version", { length: 255 }).notNull().default("1.0.0")',
404
- );
405
- expect(generatedCode).toContain(
406
- 'uniqueIndex("channels_name_key").on(table.name)',
407
- );
408
- expect(generatedCode).toContain('name: "releases_channel_id_fk"');
409
- expect(generatedCode).toContain(
410
- 'index("releases_channel_platform_order_idx").on(table.channel_id, table.platform, table.id)',
411
- );
412
- expect(generatedCode).not.toContain('key: varchar("key"');
413
- expect(generatedCode).not.toContain('value: text("value"');
414
- });
415
- });
416
-
417
- describe("migrator enhancements", () => {
418
- it("registers only the initial schema", () => {
419
- expect(hotUpdaterSchemaVersions.map((schema) => schema.version)).toEqual([
420
- "1.0.0",
421
- ]);
422
- });
423
-
424
- it("omits MySQL defaults for text and JSON columns", () => {
425
- const sql = createTableSql("mysql").join("\n");
426
-
427
- expect(sql).toContain("create table channels");
428
- expect(sql).toContain("metadata json not null");
429
- expect(sql).not.toContain("metadata json not null default");
430
- expect(sql).toContain("`key` varchar(255) primary key");
431
- expect(sql).not.toContain("\nkey varchar(255) primary key");
432
- expect(sql).toContain(
433
- "create table api_keys (\nid varchar(255) primary key not null",
434
- );
435
- expect(sql).not.toContain("create table api_keys (\nid text primary key");
436
- expect(sql).toContain(
437
- "create index bundle_patches_bundle_id_idx on bundle_patches(bundle_id)",
438
- );
439
- expect(sql).not.toContain("bundle_id(255)");
440
- });
441
-
442
- it("adds custom indexes and constraints to generated SQL", async () => {
443
- const migrationDb = new PGlite();
444
- const migrationKysely = new Kysely<object>({
445
- dialect: new PGliteDialect(migrationDb),
446
- });
447
- const migrationHotUpdater = createHotUpdater({
448
- database: kyselyAdapter({
449
- db: migrationKysely,
450
- provider: "postgresql",
451
- }),
452
- });
453
-
454
- try {
455
- const migrator = createMigrator(migrationHotUpdater);
456
- const result = await migrator.migrateToLatest({
457
- mode: "from-schema",
458
- updateSettings: false,
459
- });
460
- const sql = result.getSQL?.() ?? "";
461
-
462
- expect(sql).toContain(
463
- "create index releases_scope_order_idx on releases",
464
- );
465
- expect(sql).toContain(
466
- "add constraint releases_strategy_target_check check",
467
- );
468
- expect(sql).toContain(
469
- "add constraint bundle_patches_bundle_id_fk foreign key",
470
- );
471
- expect(sql).toContain(
472
- "create index bundle_patches_bundle_id_idx on bundle_patches",
473
- );
474
- expect(sql).toContain("insert into private_hot_updater_settings");
475
- expect(result.operations).not.toContainEqual(
476
- expect.objectContaining({
477
- sql: expect.stringContaining(
478
- "insert into private_hot_updater_settings",
479
- ),
480
- }),
481
- );
482
- } finally {
483
- await migrationKysely.destroy();
484
- await migrationDb.close();
485
- }
486
- });
487
-
488
- it("rejects an existing v0 Kysely schema instead of upgrading it", async () => {
489
- const migrationDb = new PGlite();
490
- const migrationKysely = new Kysely<object>({
491
- dialect: new PGliteDialect(migrationDb),
492
- });
493
- const migrationHotUpdater = createHotUpdater({
494
- database: kyselyAdapter({
495
- db: migrationKysely,
496
- provider: "postgresql",
497
- }),
498
- });
499
-
500
- try {
501
- await migrationDb.exec(`
502
- create table private_hot_updater_settings (
503
- key varchar(255) primary key,
504
- value text not null
505
- );
506
- insert into private_hot_updater_settings (key, value)
507
- values ('version', '0.21.0');
508
- `);
509
-
510
- const migrator = createMigrator(migrationHotUpdater);
511
- await expect(
512
- migrator.migrateToLatest({
513
- mode: "from-schema",
514
- updateSettings: true,
515
- }),
516
- ).rejects.toThrow("Hot Updater v1 cannot migrate schema 0.21.0");
517
- } finally {
518
- await migrationKysely.destroy();
519
- await migrationDb.close();
520
- }
521
- });
522
-
523
- it("honors soft relation mode by omitting SQL foreign keys", async () => {
524
- const migrationDb = new PGlite();
525
- const migrationKysely = new Kysely<object>({
526
- dialect: new PGliteDialect(migrationDb),
527
- });
528
- const migrationHotUpdater = createHotUpdater({
529
- database: kyselyAdapter({
530
- db: migrationKysely,
531
- provider: "postgresql",
532
- relationMode: "fumadb",
533
- }),
534
- });
535
-
536
- try {
537
- const migrator = createMigrator(migrationHotUpdater);
538
- const result = await migrator.migrateToLatest({
539
- mode: "from-schema",
540
- updateSettings: false,
541
- });
542
- const sql = result.getSQL?.() ?? "";
543
-
544
- expect(sql).not.toContain("add constraint bundle_patches_bundle_id_fk");
545
- expect(result.operations).not.toContainEqual(
546
- expect.objectContaining({
547
- sql: expect.stringContaining("bundle_patches_bundle_id_fk"),
548
- }),
549
- );
550
- } finally {
551
- await migrationKysely.destroy();
552
- await migrationDb.close();
553
- }
554
- });
555
-
556
- it("omits unsupported SQLite alter constraint statements", async () => {
557
- const migrationDb = new PGlite();
558
- const migrationKysely = new Kysely<object>({
559
- dialect: new PGliteDialect(migrationDb),
560
- });
561
- const migrationHotUpdater = createHotUpdater({
562
- database: kyselyAdapter({
563
- db: migrationKysely,
564
- provider: "sqlite",
565
- }),
566
- });
567
-
568
- try {
569
- const migrator = createMigrator(migrationHotUpdater);
570
- const result = await migrator.migrateToLatest({
571
- mode: "from-schema",
572
- updateSettings: false,
573
- });
574
- const sql = result.getSQL?.() ?? "";
575
-
576
- expect(sql).not.toContain("alter table bundles add constraint");
577
- expect(sql).not.toContain("alter table bundle_patches add constraint");
578
- expect(result.operations).not.toContainEqual(
579
- expect.objectContaining({
580
- sql: expect.stringContaining("add constraint"),
581
- }),
582
- );
583
- } finally {
584
- await migrationKysely.destroy();
585
- await migrationDb.close();
586
- }
587
- });
588
-
589
- it("creates MongoDB indexes for runtime query fields", async () => {
590
- const collection = {
591
- find: vi.fn(() => ({
592
- limit: () => ({ toArray: async () => [] }),
593
- })),
594
- listIndexes: () => ({ toArray: async () => [] }),
595
- };
596
- const client = {
597
- db: () => ({
598
- collection: () => collection,
599
- }),
600
- } as unknown as MongoClient;
601
- const mongoHotUpdater = createHotUpdater({
602
- database: mongoAdapter({ client }),
603
- });
604
- const result = await createMigrator(mongoHotUpdater).migrateToLatest({
605
- mode: "from-schema",
606
- });
607
-
608
- expect(result.operations).toEqual(
609
- expect.arrayContaining([
610
- expect.objectContaining({
611
- description:
612
- "Create unique MongoDB index: bundles_id_idx on bundles(id)",
613
- }),
614
- expect.objectContaining({
615
- description:
616
- "Create unique MongoDB index: bundle_patches_id_idx on bundle_patches(id)",
617
- }),
618
- expect.objectContaining({
619
- description:
620
- "Create unique MongoDB index: release_catalogs_scope_key_idx on release_catalogs(scope_key)",
621
- }),
622
- expect.objectContaining({
623
- description:
624
- "Create MongoDB index: releases_fingerprint_hash_idx on releases(fingerprint_hash)",
625
- }),
626
- expect.objectContaining({
627
- description:
628
- "Create MongoDB index: bundles_platform_idx on bundles(platform)",
629
- }),
630
- expect.objectContaining({
631
- description:
632
- "Create MongoDB index: bundle_patches_base_bundle_id_idx on bundle_patches(base_bundle_id)",
633
- }),
634
- ]),
635
- );
636
- });
637
-
638
- it("rejects from-database migrations explicitly", async () => {
639
- const migrationDb = new PGlite();
640
- const migrationKysely = new Kysely<object>({
641
- dialect: new PGliteDialect(migrationDb),
642
- });
643
- const migrationHotUpdater = createHotUpdater({
644
- database: kyselyAdapter({
645
- db: migrationKysely,
646
- provider: "postgresql",
647
- }),
648
- });
649
-
650
- try {
651
- await expect(
652
- createMigrator(migrationHotUpdater).migrateToLatest({
653
- mode: "from-database",
654
- }),
655
- ).rejects.toThrow(
656
- "Hot Updater migrations support only mode: 'from-schema'.",
657
- );
658
- } finally {
659
- await migrationKysely.destroy();
660
- await migrationDb.close();
661
- }
662
- });
663
-
664
- it("rejects runtime access when a Kysely schema is not initialized", async () => {
665
- const migrationDb = new PGlite();
666
- const migrationKysely = new Kysely<object>({
667
- dialect: new PGliteDialect(migrationDb),
668
- });
669
- const migrationHotUpdater = createHotUpdater({
670
- database: kyselyAdapter({
671
- db: migrationKysely,
672
- provider: "postgresql",
673
- }),
674
- });
675
-
676
- try {
677
- await expect(
678
- migrationHotUpdater.getBundles({ limit: 10 }),
679
- ).rejects.toThrow(
680
- "Hot Updater database schema is not initialized for kysely.",
681
- );
682
- } finally {
683
- await migrationKysely.destroy();
684
- await migrationDb.close();
685
- }
686
- });
687
-
688
- it("rejects runtime access when a Kysely schema is stale", async () => {
689
- const migrationDb = new PGlite();
690
- const migrationKysely = new Kysely<object>({
691
- dialect: new PGliteDialect(migrationDb),
692
- });
693
- const migrationHotUpdater = createHotUpdater({
694
- database: kyselyAdapter({
695
- db: migrationKysely,
696
- provider: "postgresql",
697
- }),
698
- });
699
-
700
- try {
701
- await migrationDb.exec(`
702
- create table private_hot_updater_settings (
703
- key varchar(255) primary key,
704
- value text not null
705
- );
706
- insert into private_hot_updater_settings (key, value)
707
- values ('version', '0.21.0');
708
- `);
709
-
710
- await expect(migrationHotUpdater.getChannels()).rejects.toThrow(
711
- "Hot Updater v1 cannot migrate schema 0.21.0 in place.",
712
- );
713
- } finally {
714
- await migrationKysely.destroy();
715
- await migrationDb.close();
716
- }
717
- });
718
-
719
- it("rejects runtime access when a MongoDB schema is stale", async () => {
720
- const settings = {
721
- find: vi.fn(({ key }: { readonly key: string }) => ({
722
- limit: () => ({
723
- toArray: async () =>
724
- key === "version" ? [{ key, value: "0.21.0" }] : [],
725
- }),
726
- })),
727
- };
728
- const bundles = {
729
- countDocuments: vi.fn(async () => 0),
730
- find: vi.fn(),
731
- findOne: vi.fn(),
732
- };
733
- const patches = {
734
- find: vi.fn(),
735
- };
736
- const client = {
737
- db: () => ({
738
- collection: (name: string) => {
739
- if (name === "private_hot_updater_settings") return settings;
740
- if (name === "bundle_patches") return patches;
741
- return bundles;
742
- },
743
- }),
744
- } as unknown as MongoClient;
745
- const mongoHotUpdater = createHotUpdater({
746
- database: mongoAdapter({ client }),
747
- });
748
-
749
- await expect(mongoHotUpdater.getBundles({ limit: 10 })).rejects.toThrow(
750
- "Hot Updater v1 cannot migrate schema 0.21.0 in place.",
751
- );
752
- expect(bundles.countDocuments).not.toHaveBeenCalled();
753
- });
754
- });
755
-
756
- describe("adapter filters", () => {
757
- it("returns an empty Kysely page for empty set filters", async () => {
758
- const byId = await hotUpdater.getBundles({
759
- limit: 10,
760
- where: { id: { in: [] } },
761
- });
762
- expect(byId.data).toEqual([]);
763
- expect(byId.pagination.total).toBe(0);
764
- });
765
-
766
- it("commits Prisma bundle changes inside a transaction when available", async () => {
767
- const rootBundles = {
768
- count: vi.fn(),
769
- create: vi.fn(),
770
- deleteMany: vi.fn(),
771
- findFirst: vi.fn(),
772
- findMany: vi.fn(),
773
- update: vi.fn(),
774
- upsert: vi.fn(),
775
- };
776
- const rootPatches = {
777
- count: vi.fn(),
778
- create: vi.fn(),
779
- deleteMany: vi.fn(),
780
- findFirst: vi.fn(),
781
- findMany: vi.fn(),
782
- update: vi.fn(),
783
- upsert: vi.fn(),
784
- };
785
- const channels = {
786
- count: vi.fn(),
787
- create: vi.fn(),
788
- deleteMany: vi.fn(),
789
- findFirst: vi.fn(async () => ({
790
- id: transactionChannelId,
791
- name: "production",
792
- })),
793
- findMany: vi.fn(),
794
- update: vi.fn(),
795
- upsert: vi.fn(),
796
- };
797
- const txBundles = {
798
- ...rootBundles,
799
- create: vi.fn(async ({ data }) => data),
800
- };
801
- const txPatches = { ...rootPatches };
802
- const $transaction = vi.fn(
803
- async (operation: (tx: Record<string, unknown>) => Promise<unknown>) =>
804
- operation({
805
- bundle_patches: txPatches,
806
- bundles: txBundles,
807
- channels,
808
- }),
809
- );
810
- const adapter = prismaAdapter({
811
- prisma: {
812
- $transaction,
813
- bundle_patches: rootPatches,
814
- bundles: rootBundles,
815
- channels,
816
- },
817
- provider: "postgresql",
818
- });
819
-
820
- await adapter.commit({
821
- changes: [
822
- {
823
- model: "bundles",
824
- operation: "insert",
825
- row: bundleToRow(transactionBundle),
826
- },
827
- ],
828
- });
829
-
830
- expect($transaction).toHaveBeenCalledTimes(1);
831
- expect(txBundles.create).toHaveBeenCalledTimes(1);
832
- expect(rootBundles.create).not.toHaveBeenCalled();
833
- });
834
-
835
- it("commits Drizzle bundle changes inside a transaction when available", async () => {
836
- const tables = {
837
- bundle_events: {
838
- id: "event_id",
839
- },
840
- bundle_installations: {
841
- install_id: "install_id",
842
- },
843
- bundle_patches: {
844
- bundle_id: "bundle_id",
845
- id: "patch_id",
846
- order_index: "order_index",
847
- },
848
- bundles: {
849
- id: "id",
850
- },
851
- channels: {
852
- id: sql.raw("channel_id"),
853
- name: sql.raw("channel_name"),
854
- },
855
- api_keys: {
856
- id: "access_key_id",
857
- },
858
- release_catalogs: {
859
- scope_key: "scope_key",
860
- },
861
- releases: {
862
- id: "release_id",
863
- scope_key: "scope_key",
864
- },
865
- };
866
- const rootInsert = vi.fn(() => ({
867
- values: vi.fn(() => ({ execute: vi.fn(async () => undefined) })),
868
- }));
869
- const txInsert = vi.fn(() => ({
870
- values: vi.fn(() => ({ execute: vi.fn(async () => undefined) })),
871
- }));
872
- const createDb = (insert: typeof rootInsert) => ({
873
- _: { fullSchema: tables },
874
- $count: vi.fn(),
875
- delete: vi.fn(() => ({
876
- where: vi.fn(async () => undefined),
877
- })),
878
- insert,
879
- query: {
880
- bundle_events: {
881
- findFirst: vi.fn(),
882
- findMany: vi.fn(),
883
- },
884
- bundle_installations: {
885
- findFirst: vi.fn(),
886
- findMany: vi.fn(),
887
- },
888
- bundle_patches: {
889
- findFirst: vi.fn(),
890
- findMany: vi.fn(),
891
- },
892
- bundles: {
893
- findFirst: vi.fn(async () => undefined),
894
- findMany: vi.fn(),
895
- },
896
- channels: {
897
- findFirst: vi.fn(async () => ({
898
- id: transactionChannelId,
899
- name: "production",
900
- })),
901
- findMany: vi.fn(),
902
- },
903
- api_keys: {
904
- findFirst: vi.fn(),
905
- findMany: vi.fn(),
906
- },
907
- release_catalogs: {
908
- findFirst: vi.fn(),
909
- findMany: vi.fn(),
910
- },
911
- releases: {
912
- findFirst: vi.fn(),
913
- findMany: vi.fn(),
914
- },
915
- },
916
- select: vi.fn(),
917
- update: vi.fn(() => ({
918
- set: vi.fn(() => ({
919
- where: vi.fn(async () => undefined),
920
- })),
921
- })),
922
- });
923
- const txDb = createDb(txInsert);
924
- const transaction = vi.fn(
925
- async (operation: (tx: typeof txDb) => Promise<unknown>) =>
926
- operation(txDb),
927
- );
928
- const db = {
929
- ...createDb(rootInsert),
930
- transaction,
931
- };
932
- const adapter = drizzleAdapter({
933
- db,
934
- provider: "postgresql",
935
- });
936
-
937
- await adapter.commit({
938
- changes: [
939
- {
940
- model: "bundles",
941
- operation: "insert",
942
- row: bundleToRow(transactionBundle),
943
- },
944
- ],
945
- });
946
-
947
- expect(transaction).toHaveBeenCalledTimes(1);
948
- expect(txInsert).toHaveBeenCalledTimes(1);
949
- expect(rootInsert).not.toHaveBeenCalled();
950
- });
951
-
952
- it("does not expose an implicit MongoDB transaction", () => {
953
- const bundles = {
954
- countDocuments: vi.fn(),
955
- deleteMany: vi.fn(),
956
- distinct: vi.fn(),
957
- find: vi.fn(),
958
- findOne: vi.fn(),
959
- updateOne: vi.fn(async () => undefined),
960
- };
961
- const patches = {
962
- deleteMany: vi.fn(async () => undefined),
963
- find: vi.fn(),
964
- insertMany: vi.fn(),
965
- };
966
- const client = {
967
- db: () => ({
968
- collection: (name: string) =>
969
- name === "bundle_patches" ? patches : bundles,
970
- }),
971
- } as unknown as MongoClient;
972
- const adapter = mongoAdapter({ client });
973
-
974
- expect(Reflect.has(adapter, "transaction")).toBe(false);
975
- });
976
-
977
- it("uses a MongoDB session when transactions are enabled", async () => {
978
- const client = new MongoClient("mongodb://localhost");
979
- const session = client.startSession();
980
- const withTransaction = vi.fn(
981
- async (operation: (session: ClientSession) => Promise<unknown>) =>
982
- operation(session),
983
- );
984
- Object.defineProperty(session, "withTransaction", {
985
- value: withTransaction,
986
- });
987
- const insertOne = vi.fn(async () => undefined);
988
- Object.defineProperty(client, "db", {
989
- value: () => ({
990
- collection: () => ({
991
- findOne: vi.fn(async () => ({
992
- id: transactionChannelId,
993
- name: "production",
994
- })),
995
- insertOne,
996
- updateOne: vi.fn(async () => ({ matchedCount: 1 })),
997
- }),
998
- }),
999
- });
1000
- const withSession = vi.fn(
1001
- async (operation: (session: ClientSession) => Promise<unknown>) =>
1002
- operation(session),
1003
- );
1004
- Object.defineProperty(client, "withSession", { value: withSession });
1005
- const adapter = mongoAdapter({ client, transactions: true });
1006
-
1007
- await adapter.commit({
1008
- changes: [
1009
- {
1010
- model: "bundles",
1011
- operation: "insert",
1012
- row: bundleToRow(transactionBundle),
1013
- },
1014
- ],
1015
- });
1016
-
1017
- expect(withSession).toHaveBeenCalledTimes(1);
1018
- expect(withTransaction).toHaveBeenCalledTimes(1);
1019
- expect(insertOne).toHaveBeenCalledWith(bundleToRow(transactionBundle), {
1020
- session,
1021
- });
1022
- });
1023
- });
1024
-
1025
- describe("getBundleById", () => {
1026
- it("should retrieve bundle by id without Prisma validation errors", async () => {
1027
- const bundle: Bundle = {
1028
- archiveByteSize: 1_024,
1029
- id: "00000000-0000-0000-0000-000000000010",
1030
- platform: "ios",
1031
- fileHash: "test-hash",
1032
- gitCommitHash: null,
1033
- storageUri: "s3://test-bucket/test.zip",
1034
- };
1035
-
1036
- await hotUpdater.insertBundle(bundle);
1037
-
1038
- // This should not throw a Prisma validation error
1039
- const retrieved = await hotUpdater.getBundleById(bundle.id);
1040
-
1041
- expect(retrieved).not.toBeNull();
1042
- expect(retrieved?.id).toBe(bundle.id);
1043
- expect(retrieved?.platform).toBe(bundle.platform);
1044
- expect(retrieved?.fileHash).toBe(bundle.fileHash);
1045
- });
1046
-
1047
- it("should return null for non-existent bundle id", async () => {
1048
- const retrieved = await hotUpdater.getBundleById(
1049
- "99999999-9999-9999-9999-999999999999",
1050
- );
1051
-
1052
- expect(retrieved).toBeNull();
1053
- });
1054
- });
1055
-
1056
- describe("getChannels", () => {
1057
- it("retrieves canonical Channel rows without Prisma validation errors", async () => {
1058
- await hotUpdater.insertChannel({
1059
- onConflict: "returnExisting",
1060
- row: { id: "channel-production", name: "production" },
1061
- });
1062
- await hotUpdater.insertChannel({
1063
- onConflict: "returnExisting",
1064
- row: { id: "channel-staging", name: "staging" },
1065
- });
1066
-
1067
- const channels = await hotUpdater.getChannels();
1068
-
1069
- expect(channels).toHaveLength(2);
1070
- expect(channels.map(({ name }) => name)).toEqual([
1071
- "production",
1072
- "staging",
1073
- ]);
1074
- });
1075
-
1076
- it("should return empty array when no bundles exist", async () => {
1077
- const channels = await hotUpdater.getChannels();
1078
- expect(channels).toEqual([]);
1079
- });
1080
- });
1081
-
1082
- describe("getArtifactInfo with storage plugins", () => {
1083
- beforeEach(() => {
1084
- // Fix time for deterministic signed URLs
1085
- vi.useFakeTimers();
1086
- vi.setSystemTime(new Date("2025-10-15T12:21:00Z"));
1087
- });
1088
-
1089
- afterEach(() => {
1090
- vi.useRealTimers();
1091
- });
1092
-
1093
- it("resolves s3:// storage URI to signed URL via s3StoragePlugin", async () => {
1094
- const bundle: Bundle = {
1095
- archiveByteSize: 1_024,
1096
- id: "00000000-0000-0000-0000-000000000001",
1097
- platform: "ios",
1098
- fileHash: "hash123",
1099
- gitCommitHash: null,
1100
- storageUri: "s3://test-bucket/bundles/bundle.zip",
1101
- };
1102
-
1103
- await hotUpdater.insertBundle(bundle);
1104
-
1105
- const updateInfo = await hotUpdater.getArtifactInfo(bundle.id, NIL_UUID);
1106
-
1107
- expect(updateInfo).not.toBeNull();
1108
- expect(updateInfo?.fileUrl).toBe(
1109
- "https://s3.example.com/test-bucket/bundles/bundle.zip",
1110
- );
1111
- });
1112
-
1113
- it("returns manifest metadata and hbc patch descriptors", async () => {
1114
- const currentManifestStorageUri =
1115
- "s3://test-bucket/releases/bundles/00000000-0000-0000-0000-000000000101/manifest.json";
1116
- const nextManifestStorageUri =
1117
- "s3://test-bucket/releases/bundles/00000000-0000-0000-0000-000000000102/manifest.json";
1118
- const olderBundle: Bundle = {
1119
- archiveByteSize: 1_024,
1120
- id: "00000000-0000-0000-0000-000000000100",
1121
- platform: "ios",
1122
- fileHash: "hash-older-zip",
1123
- gitCommitHash: null,
1124
- storageUri:
1125
- "s3://test-bucket/releases/bundles/00000000-0000-0000-0000-000000000100/bundle.zip",
1126
- };
1127
- const currentBundle: Bundle = {
1128
- archiveByteSize: 1_024,
1129
- id: "00000000-0000-0000-0000-000000000101",
1130
- platform: "ios",
1131
- fileHash: "hash-current-zip",
1132
- gitCommitHash: null,
1133
- storageUri:
1134
- "s3://test-bucket/releases/bundles/00000000-0000-0000-0000-000000000101/bundle.zip",
1135
- assetBaseStorageUri: "s3://test-bucket/releases/assets",
1136
- manifestFileHash: "sig:manifest-current",
1137
- manifestStorageUri: currentManifestStorageUri,
1138
- };
1139
- const nextBundle: Bundle = {
1140
- archiveByteSize: 1_024,
1141
- id: "00000000-0000-0000-0000-000000000102",
1142
- platform: "ios",
1143
- fileHash: "hash-next-zip",
1144
- gitCommitHash: null,
1145
- storageUri:
1146
- "s3://test-bucket/releases/bundles/00000000-0000-0000-0000-000000000102/bundle.zip",
1147
- assetBaseStorageUri: "s3://test-bucket/releases/assets",
1148
- manifestFileHash: "sig:manifest-next",
1149
- manifestStorageUri: nextManifestStorageUri,
1150
- patches: [
1151
- {
1152
- baseBundleId: "00000000-0000-0000-0000-000000000100",
1153
- baseFileHash: "hash-older-bundle",
1154
- byteSize: 48,
1155
- patchFileHash: "hash-older-bsdiff",
1156
- patchStorageUri:
1157
- "s3://test-bucket/releases/bundles/00000000-0000-0000-0000-000000000102/patches/00000000-0000-0000-0000-000000000100/index.ios.bundle.bsdiff",
1158
- },
1159
- {
1160
- baseBundleId: currentBundle.id,
1161
- baseFileHash: "hash-old-bundle",
1162
- byteSize: 48,
1163
- patchFileHash: "hash-bsdiff",
1164
- patchStorageUri:
1165
- "s3://test-bucket/releases/bundles/00000000-0000-0000-0000-000000000102/patches/00000000-0000-0000-0000-000000000101/index.ios.bundle.bsdiff",
1166
- },
1167
- ],
1168
- };
1169
- storageTexts.set(
1170
- currentManifestStorageUri,
1171
- JSON.stringify({
1172
- assets: {
1173
- "assets/logo.png": {
1174
- fileHash: "hash-logo",
1175
- },
1176
- "index.ios.bundle": {
1177
- fileHash: "hash-old-bundle",
1178
- },
1179
- },
1180
- bundleId: currentBundle.id,
1181
- }),
1182
- );
1183
- storageTexts.set(
1184
- nextManifestStorageUri,
1185
- JSON.stringify({
1186
- assets: {
1187
- "assets/logo.png": {
1188
- fileHash: "hash-logo",
1189
- },
1190
- "index.ios.bundle": {
1191
- fileHash: "hash-new-bundle",
1192
- },
1193
- },
1194
- bundleId: nextBundle.id,
1195
- }),
1196
- );
1197
- const fetchMock = vi.fn<typeof fetch>(async () => {
1198
- return new Response("manifest fetch should not be used", {
1199
- status: 500,
1200
- });
1201
- });
1202
-
1203
- await hotUpdater.insertBundle(olderBundle);
1204
- await hotUpdater.insertBundle(currentBundle);
1205
- await hotUpdater.insertBundle(nextBundle);
1206
- vi.stubGlobal("fetch", fetchMock);
1207
-
1208
- try {
1209
- await expect(
1210
- hotUpdater.getArtifactInfo(nextBundle.id, currentBundle.id),
1211
- ).resolves.toEqual({
1212
- changedAssets: {
1213
- "index.ios.bundle": {
1214
- file: {
1215
- compression: "br",
1216
- url: "https://s3.example.com/test-bucket/releases/assets/sha256/ha/hash-new-bundle.br",
1217
- },
1218
- fileHash: "hash-new-bundle",
1219
- patch: {
1220
- algorithm: "bsdiff",
1221
- baseBundleId: currentBundle.id,
1222
- baseFileHash: "hash-old-bundle",
1223
- patchFileHash: "hash-bsdiff",
1224
- patchUrl:
1225
- "https://s3.example.com/test-bucket/releases/bundles/00000000-0000-0000-0000-000000000102/patches/00000000-0000-0000-0000-000000000101/index.ios.bundle.bsdiff",
1226
- },
1227
- },
1228
- },
1229
- fileHash: "hash-next-zip",
1230
- fileUrl:
1231
- "https://s3.example.com/test-bucket/releases/bundles/00000000-0000-0000-0000-000000000102/bundle.zip",
1232
- manifestFileHash: "sig:manifest-next",
1233
- manifestUrl:
1234
- "https://s3.example.com/test-bucket/releases/bundles/00000000-0000-0000-0000-000000000102/manifest.json",
1235
- });
1236
- expect(fetchMock).not.toHaveBeenCalled();
1237
- } finally {
1238
- vi.unstubAllGlobals();
1239
- }
1240
- });
1241
-
1242
- it("propagates manifest storage read failures", async () => {
1243
- const nextManifestStorageUri =
1244
- "s3://test-bucket/releases/bundles/00000000-0000-0000-0000-000000000109/manifest.json";
1245
- const nextBundle: Bundle = {
1246
- archiveByteSize: 1_024,
1247
- id: "00000000-0000-0000-0000-000000000109",
1248
- platform: "ios",
1249
- fileHash: "hash-next-zip",
1250
- gitCommitHash: null,
1251
- storageUri:
1252
- "s3://test-bucket/releases/bundles/00000000-0000-0000-0000-000000000109/bundle.zip",
1253
- assetBaseStorageUri: "s3://test-bucket/releases/assets",
1254
- manifestFileHash: "sig:manifest-next",
1255
- manifestStorageUri: nextManifestStorageUri,
1256
- };
1257
-
1258
- await hotUpdater.insertBundle(nextBundle);
1259
- storageTexts.set(
1260
- nextManifestStorageUri,
1261
- new Error("storage read failed"),
1262
- );
1263
-
1264
- await expect(
1265
- hotUpdater.getArtifactInfo(nextBundle.id, NIL_UUID),
1266
- ).rejects.toThrow("storage read failed");
1267
- });
1268
- });
1269
- });