@hot-updater/server 1.0.0-rc.0 → 1.0.0-rc.14

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 (213) hide show
  1. package/dist/_virtual/_rolldown/runtime.cjs +1 -1
  2. package/dist/adapters/databaseConstraintErrors.cjs +0 -1
  3. package/dist/adapters/databasePluginUtils.cjs +14 -1
  4. package/dist/adapters/databasePluginUtils.mjs +14 -2
  5. package/dist/adapters/drizzle.cjs +9 -4
  6. package/dist/adapters/drizzle.d.cts +0 -1
  7. package/dist/adapters/drizzle.d.mts +0 -1
  8. package/dist/adapters/drizzle.mjs +10 -4
  9. package/dist/adapters/drizzleCrud.cjs +93 -3
  10. package/dist/adapters/drizzleCrud.mjs +93 -5
  11. package/dist/adapters/drizzleLazyDB.cjs +2 -0
  12. package/dist/adapters/drizzleLazyDB.mjs +2 -0
  13. package/dist/adapters/drizzleQuery.cjs +3 -2
  14. package/dist/adapters/drizzleQuery.mjs +3 -1
  15. package/dist/adapters/kysely.cjs +1 -1
  16. package/dist/adapters/kysely.d.cts +0 -1
  17. package/dist/adapters/kysely.d.mts +0 -1
  18. package/dist/adapters/kysely.mjs +2 -1
  19. package/dist/adapters/kyselyCrud.cjs +44 -5
  20. package/dist/adapters/kyselyCrud.mjs +45 -6
  21. package/dist/adapters/kyselyQuery.cjs +2 -2
  22. package/dist/adapters/kyselyQuery.mjs +2 -1
  23. package/dist/adapters/mongodb.cjs +36 -1
  24. package/dist/adapters/mongodb.d.cts +1 -1
  25. package/dist/adapters/mongodb.d.mts +1 -1
  26. package/dist/adapters/mongodb.mjs +36 -0
  27. package/dist/adapters/mongodbCollections.cjs +2 -0
  28. package/dist/adapters/mongodbCollections.mjs +2 -0
  29. package/dist/adapters/mongodbQuery.cjs +17 -4
  30. package/dist/adapters/mongodbQuery.mjs +17 -4
  31. package/dist/adapters/mongodbReads.cjs +88 -30
  32. package/dist/adapters/mongodbReads.mjs +88 -29
  33. package/dist/adapters/mongodbWrites.cjs +1 -2
  34. package/dist/adapters/mongodbWrites.mjs +1 -1
  35. package/dist/adapters/prisma.cjs +44 -7
  36. package/dist/adapters/prisma.d.cts +0 -1
  37. package/dist/adapters/prisma.d.mts +0 -1
  38. package/dist/adapters/prisma.mjs +44 -6
  39. package/dist/adapters/prismaInsights.cjs +99 -0
  40. package/dist/adapters/prismaInsights.mjs +97 -0
  41. package/dist/adapters/prismaQuery.cjs +0 -1
  42. package/dist/adapters/prismaRows.cjs +7 -8
  43. package/dist/adapters/prismaRows.mjs +8 -8
  44. package/dist/apiKeys.cjs +6 -2
  45. package/dist/apiKeys.d.cts +0 -1
  46. package/dist/apiKeys.d.mts +0 -1
  47. package/dist/apiKeys.mjs +3 -3
  48. package/dist/createHotUpdaterCore.cjs +27 -12
  49. package/dist/createHotUpdaterCore.d.cts +8 -8
  50. package/dist/createHotUpdaterCore.d.mts +8 -8
  51. package/dist/createHotUpdaterCore.mjs +26 -12
  52. package/dist/db/createBundleDiff.cjs +2 -2
  53. package/dist/db/createBundleDiff.d.cts +1 -5
  54. package/dist/db/createBundleDiff.d.mts +1 -5
  55. package/dist/db/databasePluginCore.cjs +0 -1
  56. package/dist/db/fixedMigrator.cjs +2 -2
  57. package/dist/db/fixedMigrator.mjs +2 -2
  58. package/dist/db/fixedMigratorMongo.cjs +6 -4
  59. package/dist/db/fixedMigratorMongo.mjs +6 -4
  60. package/dist/db/index.d.cts +0 -1
  61. package/dist/db/index.d.mts +0 -1
  62. package/dist/db/releaseCatalog.cjs +0 -1
  63. package/dist/db/releaseCatalog.d.cts +0 -1
  64. package/dist/db/releaseCatalog.d.mts +0 -1
  65. package/dist/db/schema/insightsCollation.cjs +14 -0
  66. package/dist/db/schema/insightsCollation.mjs +14 -0
  67. package/dist/db/schema/sql.cjs +11 -7
  68. package/dist/db/schema/sql.mjs +8 -8
  69. package/dist/db/schemaGenerators.cjs +29 -9
  70. package/dist/db/schemaGenerators.mjs +29 -9
  71. package/dist/db/schemaReadiness.cjs +2 -0
  72. package/dist/db/schemaReadiness.d.cts +1 -0
  73. package/dist/db/schemaReadiness.d.mts +1 -0
  74. package/dist/db/schemaReadiness.mjs +2 -0
  75. package/dist/db/sqlMigrationExecution.cjs +1 -1
  76. package/dist/db/sqlMigrationExecution.mjs +1 -0
  77. package/dist/db/types.cjs +3 -1
  78. package/dist/db/types.d.cts +3 -6
  79. package/dist/db/types.d.mts +3 -6
  80. package/dist/db/types.mjs +2 -2
  81. package/dist/db/updateArtifacts.cjs +0 -1
  82. package/dist/handler.cjs +5 -5
  83. package/dist/handler.d.cts +1 -2
  84. package/dist/handler.d.mts +1 -2
  85. package/dist/handler.mjs +5 -5
  86. package/dist/handlerReleaseCatalogRoutes.cjs +0 -1
  87. package/dist/handlerReleaseManagementRoutes.cjs +0 -1
  88. package/dist/handlerTypes.d.cts +0 -1
  89. package/dist/handlerTypes.d.mts +0 -1
  90. package/dist/handlerVersionRoutes.d.cts +1 -0
  91. package/dist/handlerVersionRoutes.d.mts +1 -0
  92. package/dist/index.cjs +2 -2
  93. package/dist/index.d.cts +4 -4
  94. package/dist/index.d.mts +4 -4
  95. package/dist/index.mjs +2 -2
  96. package/dist/insights/domain.d.cts +92 -0
  97. package/dist/insights/domain.d.mts +92 -0
  98. package/dist/insights/errors.cjs +15 -0
  99. package/dist/insights/errors.mjs +14 -0
  100. package/dist/{analytics → insights}/eventInput.cjs +61 -16
  101. package/dist/{analytics → insights}/eventInput.mjs +61 -18
  102. package/dist/insights/provider.cjs +332 -0
  103. package/dist/insights/provider.d.cts +6 -0
  104. package/dist/insights/provider.d.mts +6 -0
  105. package/dist/insights/provider.mjs +332 -0
  106. package/dist/insights/queryInput.cjs +93 -0
  107. package/dist/insights/queryInput.mjs +91 -0
  108. package/dist/insights/routes.cjs +58 -0
  109. package/dist/insights/routes.mjs +56 -0
  110. package/dist/insights/types.d.cts +32 -0
  111. package/dist/insights/types.d.mts +32 -0
  112. package/dist/node.d.cts +0 -1
  113. package/dist/node.d.mts +0 -1
  114. package/dist/package.cjs +1 -1
  115. package/dist/package.mjs +1 -1
  116. package/dist/schema/index.cjs +17 -3
  117. package/dist/schema/index.mjs +4 -4
  118. package/dist/schema/v1_0_0.cjs +64 -35
  119. package/dist/schema/v1_0_0.mjs +64 -36
  120. package/dist/storageAccess.cjs +0 -1
  121. package/dist/types/index.d.cts +0 -1
  122. package/dist/types/index.d.mts +0 -1
  123. package/package.json +7 -7
  124. package/src/adapters/databasePluginTestDatabase.ts +15 -5
  125. package/src/adapters/databasePluginUtils.ts +24 -0
  126. package/src/adapters/drizzle.spec.ts +203 -5
  127. package/src/adapters/drizzle.ts +16 -4
  128. package/src/adapters/drizzleCrud.ts +200 -9
  129. package/src/adapters/drizzleLazyDB.ts +33 -6
  130. package/src/adapters/kysely.spec.ts +62 -0
  131. package/src/adapters/kysely.ts +7 -1
  132. package/src/adapters/kyselyCrud.ts +115 -7
  133. package/src/adapters/kyselyInsights.spec.ts +168 -0
  134. package/src/adapters/mongodb.integration.spec.ts +483 -0
  135. package/src/adapters/mongodb.spec.ts +89 -0
  136. package/src/adapters/mongodb.ts +59 -1
  137. package/src/adapters/mongodbCollections.ts +16 -0
  138. package/src/adapters/mongodbQuery.ts +22 -3
  139. package/src/adapters/mongodbReads.ts +78 -2
  140. package/src/adapters/mongodbTestClient.ts +107 -6
  141. package/src/adapters/mongodbTestFilter.ts +5 -1
  142. package/src/adapters/mongodbWrites.ts +1 -0
  143. package/src/adapters/prisma.spec.ts +270 -0
  144. package/src/adapters/prisma.ts +75 -2
  145. package/src/adapters/prismaInsights.ts +190 -0
  146. package/src/adapters/prismaRows.ts +17 -10
  147. package/src/adapters/prismaTestClient.ts +89 -7
  148. package/src/apiKeys.integration.spec.ts +3 -3
  149. package/src/createHotUpdaterCore.ts +30 -16
  150. package/src/db/databasePluginUpdateCheck.bench.ts +10 -0
  151. package/src/db/fixedMigrator.spec.ts +63 -0
  152. package/src/db/fixedMigratorMongo.spec.ts +70 -9
  153. package/src/db/fixedMigratorMongo.ts +10 -10
  154. package/src/db/index.spec.ts +6 -1
  155. package/src/db/schema/insightsCollation.ts +21 -0
  156. package/src/db/schema/sql.ts +8 -5
  157. package/src/db/schemaGenerators.ts +42 -13
  158. package/src/db/types.spec.ts +11 -3
  159. package/src/db/types.ts +13 -7
  160. package/src/handler-standalone.integration.spec.ts +6 -8
  161. package/src/handler.ts +12 -12
  162. package/src/index.ts +3 -3
  163. package/src/insights/domain.ts +106 -0
  164. package/src/insights/errors.ts +11 -0
  165. package/src/{analytics → insights}/eventInput.ts +66 -16
  166. package/src/insights/insights.integration.spec.ts +475 -0
  167. package/src/insights/provider.spec.ts +396 -0
  168. package/src/insights/provider.ts +611 -0
  169. package/src/insights/queryInput.ts +142 -0
  170. package/src/insights/routes.ts +104 -0
  171. package/src/insights/types.ts +55 -0
  172. package/src/schema/dsl-all-versions.spec.ts +1 -1
  173. package/src/schema/v1_0_0.spec.ts +77 -3
  174. package/src/schema/v1_0_0.ts +83 -37
  175. package/dist/analytics/bounded/activeOverview.cjs +0 -87
  176. package/dist/analytics/bounded/activeOverview.mjs +0 -85
  177. package/dist/analytics/bounded/installationSearch.cjs +0 -42
  178. package/dist/analytics/bounded/installationSearch.mjs +0 -42
  179. package/dist/analytics/bounded/persistence.cjs +0 -39
  180. package/dist/analytics/bounded/persistence.mjs +0 -38
  181. package/dist/analytics/bounded/provider.cjs +0 -170
  182. package/dist/analytics/bounded/provider.d.cts +0 -7
  183. package/dist/analytics/bounded/provider.d.mts +0 -7
  184. package/dist/analytics/bounded/provider.mjs +0 -170
  185. package/dist/analytics/bounded/scan.cjs +0 -144
  186. package/dist/analytics/bounded/scan.mjs +0 -138
  187. package/dist/analytics/domain.d.cts +0 -121
  188. package/dist/analytics/domain.d.mts +0 -121
  189. package/dist/analytics/errors.cjs +0 -22
  190. package/dist/analytics/errors.mjs +0 -20
  191. package/dist/analytics/persistence.d.cts +0 -6
  192. package/dist/analytics/persistence.d.mts +0 -6
  193. package/dist/analytics/queryInput.cjs +0 -58
  194. package/dist/analytics/queryInput.mjs +0 -55
  195. package/dist/analytics/routes.cjs +0 -63
  196. package/dist/analytics/routes.mjs +0 -61
  197. package/dist/analytics/types.d.cts +0 -17
  198. package/dist/analytics/types.d.mts +0 -17
  199. package/src/analytics/analytics.integration.spec.ts +0 -144
  200. package/src/analytics/bounded/activeOverview.spec.ts +0 -189
  201. package/src/analytics/bounded/activeOverview.ts +0 -148
  202. package/src/analytics/bounded/installationSearch.spec.ts +0 -130
  203. package/src/analytics/bounded/installationSearch.ts +0 -69
  204. package/src/analytics/bounded/persistence.ts +0 -43
  205. package/src/analytics/bounded/provider.spec.ts +0 -219
  206. package/src/analytics/bounded/provider.ts +0 -229
  207. package/src/analytics/bounded/scan.ts +0 -235
  208. package/src/analytics/domain.ts +0 -139
  209. package/src/analytics/errors.ts +0 -18
  210. package/src/analytics/persistence.ts +0 -10
  211. package/src/analytics/queryInput.ts +0 -102
  212. package/src/analytics/routes.ts +0 -123
  213. package/src/analytics/types.ts +0 -44
