@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
@@ -1,8 +1,10 @@
1
- import { AnalyticsBadRequestError, AnalyticsPayloadTooLargeError } from "./errors.mjs";
2
- //#region src/analytics/eventInput.ts
1
+ import { InsightsBadRequestError, InsightsPayloadTooLargeError } from "./errors.mjs";
2
+ import { createUUIDv7 } from "@hot-updater/plugin-core";
3
+ //#region src/insights/eventInput.ts
3
4
  const MAX_EVENT_STRING_LENGTH = 1024;
4
- const EVENT_BODY_MAX_BYTES = 16 * 1024;
5
- const eventKeys = new Set([
5
+ const MAX_IDENTITY_LENGTH = 255;
6
+ const EVENT_BODY_MAX_BYTES = 16384;
7
+ const eventKeys = /* @__PURE__ */ new Set([
6
8
  "type",
7
9
  "installId",
8
10
  "toBundleId",
@@ -24,17 +26,22 @@ function isRecord(value) {
24
26
  }
25
27
  function requireStringField(payload, key) {
26
28
  const value = payload[key];
27
- if (typeof value !== "string" || value.length === 0 || value.length > MAX_EVENT_STRING_LENGTH) throw new AnalyticsBadRequestError(`Invalid event field: ${key}`);
29
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_EVENT_STRING_LENGTH || new TextDecoder("utf-8", { ignoreBOM: true }).decode(new TextEncoder().encode(value)) !== value) throw new InsightsBadRequestError(`Invalid event field: ${key}`);
28
30
  return value;
29
31
  }
30
32
  function requireNullableStringField(payload, key) {
31
33
  if (payload[key] === null) return null;
32
34
  return requireStringField(payload, key);
33
35
  }
36
+ function requireIdentityField(payload, key) {
37
+ const value = requireStringField(payload, key);
38
+ if (value.length > MAX_IDENTITY_LENGTH) throw new InsightsBadRequestError(`Invalid event field: ${key}`);
39
+ return value;
40
+ }
34
41
  async function readBoundedText(request) {
35
42
  const contentLength = request.headers.get("content-length");
36
43
  const declaredByteLength = Number(contentLength);
37
- if (contentLength !== null && Number.isSafeInteger(declaredByteLength) && declaredByteLength > 16384) throw new AnalyticsPayloadTooLargeError(EVENT_BODY_MAX_BYTES);
44
+ if (contentLength !== null && Number.isSafeInteger(declaredByteLength) && declaredByteLength > 16384) throw new InsightsPayloadTooLargeError(EVENT_BODY_MAX_BYTES);
38
45
  if (request.body === null) return "";
39
46
  const reader = request.body.getReader();
40
47
  const decoder = new TextDecoder();
@@ -46,7 +53,7 @@ async function readBoundedText(request) {
46
53
  byteLength += result.value.byteLength;
47
54
  if (byteLength > 16384) {
48
55
  await reader.cancel();
49
- throw new AnalyticsPayloadTooLargeError(EVENT_BODY_MAX_BYTES);
56
+ throw new InsightsPayloadTooLargeError(EVENT_BODY_MAX_BYTES);
50
57
  }
51
58
  text += decoder.decode(result.value, { stream: true });
52
59
  }
@@ -57,18 +64,18 @@ async function parseJson(request) {
57
64
  try {
58
65
  return JSON.parse(text);
59
66
  } catch (error) {
60
- if (error instanceof SyntaxError) throw new AnalyticsBadRequestError("Invalid event payload");
67
+ if (error instanceof SyntaxError) throw new InsightsBadRequestError("Invalid event payload");
61
68
  throw error;
62
69
  }
63
70
  }
64
71
  function requireEvent(payload) {
65
- if (!isRecord(payload) || Object.keys(payload).some((key) => !eventKeys.has(key))) throw new AnalyticsBadRequestError("Invalid event payload");
72
+ if (!isRecord(payload) || Object.keys(payload).some((key) => !eventKeys.has(key))) throw new InsightsBadRequestError("Invalid event payload");
66
73
  const platform = requireStringField(payload, "platform");
67
- if (platform !== "ios" && platform !== "android") throw new AnalyticsBadRequestError("Invalid event field: platform");
74
+ if (platform !== "ios" && platform !== "android") throw new InsightsBadRequestError("Invalid event field: platform");
68
75
  const base = {
69
- installId: requireStringField(payload, "installId"),
76
+ installId: requireIdentityField(payload, "installId"),
70
77
  toBundleId: requireStringField(payload, "toBundleId"),
71
- ...payload.userId === void 0 ? {} : { userId: requireStringField(payload, "userId") },
78
+ ...payload.userId === void 0 ? {} : { userId: requireIdentityField(payload, "userId") },
72
79
  ...payload.username === void 0 ? {} : { username: requireStringField(payload, "username") },
73
80
  platform,
74
81
  appVersion: requireStringField(payload, "appVersion"),
@@ -81,11 +88,11 @@ function requireEvent(payload) {
81
88
  };
82
89
  const type = requireStringField(payload, "type");
83
90
  switch (type) {
91
+ case "UPDATE_DOWNLOADED":
84
92
  case "UPDATE_APPLIED":
85
- case "RECOVERED":
86
- case "RELEASE_ADOPTED": {
93
+ case "RECOVERED": {
87
94
  const updateStrategy = requireStringField(payload, "updateStrategy");
88
- if (updateStrategy !== "fingerprint" && updateStrategy !== "appVersion") throw new AnalyticsBadRequestError("Invalid event field: updateStrategy");
95
+ if (updateStrategy !== "fingerprint" && updateStrategy !== "appVersion") throw new InsightsBadRequestError("Invalid event field: updateStrategy");
89
96
  return {
90
97
  ...base,
91
98
  type,
@@ -94,18 +101,54 @@ function requireEvent(payload) {
94
101
  };
95
102
  }
96
103
  case "UNCHANGED":
97
- if (payload.fromBundleId !== null || payload.updateStrategy !== null) throw new AnalyticsBadRequestError("Invalid unchanged event shape");
104
+ if (payload.fromBundleId !== null || payload.updateStrategy !== null) throw new InsightsBadRequestError("Invalid unchanged event shape");
98
105
  return {
99
106
  ...base,
100
107
  type,
101
108
  fromBundleId: null,
102
109
  updateStrategy: null
103
110
  };
104
- default: throw new AnalyticsBadRequestError("Invalid event field: type");
111
+ default: throw new InsightsBadRequestError("Invalid event field: type");
105
112
  }
106
113
  }
107
114
  async function parseBundleEventRequest(request) {
108
115
  return requireEvent(await parseJson(request));
109
116
  }
117
+ function createBundleEventRow(input) {
118
+ input = requireEvent(input);
119
+ const base = {
120
+ app_version: input.appVersion,
121
+ channel: input.channel,
122
+ from_release_id: input.fromReleaseId,
123
+ id: createUUIDv7(),
124
+ install_id: input.installId,
125
+ platform: input.platform,
126
+ received_at_ms: Date.now(),
127
+ to_bundle_id: input.toBundleId,
128
+ to_release_id: input.toReleaseId,
129
+ user_id: input.userId ?? null,
130
+ metadata: {
131
+ cohort: input.cohort,
132
+ fingerprint_hash: input.fingerprintHash,
133
+ sdk_version: input.sdkVersion ?? null,
134
+ username: input.username ?? null,
135
+ update_strategy: input.updateStrategy
136
+ }
137
+ };
138
+ switch (input.type) {
139
+ case "UPDATE_DOWNLOADED":
140
+ case "UPDATE_APPLIED":
141
+ case "RECOVERED": return {
142
+ ...base,
143
+ from_bundle_id: input.fromBundleId,
144
+ type: input.type
145
+ };
146
+ case "UNCHANGED": return {
147
+ ...base,
148
+ from_bundle_id: null,
149
+ type: input.type
150
+ };
151
+ }
152
+ }
110
153
  //#endregion
111
- export { parseBundleEventRequest };
154
+ export { EVENT_BODY_MAX_BYTES, createBundleEventRow, parseBundleEventRequest };
@@ -0,0 +1,332 @@
1
+ const require_errors = require("./errors.cjs");
2
+ const require_eventInput = require("./eventInput.cjs");
3
+ let _hot_updater_plugin_core = require("@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 require_errors.InsightsBadRequestError(`Invalid ${label}.`);
18
+ return value;
19
+ };
20
+ const requireTimestamp = (value, label) => {
21
+ if (!Number.isSafeInteger(value) || Number(value) < 0) throw new require_errors.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 require_errors.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 require_errors.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 require_errors.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 require_errors.InsightsBadRequestError) throw error;
53
+ throw new require_errors.InsightsBadRequestError("Invalid Insights cursor.");
54
+ }
55
+ };
56
+ const readScope = (input) => {
57
+ if (input.platform !== "ios" && input.platform !== "android") throw new require_errors.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 require_errors.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 require_errors.InsightsBadRequestError("Invalid Insights cursor.");
101
+ if (!sameFilter(cursor.filter, filter)) throw new require_errors.InsightsBadRequestError("Insights cursor does not match the requested events.");
102
+ if (typeof cursor.after.id !== "string" || !(0, _hot_updater_plugin_core.isUUIDv7)(cursor.after.id)) throw new require_errors.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 require_errors.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 || (0, _hot_updater_plugin_core.compareInsightsText)(right.id, left.id);
126
+ const isAfterEventCursor = (row, after) => row.received_at_ms < after.receivedAtMs || row.received_at_ms === after.receivedAtMs && (0, _hot_updater_plugin_core.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" || !(0, _hot_updater_plugin_core.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 || !(0, _hot_updater_plugin_core.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 require_errors.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 require_errors.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 && (0, _hot_updater_plugin_core.compareInsightsText)(row.install_id, input.afterInstallId) <= 0 || previous !== void 0 && (0, _hot_updater_plugin_core.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 = require_eventInput.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 require_errors.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 require_errors.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
+ exports.createInsightsProvider = createInsightsProvider;
@@ -0,0 +1,6 @@
1
+ import { InsightsProvider } from "./types.cjs";
2
+ import { InsightsModel } from "@hot-updater/plugin-core";
3
+ //#region src/insights/provider.d.ts
4
+ declare const createInsightsProvider: (model: InsightsModel) => InsightsProvider;
5
+ //#endregion
6
+ export { createInsightsProvider };
@@ -0,0 +1,6 @@
1
+ import { InsightsProvider } from "./types.mjs";
2
+ import { InsightsModel } from "@hot-updater/plugin-core";
3
+ //#region src/insights/provider.d.ts
4
+ declare const createInsightsProvider: (model: InsightsModel) => InsightsProvider;
5
+ //#endregion
6
+ export { createInsightsProvider };