@hot-updater/server 1.0.0-rc.16 → 1.0.0-rc.18

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 (309) hide show
  1. package/dist/adapters/drizzle.cjs +5 -5
  2. package/dist/adapters/drizzle.mjs +4 -4
  3. package/dist/adapters/kysely.cjs +3 -3
  4. package/dist/adapters/kysely.mjs +2 -2
  5. package/dist/adapters/mongodb.cjs +3 -3
  6. package/dist/adapters/mongodb.mjs +2 -2
  7. package/dist/adapters/mongodbAdapter.cjs +19 -1
  8. package/dist/adapters/mongodbAdapter.mjs +19 -1
  9. package/dist/adapters/prisma.cjs +5 -5
  10. package/dist/adapters/prisma.mjs +4 -4
  11. package/dist/assembly/assemblePlugins.cjs +47 -28
  12. package/dist/assembly/assemblePlugins.d.cts +3 -7
  13. package/dist/assembly/assemblePlugins.d.mts +3 -7
  14. package/dist/assembly/assemblePlugins.mjs +46 -27
  15. package/dist/assembly/clientPlugins.cjs +86 -0
  16. package/dist/assembly/clientPlugins.d.cts +16 -0
  17. package/dist/assembly/clientPlugins.d.mts +16 -0
  18. package/dist/assembly/clientPlugins.mjs +86 -0
  19. package/dist/assembly/configError.cjs +7 -0
  20. package/dist/assembly/configError.d.cts +7 -0
  21. package/dist/assembly/configError.d.mts +7 -0
  22. package/dist/assembly/configError.mjs +7 -0
  23. package/dist/assembly/databasePlugins.cjs +5 -1
  24. package/dist/assembly/databasePlugins.d.cts +5 -5
  25. package/dist/assembly/databasePlugins.d.mts +5 -5
  26. package/dist/assembly/databasePlugins.mjs +5 -1
  27. package/dist/assembly/pluginCli.cjs +125 -0
  28. package/dist/assembly/pluginCli.d.cts +59 -0
  29. package/dist/assembly/pluginCli.d.mts +59 -0
  30. package/dist/assembly/pluginCli.mjs +121 -0
  31. package/dist/createHotUpdaterCore.cjs +14 -16
  32. package/dist/createHotUpdaterCore.d.cts +10 -3
  33. package/dist/createHotUpdaterCore.d.mts +10 -3
  34. package/dist/createHotUpdaterCore.mjs +11 -13
  35. package/dist/database/aggregateBatching.cjs +626 -0
  36. package/dist/database/aggregateBatching.d.cts +10 -0
  37. package/dist/database/aggregateBatching.d.mts +10 -0
  38. package/dist/database/aggregateBatching.mjs +625 -0
  39. package/dist/{insights/errors.cjs → database/busy.cjs} +2 -15
  40. package/dist/database/busy.d.cts +12 -0
  41. package/dist/database/busy.d.mts +12 -0
  42. package/dist/{insights/errors.mjs → database/busy.mjs} +3 -14
  43. package/dist/database/database.cjs +22 -3
  44. package/dist/database/database.d.cts +15 -2
  45. package/dist/database/database.d.mts +15 -2
  46. package/dist/database/database.mjs +22 -3
  47. package/dist/database/definitions.d.cts +10 -0
  48. package/dist/database/definitions.d.mts +10 -0
  49. package/dist/database/engine.d.cts +2 -1
  50. package/dist/database/engine.d.mts +2 -1
  51. package/dist/database/engineAggregates.cjs +7 -4
  52. package/dist/database/engineAggregates.mjs +8 -5
  53. package/dist/database/engineReads.cjs +5 -3
  54. package/dist/database/engineReads.mjs +6 -4
  55. package/dist/database/engineTransaction.cjs +2 -6
  56. package/dist/database/engineTransaction.mjs +2 -6
  57. package/dist/database/fence.cjs +2 -1
  58. package/dist/database/fence.mjs +2 -1
  59. package/dist/database/index.cjs +17 -8
  60. package/dist/database/index.d.cts +5 -4
  61. package/dist/database/index.d.mts +5 -4
  62. package/dist/database/index.mjs +6 -5
  63. package/dist/database/kv/kvAdapter.cjs +15 -3
  64. package/dist/database/kv/kvAdapter.d.cts +8 -0
  65. package/dist/database/kv/kvAdapter.d.mts +8 -0
  66. package/dist/database/kv/kvAdapter.mjs +16 -4
  67. package/dist/database/resolveSchema.cjs +4 -1
  68. package/dist/database/resolveSchema.d.cts +1 -1
  69. package/dist/database/resolveSchema.d.mts +1 -1
  70. package/dist/database/resolveSchema.mjs +4 -1
  71. package/dist/database/retention.cjs +92 -0
  72. package/dist/database/retention.mjs +90 -0
  73. package/dist/database/schema.cjs +5 -2
  74. package/dist/database/schema.d.cts +30 -1
  75. package/dist/database/schema.d.mts +30 -1
  76. package/dist/database/schema.mjs +5 -2
  77. package/dist/database/sql/sqlAdapter.cjs +8 -0
  78. package/dist/database/sql/sqlAdapter.mjs +9 -1
  79. package/dist/database/sql/sqlSchema.cjs +56 -0
  80. package/dist/database/sql/sqlSchema.mjs +55 -1
  81. package/dist/db/coreDatabase.cjs +85 -0
  82. package/dist/db/coreDatabase.d.cts +57 -0
  83. package/dist/db/coreDatabase.d.mts +57 -0
  84. package/dist/db/coreDatabase.mjs +78 -0
  85. package/dist/db/index.cjs +11 -3
  86. package/dist/db/index.d.cts +7 -3
  87. package/dist/db/index.d.mts +7 -3
  88. package/dist/db/index.mjs +6 -3
  89. package/dist/db/types.d.cts +3 -3
  90. package/dist/db/types.d.mts +3 -3
  91. package/dist/diff.cjs +3 -0
  92. package/dist/diff.d.cts +2 -0
  93. package/dist/diff.d.mts +2 -0
  94. package/dist/diff.mjs +2 -0
  95. package/dist/handler.cjs +2 -14
  96. package/dist/handler.mjs +1 -13
  97. package/dist/handlerReleaseCatalogRoutes.cjs +21 -2
  98. package/dist/handlerReleaseCatalogRoutes.mjs +21 -2
  99. package/dist/index.cjs +2 -6
  100. package/dist/index.d.cts +4 -7
  101. package/dist/index.d.mts +4 -7
  102. package/dist/index.mjs +2 -4
  103. package/dist/package.cjs +1 -1
  104. package/dist/package.mjs +1 -1
  105. package/dist/{apiKeys.cjs → plugins/api-keys/apiKeys.cjs} +1 -1
  106. package/dist/{apiKeys.d.cts → plugins/api-keys/apiKeys.d.cts} +2 -2
  107. package/dist/{apiKeys.d.mts → plugins/api-keys/apiKeys.d.mts} +2 -2
  108. package/dist/{apiKeys.mjs → plugins/api-keys/apiKeys.mjs} +1 -1
  109. package/dist/plugins/api-keys/cli.cjs +115 -0
  110. package/dist/plugins/api-keys/cli.mjs +114 -0
  111. package/dist/plugins/api-keys/index.cjs +9 -6
  112. package/dist/plugins/api-keys/index.d.cts +4 -5
  113. package/dist/plugins/api-keys/index.d.mts +4 -5
  114. package/dist/plugins/api-keys/index.mjs +9 -7
  115. package/dist/plugins/api-keys/model.d.cts +20 -2
  116. package/dist/plugins/api-keys/model.d.mts +20 -2
  117. package/dist/plugins/definePlugin.cjs +1 -1
  118. package/dist/plugins/definePlugin.d.cts +130 -3
  119. package/dist/plugins/definePlugin.d.mts +130 -3
  120. package/dist/plugins/definePlugin.mjs +1 -1
  121. package/dist/plugins/index.cjs +25 -4
  122. package/dist/plugins/index.d.cts +7 -4
  123. package/dist/plugins/index.d.mts +7 -4
  124. package/dist/plugins/index.mjs +6 -4
  125. package/dist/plugins/insights/contract.cjs +193 -0
  126. package/dist/plugins/insights/contract.mjs +189 -0
  127. package/dist/{insights → plugins/insights}/domain.d.cts +60 -15
  128. package/dist/{insights → plugins/insights}/domain.d.mts +60 -15
  129. package/dist/plugins/insights/errors.cjs +15 -0
  130. package/dist/plugins/insights/errors.mjs +14 -0
  131. package/dist/{insights → plugins/insights}/eventInput.cjs +155 -22
  132. package/dist/{insights → plugins/insights}/eventInput.mjs +155 -22
  133. package/dist/plugins/insights/eventRow.cjs +49 -0
  134. package/dist/plugins/insights/eventRow.d.cts +64 -0
  135. package/dist/plugins/insights/eventRow.d.mts +64 -0
  136. package/dist/plugins/insights/eventRow.mjs +47 -0
  137. package/dist/plugins/insights/index.cjs +106 -26
  138. package/dist/plugins/insights/index.d.cts +130 -27
  139. package/dist/plugins/insights/index.d.mts +130 -27
  140. package/dist/plugins/insights/index.mjs +106 -29
  141. package/dist/plugins/insights/model.cjs +2 -2
  142. package/dist/plugins/insights/model.d.cts +1 -1
  143. package/dist/plugins/insights/model.d.mts +1 -1
  144. package/dist/plugins/insights/model.mjs +1 -1
  145. package/dist/plugins/insights/modelTypes.d.cts +176 -0
  146. package/dist/plugins/insights/modelTypes.d.mts +176 -0
  147. package/dist/plugins/insights/overview.cjs +109 -0
  148. package/dist/plugins/insights/overview.d.cts +15 -0
  149. package/dist/plugins/insights/overview.d.mts +15 -0
  150. package/dist/plugins/insights/overview.mjs +107 -0
  151. package/dist/{insights → plugins/insights}/provider.cjs +33 -14
  152. package/dist/{insights → plugins/insights}/provider.d.cts +2 -2
  153. package/dist/{insights → plugins/insights}/provider.d.mts +2 -2
  154. package/dist/{insights → plugins/insights}/provider.mjs +30 -11
  155. package/dist/{insights → plugins/insights}/queryInput.cjs +2 -2
  156. package/dist/{insights → plugins/insights}/queryInput.mjs +2 -2
  157. package/dist/plugins/insights/reads.cjs +298 -88
  158. package/dist/plugins/insights/reads.d.cts +61 -0
  159. package/dist/plugins/insights/reads.d.mts +61 -0
  160. package/dist/plugins/insights/reads.mjs +298 -90
  161. package/dist/plugins/insights/recordEvent.cjs +223 -39
  162. package/dist/plugins/insights/recordEvent.d.cts +9 -4
  163. package/dist/plugins/insights/recordEvent.d.mts +9 -4
  164. package/dist/plugins/insights/recordEvent.mjs +221 -37
  165. package/dist/{insights → plugins/insights}/routes.cjs +3 -30
  166. package/dist/{insights → plugins/insights}/routes.mjs +4 -28
  167. package/dist/plugins/insights/schema.cjs +182 -40
  168. package/dist/plugins/insights/schema.d.cts +446 -6
  169. package/dist/plugins/insights/schema.d.mts +446 -6
  170. package/dist/plugins/insights/schema.mjs +180 -41
  171. package/dist/plugins/insights/testing/eventRow.d.mts +64 -0
  172. package/dist/plugins/insights/testing/expectInsightsIndex.mjs +18 -0
  173. package/dist/plugins/insights/testing/fixtures.d.mts +8 -0
  174. package/dist/plugins/insights/testing/fixtures.mjs +25 -0
  175. package/dist/plugins/insights/testing/index.d.mts +24 -0
  176. package/dist/plugins/insights/testing/index.mjs +25 -0
  177. package/dist/plugins/insights/testing/insightsModelTests.mjs +714 -0
  178. package/dist/plugins/insights/testing/modelTypes.d.mts +176 -0
  179. package/dist/plugins/insights/testing/setupInsightsHttpTestSuite.d.mts +11 -0
  180. package/dist/plugins/insights/testing/setupInsightsHttpTestSuite.mjs +107 -0
  181. package/dist/plugins/insights/testing/setupInsightsModelTestSuite.d.mts +11 -0
  182. package/dist/plugins/insights/testing/setupInsightsModelTestSuite.mjs +31 -0
  183. package/dist/plugins/insights/testing/types.d.mts +26 -0
  184. package/dist/{insights → plugins/insights}/types.d.cts +3 -2
  185. package/dist/{insights → plugins/insights}/types.d.mts +3 -2
  186. package/package.json +18 -7
  187. package/src/adapters/drizzle.conformance.integration.spec.ts +2 -2
  188. package/src/adapters/drizzle.readBudgets.integration.spec.ts +6 -4
  189. package/src/adapters/drizzle.spec.ts +15 -7
  190. package/src/adapters/drizzle.ts +6 -6
  191. package/src/adapters/kysely.conformance.integration.spec.ts +2 -2
  192. package/src/adapters/kysely.readBudgets.integration.spec.ts +4 -2
  193. package/src/adapters/kysely.spec.ts +13 -9
  194. package/src/adapters/kysely.ts +2 -2
  195. package/src/adapters/mongodb.integration.spec.ts +98 -7
  196. package/src/adapters/mongodb.ts +2 -2
  197. package/src/adapters/mongodbAdapter.ts +14 -0
  198. package/src/adapters/prisma.conformance.integration.spec.ts +2 -2
  199. package/src/adapters/prisma.integration.spec.ts +16 -8
  200. package/src/adapters/prisma.readBudgets.integration.spec.ts +5 -2
  201. package/src/adapters/prisma.spec.ts +17 -9
  202. package/src/adapters/prisma.ts +6 -6
  203. package/src/adapters/prismaTestClients.ts +8 -1
  204. package/src/assembly/assemblePlugins.ts +73 -40
  205. package/src/assembly/assembly.spec.ts +63 -11
  206. package/src/assembly/assembly.types.spec.ts +50 -2
  207. package/src/assembly/clientPlugins.ts +113 -0
  208. package/src/assembly/configError.ts +4 -0
  209. package/src/assembly/databasePlugins.ts +11 -5
  210. package/src/assembly/pluginCli.spec.ts +254 -0
  211. package/src/assembly/pluginCli.ts +248 -0
  212. package/src/assembly/{builtInRoutes.spec.ts → pluginRoutes.spec.ts} +10 -37
  213. package/src/createHotUpdaterCore.ts +21 -17
  214. package/src/database/aggregateBatching.spec.ts +577 -0
  215. package/src/database/aggregateBatching.ts +803 -0
  216. package/src/{insights/errors.spec.ts → database/busy.spec.ts} +2 -5
  217. package/src/{insights/errors.ts → database/busy.ts} +1 -13
  218. package/src/database/database.ts +39 -8
  219. package/src/database/definitions.ts +4 -0
  220. package/src/database/engineAggregates.spec.ts +4 -7
  221. package/src/database/engineAggregates.ts +5 -9
  222. package/src/database/engineReads.ts +7 -5
  223. package/src/database/engineTransaction.ts +1 -7
  224. package/src/database/fence.spec.ts +5 -5
  225. package/src/database/fence.ts +4 -0
  226. package/src/database/index.ts +13 -7
  227. package/src/database/kv/kvAdapter.batching.integration.spec.ts +15 -0
  228. package/src/database/kv/kvAdapter.conformance.integration.spec.ts +2 -0
  229. package/src/database/kv/kvAdapter.spec.ts +128 -1
  230. package/src/database/kv/kvAdapter.ts +30 -1
  231. package/src/database/kv/kvTestStore.ts +28 -1
  232. package/src/database/resolveSchema.ts +4 -1
  233. package/src/database/retention.spec.ts +314 -0
  234. package/src/database/retention.ts +129 -0
  235. package/src/database/schema.ts +44 -0
  236. package/src/database/sql/sqlAdapter.integration.spec.ts +4 -7
  237. package/src/database/sql/sqlAdapter.readBudgets.integration.spec.ts +18 -4
  238. package/src/database/sql/sqlAdapter.spec.ts +91 -3
  239. package/src/database/sql/sqlAdapter.ts +20 -0
  240. package/src/database/sql/sqlSchema.ts +81 -0
  241. package/src/databaseTestSuite.spec.ts +9 -4
  242. package/src/db/coreDatabase.ts +153 -0
  243. package/src/db/engineSql.spec.ts +8 -7
  244. package/src/db/index.ts +19 -2
  245. package/src/db/pluginTables.spec.ts +57 -27
  246. package/src/db/types.ts +3 -3
  247. package/src/diff.ts +6 -0
  248. package/src/handler-standalone.integration.spec.ts +2 -3
  249. package/src/handler.ts +1 -32
  250. package/src/handlerReleaseCatalogRoutes.ts +26 -2
  251. package/src/index.ts +0 -10
  252. package/src/{apiKeys.integration.spec.ts → plugins/api-keys/apiKeys.integration.spec.ts} +4 -4
  253. package/src/{apiKeys.spec.ts → plugins/api-keys/apiKeys.spec.ts} +3 -3
  254. package/src/{apiKeys.ts → plugins/api-keys/apiKeys.ts} +1 -1
  255. package/src/plugins/api-keys/apiKeysPlugin.spec.ts +11 -15
  256. package/src/plugins/api-keys/cli.spec.ts +187 -0
  257. package/src/plugins/api-keys/cli.ts +140 -0
  258. package/src/plugins/api-keys/index.ts +48 -41
  259. package/src/plugins/api-keys/model.ts +21 -2
  260. package/src/plugins/definePlugin.ts +144 -2
  261. package/src/plugins/index.ts +20 -2
  262. package/src/plugins/insights/contract.spec.ts +285 -0
  263. package/src/plugins/insights/contract.ts +372 -0
  264. package/src/{insights → plugins/insights}/domain.ts +73 -15
  265. package/src/plugins/insights/errors.ts +11 -0
  266. package/src/{insights → plugins/insights}/eventInput.ts +189 -29
  267. package/src/plugins/insights/eventRow.ts +209 -0
  268. package/src/plugins/insights/index.ts +181 -45
  269. package/src/{insights → plugins/insights}/insights.integration.spec.ts +330 -34
  270. package/src/plugins/insights/insightsRollout.integration.spec.ts +1 -2
  271. package/src/plugins/insights/model.spec.ts +3 -5
  272. package/src/plugins/insights/model.ts +2 -3
  273. package/src/plugins/insights/modelTypes.ts +197 -0
  274. package/src/plugins/insights/overview.spec.ts +64 -0
  275. package/src/plugins/insights/overview.ts +214 -0
  276. package/src/{insights → plugins/insights}/provider.spec.ts +21 -10
  277. package/src/{insights → plugins/insights}/provider.ts +58 -21
  278. package/src/{insights → plugins/insights}/queryInput.ts +2 -2
  279. package/src/plugins/insights/reads.spec.ts +340 -52
  280. package/src/plugins/insights/reads.ts +453 -123
  281. package/src/plugins/insights/recordEvent.spec.ts +474 -20
  282. package/src/plugins/insights/recordEvent.ts +301 -63
  283. package/src/plugins/insights/retention.spec.ts +115 -0
  284. package/src/{insights → plugins/insights}/routes.ts +1 -31
  285. package/src/plugins/insights/schema.ts +356 -176
  286. package/src/plugins/insights/testing/expectInsightsIndex.spec.ts +42 -0
  287. package/src/plugins/insights/testing/expectInsightsIndex.ts +20 -0
  288. package/src/plugins/insights/testing/fixtures.ts +30 -0
  289. package/src/plugins/insights/testing/index.ts +45 -0
  290. package/src/plugins/insights/testing/insightsModelTests.ts +860 -0
  291. package/src/plugins/insights/testing/setupInsightsHttpTestSuite.ts +152 -0
  292. package/src/plugins/insights/testing/setupInsightsModelTestSuite.ts +36 -0
  293. package/src/plugins/insights/testing/types.ts +30 -0
  294. package/src/{insights → plugins/insights}/types.ts +1 -1
  295. package/src/readBudgets.testFixtures.ts +2 -2
  296. package/src/releaseCatalogRoutes.integration.spec.ts +7 -0
  297. package/src/retention.spec.ts +73 -0
  298. package/src/runtime.spec.ts +11 -12
  299. package/src/runtime.testFixtures.ts +7 -2
  300. package/src/testUtilsMutation.integration.spec.ts +2 -1
  301. package/src/testUtilsPackage.integration.spec.ts +7 -3
  302. package/dist/db/builtInDatabase.cjs +0 -104
  303. package/dist/db/builtInDatabase.d.cts +0 -38
  304. package/dist/db/builtInDatabase.d.mts +0 -38
  305. package/dist/db/builtInDatabase.mjs +0 -97
  306. package/dist/plugins/builtIn.cjs +0 -7
  307. package/dist/plugins/builtIn.mjs +0 -6
  308. package/src/db/builtInDatabase.ts +0 -149
  309. package/src/plugins/builtIn.ts +0 -5