@@ -0,0 +1,332 @@
1
+ import { InsightsBadRequestError } from "./errors.mjs";
2
+ import { createBundleEventRow } from "./eventInput.mjs";
3
+ import { compareInsightsText, isInsightsMovementEvent, isUUIDv7 } from "@hot-updater/plugin-core";
4
+ //#region src/insights/provider.ts
5
+ const DEFAULT_PAGE_LIMIT = 50;
6
+ const MAX_PAGE_LIMIT = 100;
7
+ const MAX_EVENT_ID_LENGTH = 1024;
8
+ const MAX_IDENTITY_LENGTH = 255;
9
+ const MAX_CURSOR_LENGTH = 8192;
10
+ const WINDOW_MS = {
11
+ "24h": 864e5,
12
+ "7d": 6048e5,
13
+ "30d": 2592e6
14
+ };
15
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16
+ const requireString = (value, label, maximumLength) => {
17
+ if (typeof value !== "string" || value.length === 0 || value.length > maximumLength || new TextDecoder("utf-8", { ignoreBOM: true }).decode(new TextEncoder().encode(value)) !== value) throw new InsightsBadRequestError(`Invalid ${label}.`);
18
+ return value;
19
+ };
20
+ const requireTimestamp = (value, label) => {
21
+ if (!Number.isSafeInteger(value) || Number(value) < 0) throw new InsightsBadRequestError(`Invalid ${label}.`);
22
+ return Number(value);
23
+ };
24
+ const readLimit = (value) => {
25
+ const limit = value ?? DEFAULT_PAGE_LIMIT;
26
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_PAGE_LIMIT) throw new InsightsBadRequestError("Invalid page limit.");
27
+ return limit;
28
+ };
29
+ const encodeBase64Url = (value) => {
30
+ const bytes = new TextEncoder().encode(value);
31
+ let binary = "";
32
+ for (const byte of bytes) binary += String.fromCharCode(byte);
33
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
34
+ };
35
+ const decodeBase64Url = (value) => {
36
+ if (value.length === 0 || value.length > MAX_CURSOR_LENGTH) throw new InsightsBadRequestError("Invalid Insights cursor.");
37
+ try {
38
+ const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
39
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
40
+ const binary = atob(padded);
41
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
42
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
43
+ } catch {
44
+ throw new InsightsBadRequestError("Invalid Insights cursor.");
45
+ }
46
+ };
47
+ const encodeCursor = (value) => encodeBase64Url(JSON.stringify(value));
48
+ const decodeCursor = (value) => {
49
+ try {
50
+ return JSON.parse(decodeBase64Url(value));
51
+ } catch (error) {
52
+ if (error instanceof InsightsBadRequestError) throw error;
53
+ throw new InsightsBadRequestError("Invalid Insights cursor.");
54
+ }
55
+ };
56
+ const readScope = (input) => {
57
+ if (input.platform !== "ios" && input.platform !== "android") throw new InsightsBadRequestError("Invalid Insights platform.");
58
+ return {
59
+ platform: input.platform,
60
+ channel: requireString(input.channel, "channel", MAX_EVENT_ID_LENGTH)
61
+ };
62
+ };
63
+ const bundleFilter = (input) => {
64
+ const scope = readScope(input);
65
+ const bundleId = requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
66
+ switch (input.outcome) {
67
+ case "downloaded": return {
68
+ ...scope,
69
+ type: "UPDATE_DOWNLOADED",
70
+ toBundleId: bundleId
71
+ };
72
+ case "applied": return {
73
+ ...scope,
74
+ type: "UPDATE_APPLIED",
75
+ toBundleId: bundleId
76
+ };
77
+ case "recovered": return {
78
+ ...scope,
79
+ type: "RECOVERED",
80
+ fromBundleId: bundleId
81
+ };
82
+ case "unchanged": return {
83
+ ...scope,
84
+ type: "UNCHANGED",
85
+ toBundleId: bundleId
86
+ };
87
+ default: throw new InsightsBadRequestError("Invalid Insights outcome.");
88
+ }
89
+ };
90
+ const sameFilter = (left, right) => {
91
+ if (!isRecord(left) || left.kind !== right.kind) return false;
92
+ switch (right.kind) {
93
+ case "all": return true;
94
+ case "installationMovement": return left.installId === right.installId;
95
+ case "bundle": return left.platform === right.platform && left.channel === right.channel && left.type === right.type && (right.type === "RECOVERED" ? left.fromBundleId === right.fromBundleId : left.toBundleId === right.toBundleId);
96
+ }
97
+ };
98
+ const readEventCursor = (value, filter) => {
99
+ const cursor = decodeCursor(value);
100
+ if (!isRecord(cursor) || cursor.version !== 2 || cursor.kind !== "events" || !isRecord(cursor.filter) || !isRecord(cursor.after)) throw new InsightsBadRequestError("Invalid Insights cursor.");
101
+ if (!sameFilter(cursor.filter, filter)) throw new InsightsBadRequestError("Insights cursor does not match the requested events.");
102
+ if (typeof cursor.after.id !== "string" || !isUUIDv7(cursor.after.id)) throw new InsightsBadRequestError("Invalid Insights event cursor ID.");
103
+ return {
104
+ after: {
105
+ id: cursor.after.id,
106
+ receivedAtMs: requireTimestamp(cursor.after.receivedAtMs, "event cursor")
107
+ },
108
+ beforeReceivedAtMs: requireTimestamp(cursor.beforeReceivedAtMs, "event cutoff"),
109
+ kind: "events",
110
+ sinceMs: requireTimestamp(cursor.sinceMs, "event start"),
111
+ filter,
112
+ version: 2
113
+ };
114
+ };
115
+ const readUserInstallationCursor = (value, userId) => {
116
+ const cursor = decodeCursor(value);
117
+ if (!isRecord(cursor) || cursor.version !== 1 || cursor.kind !== "user-installations" || cursor.userId !== userId) throw new InsightsBadRequestError("Insights cursor does not match the requested user ID.");
118
+ return {
119
+ afterInstallId: requireString(cursor.afterInstallId, "installation cursor", MAX_IDENTITY_LENGTH),
120
+ kind: "user-installations",
121
+ userId,
122
+ version: 1
123
+ };
124
+ };
125
+ const compareEventNewest = (left, right) => right.received_at_ms - left.received_at_ms || compareInsightsText(right.id, left.id);
126
+ const isAfterEventCursor = (row, after) => row.received_at_ms < after.receivedAtMs || row.received_at_ms === after.receivedAtMs && compareInsightsText(row.id, after.id) < 0;
127
+ const assertEventRows = (rows, input) => {
128
+ if (rows.length > input.limit) throw new Error("Insights database returned too many event rows.");
129
+ for (let index = 0; index < rows.length; index += 1) {
130
+ const row = rows[index];
131
+ const previous = rows[index - 1];
132
+ if (!row || typeof row.id !== "string" || !isUUIDv7(row.id) || !Number.isSafeInteger(row.received_at_ms) || row.received_at_ms >= input.beforeReceivedAtMs || row.received_at_ms < input.sinceMs || previous !== void 0 && compareEventNewest(previous, row) >= 0 || input.after !== void 0 && !isAfterEventCursor(row, input.after) || input.filter.kind === "installationMovement" && (row.install_id !== input.filter.installId || !isInsightsMovementEvent(row)) || input.filter.kind === "bundle" && (row.platform !== input.filter.platform || row.channel !== input.filter.channel || row.type !== input.filter.type || (input.filter.type === "RECOVERED" ? row.from_bundle_id !== input.filter.fromBundleId : row.to_bundle_id !== input.filter.toBundleId))) throw new Error("Insights database returned invalid event rows.");
133
+ }
134
+ };
135
+ const toEventHistoryRow = (row) => ({
136
+ appVersion: row.app_version,
137
+ channel: row.channel,
138
+ cohort: row.metadata.cohort,
139
+ fromBundleId: row.from_bundle_id,
140
+ id: row.id,
141
+ installId: row.install_id,
142
+ platform: row.platform,
143
+ receivedAtMs: row.received_at_ms,
144
+ toBundleId: row.to_bundle_id,
145
+ type: row.type,
146
+ userId: row.user_id,
147
+ username: row.metadata.username
148
+ });
149
+ const toInstallationRow = (row) => ({
150
+ appVersion: row.app_version,
151
+ channel: row.channel,
152
+ cohort: row.metadata.cohort,
153
+ installId: row.install_id,
154
+ lastKnownBundleId: row.type === "UPDATE_DOWNLOADED" ? row.from_bundle_id : row.to_bundle_id,
155
+ pendingBundleId: row.type === "UPDATE_DOWNLOADED" ? row.to_bundle_id : null,
156
+ pendingReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.to_release_id : null,
157
+ latestStatus: row.type,
158
+ platform: row.platform,
159
+ receivedAtMs: row.received_at_ms,
160
+ userId: row.user_id,
161
+ username: row.metadata.username
162
+ });
163
+ const pageEventRows = async (model, input, filter, map) => {
164
+ const limit = readLimit(input.limit);
165
+ const cursor = input.cursor === void 0 ? void 0 : readEventCursor(input.cursor, filter);
166
+ const beforeReceivedAtMs = cursor?.beforeReceivedAtMs ?? (input.beforeReceivedAtMs === void 0 ? Date.now() : requireTimestamp(input.beforeReceivedAtMs, "event cutoff"));
167
+ if (cursor !== void 0 && input.beforeReceivedAtMs !== void 0 && input.beforeReceivedAtMs !== beforeReceivedAtMs) throw new InsightsBadRequestError("Insights cursor does not match the requested event cutoff.");
168
+ const sinceMs = cursor?.sinceMs ?? (input.sinceMs === void 0 ? 0 : requireTimestamp(input.sinceMs, "event start"));
169
+ if (sinceMs > beforeReceivedAtMs || input.sinceMs !== void 0 && input.sinceMs !== sinceMs || cursor !== void 0 && (cursor.after.receivedAtMs < sinceMs || cursor.after.receivedAtMs >= beforeReceivedAtMs)) throw new InsightsBadRequestError("Insights cursor or range does not match the requested event start.");
170
+ const databaseInput = {
171
+ filter,
172
+ sinceMs,
173
+ beforeReceivedAtMs,
174
+ ...cursor === void 0 ? {} : { after: cursor.after },
175
+ limit: limit + 1
176
+ };
177
+ const rows = await model.listEvents(databaseInput);
178
+ assertEventRows(rows, databaseInput);
179
+ const pageRows = rows.slice(0, limit);
180
+ const last = pageRows.at(-1);
181
+ return {
182
+ beforeReceivedAtMs,
183
+ data: pageRows.map(map),
184
+ nextCursor: rows.length > limit && last ? encodeCursor({
185
+ after: {
186
+ id: last.id,
187
+ receivedAtMs: last.received_at_ms
188
+ },
189
+ beforeReceivedAtMs,
190
+ kind: "events",
191
+ filter,
192
+ sinceMs,
193
+ version: 2
194
+ }) : null
195
+ };
196
+ };
197
+ const assertInstallationRows = (rows, input) => {
198
+ if (rows.length > input.limit) throw new Error("Insights database returned too many installation rows.");
199
+ for (let index = 0; index < rows.length; index += 1) {
200
+ const row = rows[index];
201
+ const previous = rows[index - 1];
202
+ if (!row || row.user_id !== input.userId || input.afterInstallId !== void 0 && compareInsightsText(row.install_id, input.afterInstallId) <= 0 || previous !== void 0 && compareInsightsText(previous.install_id, row.install_id) >= 0) throw new Error("Insights database returned invalid installation rows.");
203
+ }
204
+ };
205
+ const createInsightsProvider = (model) => Object.freeze({
206
+ async appendBundleEvent(input) {
207
+ const event = createBundleEventRow(input);
208
+ await model.recordEvent({ event });
209
+ },
210
+ listEvents(input) {
211
+ const filter = input.bundle === void 0 ? { kind: "all" } : {
212
+ kind: "bundle",
213
+ ...bundleFilter(input.bundle)
214
+ };
215
+ return pageEventRows(model, input, filter, toEventHistoryRow);
216
+ },
217
+ async listInstallationEvents(input) {
218
+ if ("bundle" in input && input.bundle !== void 0) throw new InsightsBadRequestError("Installation movement queries cannot include a bundle filter.");
219
+ const installId = requireString(input.installId, "install ID", MAX_IDENTITY_LENGTH);
220
+ return pageEventRows(model, input, {
221
+ kind: "installationMovement",
222
+ installId
223
+ }, (row) => toEventHistoryRow(row));
224
+ },
225
+ async getInstallation({ installId }) {
226
+ const normalizedInstallId = requireString(installId, "install ID", MAX_IDENTITY_LENGTH);
227
+ const rows = await model.findLatestEvents({ installId: normalizedInstallId });
228
+ const row = rows[0] ?? null;
229
+ if (rows.length > 1 || row !== null && row.install_id !== normalizedInstallId) throw new Error("Insights database returned an invalid installation.");
230
+ return row === null ? null : toInstallationRow(row);
231
+ },
232
+ async pageInstallationsByCurrentUserId(input) {
233
+ const userId = requireString(input.userId, "user ID", MAX_IDENTITY_LENGTH);
234
+ const limit = readLimit(input.limit);
235
+ const cursor = input.cursor === void 0 ? void 0 : readUserInstallationCursor(input.cursor, userId);
236
+ const databaseInput = {
237
+ userId,
238
+ ...cursor === void 0 ? {} : { afterInstallId: cursor.afterInstallId },
239
+ limit: limit + 1
240
+ };
241
+ const rows = await model.findLatestEvents(databaseInput);
242
+ assertInstallationRows(rows, databaseInput);
243
+ const pageRows = rows.slice(0, limit);
244
+ const last = pageRows.at(-1);
245
+ return {
246
+ data: pageRows.map(toInstallationRow),
247
+ nextCursor: rows.length > limit && last ? encodeCursor({
248
+ afterInstallId: last.install_id,
249
+ kind: "user-installations",
250
+ userId,
251
+ version: 1
252
+ }) : null
253
+ };
254
+ },
255
+ async getReportingOverview(input) {
256
+ const scope = readScope(input);
257
+ const { window } = input;
258
+ if (!Object.hasOwn(WINDOW_MS, window)) throw new InsightsBadRequestError("Invalid reporting installation window.");
259
+ const beforeReceivedAtMs = Date.now();
260
+ const sinceMs = Math.max(0, beforeReceivedAtMs - WINDOW_MS[window]);
261
+ const measure = async (count) => {
262
+ const value = await count;
263
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("Insights database returned an invalid count.");
264
+ return {
265
+ count: value,
266
+ measuredAtMs: Date.now()
267
+ };
268
+ };
269
+ const bundleId = input.bundleId === void 0 ? void 0 : requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
270
+ const reporting = measure(model.countLatestEvents({
271
+ ...scope,
272
+ sinceMs
273
+ }));
274
+ if (bundleId === void 0) return {
275
+ ...scope,
276
+ window,
277
+ sinceMs,
278
+ beforeReceivedAtMs,
279
+ reportingInstallations: await reporting
280
+ };
281
+ const countOutcome = (outcome) => measure(model.countEvents({
282
+ filter: bundleFilter({
283
+ ...scope,
284
+ bundleId,
285
+ outcome
286
+ }),
287
+ sinceMs,
288
+ beforeReceivedAtMs
289
+ }));
290
+ const [reportingInstallations, bundleInstallations, downloadedReports, appliedReports, recoveredReports, unchangedReports] = await Promise.all([
291
+ reporting,
292
+ measure(model.countLatestEvents({
293
+ ...scope,
294
+ sinceMs,
295
+ bundle: [{
296
+ field: "from_bundle_id",
297
+ value: bundleId,
298
+ types: ["UPDATE_DOWNLOADED"]
299
+ }, {
300
+ field: "to_bundle_id",
301
+ value: bundleId,
302
+ types: [
303
+ "UNCHANGED",
304
+ "UPDATE_APPLIED",
305
+ "RECOVERED"
306
+ ]
307
+ }]
308
+ })),
309
+ countOutcome("downloaded"),
310
+ countOutcome("applied"),
311
+ countOutcome("recovered"),
312
+ countOutcome("unchanged")
313
+ ]);
314
+ return {
315
+ ...scope,
316
+ window,
317
+ sinceMs,
318
+ beforeReceivedAtMs,
319
+ reportingInstallations,
320
+ bundle: {
321
+ bundleId,
322
+ reportingInstallations: bundleInstallations,
323
+ downloadedReports,
324
+ appliedReports,
325
+ recoveredReports,
326
+ unchangedReports
327
+ }
328
+ };
329
+ }
330
+ });
331
+ //#endregion
332
+ export { createInsightsProvider };
@@ -0,0 +1,93 @@
1
+ const require_errors = require("./errors.cjs");
2
+ //#region src/insights/queryInput.ts
3
+ const MAX_PAGE_LIMIT = 100;
4
+ const MAX_IDENTITY_LENGTH = 255;
5
+ const MAX_CURSOR_LENGTH = 8192;
6
+ const readSingle = (url, key) => {
7
+ const values = url.searchParams.getAll(key);
8
+ if (values.length > 1) throw new require_errors.InsightsBadRequestError(`Duplicate '${key}' query parameter.`);
9
+ return values[0];
10
+ };
11
+ const readPageLimit = (url) => {
12
+ const value = readSingle(url, "limit");
13
+ if (value === void 0) return void 0;
14
+ const limit = Number(value);
15
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_PAGE_LIMIT) throw new require_errors.InsightsBadRequestError("Invalid 'limit' query parameter.");
16
+ return limit;
17
+ };
18
+ const readCursor = (url) => {
19
+ const cursor = readSingle(url, "cursor");
20
+ if (cursor !== void 0 && (cursor.length === 0 || cursor.length > MAX_CURSOR_LENGTH)) throw new require_errors.InsightsBadRequestError("Invalid 'cursor' query parameter.");
21
+ return cursor;
22
+ };
23
+ const readId = (url, key, maximumLength = MAX_IDENTITY_LENGTH) => {
24
+ const value = readSingle(url, key);
25
+ if (value === void 0 || value.length === 0 || value.length > maximumLength) throw new require_errors.InsightsBadRequestError(`Invalid '${key}' query parameter.`);
26
+ return value;
27
+ };
28
+ const readTimestamp = (url, key) => {
29
+ const raw = readSingle(url, key);
30
+ if (raw === void 0) return void 0;
31
+ const value = Number(raw);
32
+ if (!raw.length || !Number.isSafeInteger(value) || value < 0) throw new require_errors.InsightsBadRequestError(`Invalid '${key}' query parameter.`);
33
+ return value;
34
+ };
35
+ const readScope = (url) => {
36
+ const platform = readSingle(url, "platform");
37
+ if (platform !== "ios" && platform !== "android") throw new require_errors.InsightsBadRequestError("Invalid 'platform' query parameter.");
38
+ return {
39
+ platform,
40
+ channel: readId(url, "channel", 1024)
41
+ };
42
+ };
43
+ const parseEventPageInput = (request) => {
44
+ const url = new URL(request.url);
45
+ const bundleFields = [
46
+ "bundleId",
47
+ "outcome",
48
+ "platform",
49
+ "channel"
50
+ ];
51
+ let bundle;
52
+ if (bundleFields.some((key) => url.searchParams.has(key))) {
53
+ const outcome = readSingle(url, "outcome");
54
+ if (outcome !== "downloaded" && outcome !== "applied" && outcome !== "recovered" && outcome !== "unchanged") throw new require_errors.InsightsBadRequestError("Invalid 'outcome' query parameter.");
55
+ bundle = {
56
+ ...readScope(url),
57
+ bundleId: readId(url, "bundleId", 1024),
58
+ outcome
59
+ };
60
+ }
61
+ return {
62
+ beforeReceivedAtMs: readTimestamp(url, "beforeReceivedAtMs"),
63
+ sinceMs: readTimestamp(url, "sinceMs"),
64
+ cursor: readCursor(url),
65
+ limit: readPageLimit(url),
66
+ ...bundle === void 0 ? {} : { bundle }
67
+ };
68
+ };
69
+ const parseUserInstallationPageInput = (request) => {
70
+ const url = new URL(request.url);
71
+ const cursor = readCursor(url);
72
+ const limit = readPageLimit(url);
73
+ return {
74
+ userId: readId(url, "userId"),
75
+ ...cursor === void 0 ? {} : { cursor },
76
+ ...limit === void 0 ? {} : { limit }
77
+ };
78
+ };
79
+ const parseReportingOverviewInput = (request) => {
80
+ const url = new URL(request.url);
81
+ const window = readSingle(url, "window") ?? "30d";
82
+ if (window !== "24h" && window !== "7d" && window !== "30d") throw new require_errors.InsightsBadRequestError("Invalid 'window' query parameter.");
83
+ const bundleId = readSingle(url, "bundleId");
84
+ return {
85
+ ...readScope(url),
86
+ window,
87
+ ...bundleId === void 0 ? {} : { bundleId: readId(url, "bundleId", 1024) }
88
+ };
89
+ };
90
+ //#endregion
91
+ exports.parseEventPageInput = parseEventPageInput;
92
+ exports.parseReportingOverviewInput = parseReportingOverviewInput;
93
+ exports.parseUserInstallationPageInput = parseUserInstallationPageInput;
@@ -0,0 +1,91 @@
1
+ import { InsightsBadRequestError } from "./errors.mjs";
2
+ //#region src/insights/queryInput.ts
3
+ const MAX_PAGE_LIMIT = 100;
4
+ const MAX_IDENTITY_LENGTH = 255;
5
+ const MAX_CURSOR_LENGTH = 8192;
6
+ const readSingle = (url, key) => {
7
+ const values = url.searchParams.getAll(key);
8
+ if (values.length > 1) throw new InsightsBadRequestError(`Duplicate '${key}' query parameter.`);
9
+ return values[0];
10
+ };
11
+ const readPageLimit = (url) => {
12
+ const value = readSingle(url, "limit");
13
+ if (value === void 0) return void 0;
14
+ const limit = Number(value);
15
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_PAGE_LIMIT) throw new InsightsBadRequestError("Invalid 'limit' query parameter.");
16
+ return limit;
17
+ };
18
+ const readCursor = (url) => {
19
+ const cursor = readSingle(url, "cursor");
20
+ if (cursor !== void 0 && (cursor.length === 0 || cursor.length > MAX_CURSOR_LENGTH)) throw new InsightsBadRequestError("Invalid 'cursor' query parameter.");
21
+ return cursor;
22
+ };
23
+ const readId = (url, key, maximumLength = MAX_IDENTITY_LENGTH) => {
24
+ const value = readSingle(url, key);
25
+ if (value === void 0 || value.length === 0 || value.length > maximumLength) throw new InsightsBadRequestError(`Invalid '${key}' query parameter.`);
26
+ return value;
27
+ };
28
+ const readTimestamp = (url, key) => {
29
+ const raw = readSingle(url, key);
30
+ if (raw === void 0) return void 0;
31
+ const value = Number(raw);
32
+ if (!raw.length || !Number.isSafeInteger(value) || value < 0) throw new InsightsBadRequestError(`Invalid '${key}' query parameter.`);
33
+ return value;
34
+ };
35
+ const readScope = (url) => {
36
+ const platform = readSingle(url, "platform");
37
+ if (platform !== "ios" && platform !== "android") throw new InsightsBadRequestError("Invalid 'platform' query parameter.");
38
+ return {
39
+ platform,
40
+ channel: readId(url, "channel", 1024)
41
+ };
42
+ };
43
+ const parseEventPageInput = (request) => {
44
+ const url = new URL(request.url);
45
+ const bundleFields = [
46
+ "bundleId",
47
+ "outcome",
48
+ "platform",
49
+ "channel"
50
+ ];
51
+ let bundle;
52
+ if (bundleFields.some((key) => url.searchParams.has(key))) {
53
+ const outcome = readSingle(url, "outcome");
54
+ if (outcome !== "downloaded" && outcome !== "applied" && outcome !== "recovered" && outcome !== "unchanged") throw new InsightsBadRequestError("Invalid 'outcome' query parameter.");
55
+ bundle = {
56
+ ...readScope(url),
57
+ bundleId: readId(url, "bundleId", 1024),
58
+ outcome
59
+ };
60
+ }
61
+ return {
62
+ beforeReceivedAtMs: readTimestamp(url, "beforeReceivedAtMs"),
63
+ sinceMs: readTimestamp(url, "sinceMs"),
64
+ cursor: readCursor(url),
65
+ limit: readPageLimit(url),
66
+ ...bundle === void 0 ? {} : { bundle }
67
+ };
68
+ };
69
+ const parseUserInstallationPageInput = (request) => {
70
+ const url = new URL(request.url);
71
+ const cursor = readCursor(url);
72
+ const limit = readPageLimit(url);
73
+ return {
74
+ userId: readId(url, "userId"),
75
+ ...cursor === void 0 ? {} : { cursor },
76
+ ...limit === void 0 ? {} : { limit }
77
+ };
78
+ };
79
+ const parseReportingOverviewInput = (request) => {
80
+ const url = new URL(request.url);
81
+ const window = readSingle(url, "window") ?? "30d";
82
+ if (window !== "24h" && window !== "7d" && window !== "30d") throw new InsightsBadRequestError("Invalid 'window' query parameter.");
83
+ const bundleId = readSingle(url, "bundleId");
84
+ return {
85
+ ...readScope(url),
86
+ window,
87
+ ...bundleId === void 0 ? {} : { bundleId: readId(url, "bundleId", 1024) }
88
+ };
89
+ };
90
+ //#endregion
91
+ export { parseEventPageInput, parseReportingOverviewInput, parseUserInstallationPageInput };
@@ -0,0 +1,58 @@
1
+ const require_errors = require("./errors.cjs");
2
+ const require_eventInput = require("./eventInput.cjs");
3
+ const require_queryInput = require("./queryInput.cjs");
4
+ //#region src/insights/routes.ts
5
+ const json = (body, status) => Response.json(body, {
6
+ headers: { "cache-control": "private, no-store" },
7
+ status
8
+ });
9
+ const requireParam = (params, key) => {
10
+ const value = params[key];
11
+ if (value === void 0 || value.length === 0) throw new require_errors.InsightsBadRequestError(`Missing route parameter: ${key}`);
12
+ try {
13
+ return decodeURIComponent(value);
14
+ } catch {
15
+ throw new require_errors.InsightsBadRequestError(`Invalid route parameter: ${key}`);
16
+ }
17
+ };
18
+ const run = async (operation) => {
19
+ try {
20
+ return await operation();
21
+ } catch (error) {
22
+ if (error instanceof require_errors.InsightsBadRequestError) return json({ error: error.message }, 400);
23
+ if (error instanceof require_errors.InsightsPayloadTooLargeError) return json({ error: error.message }, 413);
24
+ throw error;
25
+ }
26
+ };
27
+ const query = (operation) => run(async () => json(await operation(), 200));
28
+ const createInsightsRouteHandlers = (provider) => ({
29
+ appendBundleEvent: async (_params, request) => run(async () => {
30
+ await provider.appendBundleEvent(await require_eventInput.parseBundleEventRequest(request));
31
+ return new Response(null, { status: 204 });
32
+ }),
33
+ getReportingOverview: (_params, request) => query(() => provider.getReportingOverview(require_queryInput.parseReportingOverviewInput(request))),
34
+ getInstallation: (params) => run(async () => {
35
+ const installation = await provider.getInstallation({ installId: requireParam(params, "installId") });
36
+ return installation === null ? json({ error: "Installation not found" }, 404) : json(installation, 200);
37
+ }),
38
+ listEvents: (_params, request) => query(() => provider.listEvents(require_queryInput.parseEventPageInput(request))),
39
+ listInstallationEvents: (params, request) => query(() => provider.listInstallationEvents({
40
+ ...require_queryInput.parseEventPageInput(request),
41
+ installId: requireParam(params, "installId")
42
+ })),
43
+ pageInstallationsByCurrentUserId: (_params, request) => query(() => provider.pageInstallationsByCurrentUserId(require_queryInput.parseUserInstallationPageInput(request)))
44
+ });
45
+ const registerInsightsClientRoutes = (add) => {
46
+ add("POST", "/events", "appendBundleEvent");
47
+ };
48
+ const registerInsightsAdminRoutes = (add) => {
49
+ add("GET", "/events", "listEvents");
50
+ add("GET", "/overview", "getReportingOverview");
51
+ add("GET", "/installations", "pageInstallationsByCurrentUserId");
52
+ add("GET", "/installations/:installId/events", "listInstallationEvents");
53
+ add("GET", "/installations/:installId", "getInstallation");
54
+ };
55
+ //#endregion
56
+ exports.createInsightsRouteHandlers = createInsightsRouteHandlers;
57
+ exports.registerInsightsAdminRoutes = registerInsightsAdminRoutes;
58
+ exports.registerInsightsClientRoutes = registerInsightsClientRoutes;
@@ -0,0 +1,56 @@
1
+ import { InsightsBadRequestError, InsightsPayloadTooLargeError } from "./errors.mjs";
2
+ import { parseBundleEventRequest } from "./eventInput.mjs";
3
+ import { parseEventPageInput, parseReportingOverviewInput, parseUserInstallationPageInput } from "./queryInput.mjs";
4
+ //#region src/insights/routes.ts
5
+ const json = (body, status) => Response.json(body, {
6
+ headers: { "cache-control": "private, no-store" },
7
+ status
8
+ });
9
+ const requireParam = (params, key) => {
10
+ const value = params[key];
11
+ if (value === void 0 || value.length === 0) throw new InsightsBadRequestError(`Missing route parameter: ${key}`);
12
+ try {
13
+ return decodeURIComponent(value);
14
+ } catch {
15
+ throw new InsightsBadRequestError(`Invalid route parameter: ${key}`);
16
+ }
17
+ };
18
+ const run = async (operation) => {
19
+ try {
20
+ return await operation();
21
+ } catch (error) {
22
+ if (error instanceof InsightsBadRequestError) return json({ error: error.message }, 400);
23
+ if (error instanceof InsightsPayloadTooLargeError) return json({ error: error.message }, 413);
24
+ throw error;
25
+ }
26
+ };
27
+ const query = (operation) => run(async () => json(await operation(), 200));
28
+ const createInsightsRouteHandlers = (provider) => ({
29
+ appendBundleEvent: async (_params, request) => run(async () => {
30
+ await provider.appendBundleEvent(await parseBundleEventRequest(request));
31
+ return new Response(null, { status: 204 });
32
+ }),
33
+ getReportingOverview: (_params, request) => query(() => provider.getReportingOverview(parseReportingOverviewInput(request))),
34
+ getInstallation: (params) => run(async () => {
35
+ const installation = await provider.getInstallation({ installId: requireParam(params, "installId") });
36
+ return installation === null ? json({ error: "Installation not found" }, 404) : json(installation, 200);
37
+ }),
38
+ listEvents: (_params, request) => query(() => provider.listEvents(parseEventPageInput(request))),
39
+ listInstallationEvents: (params, request) => query(() => provider.listInstallationEvents({
40
+ ...parseEventPageInput(request),
41
+ installId: requireParam(params, "installId")
42
+ })),
43
+ pageInstallationsByCurrentUserId: (_params, request) => query(() => provider.pageInstallationsByCurrentUserId(parseUserInstallationPageInput(request)))
44
+ });
45
+ const registerInsightsClientRoutes = (add) => {
46
+ add("POST", "/events", "appendBundleEvent");
47
+ };
48
+ const registerInsightsAdminRoutes = (add) => {
49
+ add("GET", "/events", "listEvents");
50
+ add("GET", "/overview", "getReportingOverview");
51
+ add("GET", "/installations", "pageInstallationsByCurrentUserId");
52
+ add("GET", "/installations/:installId/events", "listInstallationEvents");
53
+ add("GET", "/installations/:installId", "getInstallation");
54
+ };
55
+ //#endregion
56
+ export { createInsightsRouteHandlers, registerInsightsAdminRoutes, registerInsightsClientRoutes };
@@ -0,0 +1,32 @@
1
+ import { ActiveInstallationWindow, CreateBundleEventRequest, CursorPage, EventCursorPage, EventHistoryRow, InsightsBundleSelection, InsightsScope, InstallationHistoryRow, InstallationRow, ReportingOverview } from "./domain.cjs";
2
+ //#region src/insights/types.d.ts
3
+ type InsightsEventPageInput = {
4
+ readonly beforeReceivedAtMs?: number;
5
+ readonly sinceMs?: number;
6
+ readonly bundle?: InsightsBundleSelection;
7
+ readonly cursor?: string;
8
+ readonly limit?: number;
9
+ };
10
+ type InsightsInstallationEventPageInput = Omit<InsightsEventPageInput, "bundle"> & {
11
+ readonly installId: string;
12
+ };
13
+ type InsightsUserInstallationPageInput = {
14
+ readonly userId: string;
15
+ readonly cursor?: string;
16
+ readonly limit?: number;
17
+ };
18
+ type InsightsProvider = {
19
+ appendBundleEvent(input: CreateBundleEventRequest): Promise<void>;
20
+ listEvents(input: InsightsEventPageInput): Promise<EventCursorPage<EventHistoryRow>>;
21
+ listInstallationEvents(input: InsightsInstallationEventPageInput): Promise<EventCursorPage<InstallationHistoryRow>>;
22
+ getInstallation(input: {
23
+ readonly installId: string;
24
+ }): Promise<InstallationRow | null>;
25
+ pageInstallationsByCurrentUserId(input: InsightsUserInstallationPageInput): Promise<CursorPage<InstallationRow>>;
26
+ getReportingOverview(input: InsightsScope & {
27
+ readonly window: ActiveInstallationWindow;
28
+ readonly bundleId?: string;
29
+ }): Promise<ReportingOverview>;
30
+ };
31
+ //#endregion
32
+ export { InsightsEventPageInput, InsightsInstallationEventPageInput, InsightsProvider, InsightsUserInstallationPageInput };