@warlock.js/devtools 5.55.0 → 5.57.0

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 (240) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +26 -13
  3. package/cjs/ai-source-DTpxumMA.cjs +381 -0
  4. package/cjs/ai-source-DTpxumMA.cjs.map +1 -0
  5. package/cjs/auth-DzU0gHDG.cjs +1655 -0
  6. package/cjs/auth-DzU0gHDG.cjs.map +1 -0
  7. package/cjs/boot-Dy5OqgTM.cjs +138 -0
  8. package/cjs/boot-Dy5OqgTM.cjs.map +1 -0
  9. package/cjs/capture-CqIiaznN.cjs +1342 -0
  10. package/cjs/capture-CqIiaznN.cjs.map +1 -0
  11. package/cjs/cascade-store-pHjKeSFm.cjs +863 -0
  12. package/cjs/cascade-store-pHjKeSFm.cjs.map +1 -0
  13. package/cjs/collector-CJbQbzzK.cjs +271 -0
  14. package/cjs/collector-CJbQbzzK.cjs.map +1 -0
  15. package/cjs/contracts-CVmplkNb.cjs +112 -0
  16. package/cjs/contracts-CVmplkNb.cjs.map +1 -0
  17. package/cjs/current-request-id-BoJJb3y7.cjs +37 -0
  18. package/cjs/current-request-id-BoJJb3y7.cjs.map +1 -0
  19. package/cjs/errors-CyZp5yS-.cjs +177 -0
  20. package/cjs/errors-CyZp5yS-.cjs.map +1 -0
  21. package/cjs/histogram-BaI-PnCv.cjs +102 -0
  22. package/cjs/histogram-BaI-PnCv.cjs.map +1 -0
  23. package/cjs/http-DCfXQvw-.cjs +870 -0
  24. package/cjs/http-DCfXQvw-.cjs.map +1 -0
  25. package/cjs/index.cjs +2 -1
  26. package/cjs/insights-BKtqxdnP.cjs +811 -0
  27. package/cjs/insights-BKtqxdnP.cjs.map +1 -0
  28. package/cjs/ip-DbNhPOzi.cjs +153 -0
  29. package/cjs/ip-DbNhPOzi.cjs.map +1 -0
  30. package/cjs/migrations-w7GMsrQw.cjs +297 -0
  31. package/cjs/migrations-w7GMsrQw.cjs.map +1 -0
  32. package/cjs/openapi-CC7OAUc6.cjs +52 -0
  33. package/cjs/openapi-CC7OAUc6.cjs.map +1 -0
  34. package/cjs/options-CWqFC5__.cjs +181 -0
  35. package/cjs/options-CWqFC5__.cjs.map +1 -0
  36. package/cjs/panels-Rcmeitu3.cjs +318 -0
  37. package/cjs/panels-Rcmeitu3.cjs.map +1 -0
  38. package/cjs/process-panel-DEOnLxoT.cjs +48 -0
  39. package/cjs/process-panel-DEOnLxoT.cjs.map +1 -0
  40. package/cjs/production/index.cjs +238 -0
  41. package/cjs/production/index.cjs.map +1 -0
  42. package/cjs/rolldown-runtime-Zuuoy_Rh.cjs +52 -0
  43. package/cjs/server-ykxsOwob.cjs +184 -0
  44. package/cjs/server-ykxsOwob.cjs.map +1 -0
  45. package/cjs/{src-Xwm3Eel9.cjs → src-UPtTCI2j.cjs} +210 -293
  46. package/cjs/src-UPtTCI2j.cjs.map +1 -0
  47. package/cjs/store-aq207T8v.cjs +9 -0
  48. package/cjs/stream-route-CJTABkUy.cjs +875 -0
  49. package/cjs/stream-route-CJTABkUy.cjs.map +1 -0
  50. package/esm/devtools-connector.d.mts +16 -13
  51. package/esm/devtools-connector.d.mts.map +1 -1
  52. package/esm/devtools-connector.mjs +127 -18
  53. package/esm/devtools-connector.mjs.map +1 -1
  54. package/esm/index.d.mts +4 -2
  55. package/esm/index.mjs +2 -1
  56. package/esm/options.mjs +2 -1
  57. package/esm/options.mjs.map +1 -1
  58. package/esm/panel-tokens.d.mts +13 -0
  59. package/esm/panel-tokens.d.mts.map +1 -0
  60. package/esm/panel-tokens.mjs +45 -0
  61. package/esm/panel-tokens.mjs.map +1 -0
  62. package/esm/panels.mjs +73 -8
  63. package/esm/panels.mjs.map +1 -1
  64. package/esm/production/auth/common-passwords.mjs +303 -0
  65. package/esm/production/auth/common-passwords.mjs.map +1 -0
  66. package/esm/production/auth/default-crypto.mjs +19 -0
  67. package/esm/production/auth/default-crypto.mjs.map +1 -0
  68. package/esm/production/auth/helpers.mjs +77 -0
  69. package/esm/production/auth/helpers.mjs.map +1 -0
  70. package/esm/production/auth/index.mjs +6 -0
  71. package/esm/production/auth/passkeys.mjs +96 -0
  72. package/esm/production/auth/passkeys.mjs.map +1 -0
  73. package/esm/production/auth/service.mjs +1166 -0
  74. package/esm/production/auth/service.mjs.map +1 -0
  75. package/esm/production/boot.mjs +138 -0
  76. package/esm/production/boot.mjs.map +1 -0
  77. package/esm/production/capture/dev-stats.mjs +83 -0
  78. package/esm/production/capture/dev-stats.mjs.map +1 -0
  79. package/esm/production/capture/engine.mjs +442 -0
  80. package/esm/production/capture/engine.mjs.map +1 -0
  81. package/esm/production/capture/explain.mjs +271 -0
  82. package/esm/production/capture/explain.mjs.map +1 -0
  83. package/esm/production/capture/filter.mjs +24 -0
  84. package/esm/production/capture/filter.mjs.map +1 -0
  85. package/esm/production/capture/index.mjs +7 -0
  86. package/esm/production/capture/production-capture.mjs +134 -0
  87. package/esm/production/capture/production-capture.mjs.map +1 -0
  88. package/esm/production/capture/redact.mjs +109 -0
  89. package/esm/production/capture/redact.mjs.map +1 -0
  90. package/esm/production/capture/stats-stores.mjs +300 -0
  91. package/esm/production/capture/stats-stores.mjs.map +1 -0
  92. package/esm/production/cli/actions.mjs +151 -0
  93. package/esm/production/cli/actions.mjs.map +1 -0
  94. package/esm/production/cli/index.d.mts +17 -0
  95. package/esm/production/cli/index.d.mts.map +1 -0
  96. package/esm/production/cli/index.mjs +86 -0
  97. package/esm/production/cli/index.mjs.map +1 -0
  98. package/esm/production/contracts.d.mts +592 -0
  99. package/esm/production/contracts.d.mts.map +1 -0
  100. package/esm/production/contracts.mjs +95 -0
  101. package/esm/production/contracts.mjs.map +1 -0
  102. package/esm/production/errors.d.mts +31 -0
  103. package/esm/production/errors.d.mts.map +1 -0
  104. package/esm/production/errors.mjs +142 -0
  105. package/esm/production/errors.mjs.map +1 -0
  106. package/esm/production/http/access.mjs +124 -0
  107. package/esm/production/http/access.mjs.map +1 -0
  108. package/esm/production/http/auth-routes.mjs +280 -0
  109. package/esm/production/http/auth-routes.mjs.map +1 -0
  110. package/esm/production/http/client.mjs +57 -0
  111. package/esm/production/http/client.mjs.map +1 -0
  112. package/esm/production/http/constants.mjs +11 -0
  113. package/esm/production/http/constants.mjs.map +1 -0
  114. package/esm/production/http/context.mjs +14 -0
  115. package/esm/production/http/context.mjs.map +1 -0
  116. package/esm/production/http/cookie.mjs +39 -0
  117. package/esm/production/http/cookie.mjs.map +1 -0
  118. package/esm/production/http/headers.mjs +25 -0
  119. package/esm/production/http/headers.mjs.map +1 -0
  120. package/esm/production/http/index.mjs +10 -0
  121. package/esm/production/http/ip.mjs +130 -0
  122. package/esm/production/http/ip.mjs.map +1 -0
  123. package/esm/production/http/mount.mjs +300 -0
  124. package/esm/production/http/mount.mjs.map +1 -0
  125. package/esm/production/http/state.mjs +54 -0
  126. package/esm/production/http/state.mjs.map +1 -0
  127. package/esm/production/index.d.mts +6 -0
  128. package/esm/production/index.mjs +5 -0
  129. package/esm/production/insights/cap-report.mjs +67 -0
  130. package/esm/production/insights/cap-report.mjs.map +1 -0
  131. package/esm/production/insights/health.mjs +88 -0
  132. package/esm/production/insights/health.mjs.map +1 -0
  133. package/esm/production/insights/index.mjs +10 -0
  134. package/esm/production/insights/insights.mjs +167 -0
  135. package/esm/production/insights/insights.mjs.map +1 -0
  136. package/esm/production/insights/instance.mjs +24 -0
  137. package/esm/production/insights/instance.mjs.map +1 -0
  138. package/esm/production/insights/jobs.mjs +100 -0
  139. package/esm/production/insights/jobs.mjs.map +1 -0
  140. package/esm/production/insights/reporter.mjs +59 -0
  141. package/esm/production/insights/reporter.mjs.map +1 -0
  142. package/esm/production/insights/resources.mjs +139 -0
  143. package/esm/production/insights/resources.mjs.map +1 -0
  144. package/esm/production/insights/writer.mjs +72 -0
  145. package/esm/production/insights/writer.mjs.map +1 -0
  146. package/esm/production/openapi.mjs +52 -0
  147. package/esm/production/openapi.mjs.map +1 -0
  148. package/esm/production/options.d.mts +60 -0
  149. package/esm/production/options.d.mts.map +1 -0
  150. package/esm/production/options.mjs +170 -0
  151. package/esm/production/options.mjs.map +1 -0
  152. package/esm/production/stats/histogram.mjs +67 -0
  153. package/esm/production/stats/histogram.mjs.map +1 -0
  154. package/esm/production/stats/merge.mjs +106 -0
  155. package/esm/production/stats/merge.mjs.map +1 -0
  156. package/esm/production/store/cascade-store.mjs +322 -0
  157. package/esm/production/store/cascade-store.mjs.map +1 -0
  158. package/esm/production/store/index.mjs +5 -0
  159. package/esm/production/store/mapping.mjs +258 -0
  160. package/esm/production/store/mapping.mjs.map +1 -0
  161. package/esm/production/store/memory-store.mjs +291 -0
  162. package/esm/production/store/memory-store.mjs.map +1 -0
  163. package/esm/production/store/migrations.d.mts +11 -0
  164. package/esm/production/store/migrations.d.mts.map +1 -0
  165. package/esm/production/store/migrations.mjs +29 -0
  166. package/esm/production/store/migrations.mjs.map +1 -0
  167. package/esm/production/store/models/account.migration.mjs +34 -0
  168. package/esm/production/store/models/account.migration.mjs.map +1 -0
  169. package/esm/production/store/models/account.model.mjs +13 -0
  170. package/esm/production/store/models/account.model.mjs.map +1 -0
  171. package/esm/production/store/models/audit.migration.mjs +30 -0
  172. package/esm/production/store/models/audit.migration.mjs.map +1 -0
  173. package/esm/production/store/models/audit.model.mjs +13 -0
  174. package/esm/production/store/models/audit.model.mjs.map +1 -0
  175. package/esm/production/store/models/base.mjs +27 -0
  176. package/esm/production/store/models/base.mjs.map +1 -0
  177. package/esm/production/store/models/index.mjs +17 -0
  178. package/esm/production/store/models/invite.migration.mjs +26 -0
  179. package/esm/production/store/models/invite.migration.mjs.map +1 -0
  180. package/esm/production/store/models/invite.model.mjs +13 -0
  181. package/esm/production/store/models/invite.model.mjs.map +1 -0
  182. package/esm/production/store/models/report.migration.mjs +20 -0
  183. package/esm/production/store/models/report.migration.mjs.map +1 -0
  184. package/esm/production/store/models/report.model.mjs +13 -0
  185. package/esm/production/store/models/report.model.mjs.map +1 -0
  186. package/esm/production/store/models/sample.migration.mjs +25 -0
  187. package/esm/production/store/models/sample.migration.mjs.map +1 -0
  188. package/esm/production/store/models/sample.model.mjs +13 -0
  189. package/esm/production/store/models/sample.model.mjs.map +1 -0
  190. package/esm/production/store/models/session.migration.mjs +31 -0
  191. package/esm/production/store/models/session.migration.mjs.map +1 -0
  192. package/esm/production/store/models/session.model.mjs +13 -0
  193. package/esm/production/store/models/session.model.mjs.map +1 -0
  194. package/esm/production/store/models/state.migration.mjs +26 -0
  195. package/esm/production/store/models/state.migration.mjs.map +1 -0
  196. package/esm/production/store/models/state.model.mjs +13 -0
  197. package/esm/production/store/models/state.model.mjs.map +1 -0
  198. package/esm/query-shape.mjs +14 -1
  199. package/esm/query-shape.mjs.map +1 -1
  200. package/esm/server/explain-route.mjs +26 -1
  201. package/esm/server/explain-route.mjs.map +1 -1
  202. package/esm/server/index.mjs +9 -4
  203. package/esm/server/index.mjs.map +1 -1
  204. package/esm/server/insights-routes.mjs +62 -0
  205. package/esm/server/insights-routes.mjs.map +1 -0
  206. package/esm/server/log-routes.mjs +32 -5
  207. package/esm/server/log-routes.mjs.map +1 -1
  208. package/esm/server/openapi-routes.mjs +3 -2
  209. package/esm/server/openapi-routes.mjs.map +1 -1
  210. package/esm/server/requests-routes.mjs +125 -0
  211. package/esm/server/requests-routes.mjs.map +1 -1
  212. package/esm/server/session-routes.mjs +42 -0
  213. package/esm/server/session-routes.mjs.map +1 -0
  214. package/esm/server/stream-route.mjs +81 -11
  215. package/esm/server/stream-route.mjs.map +1 -1
  216. package/esm/server/ui-assets.mjs +34 -25
  217. package/esm/server/ui-assets.mjs.map +1 -1
  218. package/esm/sources/log-source.mjs +14 -1
  219. package/esm/sources/log-source.mjs.map +1 -1
  220. package/esm/types.d.mts +208 -3
  221. package/esm/types.d.mts.map +1 -1
  222. package/esm/ui-root.mjs +9 -4
  223. package/esm/ui-root.mjs.map +1 -1
  224. package/llms-full.txt +166 -21
  225. package/llms.txt +2 -2
  226. package/package.json +32 -8
  227. package/skills/SKILL.md +166 -21
  228. package/ui/dashboard/assets/app.css +3 -0
  229. package/ui/dashboard/assets/app.js +50 -0
  230. package/ui/dashboard/build-info.json +21 -0
  231. package/ui/dashboard/index.html +16 -0
  232. package/ui/panels/processes.js +12 -3
  233. package/cjs/ai-source-Dz_3tlZ5.cjs +0 -703
  234. package/cjs/ai-source-Dz_3tlZ5.cjs.map +0 -1
  235. package/cjs/server-B11ShQYE.cjs +0 -628
  236. package/cjs/server-B11ShQYE.cjs.map +0 -1
  237. package/cjs/src-Xwm3Eel9.cjs.map +0 -1
  238. package/ui/app.css +0 -376
  239. package/ui/app.js +0 -1158
  240. package/ui/index.html +0 -28