@@ -1,3 +1,4 @@
1
+ import { definePlugin } from "../definePlugin";
1
2
  import {
2
3
  API_KEY_HEADER_NAME,
3
4
  authenticateApiKey,
@@ -5,13 +6,18 @@ import {
5
6
  normalizeApiKeyHeaderName,
6
7
  provisionApiKey,
7
8
  registerApiKey,
8
- } from "../../apiKeys";
9
- import { markBuiltIn } from "../builtIn";
10
- import { definePlugin } from "../definePlugin";
9
+ } from "./apiKeys";
10
+ import { apiKeysCli } from "./cli";
11
11
  import { createApiKeyModel } from "./model";
12
12
  import { apiKeysSchema } from "./schema";
13
13
 
14
- export { createApiKeyModel } from "./model";
14
+ export {
15
+ API_KEY_HEADER_NAME,
16
+ type ApiKeyManagementAPI,
17
+ type ApiKeyMetadata,
18
+ type CreatedApiKey,
19
+ } from "./apiKeys";
20
+ export { createApiKeyModel, type ApiKeyModel, type ApiKeyRow } from "./model";
15
21
  export { apiKeysSchema, type ApiKeysSchema } from "./schema";
16
22
 
17
23
  export interface ApiKeysOptions {
@@ -20,47 +26,48 @@ export interface ApiKeysOptions {
20
26
  }
21
27
 
22
28
  /**
23
- * Built-in API keys: protects client routes with keys whose SHA-256 digests
29
+ * API keys: protects client routes with keys whose SHA-256 digests
24
30
  * are stored, and manages them in-process.
25
31
  */
26
32
  export const apiKeys = (options: ApiKeysOptions = {}) => {
27
33
  const headerName = normalizeApiKeyHeaderName(
28
34
  options.headerName ?? API_KEY_HEADER_NAME,
29
35
  );
30
- return markBuiltIn(
31
- definePlugin({
32
- id: "apiKeys",
33
- provides: { clientAuth: true },
34
- schemaVersion: "1.0.0",
35
- schema: apiKeysSchema,
36
- init: ({ db }) => {
37
- const model = createApiKeyModel(db);
38
- return {
39
- api: {
40
- ...createApiKeyManagement({ apiKeys: model }),
41
- /** Registers a known plaintext key idempotently, for managed init. */
42
- register: (input: {
43
- readonly apiKey: string;
44
- readonly name: string;
45
- readonly createdAtMs?: number;
46
- }) => registerApiKey({ ...input, apiKeys: model }),
47
- /** Reuses a saved key or creates one, for managed init. */
48
- provision: (input: {
49
- readonly existingApiKey?: string;
50
- readonly name: string;
51
- }) => provisionApiKey({ ...input, apiKeys: model }),
52
- },
53
- clientAuth: {
54
- varyHeaders: [headerName],
55
- authenticate: (headers: Headers) =>
56
- authenticateApiKey({
57
- apiKeys: model,
58
- headerName,
59
- request: { headers } as Request,
60
- }),
61
- },
62
- };
63
- },
64
- }),
65
- );
36
+ return definePlugin({
37
+ id: "apiKeys",
38
+ // Keeps its table's name, api_keys, and with it the camelCase id.
39
+ namespace: false,
40
+ provides: { clientAuth: true },
41
+ schemaVersion: "1.0.0",
42
+ schema: apiKeysSchema,
43
+ init: ({ db }) => {
44
+ const model = createApiKeyModel(db);
45
+ return {
46
+ api: {
47
+ ...createApiKeyManagement({ apiKeys: model }),
48
+ /** Registers a known plaintext key idempotently, for managed init. */
49
+ register: (input: {
50
+ readonly apiKey: string;
51
+ readonly name: string;
52
+ readonly createdAtMs?: number;
53
+ }) => registerApiKey({ ...input, apiKeys: model }),
54
+ /** Reuses a saved key or creates one, for managed init. */
55
+ provision: (input: {
56
+ readonly existingApiKey?: string;
57
+ readonly name: string;
58
+ }) => provisionApiKey({ ...input, apiKeys: model }),
59
+ },
60
+ clientAuth: {
61
+ varyHeaders: [headerName],
62
+ authenticate: (headers: Headers) =>
63
+ authenticateApiKey({
64
+ apiKeys: model,
65
+ headerName,
66
+ request: { headers } as Request,
67
+ }),
68
+ },
69
+ };
70
+ },
71
+ cli: apiKeysCli(headerName),
72
+ });
66
73
  };
@@ -1,9 +1,28 @@
1
- import type { ApiKeyModel, ApiKeyRow } from "@hot-updater/plugin-core";
2
-
3
1
  import type { HotUpdaterDatabase } from "../../database/database";
4
2
  import { DatabaseConstraintError } from "../../database/errors";
5
3
  import type { ApiKeysSchema } from "./schema";
6
4
 
5
+ export interface ApiKeyRow {
6
+ readonly id: string;
7
+ readonly hash: string;
8
+ readonly name: string;
9
+ readonly prefix: string;
10
+ readonly role: "client";
11
+ readonly created_at_ms: number;
12
+ readonly revoked_at_ms: number | null;
13
+ }
14
+
15
+ /** The api-keys plugin's storage: key rows by id and by hash. */
16
+ export interface ApiKeyModel {
17
+ create(row: ApiKeyRow): Promise<"created" | "existing">;
18
+ findByHash(hash: string): Promise<ApiKeyRow | null>;
19
+ list(): Promise<readonly ApiKeyRow[]>;
20
+ revoke(input: {
21
+ readonly id: string;
22
+ readonly revokedAtMs: number;
23
+ }): Promise<ApiKeyRow | null>;
24
+ }
25
+
7
26
  const toRow = (row: Readonly<Record<string, unknown>>): ApiKeyRow =>
8
27
  ({
9
28
  id: row.id,
@@ -19,7 +19,7 @@ export interface PluginEndpoint {
19
19
  ) => Promise<Response>;
20
20
  }
21
21
 
22
- /** The client-route policy a plugin provides, such as API keys. */
22
+ /** The client-route policy a plugin provides, such as a key or token check. */
23
23
  export interface ClientAuth {
24
24
  /** Request headers the decision reads; core adds them to `Vary` on cacheable client responses. */
25
25
  readonly varyHeaders: readonly string[];
@@ -56,6 +56,137 @@ export type InstanceFor<TProvides, TInstance> = TProvides extends {
56
56
  readonly clientAuth?: "Declare provides: { clientAuth: true } to return clientAuth";
57
57
  };
58
58
 
59
+ /** A positional argument of a plugin command. */
60
+ export interface PluginCommandArgument {
61
+ /** The key of its value in `args`. */
62
+ readonly name: string;
63
+ readonly description: string;
64
+ /** Defaults to true. */
65
+ readonly required?: boolean;
66
+ }
67
+
68
+ /** An option of a plugin command. */
69
+ export interface PluginCommandOption {
70
+ /** Flags as the CLI writes them, such as `--name <name>` or `-y, --yes`. */
71
+ readonly flags: string;
72
+ readonly description: string;
73
+ /** The command fails without it. */
74
+ readonly required?: boolean;
75
+ }
76
+
77
+ export interface PluginTableColumn<TKey extends string> {
78
+ readonly key: TKey;
79
+ readonly label?: string;
80
+ /** Styles the padded cell. */
81
+ readonly format?: (value: string) => string;
82
+ }
83
+
84
+ /**
85
+ * The CLI's output style, so plugin commands read like core ones: the
86
+ * formatters return styled text, and the writers print it.
87
+ */
88
+ export interface PluginCommandUi {
89
+ block(heading: string, lines: readonly string[]): string;
90
+ kv(label: string, value: string): string;
91
+ table<TKey extends string>(
92
+ columns: readonly PluginTableColumn<TKey>[],
93
+ rows: readonly Readonly<Record<TKey, string>>[],
94
+ ): string;
95
+ id(value: string): string;
96
+ muted(value: string): string;
97
+ success(value: string): string;
98
+ danger(value: string): string;
99
+ warning(value: string): string;
100
+ message(text: string): void;
101
+ info(text: string): void;
102
+ warn(text: string): void;
103
+ /** Writes machine-readable output, such as JSON, to stdout. */
104
+ print(text: string): void;
105
+ /**
106
+ * Returns once the user agrees to `message`. Declining ends the command,
107
+ * and a non-interactive shell fails it, asking for `-y`.
108
+ */
109
+ confirm(message: string): Promise<void>;
110
+ }
111
+
112
+ /** A plugin command run over a database the CLI opens itself. */
113
+ export interface PluginCommandContext<Api = unknown> {
114
+ /** The plugin's API over that database, assembled as the server assembles it. */
115
+ readonly api: Api;
116
+ /** Positional arguments by name. */
117
+ readonly args: Readonly<Record<string, string | undefined>>;
118
+ /** Options by camel-cased long flag: `dryRun` for `--dry-run`. */
119
+ readonly options: Readonly<Record<string, unknown>>;
120
+ readonly ui: PluginCommandUi;
121
+ }
122
+
123
+ /**
124
+ * A `hot-updater` command a plugin adds. It groups `commands`, or runs `run`
125
+ * over a database the CLI opens itself, so it refuses a `standaloneRepository`
126
+ * config. A command that runs also takes the server config's path as its
127
+ * last, optional argument.
128
+ */
129
+ export interface PluginCommand<Api = unknown> {
130
+ /** Lowercase words joined by hyphens, such as `api-key`. */
131
+ readonly name: string;
132
+ readonly description: string;
133
+ readonly arguments?: readonly PluginCommandArgument[];
134
+ readonly options?: readonly PluginCommandOption[];
135
+ readonly commands?: readonly PluginCommand<Api>[];
136
+ run?(context: PluginCommandContext<Api>): Promise<void>;
137
+ }
138
+
139
+ /**
140
+ * The credential an app sends to client routes that the plugin's clientAuth
141
+ * guards. Init provisions it and prints the header to send, the agent
142
+ * scaffold stores it, and doctor checks it.
143
+ */
144
+ export interface PluginClientCredential<Api = unknown> {
145
+ /** Its name in output, such as "API key". */
146
+ readonly label: string;
147
+ /** The request header that carries it, one of clientAuth's varyHeaders. */
148
+ readonly header: string;
149
+ /** The environment variable init stores it in. */
150
+ readonly env: string;
151
+ /** A new credential, made without a database, so tooling can save it before registering it. */
152
+ generate(): string;
153
+ /** Registers `existing` idempotently, or creates one; returns the credential. */
154
+ provision(
155
+ api: Api,
156
+ input: { readonly existing?: string; readonly name: string },
157
+ ): Promise<string>;
158
+ }
159
+
160
+ /**
161
+ * A client plugin an app adds to `HotUpdater.init`'s `plugins` to work with
162
+ * the server plugin. Init prints it in the app code, and the agent scaffold
163
+ * asks for it.
164
+ */
165
+ export interface PluginClientPlugin {
166
+ /** The module that exports it, such as `@hot-updater/react-native/plugins/insights`. */
167
+ readonly module: string;
168
+ /** The export, which the app calls with no arguments, such as `insights`. */
169
+ readonly name: string;
170
+ }
171
+
172
+ /** What a plugin adds to the `hot-updater` CLI. */
173
+ export interface PluginCli<Api = unknown> {
174
+ /** Commands the CLI finds in the project's plugins. */
175
+ readonly commands?: readonly PluginCommand<Api>[];
176
+ /** Needs provides: { clientAuth: true }. */
177
+ readonly clientCredential?: PluginClientCredential<Api>;
178
+ readonly clientPlugin?: PluginClientPlugin;
179
+ }
180
+
181
+ /** CLI additions whose `clientCredential` matches what the plugin declares it provides. */
182
+ export type CliFor<TProvides, TApi> = TProvides extends {
183
+ readonly clientAuth: true;
184
+ }
185
+ ? PluginCli<TApi>
186
+ : Omit<PluginCli<TApi>, "clientCredential"> & {
187
+ readonly clientCredential?: "Declare provides: { clientAuth: true } to add clientCredential";
188
+ };
189
+
59
190
  export interface HotUpdaterPlugin<
60
191
  TId extends string = string,
61
192
  TSchema extends ModuleSchema = ModuleSchema,
@@ -68,13 +199,22 @@ export interface HotUpdaterPlugin<
68
199
  /** Stored under the settings key `schema.<id>`. */
69
200
  readonly schemaVersion: string;
70
201
  readonly schema: TSchema;
202
+ /**
203
+ * `false` keeps the declared table names instead of prefixing them with
204
+ * the plugin's id. The plugin then owns collisions with core's tables and
205
+ * other plugins' tables, which startup checks for the plugins a server
206
+ * runs, and only such a plugin may take a camelCase id.
207
+ */
208
+ readonly namespace?: false;
71
209
  /** Called once at startup, synchronously. */
72
210
  init(context: PluginContext<TSchema>): TInstance;
211
+ /** Read by the CLI only; the server never runs it. */
212
+ readonly cli?: PluginCli<TInstance["api"]>;
73
213
  /** Only core modules carry a kind. */
74
214
  readonly kind?: "Core is built in; it is not a plugin";
75
215
  }
76
216
 
77
- /** Declares a plugin; built-in and third-party plugins use the same contract. */
217
+ /** Declares a plugin; Hot Updater's own plugins and third-party ones use the same contract. */
78
218
  export const definePlugin = <
79
219
  const TId extends string,
80
220
  const TSchema extends ModuleSchema,
@@ -85,7 +225,9 @@ export const definePlugin = <
85
225
  readonly provides?: TProvides;
86
226
  readonly schemaVersion: string;
87
227
  readonly schema: TSchema;
228
+ readonly namespace?: false;
88
229
  init(context: PluginContext<TSchema>): InstanceFor<TProvides, TInstance>;
230
+ readonly cli?: CliFor<TProvides, NoInfer<TInstance["api"]>>;
89
231
  }): HotUpdaterPlugin<TId, TSchema, TInstance, TProvides> =>
90
232
  plugin as HotUpdaterPlugin<TId, TSchema, TInstance, TProvides>;
91
233
 
@@ -1,20 +1,36 @@
1
1
  /**
2
- * The plugin authoring API. Built-in and third-party plugins declare their
3
- * tables and aggregates here and receive a typed database handle in `init`.
2
+ * The plugin authoring API. Hot Updater's own plugins and third-party ones
3
+ * declare their tables and aggregates here and receive a typed database
4
+ * handle in `init`.
4
5
  */
6
+ export {
7
+ addDistinct,
8
+ countDistinct,
9
+ mergeDistinct,
10
+ } from "@hot-updater/plugin-core/internal";
5
11
  export {
6
12
  definePlugin,
7
13
  type AnyHotUpdaterPlugin,
14
+ type CliFor,
8
15
  type ClientAuth,
9
16
  type CoreReader,
10
17
  type HotUpdaterPlugin,
11
18
  type InstanceFor,
12
19
  type PluginApis,
20
+ type PluginCli,
21
+ type PluginClientCredential,
22
+ type PluginClientPlugin,
23
+ type PluginCommand,
24
+ type PluginCommandArgument,
25
+ type PluginCommandContext,
26
+ type PluginCommandOption,
27
+ type PluginCommandUi,
13
28
  type PluginContext,
14
29
  type PluginEndpoint,
15
30
  type PluginEndpointMethod,
16
31
  type PluginInstance,
17
32
  type PluginProvides,
33
+ type PluginTableColumn,
18
34
  } from "./definePlugin";