@@ -0,0 +1,300 @@
1
+ import { createHistogram, recordDuration, shortId } from "../stats/histogram.mjs";
2
+
3
+ //#region ../../packages/devtools/src/production/capture/stats-stores.ts
4
+ const SHAPE_MAX = 2e3;
5
+ const MESSAGE_MAX = 500;
6
+ const STACK_MAX = 4e3;
7
+ const LOG_MESSAGE_MAX = 1e3;
8
+ const PHASES_PER_ROUTE = 30;
9
+ const MONGO_EXPLAINABLE = /* @__PURE__ */ new Set([
10
+ "find",
11
+ "aggregate",
12
+ "count"
13
+ ]);
14
+ const SQL_START = /^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*(select|with)\b/i;
15
+ /** Whether a normalized query shape can be explained (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */
16
+ function isExplainableShape(driver, shape) {
17
+ if (driver === "postgres") return SQL_START.test(shape);
18
+ const space = shape.indexOf(" ");
19
+ const head = space === -1 ? shape : shape.slice(0, space);
20
+ const command = head.slice(head.lastIndexOf(".") + 1);
21
+ return MONGO_EXPLAINABLE.has(command);
22
+ }
23
+ const shapeIds = /* @__PURE__ */ new Map();
24
+ const SHAPE_ID_CACHE = 2e3;
25
+ /** `shortId` of a query shape, remembered: the same few hundred shapes arrive over and over. */
26
+ function shapeIdOf(shape) {
27
+ let id = shapeIds.get(shape);
28
+ if (id === void 0) {
29
+ if (shapeIds.size >= SHAPE_ID_CACHE) shapeIds.clear();
30
+ id = shortId(shape);
31
+ shapeIds.set(shape, id);
32
+ }
33
+ return id;
34
+ }
35
+ function truncate(value, maximum) {
36
+ return value.length > maximum ? value.slice(0, maximum) : value;
37
+ }
38
+ function copyHistogram(histogram) {
39
+ return {
40
+ ...histogram,
41
+ counts: [...histogram.counts]
42
+ };
43
+ }
44
+ /** Bounded per-shape query statistics. */
45
+ function createQueryStats(limits) {
46
+ const entries = /* @__PURE__ */ new Map();
47
+ let evictedCount = 0;
48
+ const touch = (shape, driver, connection, at) => {
49
+ const id = shapeIdOf(shape);
50
+ let entry = entries.get(id);
51
+ if (entry) {
52
+ entries.delete(id);
53
+ entry.stats.lastSeen = Math.max(entry.stats.lastSeen, at);
54
+ } else entry = {
55
+ example: void 0,
56
+ stats: {
57
+ id,
58
+ shape: truncate(shape, SHAPE_MAX),
59
+ driver,
60
+ connection,
61
+ count: 0,
62
+ errors: 0,
63
+ histogram: createHistogram(),
64
+ nPlusOne: {
65
+ requests: 0,
66
+ maxPerRequest: 0
67
+ },
68
+ slowest: null,
69
+ firstSeen: at,
70
+ lastSeen: at,
71
+ explainable: isExplainableShape(driver, shape)
72
+ }
73
+ };
74
+ entries.set(id, entry);
75
+ while (entries.size > limits.maxShapes) {
76
+ const oldest = entries.keys().next().value;
77
+ entries.delete(oldest);
78
+ evictedCount++;
79
+ }
80
+ return entry;
81
+ };
82
+ return {
83
+ record(query) {
84
+ const entry = touch(query.shape, query.driver, query.connection, query.at);
85
+ entry.stats.count++;
86
+ if (query.failed) entry.stats.errors++;
87
+ recordDuration(entry.stats.histogram, query.durationMs);
88
+ const slowest = entry.stats.slowest;
89
+ if (!slowest || query.durationMs > slowest.durationMs) entry.stats.slowest = {
90
+ durationMs: query.durationMs,
91
+ at: query.at,
92
+ route: query.route,
93
+ requestId: query.requestId,
94
+ instance: limits.instance
95
+ };
96
+ },
97
+ recordNPlusOne(shape, count) {
98
+ const known = entries.get(shapeIdOf(shape))?.stats;
99
+ const entry = touch(shape, known?.driver ?? "postgres", known?.connection ?? "", Date.now());
100
+ entry.stats.nPlusOne.requests++;
101
+ if (count > entry.stats.nPlusOne.maxPerRequest) entry.stats.nPlusOne.maxPerRequest = count;
102
+ },
103
+ rememberExample(query) {
104
+ const entry = touch(query.shape, query.driver, query.connection, query.startedAt);
105
+ if (!entry.example || query.durationMs > entry.example.durationMs) entry.example = {
106
+ ...query,
107
+ ...query.bindings === void 0 ? {} : { bindings: [...query.bindings] }
108
+ };
109
+ const slowest = entry.stats.slowest;
110
+ if (!slowest || query.durationMs > slowest.durationMs) entry.stats.slowest = {
111
+ durationMs: query.durationMs,
112
+ at: query.startedAt,
113
+ route: null,
114
+ requestId: null,
115
+ instance: limits.instance
116
+ };
117
+ },
118
+ example(shapeId) {
119
+ return entries.get(shapeId)?.example;
120
+ },
121
+ snapshot(limit) {
122
+ return [...entries.values()].map(({ stats }) => stats).sort((a, b) => b.histogram.sumMs - a.histogram.sumMs).slice(0, Math.max(0, limit)).map((stats) => ({
123
+ ...stats,
124
+ histogram: copyHistogram(stats.histogram),
125
+ nPlusOne: { ...stats.nPlusOne },
126
+ slowest: stats.slowest ? { ...stats.slowest } : null
127
+ }));
128
+ },
129
+ evicted: () => evictedCount,
130
+ clear() {
131
+ entries.clear();
132
+ }
133
+ };
134
+ }
135
+ /** Bounded per-route statistics. */
136
+ function createRouteStats(limits) {
137
+ const entries = /* @__PURE__ */ new Map();
138
+ let evictedCount = 0;
139
+ return {
140
+ record(request) {
141
+ const route = request.route === "" ? "(unmatched)" : request.route;
142
+ const key = `${request.method} ${route}`;
143
+ let entry = entries.get(key);
144
+ if (entry) entries.delete(key);
145
+ else entry = {
146
+ phases: /* @__PURE__ */ new Map(),
147
+ stats: {
148
+ key,
149
+ method: request.method,
150
+ route,
151
+ count: 0,
152
+ errors: 0,
153
+ histogram: createHistogram(),
154
+ phases: [],
155
+ slowest: null
156
+ }
157
+ };
158
+ entries.set(key, entry);
159
+ while (entries.size > limits.maxRoutes) {
160
+ entries.delete(entries.keys().next().value);
161
+ evictedCount++;
162
+ }
163
+ entry.stats.count++;
164
+ if (request.failed) entry.stats.errors++;
165
+ recordDuration(entry.stats.histogram, request.durationMs);
166
+ const slowest = entry.stats.slowest;
167
+ if (!slowest || request.durationMs > slowest.durationMs) entry.stats.slowest = {
168
+ durationMs: request.durationMs,
169
+ at: request.at,
170
+ requestId: request.requestId,
171
+ instance: limits.instance
172
+ };
173
+ for (const phase of request.phases) {
174
+ let stats = entry.phases.get(phase.name);
175
+ if (!stats) {
176
+ if (entry.phases.size >= PHASES_PER_ROUTE) {
177
+ let smallest;
178
+ for (const [name, candidate] of entry.phases) if (smallest === void 0 || candidate.sumMs < (entry.phases.get(smallest)?.sumMs ?? 0)) smallest = name;
179
+ if (smallest !== void 0) entry.phases.delete(smallest);
180
+ }
181
+ stats = {
182
+ name: phase.name,
183
+ count: 0,
184
+ sumMs: 0,
185
+ maxMs: 0
186
+ };
187
+ entry.phases.set(phase.name, stats);
188
+ }
189
+ const duration = Number.isFinite(phase.durationMs) ? Math.max(0, phase.durationMs) : 0;
190
+ stats.count++;
191
+ stats.sumMs += duration;
192
+ if (duration > stats.maxMs) stats.maxMs = duration;
193
+ }
194
+ },
195
+ snapshot(limit) {
196
+ return [...entries.values()].sort((a, b) => b.stats.histogram.sumMs - a.stats.histogram.sumMs).slice(0, Math.max(0, limit)).map(({ stats, phases }) => ({
197
+ ...stats,
198
+ histogram: copyHistogram(stats.histogram),
199
+ slowest: stats.slowest ? { ...stats.slowest } : null,
200
+ phases: [...phases.values()].sort((a, b) => b.sumMs - a.sumMs).slice(0, PHASES_PER_ROUTE).map((phase) => ({ ...phase }))
201
+ }));
202
+ },
203
+ evicted: () => evictedCount,
204
+ clear() {
205
+ entries.clear();
206
+ }
207
+ };
208
+ }
209
+ const QUOTED = /'(?:''|[^'])*'|"(?:\\.|[^"\\])*"/g;
210
+ const UUID = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
211
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
212
+ const HEX_ID = /\b0x[0-9a-f]+\b|\b(?=[0-9a-f]*\d)[0-9a-f]{8,}\b/gi;
213
+ /** A random id of letters and digits (request ids, tokens): 16+ characters with both. */
214
+ const TOKEN_ID = /\b(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{16,}\b/g;
215
+ const NUMBER = /\d+(?:\.\d+)?/g;
216
+ /**
217
+ * Replaces the parts of an error message that change between occurrences
218
+ * (quoted strings, emails, UUIDs, hex ids, random ids such as request ids,
219
+ * numbers) so equal errors group.
220
+ */
221
+ function normalizeErrorMessage(message) {
222
+ return message.replace(QUOTED, "<str>").replace(UUID, "<uuid>").replace(EMAIL, "<email>").replace(HEX_ID, "<hex>").replace(TOKEN_ID, "<id>").replace(NUMBER, "<n>");
223
+ }
224
+ /** Bounded error groups. */
225
+ function createErrorGroups(limits) {
226
+ const groups = /* @__PURE__ */ new Map();
227
+ let evictedCount = 0;
228
+ return {
229
+ record(input) {
230
+ const id = shortId(`${input.source}\n${input.name ?? ""}\n${normalizeErrorMessage(input.message)}\n${input.route ?? ""}`);
231
+ const known = groups.get(id);
232
+ const message = truncate(input.message, MESSAGE_MAX);
233
+ const stack = input.stack === null ? null : truncate(input.stack, STACK_MAX);
234
+ if (known) {
235
+ groups.delete(id);
236
+ known.count++;
237
+ known.message = message;
238
+ known.lastSeen = Math.max(known.lastSeen, input.at);
239
+ known.lastRequestId = input.requestId;
240
+ known.status = input.status ?? known.status;
241
+ if (stack !== null) known.stack = stack;
242
+ groups.set(id, known);
243
+ } else groups.set(id, {
244
+ id,
245
+ message,
246
+ name: input.name,
247
+ source: input.source,
248
+ route: input.route,
249
+ status: input.status,
250
+ count: 1,
251
+ firstSeen: input.at,
252
+ lastSeen: input.at,
253
+ lastRequestId: input.requestId,
254
+ stack
255
+ });
256
+ while (groups.size > limits.maxGroups) {
257
+ groups.delete(groups.keys().next().value);
258
+ evictedCount++;
259
+ }
260
+ },
261
+ snapshot(limit) {
262
+ return [...groups.values()].sort((a, b) => b.lastSeen - a.lastSeen).slice(0, Math.max(0, limit)).map((group) => ({ ...group }));
263
+ },
264
+ evicted: () => evictedCount,
265
+ clear() {
266
+ groups.clear();
267
+ }
268
+ };
269
+ }
270
+ /** Recent warn/error log entries, bounded. */
271
+ function createRecentLogs(limits) {
272
+ const entries = [];
273
+ return {
274
+ record(entry) {
275
+ entries.push({
276
+ ...entry,
277
+ message: truncate(entry.message, LOG_MESSAGE_MAX)
278
+ });
279
+ while (entries.length > limits.maxEntries) entries.shift();
280
+ },
281
+ snapshot(limit, filter = {}) {
282
+ const module = filter.module?.toLowerCase();
283
+ const result = [];
284
+ for (let index = entries.length - 1; index >= 0 && result.length < limit; index--) {
285
+ const entry = entries[index];
286
+ if (filter.level && entry.level !== filter.level) continue;
287
+ if (module && !entry.module.toLowerCase().includes(module)) continue;
288
+ result.push({ ...entry });
289
+ }
290
+ return result;
291
+ },
292
+ clear() {
293
+ entries.length = 0;
294
+ }
295
+ };
296
+ }
297
+
298
+ //#endregion
299
+ export { createErrorGroups, createQueryStats, createRecentLogs, createRouteStats, isExplainableShape, normalizeErrorMessage, shapeIdOf, truncate };
300
+ //# sourceMappingURL=stats-stores.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stats-stores.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/capture/stats-stores.ts"],"sourcesContent":["import type {\n DevtoolsErrorGroup,\n DevtoolsHistogram,\n DevtoolsQueryShapeStats,\n DevtoolsReportLogEntry,\n DevtoolsRoutePhaseStats,\n DevtoolsRouteStats,\n} from \"../contracts\";\nimport { createHistogram, recordDuration, shortId } from \"../stats\";\nimport type { DevtoolsQuery } from \"../../types\";\nimport type {\n DevtoolsErrorGroups,\n DevtoolsQueryObservation,\n DevtoolsQueryStats,\n DevtoolsRecentLogs,\n DevtoolsRequestObservation,\n DevtoolsRouteStatsStore,\n} from \"./types\";\n\nconst SHAPE_MAX = 2000;\nconst MESSAGE_MAX = 500;\nconst STACK_MAX = 4000;\nconst LOG_MESSAGE_MAX = 1000;\nconst PHASES_PER_ROUTE = 30;\n\nconst MONGO_EXPLAINABLE = new Set([\"find\", \"aggregate\", \"count\"]);\nconst SQL_START = /^(?:\\s|--[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/)*(select|with)\\b/i;\n\n/** Whether a normalized query shape can be explained (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */\nexport function isExplainableShape(driver: \"postgres\" | \"mongodb\", shape: string): boolean {\n if (driver === \"postgres\") return SQL_START.test(shape);\n\n // MongoDB shapes read `<collection>.<command> <json>`; the collection may hold dots.\n const space = shape.indexOf(\" \");\n const head = space === -1 ? shape : shape.slice(0, space);\n const command = head.slice(head.lastIndexOf(\".\") + 1);\n\n return MONGO_EXPLAINABLE.has(command);\n}\n\nconst shapeIds = new Map<string, string>();\nconst SHAPE_ID_CACHE = 2000;\n\n/** `shortId` of a query shape, remembered: the same few hundred shapes arrive over and over. */\nexport function shapeIdOf(shape: string): string {\n let id = shapeIds.get(shape);\n\n if (id === undefined) {\n if (shapeIds.size >= SHAPE_ID_CACHE) shapeIds.clear();\n\n id = shortId(shape);\n shapeIds.set(shape, id);\n }\n\n return id;\n}\n\nexport function truncate(value: string, maximum: number): string {\n return value.length > maximum ? value.slice(0, maximum) : value;\n}\n\nfunction copyHistogram(histogram: DevtoolsHistogram): DevtoolsHistogram {\n return { ...histogram, counts: [...histogram.counts] };\n}\n\n// ---------------------------------------------------------------------------\n// Query statistics\n// ---------------------------------------------------------------------------\n\ntype QueryEntry = {\n stats: DevtoolsQueryShapeStats;\n example: DevtoolsQuery | undefined;\n};\n\n/** Bounded per-shape query statistics. */\nexport function createQueryStats(limits: {\n maxShapes: number;\n instance: string;\n}): DevtoolsQueryStats {\n // Insertion order is recency: a touched entry moves to the end.\n const entries = new Map<string, QueryEntry>();\n let evictedCount = 0;\n\n const touch = (\n shape: string,\n driver: \"postgres\" | \"mongodb\",\n connection: string,\n at: number,\n ): QueryEntry => {\n const id = shapeIdOf(shape);\n let entry = entries.get(id);\n\n if (entry) {\n entries.delete(id);\n entry.stats.lastSeen = Math.max(entry.stats.lastSeen, at);\n } else {\n entry = {\n example: undefined,\n stats: {\n id,\n shape: truncate(shape, SHAPE_MAX),\n driver,\n connection,\n count: 0,\n errors: 0,\n histogram: createHistogram(),\n nPlusOne: { requests: 0, maxPerRequest: 0 },\n slowest: null,\n firstSeen: at,\n lastSeen: at,\n explainable: isExplainableShape(driver, shape),\n },\n };\n }\n\n entries.set(id, entry);\n\n while (entries.size > limits.maxShapes) {\n const oldest = entries.keys().next().value as string;\n\n entries.delete(oldest);\n evictedCount++;\n }\n\n return entry;\n };\n\n return {\n record(query: DevtoolsQueryObservation) {\n const entry = touch(query.shape, query.driver, query.connection, query.at);\n\n entry.stats.count++;\n if (query.failed) entry.stats.errors++;\n recordDuration(entry.stats.histogram, query.durationMs);\n\n const slowest = entry.stats.slowest;\n\n if (!slowest || query.durationMs > slowest.durationMs) {\n entry.stats.slowest = {\n durationMs: query.durationMs,\n at: query.at,\n route: query.route,\n requestId: query.requestId,\n instance: limits.instance,\n };\n }\n },\n recordNPlusOne(shape, count) {\n const known = entries.get(shapeIdOf(shape))?.stats;\n const entry = touch(shape, known?.driver ?? \"postgres\", known?.connection ?? \"\", Date.now());\n\n entry.stats.nPlusOne.requests++;\n if (count > entry.stats.nPlusOne.maxPerRequest) entry.stats.nPlusOne.maxPerRequest = count;\n },\n rememberExample(query) {\n const entry = touch(query.shape, query.driver, query.connection, query.startedAt);\n\n if (!entry.example || query.durationMs > entry.example.durationMs) {\n // A copy: the caller may strip the original, and the bindings array is the caller's.\n entry.example = {\n ...query,\n ...(query.bindings === undefined ? {} : { bindings: [...query.bindings] }),\n };\n }\n\n const slowest = entry.stats.slowest;\n\n if (!slowest || query.durationMs > slowest.durationMs) {\n entry.stats.slowest = {\n durationMs: query.durationMs,\n at: query.startedAt,\n route: null,\n requestId: null,\n instance: limits.instance,\n };\n }\n },\n example(shapeId) {\n return entries.get(shapeId)?.example;\n },\n snapshot(limit) {\n return [...entries.values()]\n .map(({ stats }) => stats)\n .sort((a, b) => b.histogram.sumMs - a.histogram.sumMs)\n .slice(0, Math.max(0, limit))\n .map((stats) => ({\n ...stats,\n histogram: copyHistogram(stats.histogram),\n nPlusOne: { ...stats.nPlusOne },\n slowest: stats.slowest ? { ...stats.slowest } : null,\n }));\n },\n evicted: () => evictedCount,\n clear() {\n entries.clear();\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Route statistics\n// ---------------------------------------------------------------------------\n\ntype RouteEntry = {\n stats: DevtoolsRouteStats;\n phases: Map<string, DevtoolsRoutePhaseStats>;\n};\n\n/** Bounded per-route statistics. */\nexport function createRouteStats(limits: {\n maxRoutes: number;\n instance: string;\n}): DevtoolsRouteStatsStore {\n const entries = new Map<string, RouteEntry>();\n let evictedCount = 0;\n\n return {\n record(request: DevtoolsRequestObservation) {\n const route = request.route === \"\" ? \"(unmatched)\" : request.route;\n const key = `${request.method} ${route}`;\n let entry = entries.get(key);\n\n if (entry) {\n entries.delete(key);\n } else {\n entry = {\n phases: new Map(),\n stats: {\n key,\n method: request.method,\n route,\n count: 0,\n errors: 0,\n histogram: createHistogram(),\n phases: [],\n slowest: null,\n },\n };\n }\n\n entries.set(key, entry);\n\n while (entries.size > limits.maxRoutes) {\n entries.delete(entries.keys().next().value as string);\n evictedCount++;\n }\n\n entry.stats.count++;\n if (request.failed) entry.stats.errors++;\n recordDuration(entry.stats.histogram, request.durationMs);\n\n const slowest = entry.stats.slowest;\n\n if (!slowest || request.durationMs > slowest.durationMs) {\n entry.stats.slowest = {\n durationMs: request.durationMs,\n at: request.at,\n requestId: request.requestId,\n instance: limits.instance,\n };\n }\n\n for (const phase of request.phases) {\n let stats = entry.phases.get(phase.name);\n\n if (!stats) {\n if (entry.phases.size >= PHASES_PER_ROUTE) {\n // Make room by dropping the phase with the smallest total.\n let smallest: string | undefined;\n\n for (const [name, candidate] of entry.phases) {\n if (\n smallest === undefined ||\n candidate.sumMs < (entry.phases.get(smallest)?.sumMs ?? 0)\n ) {\n smallest = name;\n }\n }\n\n if (smallest !== undefined) entry.phases.delete(smallest);\n }\n\n stats = { name: phase.name, count: 0, sumMs: 0, maxMs: 0 };\n entry.phases.set(phase.name, stats);\n }\n\n const duration = Number.isFinite(phase.durationMs) ? Math.max(0, phase.durationMs) : 0;\n\n stats.count++;\n stats.sumMs += duration;\n if (duration > stats.maxMs) stats.maxMs = duration;\n }\n },\n snapshot(limit) {\n return [...entries.values()]\n .sort((a, b) => b.stats.histogram.sumMs - a.stats.histogram.sumMs)\n .slice(0, Math.max(0, limit))\n .map(({ stats, phases }) => ({\n ...stats,\n histogram: copyHistogram(stats.histogram),\n slowest: stats.slowest ? { ...stats.slowest } : null,\n phases: [...phases.values()]\n .sort((a, b) => b.sumMs - a.sumMs)\n .slice(0, PHASES_PER_ROUTE)\n .map((phase) => ({ ...phase })),\n }));\n },\n evicted: () => evictedCount,\n clear() {\n entries.clear();\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Error groups\n// ---------------------------------------------------------------------------\n\nconst QUOTED = /'(?:''|[^'])*'|\"(?:\\\\.|[^\"\\\\])*\"/g;\nconst UUID = /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi;\nconst EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/g;\nconst HEX_ID = /\\b0x[0-9a-f]+\\b|\\b(?=[0-9a-f]*\\d)[0-9a-f]{8,}\\b/gi;\n/** A random id of letters and digits (request ids, tokens): 16+ characters with both. */\nconst TOKEN_ID = /\\b(?=[A-Za-z0-9_-]*\\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{16,}\\b/g;\nconst NUMBER = /\\d+(?:\\.\\d+)?/g;\n\n/**\n * Replaces the parts of an error message that change between occurrences\n * (quoted strings, emails, UUIDs, hex ids, random ids such as request ids,\n * numbers) so equal errors group.\n */\nexport function normalizeErrorMessage(message: string): string {\n return message\n .replace(QUOTED, \"<str>\")\n .replace(UUID, \"<uuid>\")\n .replace(EMAIL, \"<email>\")\n .replace(HEX_ID, \"<hex>\")\n .replace(TOKEN_ID, \"<id>\")\n .replace(NUMBER, \"<n>\");\n}\n\n/** Bounded error groups. */\nexport function createErrorGroups(limits: { maxGroups: number }): DevtoolsErrorGroups {\n const groups = new Map<string, DevtoolsErrorGroup>();\n let evictedCount = 0;\n\n return {\n record(input) {\n const id = shortId(\n `${input.source}\\n${input.name ?? \"\"}\\n${normalizeErrorMessage(input.message)}\\n${input.route ?? \"\"}`,\n );\n const known = groups.get(id);\n const message = truncate(input.message, MESSAGE_MAX);\n const stack = input.stack === null ? null : truncate(input.stack, STACK_MAX);\n\n if (known) {\n groups.delete(id);\n known.count++;\n known.message = message;\n known.lastSeen = Math.max(known.lastSeen, input.at);\n known.lastRequestId = input.requestId;\n known.status = input.status ?? known.status;\n if (stack !== null) known.stack = stack;\n groups.set(id, known);\n } else {\n groups.set(id, {\n id,\n message,\n name: input.name,\n source: input.source,\n route: input.route,\n status: input.status,\n count: 1,\n firstSeen: input.at,\n lastSeen: input.at,\n lastRequestId: input.requestId,\n stack,\n });\n }\n\n while (groups.size > limits.maxGroups) {\n groups.delete(groups.keys().next().value as string);\n evictedCount++;\n }\n },\n snapshot(limit) {\n return [...groups.values()]\n .sort((a, b) => b.lastSeen - a.lastSeen)\n .slice(0, Math.max(0, limit))\n .map((group) => ({ ...group }));\n },\n evicted: () => evictedCount,\n clear() {\n groups.clear();\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Recent logs\n// ---------------------------------------------------------------------------\n\n/** Recent warn/error log entries, bounded. */\nexport function createRecentLogs(limits: { maxEntries: number }): DevtoolsRecentLogs {\n // Oldest first internally; read newest first.\n const entries: DevtoolsReportLogEntry[] = [];\n\n return {\n record(entry) {\n entries.push({ ...entry, message: truncate(entry.message, LOG_MESSAGE_MAX) });\n\n while (entries.length > limits.maxEntries) entries.shift();\n },\n snapshot(limit, filter = {}) {\n const module = filter.module?.toLowerCase();\n const result: DevtoolsReportLogEntry[] = [];\n\n for (let index = entries.length - 1; index >= 0 && result.length < limit; index--) {\n const entry = entries[index] as DevtoolsReportLogEntry;\n\n if (filter.level && entry.level !== filter.level) continue;\n if (module && !entry.module.toLowerCase().includes(module)) continue;\n\n result.push({ ...entry });\n }\n\n return result;\n },\n clear() {\n entries.length = 0;\n },\n };\n}\n"],"mappings":";;;AAmBA,MAAM,YAAY;AAClB,MAAM,cAAc;AACpB,MAAM,YAAY;AAClB,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AAEzB,MAAM,oCAAoB,IAAI,IAAI;CAAC;CAAQ;CAAa;AAAO,CAAC;AAChE,MAAM,YAAY;;AAGlB,SAAgB,mBAAmB,QAAgC,OAAwB;CACzF,IAAI,WAAW,YAAY,OAAO,UAAU,KAAK,KAAK;CAGtD,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,MAAM,OAAO,UAAU,KAAK,QAAQ,MAAM,MAAM,GAAG,KAAK;CACxD,MAAM,UAAU,KAAK,MAAM,KAAK,YAAY,GAAG,IAAI,CAAC;CAEpD,OAAO,kBAAkB,IAAI,OAAO;AACtC;AAEA,MAAM,2BAAW,IAAI,IAAoB;AACzC,MAAM,iBAAiB;;AAGvB,SAAgB,UAAU,OAAuB;CAC/C,IAAI,KAAK,SAAS,IAAI,KAAK;CAE3B,IAAI,OAAO,QAAW;EACpB,IAAI,SAAS,QAAQ,gBAAgB,SAAS,MAAM;EAEpD,KAAK,QAAQ,KAAK;EAClB,SAAS,IAAI,OAAO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G,KAAK,CAAC,CAAC,CAC5B,KAAK,WAAW,EAAE,GAAG,MAAM,EAAE;EAClC;EACA,eAAe;EACf,QAAQ;GACN,OAAO,MAAM;EACf;CACF;AACF;;AAOA,SAAgB,iBAAiB,QAAoD;CAEnF,MAAM,UAAoC,CAAC;CAE3C,OAAO;EACL,OAAO,OAAO;GACZ,QAAQ,KAAK;IAAE,GAAG;IAAO,SAAS,SAAS,MAAM,SAAS,eAAe;GAAE,CAAC;GAE5E,OAAO,QAAQ,SAAS,OAAO,YAAY,QAAQ,MAAM;EAC3D;EACA,SAAS,OAAO,SAAS,CAAC,GAAG;GAC3B,MAAM,SAAS,OAAO,QAAQ,YAAY;GAC1C,MAAM,SAAmC,CAAC;GAE1C,KAAK,IAAI,QAAQ,QAAQ,SAAS,GAAG,SAAS,KAAK,OAAO,SAAS,OAAO,SAAS;IACjF,MAAM,QAAQ,QAAQ;IAEtB,IAAI,OAAO,SAAS,MAAM,UAAU,OAAO,OAAO;IAClD,IAAI,UAAU,CAAC,MAAM,OAAO,YAAY,CAAC,CAAC,SAAS,MAAM,GAAG;IAE5D,OAAO,KAAK,EAAE,GAAG,MAAM,CAAC;GAC1B;GAEA,OAAO;EACT;EACA,QAAQ;GACN,QAAQ,SAAS;EACnB;CACF;AACF"}
@@ -0,0 +1,151 @@
1
+ import { DEVTOOLS_CONFIG_CODES, DevtoolsProductionConfigError, DevtoolsStoreConflictError, createErrorRef } from "../errors.mjs";
2
+
3
+ //#region ../../packages/devtools/src/production/cli/actions.ts
4
+ /** The `ip` value of every audit entry a command writes. */
5
+ const CLI_AUDIT_IP = "cli";
6
+ const MAX_WRITE_ATTEMPTS = 5;
7
+ /** Tells the owner what to do when the database cannot be used. Returns the exit code (1). */
8
+ function reportStoreError(io, error) {
9
+ if (error instanceof DevtoolsProductionConfigError) {
10
+ io.err(error.message);
11
+ return 1;
12
+ }
13
+ const detail = error instanceof Error ? error.message : String(error);
14
+ io.err(`Could not use the database: ${detail}. Check that the database is reachable and its settings are correct, then run the command again. If the tables are missing: ${DEVTOOLS_CONFIG_CODES.DT008}`);
15
+ return 1;
16
+ }
17
+ /**
18
+ * `warlock devtools:enable`: clears the disable flag and the global lock and
19
+ * stops earlier failures from counting. Returns the exit code.
20
+ */
21
+ async function runEnable(context) {
22
+ const { store, now, io } = context;
23
+ try {
24
+ await store.verify();
25
+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt++) {
26
+ const state = await store.state.read();
27
+ const at = now();
28
+ if (!await store.state.update(state.version, {
29
+ disabled: false,
30
+ disabledPathHash: null,
31
+ lockedUntil: null,
32
+ failuresResetAt: at
33
+ })) continue;
34
+ await store.audit.append({
35
+ at,
36
+ type: "dashboard.enabled",
37
+ accountId: null,
38
+ email: null,
39
+ ip: "cli",
40
+ userAgent: null,
41
+ detail: {
42
+ wasDisabled: state.disabled,
43
+ wasLocked: state.lockedUntil !== null && state.lockedUntil > at
44
+ },
45
+ ref: createErrorRef()
46
+ });
47
+ io.out([
48
+ "The devtools dashboard is enabled.",
49
+ state.disabled ? "- The disable switch is cleared." : "- The disable switch was not set.",
50
+ state.lockedUntil !== null && state.lockedUntil > at ? "- The global lock is cleared." : "- The dashboard was not locked.",
51
+ "- Earlier failed sign-ins no longer count toward the limits."
52
+ ].join("\n"));
53
+ return 0;
54
+ }
55
+ io.err("Another process kept changing the dashboard state, so nothing was saved. Run `warlock devtools:enable` again.");
56
+ return 1;
57
+ } catch (error) {
58
+ return reportStoreError(io, error);
59
+ }
60
+ }
61
+ /** Normalises the `--email` option or `DEVTOOLS_ADMIN_EMAIL`. Returns `null` when there is none. */
62
+ function resolveAdminEmail(option, env) {
63
+ const email = (typeof option === "string" && option.trim() !== "" ? option : env.DEVTOOLS_ADMIN_EMAIL)?.trim().toLowerCase() ?? "";
64
+ return email === "" ? null : email;
65
+ }
66
+ /**
67
+ * `warlock devtools:reset-admin`: creates the admin account or resets it to a
68
+ * printed temporary password, without second factors, and signs it out
69
+ * everywhere. Returns the exit code.
70
+ */
71
+ async function runResetAdmin(context, email) {
72
+ const { store, now, io, generatePassword, hashPassword } = context;
73
+ if (email === null || !email.includes("@")) {
74
+ io.err(email === null ? "No email was given. Run `warlock devtools:reset-admin --email <email>`, or set DEVTOOLS_ADMIN_EMAIL." : `"${email}" is not an email address. Run \`warlock devtools:reset-admin --email <email>\` with a valid address.`);
75
+ return 1;
76
+ }
77
+ try {
78
+ await store.verify();
79
+ const password = generatePassword();
80
+ const passwordHash = await hashPassword(password);
81
+ for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt++) {
82
+ const at = now();
83
+ const existing = await store.accounts.findByEmail(email);
84
+ const account = existing ? await store.accounts.update(existing.id, existing.version, {
85
+ role: "admin",
86
+ passwordHash,
87
+ passwordSource: "reset",
88
+ mustChangePassword: true,
89
+ totpSecret: null,
90
+ totpEnabledAt: null,
91
+ totpLastStep: null,
92
+ recoveryCodes: [],
93
+ passkeys: [],
94
+ failuresResetAt: at
95
+ }) : await createAdmin(store, email, passwordHash, at);
96
+ if (!account) continue;
97
+ const signedOut = await store.sessions.removeForAccount(account.id);
98
+ await store.audit.append({
99
+ at,
100
+ type: "admin.reset",
101
+ accountId: account.id,
102
+ email,
103
+ ip: "cli",
104
+ userAgent: null,
105
+ detail: {
106
+ created: existing === null,
107
+ sessionsRemoved: signedOut
108
+ },
109
+ ref: createErrorRef()
110
+ });
111
+ io.out([
112
+ existing ? `The admin account ${email} was reset.` : `The admin account ${email} was created.`,
113
+ `Temporary password: ${password}`,
114
+ "Sign in with it; the dashboard asks for a new password and a second factor.",
115
+ signedOut > 0 ? `${signedOut} open session(s) were signed out.` : "The account had no open sessions."
116
+ ].join("\n"));
117
+ return 0;
118
+ }
119
+ io.err(`Another process kept changing the account ${email}, so nothing was saved. Run the command again.`);
120
+ return 1;
121
+ } catch (error) {
122
+ return reportStoreError(io, error);
123
+ }
124
+ }
125
+ /** Creates the account; `null` when another process created it first (the caller retries as a reset). */
126
+ async function createAdmin(store, email, passwordHash, at) {
127
+ try {
128
+ return await store.accounts.create({
129
+ email,
130
+ role: "admin",
131
+ passwordHash,
132
+ passwordSource: "reset",
133
+ mustChangePassword: true,
134
+ totpSecret: null,
135
+ totpEnabledAt: null,
136
+ totpLastStep: null,
137
+ recoveryCodes: [],
138
+ passkeys: [],
139
+ failuresResetAt: at,
140
+ lastLoginAt: null,
141
+ createdBy: null
142
+ });
143
+ } catch (error) {
144
+ if (error instanceof DevtoolsStoreConflictError) return null;
145
+ throw error;
146
+ }
147
+ }
148
+
149
+ //#endregion
150
+ export { reportStoreError, resolveAdminEmail, runEnable, runResetAdmin };
151
+ //# sourceMappingURL=actions.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actions.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/cli/actions.ts"],"sourcesContent":["import {\n DEVTOOLS_CONFIG_CODES,\n DevtoolsProductionConfigError,\n DevtoolsStoreConflictError,\n createErrorRef,\n} from \"../errors\";\nimport type { DevtoolsAccountRecord, DevtoolsStore } from \"../store/types\";\n\n/** Where the commands print. */\nexport type CliOutput = {\n out(line: string): void;\n err(line: string): void;\n};\n\n/** What a command needs; specs pass a memory store, a fixed clock and fakes. */\nexport type DevtoolsCliContext = {\n store: DevtoolsStore;\n now: () => number;\n io: CliOutput;\n};\n\nexport type ResetAdminContext = DevtoolsCliContext & {\n /** Returns a new random password (`generateTemporaryPassword()`). */\n generatePassword: () => string;\n /** Core's `hashPassword`. */\n hashPassword: (password: string) => Promise<string>;\n};\n\n/** The `ip` value of every audit entry a command writes. */\nexport const CLI_AUDIT_IP = \"cli\";\n\nconst MAX_WRITE_ATTEMPTS = 5;\n\n/** Tells the owner what to do when the database cannot be used. Returns the exit code (1). */\nexport function reportStoreError(io: CliOutput, error: unknown): number {\n if (error instanceof DevtoolsProductionConfigError) {\n io.err(error.message);\n\n return 1;\n }\n\n const detail = error instanceof Error ? error.message : String(error);\n\n io.err(\n `Could not use the database: ${detail}. Check that the database is reachable and its settings are correct, then run the command again. ` +\n `If the tables are missing: ${DEVTOOLS_CONFIG_CODES.DT008}`,\n );\n\n return 1;\n}\n\n/**\n * `warlock devtools:enable`: clears the disable flag and the global lock and\n * stops earlier failures from counting. Returns the exit code.\n */\nexport async function runEnable(context: DevtoolsCliContext): Promise<number> {\n const { store, now, io } = context;\n\n try {\n await store.verify();\n\n for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt++) {\n const state = await store.state.read();\n const at = now();\n const updated = await store.state.update(state.version, {\n disabled: false,\n disabledPathHash: null,\n lockedUntil: null,\n failuresResetAt: at,\n });\n\n if (!updated) continue;\n\n await store.audit.append({\n at,\n type: \"dashboard.enabled\",\n accountId: null,\n email: null,\n ip: CLI_AUDIT_IP,\n userAgent: null,\n detail: {\n wasDisabled: state.disabled,\n wasLocked: state.lockedUntil !== null && state.lockedUntil > at,\n },\n ref: createErrorRef(),\n });\n\n io.out(\n [\n \"The devtools dashboard is enabled.\",\n state.disabled ? \"- The disable switch is cleared.\" : \"- The disable switch was not set.\",\n state.lockedUntil !== null && state.lockedUntil > at\n ? \"- The global lock is cleared.\"\n : \"- The dashboard was not locked.\",\n \"- Earlier failed sign-ins no longer count toward the limits.\",\n ].join(\"\\n\"),\n );\n\n return 0;\n }\n\n io.err(\n \"Another process kept changing the dashboard state, so nothing was saved. Run `warlock devtools:enable` again.\",\n );\n\n return 1;\n } catch (error) {\n return reportStoreError(io, error);\n }\n}\n\n/** Normalises the `--email` option or `DEVTOOLS_ADMIN_EMAIL`. Returns `null` when there is none. */\nexport function resolveAdminEmail(\n option: unknown,\n env: Record<string, string | undefined>,\n): string | null {\n const raw =\n typeof option === \"string\" && option.trim() !== \"\" ? option : env.DEVTOOLS_ADMIN_EMAIL;\n const email = raw?.trim().toLowerCase() ?? \"\";\n\n return email === \"\" ? null : email;\n}\n\n/**\n * `warlock devtools:reset-admin`: creates the admin account or resets it to a\n * printed temporary password, without second factors, and signs it out\n * everywhere. Returns the exit code.\n */\nexport async function runResetAdmin(\n context: ResetAdminContext,\n email: string | null,\n): Promise<number> {\n const { store, now, io, generatePassword, hashPassword } = context;\n\n if (email === null || !email.includes(\"@\")) {\n io.err(\n email === null\n ? \"No email was given. Run `warlock devtools:reset-admin --email <email>`, or set DEVTOOLS_ADMIN_EMAIL.\"\n : `\"${email}\" is not an email address. Run \\`warlock devtools:reset-admin --email <email>\\` with a valid address.`,\n );\n\n return 1;\n }\n\n try {\n await store.verify();\n\n const password = generatePassword();\n const passwordHash = await hashPassword(password);\n\n for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt++) {\n const at = now();\n const existing = await store.accounts.findByEmail(email);\n const account = existing\n ? await store.accounts.update(existing.id, existing.version, {\n role: \"admin\",\n passwordHash,\n passwordSource: \"reset\",\n mustChangePassword: true,\n totpSecret: null,\n totpEnabledAt: null,\n totpLastStep: null,\n recoveryCodes: [],\n passkeys: [],\n failuresResetAt: at,\n })\n : await createAdmin(store, email, passwordHash, at);\n\n if (!account) continue;\n\n const signedOut = await store.sessions.removeForAccount(account.id);\n\n await store.audit.append({\n at,\n type: \"admin.reset\",\n accountId: account.id,\n email,\n ip: CLI_AUDIT_IP,\n userAgent: null,\n detail: { created: existing === null, sessionsRemoved: signedOut },\n ref: createErrorRef(),\n });\n\n io.out(\n [\n existing\n ? `The admin account ${email} was reset.`\n : `The admin account ${email} was created.`,\n `Temporary password: ${password}`,\n \"Sign in with it; the dashboard asks for a new password and a second factor.\",\n signedOut > 0\n ? `${signedOut} open session(s) were signed out.`\n : \"The account had no open sessions.\",\n ].join(\"\\n\"),\n );\n\n return 0;\n }\n\n io.err(\n `Another process kept changing the account ${email}, so nothing was saved. Run the command again.`,\n );\n\n return 1;\n } catch (error) {\n return reportStoreError(io, error);\n }\n}\n\n/** Creates the account; `null` when another process created it first (the caller retries as a reset). */\nasync function createAdmin(\n store: DevtoolsStore,\n email: string,\n passwordHash: string,\n at: number,\n): Promise<DevtoolsAccountRecord | null> {\n try {\n return await store.accounts.create({\n email,\n role: \"admin\",\n passwordHash,\n passwordSource: \"reset\",\n mustChangePassword: true,\n totpSecret: null,\n totpEnabledAt: null,\n totpLastStep: null,\n recoveryCodes: [],\n passkeys: [],\n failuresResetAt: at,\n lastLoginAt: null,\n createdBy: null,\n });\n } catch (error) {\n if (error instanceof DevtoolsStoreConflictError) return null;\n\n throw error;\n }\n}\n"],"mappings":";;;;AA6BA,MAAa,eAAe;AAE5B,MAAM,qBAAqB;;AAG3B,SAAgB,iBAAiB,IAAe,OAAwB;CACtE,IAAI,iBAAiB,+BAA+B;EAClD,GAAG,IAAI,MAAM,OAAO;EAEpB,OAAO;CACT;CAEA,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAEpE,GAAG,IACD,+BAA+B,OAAO,8HACN,sBAAsB,OACxD;CAEA,OAAO;AACT;;;;;AAMA,eAAsB,UAAU,SAA8C;CAC5E,MAAM,EAAE,OAAO,KAAK,OAAO;CAE3B,IAAI;EACF,MAAM,MAAM,OAAO;EAEnB,KAAK,IAAI,UAAU,GAAG,UAAU,oBAAoB,WAAW;GAC7D,MAAM,QAAQ,MAAM,MAAM,MAAM,KAAK;GACrC,MAAM,KAAK,IAAI;GAQf,IAAI,CAAC,MAPiB,MAAM,MAAM,OAAO,MAAM,SAAS;IACtD,UAAU;IACV,kBAAkB;IAClB,aAAa;IACb,iBAAiB;GACnB,CAAC,GAEa;GAEd,MAAM,MAAM,MAAM,OAAO;IACvB;IACA,MAAM;IACN,WAAW;IACX,OAAO;IACP;IACA,WAAW;IACX,QAAQ;KACN,aAAa,MAAM;KACnB,WAAW,MAAM,gBAAgB,QAAQ,MAAM,cAAc;IAC/D;IACA,KAAK,eAAe;GACtB,CAAC;GAED,GAAG,IACD;IACE;IACA,MAAM,WAAW,qCAAqC;IACtD,MAAM,gBAAgB,QAAQ,MAAM,cAAc,KAC9C,kCACA;IACJ;GACF,CAAC,CAAC,KAAK,IAAI,CACb;GAEA,OAAO;EACT;EAEA,GAAG,IACD,+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AqB,MAAM,eAC3B,qBAAqB,MAAM;IAC/B,uBAAuB;IACvB;IACA,YAAY,IACR,GAAG,UAAU,qCACb;GACN,CAAC,CAAC,KAAK,IAAI,CACb;GAEA,OAAO;EACT;EAEA,GAAG,IACD,6CAA6C,MAAM,+CACrD;EAEA,OAAO;CACT,SAAS,OAAO;EACd,OAAO,iBAAiB,IAAI,KAAK;CACnC;AACF;;AAGA,eAAe,YACb,OACA,OACA,cACA,IACuC;CACvC,IAAI;EACF,OAAO,MAAM,MAAM,SAAS,OAAO;GACjC;GACA,MAAM;GACN;GACA,gBAAgB;GAChB,oBAAoB;GACpB,YAAY;GACZ,eAAe;GACf,cAAc;GACd,eAAe,CAAC;GAChB,UAAU,CAAC;GACX,iBAAiB;GACjB,aAAa;GACb,WAAW;EACb,CAAC;CACH,SAAS,OAAO;EACd,IAAI,iBAAiB,4BAA4B,OAAO;EAExD,MAAM;CACR;AACF"}
@@ -0,0 +1,17 @@
1
+ import { CLICommand } from "@warlock.js/core";
2
+ //#region ../../packages/devtools/src/production/cli/index.d.ts
3
+ /**
4
+ * `warlock devtools:enable` and `warlock devtools:reset-admin`, for
5
+ * `warlock.config.ts > cli.commands`. Both connect to the database only
6
+ * (no HTTP server) and write an audit entry with `ip: "cli"`.
7
+ *
8
+ * - `devtools:enable`: clears the disable flag and the global lock, and sets
9
+ * `failuresResetAt` so earlier failures stop counting.
10
+ * - `devtools:reset-admin [--email <email>]` (default `DEVTOOLS_ADMIN_EMAIL`):
11
+ * creates or resets that account as an admin with a printed temporary
12
+ * password (must be changed at sign-in), clears its second factors and
13
+ * recovery codes, unlocks it, and signs out its sessions.
14
+ */
15
+ export declare function registerDevtoolsCommands(): CLICommand[];
16
+ //#endregion
17
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/cli/index.ts"],"mappings":";;;;;;;;;;;;;;wBA2DgB,4BAA4B"}
@@ -0,0 +1,86 @@
1
+ import { reportStoreError, resolveAdminEmail, runEnable, runResetAdmin } from "./actions.mjs";
2
+ import { command } from "@warlock.js/core";
3
+
4
+ //#region ../../packages/devtools/src/production/cli/index.ts
5
+ /** The same boot as `warlock migrate`: the app's config and the database connection, no HTTP server. */
6
+ const PRELOAD = {
7
+ config: true,
8
+ warlockConfig: true,
9
+ bootstrap: true,
10
+ connectors: ["database"]
11
+ };
12
+ /** Print with the stream's own write, so a boot that moves `console.log` never mixes into the answer. */
13
+ const io = {
14
+ out: (line) => void process.stdout.write(`${line}\n`),
15
+ err: (line) => void process.stderr.write(`${line}\n`)
16
+ };
17
+ /** Exit with `code` once stdout and stderr are flushed (a non-zero code only; 0 lets the CLI finish). */
18
+ async function exitWith(code) {
19
+ if (code === 0) return;
20
+ process.exitCode = code;
21
+ await Promise.race([Promise.all([process.stdout, process.stderr].map((stream) => new Promise((resolve) => stream.write("", () => resolve())))), new Promise((resolve) => setTimeout(resolve, 500).unref())]);
22
+ process.exit(code);
23
+ }
24
+ /** The store of the app's database, or the exit code of the error that stopped it. */
25
+ async function openStore() {
26
+ try {
27
+ const { createCascadeStore } = await import("../store/cascade-store.mjs");
28
+ return { store: await createCascadeStore() };
29
+ } catch (error) {
30
+ return { code: reportStoreError(io, error) };
31
+ }
32
+ }
33
+ /**
34
+ * `warlock devtools:enable` and `warlock devtools:reset-admin`, for
35
+ * `warlock.config.ts > cli.commands`. Both connect to the database only
36
+ * (no HTTP server) and write an audit entry with `ip: "cli"`.
37
+ *
38
+ * - `devtools:enable`: clears the disable flag and the global lock, and sets
39
+ * `failuresResetAt` so earlier failures stop counting.
40
+ * - `devtools:reset-admin [--email <email>]` (default `DEVTOOLS_ADMIN_EMAIL`):
41
+ * creates or resets that account as an admin with a printed temporary
42
+ * password (must be changed at sign-in), clears its second factors and
43
+ * recovery codes, unlocks it, and signs out its sessions.
44
+ */
45
+ function registerDevtoolsCommands() {
46
+ return [command({
47
+ name: "devtools:enable",
48
+ description: "Turn the production devtools dashboard back on: clears the disable switch, the global lock and the failure counters",
49
+ preload: PRELOAD,
50
+ action: async () => {
51
+ const opened = await openStore();
52
+ if (!opened.store) return exitWith(opened.code);
53
+ await exitWith(await runEnable({
54
+ store: opened.store,
55
+ now: Date.now,
56
+ io
57
+ }));
58
+ }
59
+ }), command({
60
+ name: "devtools:reset-admin",
61
+ description: "Create or reset a devtools admin account with a printed temporary password (no second factor, signed out everywhere)",
62
+ preload: PRELOAD,
63
+ action: async ({ options }) => {
64
+ const email = resolveAdminEmail(options.email, process.env);
65
+ const opened = await openStore();
66
+ if (!opened.store) return exitWith(opened.code);
67
+ const [{ hashPassword }, { generateTemporaryPassword }] = await Promise.all([import("@warlock.js/core"), import("../auth/index.mjs")]);
68
+ await exitWith(await runResetAdmin({
69
+ store: opened.store,
70
+ now: Date.now,
71
+ io,
72
+ generatePassword: generateTemporaryPassword,
73
+ hashPassword
74
+ }, email));
75
+ },
76
+ options: [{
77
+ text: "--email, -e",
78
+ description: "The admin email (default: DEVTOOLS_ADMIN_EMAIL)",
79
+ type: "string"
80
+ }]
81
+ })];
82
+ }
83
+
84
+ //#endregion
85
+ export { registerDevtoolsCommands };
86
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/cli/index.ts"],"sourcesContent":["import { command, type CLICommand, type CLICommandPreload } from \"@warlock.js/core\";\nimport { reportStoreError, runEnable, runResetAdmin, resolveAdminEmail } from \"./actions\";\nimport type { CliOutput } from \"./actions\";\n\n/** The same boot as `warlock migrate`: the app's config and the database connection, no HTTP server. */\nconst PRELOAD: CLICommandPreload = {\n config: true,\n warlockConfig: true,\n bootstrap: true,\n connectors: [\"database\"],\n};\n\n/** Print with the stream's own write, so a boot that moves `console.log` never mixes into the answer. */\nconst io: CliOutput = {\n out: (line) => void process.stdout.write(`${line}\\n`),\n err: (line) => void process.stderr.write(`${line}\\n`),\n};\n\n/** Exit with `code` once stdout and stderr are flushed (a non-zero code only; 0 lets the CLI finish). */\nasync function exitWith(code: number): Promise<void> {\n if (code === 0) return;\n\n process.exitCode = code;\n\n await Promise.race([\n Promise.all(\n [process.stdout, process.stderr].map(\n (stream) => new Promise<void>((resolve) => stream.write(\"\", () => resolve())),\n ),\n ),\n new Promise<void>((resolve) => setTimeout(resolve, 500).unref()),\n ]);\n\n process.exit(code);\n}\n\n/** The store of the app's database, or the exit code of the error that stopped it. */\nasync function openStore() {\n try {\n const { createCascadeStore } = await import(\"../store/cascade-store\");\n\n return { store: await createCascadeStore() };\n } catch (error) {\n return { code: reportStoreError(io, error) };\n }\n}\n\n/**\n * `warlock devtools:enable` and `warlock devtools:reset-admin`, for\n * `warlock.config.ts > cli.commands`. Both connect to the database only\n * (no HTTP server) and write an audit entry with `ip: \"cli\"`.\n *\n * - `devtools:enable`: clears the disable flag and the global lock, and sets\n * `failuresResetAt` so earlier failures stop counting.\n * - `devtools:reset-admin [--email <email>]` (default `DEVTOOLS_ADMIN_EMAIL`):\n * creates or resets that account as an admin with a printed temporary\n * password (must be changed at sign-in), clears its second factors and\n * recovery codes, unlocks it, and signs out its sessions.\n */\nexport function registerDevtoolsCommands(): CLICommand[] {\n const enable = command({\n name: \"devtools:enable\",\n description:\n \"Turn the production devtools dashboard back on: clears the disable switch, the global lock and the failure counters\",\n preload: PRELOAD,\n action: async () => {\n const opened = await openStore();\n\n if (!opened.store) return exitWith(opened.code);\n\n await exitWith(await runEnable({ store: opened.store, now: Date.now, io }));\n },\n });\n\n const resetAdmin = command({\n name: \"devtools:reset-admin\",\n description:\n \"Create or reset a devtools admin account with a printed temporary password (no second factor, signed out everywhere)\",\n preload: PRELOAD,\n action: async ({ options }) => {\n const email = resolveAdminEmail(options.email, process.env);\n const opened = await openStore();\n\n if (!opened.store) return exitWith(opened.code);\n\n const [{ hashPassword }, { generateTemporaryPassword }] = await Promise.all([\n import(\"@warlock.js/core\"),\n import(\"../auth\"),\n ]);\n\n await exitWith(\n await runResetAdmin(\n {\n store: opened.store,\n now: Date.now,\n io,\n generatePassword: generateTemporaryPassword,\n hashPassword,\n },\n email,\n ),\n );\n },\n options: [\n {\n text: \"--email, -e\",\n description: \"The admin email (default: DEVTOOLS_ADMIN_EMAIL)\",\n type: \"string\",\n },\n ],\n });\n\n return [enable, resetAdmin];\n}\n"],"mappings":";;;;;AAKA,MAAM,UAA6B;CACjC,QAAQ;CACR,eAAe;CACf,WAAW;CACX,YAAY,CAAC,UAAU;AACzB;;AAGA,MAAM,KAAgB;CACpB,MAAM,SAAS,KAAK,QAAQ,OAAO,MAAM,GAAG,KAAK,GAAG;CACpD,MAAM,SAAS,KAAK,QAAQ,OAAO,MAAM,GAAG,KAAK,GAAG;AACtD;;AAGA,eAAe,SAAS,MAA6B;CACnD,IAAI,SAAS,GAAG;CAEhB,QAAQ,WAAW;CAEnB,MAAM,QAAQ,KAAK,CACjB,QAAQ,IACN,CAAC,QAAQ,QAAQ,QAAQ,MAAM,CAAC,CAAC,KAC9B,WAAW,IAAI,SAAe,YAAY,OAAO,MAAM,UAAU,QAAQ,CAAC,CAAC,CAC9E,CACF,GACA,IAAI,SAAe,YAAY,WAAW,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC,CACjE,CAAC;CAED,QAAQ,KAAK,IAAI;AACnB;;AAGA,eAAe,YAAY;CACzB,IAAI;EACF,MAAM,EAAE,uBAAuB,MAAM,OAAO;EAE5C,OAAO,EAAE,OAAO,MAAM,mBAAmB,EAAE;CAC7C,SAAS,OAAO;EACd,OAAO,EAAE,MAAM,iBAAiB,IAAI,KAAK,EAAE;CAC7C;AACF;;;;;;;;;;;;;AAcA,SAAgB,2BAAyC;CAqDvD,OAAO,CApDQ,QAAQ;EACrB,MAAM;EACN,aACE;EACF,SAAS;EACT,QAAQ,YAAY;GAClB,MAAM,SAAS,MAAM,UAAU;GAE/B,IAAI,CAAC,OAAO,OAAO,OAAO,SAAS,OAAO,IAAI;GAE9C,MAAM,SAAS,MAAM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