19
35
  export {
20
36
  defineAggregate,
@@ -27,6 +43,7 @@ export {
27
43
  type IndexDefinition,
28
44
  type ModuleSchema,
29
45
  type ReferenceAction,
46
+ type RetentionDefinition,
30
47
  type TableDefinition,
31
48
  } from "../database/schema";
32
49
  export type {
@@ -50,6 +67,7 @@ export {
50
67
  DatabaseTransactionError,
51
68
  type ConstraintReason,
52
69
  } from "../database/errors";
70
+ export { isDatabaseBusyError } from "../database/busy";
53
71
  export { DatabaseQueryError } from "../database/engineReads";
54
72
  export { DatabaseCursorError } from "../database/cursor";
55
73
  export { HotUpdaterConfigError } from "../assembly/assemblePlugins";
@@ -0,0 +1,285 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+
3
+ import { createValidatedInsightsModel } from "./contract";
4
+ import type { BundleEventRow } from "./eventRow";
5
+ import type {
6
+ InsightsFindLatestEventsInput,
7
+ InsightsListEventsInput,
8
+ InsightsModel,
9
+ } from "./modelTypes";
10
+
11
+ const event: BundleEventRow = {
12
+ id: "00000000-0000-7000-8000-000000000001",
13
+ type: "UPDATE_APPLIED",
14
+ install_id: "install",
15
+ user_id: "user",
16
+ metadata: {
17
+ cohort: "0",
18
+ update_strategy: "appVersion",
19
+ fingerprint_hash: null,
20
+ sdk_version: null,
21
+ },
22
+ from_bundle_id: "bundle-a",
23
+ to_bundle_id: "bundle-b",
24
+ from_release_id: null,
25
+ to_release_id: null,
26
+ platform: "ios",
27
+ app_version: "1",
28
+ channel: "production",
29
+
30
+ received_at_ms: 100,
31
+ };
32
+
33
+ /** A provider that stores nothing, behind the validating wrapper under test. */
34
+ const emptyModel: InsightsModel = {
35
+ recordEvent: async () => undefined,
36
+ listEvents: async () => [],
37
+ findLatestEvents: async () => [],
38
+ countLatestEvents: async () => 0,
39
+ countEvents: async () => 0,
40
+ getReleaseActivity: async () => ({
41
+ coverage: { kind: "complete", sinceMs: 0 },
42
+ data: [],
43
+ measuredAtMs: 0,
44
+ }),
45
+ getAppUsage: async () => ({
46
+ coverage: { kind: "complete", sinceMs: 0 },
47
+ activeInstallations: 0,
48
+ points: [],
49
+ appVersions: [],
50
+ versions: [],
51
+ platforms: [],
52
+ bundleDistribution: [],
53
+ measuredAtMs: 0,
54
+ }),
55
+ };
56
+
57
+ const createModel = (overrides: Partial<InsightsModel>) =>
58
+ createValidatedInsightsModel({ ...emptyModel, ...overrides });
59
+
60
+ describe("public Insights validation", () => {
61
+ it("prevents malformed Unicode and noncanonical event IDs from reaching providers", async () => {
62
+ const recordEvent = vi.fn(async () => undefined);
63
+ const model = createModel({ recordEvent });
64
+ for (const invalid of [
65
+ { ...event, install_id: "broken-\ud800" },
66
+ { ...event, user_id: "broken-\udc00" },
67
+ { ...event, metadata: { ...event.metadata, cohort: "broken-\ud800" } },
68
+ { ...event, id: "not-a-uuid" },
69
+ ]) {
70
+ await expect(
71
+ model.recordEvent({
72
+ event: invalid,
73
+ }),
74
+ ).rejects.toMatchObject({ code: "invalid-data" });
75
+ }
76
+ expect(recordEvent).not.toHaveBeenCalled();
77
+ });
78
+
79
+ it("takes an update failure with what failed, and refuses one without it", async () => {
80
+ const recordEvent = vi.fn(async () => undefined);
81
+ const model = createModel({ recordEvent });
82
+ const failed = {
83
+ ...event,
84
+ type: "UPDATE_FAILED",
85
+ metadata: {
86
+ ...event.metadata,
87
+ failure: {
88
+ stage: "download",
89
+ reason: "http",
90
+ resource: "artifact",
91
+ http_status: 403,
92
+ origin_code: "AccessDenied",
93
+ },
94
+ },
95
+ } as BundleEventRow;
96
+ await model.recordEvent({ event: failed });
97
+ expect(recordEvent).toHaveBeenCalledTimes(1);
98
+ for (const invalid of [
99
+ { ...failed, metadata: event.metadata },
100
+ { ...failed, from_bundle_id: null },
101
+ {
102
+ ...failed,
103
+ metadata: {
104
+ ...failed.metadata,
105
+ failure: { stage: "download", reason: "http", http_status: "403" },
106
+ },
107
+ },
108
+ {
109
+ ...failed,
110
+ metadata: { ...failed.metadata, failure: { stage: "download" } },
111
+ },
112
+ {
113
+ ...event,
114
+ type: "UPDATE_DOWNLOADED",
115
+ metadata: { ...event.metadata, patch_fallback: "yes" },
116
+ },
117
+ ]) {
118
+ await expect(
119
+ model.recordEvent({ event: invalid as BundleEventRow }),
120
+ ).rejects.toMatchObject({ code: "invalid-data" });
121
+ }
122
+ expect(recordEvent).toHaveBeenCalledTimes(1);
123
+ });
124
+
125
+ it.each([
126
+ { installId: "install", userId: "user", limit: 1 },
127
+ { installId: "install", limit: 1 },
128
+ { userId: "user", limit: 102 },
129
+ { userId: "user", limit: 1, afterInstallId: "\ud800" },
130
+ { userId: "user", limit: 0 },
131
+ ])(
132
+ "rejects invalid installation query form %j before provider I/O",
133
+ async (input) => {
134
+ const findLatestEvents = vi.fn(async () => []);
135
+ const model = createModel({ findLatestEvents });
136
+ await expect(
137
+ model.findLatestEvents(input as InsightsFindLatestEventsInput),
138
+ ).rejects.toMatchObject({ code: "invalid-query" });
139
+ expect(findLatestEvents).not.toHaveBeenCalled();
140
+ },
141
+ );
142
+
143
+ it("rejects cursors outside their interval and conflicting raw bundle predicates", async () => {
144
+ const listEvents = vi.fn(async () => []);
145
+ const model = createModel({ listEvents });
146
+ const query: InsightsListEventsInput = {
147
+ filter: { kind: "all" },
148
+ sinceMs: 100,
149
+ beforeReceivedAtMs: 200,
150
+ limit: 10,
151
+ };
152
+ for (const receivedAtMs of [99, 200]) {
153
+ await expect(
154
+ model.listEvents({ ...query, after: { receivedAtMs, id: event.id } }),
155
+ ).rejects.toMatchObject({ code: "invalid-query" });
156
+ }
157
+ await expect(
158
+ model.listEvents({
159
+ ...query,
160
+ filter: {
161
+ kind: "bundle",
162
+ type: "RECOVERED",
163
+ platform: "ios",
164
+ channel: "production",
165
+ fromBundleId: "bundle-b",
166
+ toBundleId: "bundle-a",
167
+ },
168
+ } as InsightsListEventsInput),
169
+ ).rejects.toMatchObject({ code: "invalid-query" });
170
+ expect(listEvents).not.toHaveBeenCalled();
171
+ });
172
+
173
+ it("rejects provider rows that violate the requested filter, range, or cursor order", async () => {
174
+ const query: InsightsListEventsInput = {
175
+ filter: { kind: "all" },
176
+ sinceMs: 100,
177
+ beforeReceivedAtMs: 200,
178
+ limit: 10,
179
+ };
180
+ for (const rows of [
181
+ [{ ...event, received_at_ms: 99 }],
182
+ [{ ...event, received_at_ms: 200 }],
183
+ [event, event],
184
+ ]) {
185
+ await expect(
186
+ createModel({ listEvents: async () => rows }).listEvents(query),
187
+ ).rejects.toMatchObject({ code: "invalid-result" });
188
+ }
189
+ await expect(
190
+ createModel({ listEvents: async () => [event] }).listEvents({
191
+ ...query,
192
+ filter: {
193
+ kind: "bundle",
194
+ platform: "ios",
195
+ channel: "production",
196
+ type: "RECOVERED",
197
+ fromBundleId: "bundle-b",
198
+ },
199
+ }),
200
+ ).rejects.toMatchObject({ code: "invalid-result" });
201
+ await expect(
202
+ createModel({ listEvents: async () => [event] }).listEvents({
203
+ ...query,
204
+ after: { receivedAtMs: event.received_at_ms, id: event.id },
205
+ }),
206
+ ).rejects.toMatchObject({ code: "invalid-result" });
207
+ });
208
+
209
+ it("rejects stale user membership and incorrectly ordered identity results", async () => {
210
+ const row = event;
211
+ await expect(
212
+ createModel({ findLatestEvents: async () => [row] }).findLatestEvents({
213
+ userId: "different",
214
+ limit: 10,
215
+ }),
216
+ ).rejects.toMatchObject({ code: "invalid-result" });
217
+ await expect(
218
+ createModel({
219
+ findLatestEvents: async () => [row, row],
220
+ }).findLatestEvents({ installId: "install" }),
221
+ ).rejects.toMatchObject({ code: "invalid-result" });
222
+ await expect(
223
+ createModel({
224
+ findLatestEvents: async () => [
225
+ { ...row, install_id: "😀" },
226
+ { ...row, install_id: "\ue000" },
227
+ ],
228
+ }).findLatestEvents({ userId: "user", limit: 10 }),
229
+ ).rejects.toMatchObject({ code: "invalid-result" });
230
+ });
231
+
232
+ it("passes bundle predicates on both fields that share a type to the model", async () => {
233
+ const countLatestEvents = vi.fn(async () => 1);
234
+ const model = createModel({ countLatestEvents });
235
+ const input = {
236
+ platform: "ios",
237
+ channel: "production",
238
+ sinceMs: 0,
239
+ bundle: [
240
+ { field: "from_bundle_id", value: "A", types: ["UPDATE_DOWNLOADED"] },
241
+ {
242
+ field: "to_bundle_id",
243
+ value: "B",
244
+ types: ["UPDATE_APPLIED", "UPDATE_DOWNLOADED"],
245
+ },
246
+ ],
247
+ } as const;
248
+ await expect(model.countLatestEvents(input)).resolves.toBe(1);
249
+ expect(countLatestEvents).toHaveBeenCalledWith(input);
250
+ });
251
+
252
+ it("propagates native failures and rejects invalid scalar counts", async () => {
253
+ const failure = new Error("native query failed");
254
+ const countInput = {
255
+ platform: "ios",
256
+ channel: "production",
257
+ sinceMs: 0,
258
+ } as const;
259
+ await expect(
260
+ createModel({
261
+ countLatestEvents: async () => {
262
+ throw failure;
263
+ },
264
+ }).countLatestEvents(countInput),
265
+ ).rejects.toBe(failure);
266
+ await expect(
267
+ createModel({
268
+ listEvents: async () => {
269
+ throw failure;
270
+ },
271
+ }).listEvents({
272
+ filter: { kind: "all" },
273
+ beforeReceivedAtMs: 200,
274
+ limit: 10,
275
+ }),
276
+ ).rejects.toBe(failure);
277
+ for (const count of [-1, 0.5, Number.MAX_SAFE_INTEGER + 1, Number.NaN]) {
278
+ await expect(
279
+ createModel({
280
+ countLatestEvents: async () => count,
281
+ }).countLatestEvents(countInput),
282
+ ).rejects.toMatchObject({ code: "invalid-result" });
283
+ }
284
+ });
285
+ });