@hansenexus/hud 0.4.0 → 0.5.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 (157) hide show
  1. package/README.md +603 -9
  2. package/dist/a11y-B5DUaiCs.js +246 -0
  3. package/dist/a11y-panel-p_t4eD7p.js +207 -0
  4. package/dist/{capabilities-CjulXFQX.js → access-C7zlaqj6.js} +1 -90
  5. package/dist/{access-CNvJOwKM.d.ts → access-D_ewAEJG.d.ts} +11 -4
  6. package/dist/access-panel-CEfTr9ZI.js +123 -0
  7. package/dist/adapter-BYoxPYTI.d.ts +33 -0
  8. package/dist/adapter-hcwmJtNx.js +65 -0
  9. package/dist/auto/runtime.d.ts +65 -0
  10. package/dist/auto/runtime.js +50 -0
  11. package/dist/auto.d.ts +15 -0
  12. package/dist/auto.js +33 -0
  13. package/dist/capabilities-rDSKjXpq.js +110 -0
  14. package/dist/capture-CwrIwLqi.js +300 -0
  15. package/dist/capture-buffer-Bbbo6omF.d.ts +35 -0
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +275 -0
  18. package/dist/data-panel-DhxAmP91.js +817 -0
  19. package/dist/data-store-ChF1td_P.js +164 -0
  20. package/dist/define-hud-CHPedaQ5.d.ts +50 -0
  21. package/dist/design-D0kGgPoP.js +87 -0
  22. package/dist/detect-BxHZ0pxW.d.ts +25 -0
  23. package/dist/detect-CHZiSeZs.js +63 -0
  24. package/dist/dispatch-panel-B-xr_Giy.js +279 -0
  25. package/dist/{env-vEjyJfPW.d.ts → env-CApnbI0r.d.ts} +2 -0
  26. package/dist/{env-DfxpPfs9.js → env-CaiFPIhF.js} +3 -0
  27. package/dist/file-xdSaQ2uR.js +103 -0
  28. package/dist/flags-DVtaJ8pQ.d.ts +58 -0
  29. package/dist/flags.d.ts +2 -0
  30. package/dist/flags.js +82 -0
  31. package/dist/force-state-panel-_otVYh9i.js +97 -0
  32. package/dist/generate-C8lQl3Eh.js +53 -0
  33. package/dist/handler-BpVhxEmU.js +106 -0
  34. package/dist/{handler-WmE4Lu7l.d.ts → handler-DtYVCZY6.d.ts} +1 -1
  35. package/dist/index-BAV_1W8a.d.ts +43 -0
  36. package/dist/index-BJ26pse9.d.ts +70 -0
  37. package/dist/index-BnQ0dTZf.d.ts +19 -0
  38. package/dist/index-CwfX-W87.d.ts +72 -0
  39. package/dist/index-DcH9V3cU.d.ts +48 -0
  40. package/dist/index-DqOyNf1u.d.ts +65 -0
  41. package/dist/index-DstI_ike.d.ts +66 -0
  42. package/dist/index-Dxz4fn4j.d.ts +42 -0
  43. package/dist/index-Hhh7OXzU.d.ts +129 -0
  44. package/dist/index-ReFbhQ9p.d.ts +25 -0
  45. package/dist/index-RgXfMBuW.d.ts +48 -0
  46. package/dist/{index-BYsdS-7d.d.ts → index-gCZBO53s.d.ts} +21 -3
  47. package/dist/index.d.ts +5 -5
  48. package/dist/index.js +710 -69
  49. package/dist/inspect-C9Ft8fqn.js +142 -0
  50. package/dist/inspect-root-BkaupBMp.js +429 -0
  51. package/dist/meta-Bv0sEao3.js +6 -0
  52. package/dist/meta-C_G7MB5w.d.ts +49 -0
  53. package/dist/mocks-CA-wM2SB.d.ts +109 -0
  54. package/dist/mocks-ESiRqk9o.js +150 -0
  55. package/dist/msw-browser-wjaYgkB7.d.ts +31 -0
  56. package/dist/next/config.d.ts +52 -0
  57. package/dist/next/config.js +78 -0
  58. package/dist/next.d.ts +14 -4
  59. package/dist/next.js +5 -3
  60. package/dist/observe-CdDnDBRP.js +89 -0
  61. package/dist/observe-panel-Cgp1M8oT.js +347 -0
  62. package/dist/ops-panel-CEqDe_UT.js +234 -0
  63. package/dist/{payload-CLKDVZWl.d.ts → payload-MUQ9ciER.d.ts} +25 -1
  64. package/dist/plugins/a11y.d.ts +2 -0
  65. package/dist/plugins/a11y.js +2 -0
  66. package/dist/plugins/access/server.d.ts +5 -5
  67. package/dist/plugins/access/server.js +4 -3
  68. package/dist/plugins/access.d.ts +5 -5
  69. package/dist/plugins/access.js +16 -215
  70. package/dist/plugins/agent/server.d.ts +3 -38
  71. package/dist/plugins/agent/server.js +47 -21
  72. package/dist/plugins/agent.d.ts +4 -4
  73. package/dist/plugins/agent.js +6 -348
  74. package/dist/plugins/capture/server.d.ts +92 -0
  75. package/dist/plugins/capture/server.js +248 -0
  76. package/dist/plugins/capture.d.ts +24 -0
  77. package/dist/plugins/capture.js +70 -0
  78. package/dist/plugins/data/msw-browser.d.ts +2 -0
  79. package/dist/plugins/data/msw-browser.js +39 -0
  80. package/dist/plugins/data/msw-node.d.ts +36 -0
  81. package/dist/plugins/data/msw-node.js +68 -0
  82. package/dist/plugins/data/server.d.ts +257 -0
  83. package/dist/plugins/data/server.js +717 -0
  84. package/dist/plugins/data.d.ts +6 -0
  85. package/dist/plugins/data.js +51 -0
  86. package/dist/plugins/design/server.d.ts +54 -0
  87. package/dist/plugins/design/server.js +198 -0
  88. package/dist/plugins/design.d.ts +4 -124
  89. package/dist/plugins/design.js +4 -619
  90. package/dist/plugins/inspect/convex.d.ts +2 -0
  91. package/dist/plugins/inspect/convex.js +486 -0
  92. package/dist/plugins/inspect/react-query.d.ts +2 -0
  93. package/dist/plugins/inspect/react-query.js +225 -0
  94. package/dist/plugins/inspect/sockets.d.ts +51 -0
  95. package/dist/plugins/inspect/sockets.js +397 -0
  96. package/dist/plugins/inspect/swr.d.ts +2 -0
  97. package/dist/plugins/inspect/swr.js +218 -0
  98. package/dist/plugins/inspect.d.ts +4 -0
  99. package/dist/plugins/inspect.js +3 -0
  100. package/dist/plugins/observe.d.ts +4 -64
  101. package/dist/plugins/observe.js +1 -616
  102. package/dist/plugins/ops/server.d.ts +1 -1
  103. package/dist/plugins/ops/server.js +2 -1
  104. package/dist/plugins/ops.d.ts +2 -1
  105. package/dist/plugins/ops.js +15 -336
  106. package/dist/plugins/routes/server.d.ts +88 -0
  107. package/dist/plugins/routes/server.js +62 -0
  108. package/dist/plugins/routes.d.ts +3 -0
  109. package/dist/plugins/routes.js +216 -0
  110. package/dist/plugins/seo.d.ts +2 -0
  111. package/dist/plugins/seo.js +2 -0
  112. package/dist/plugins/vitals.d.ts +2 -25
  113. package/dist/plugins/vitals.js +3 -2
  114. package/dist/{plugins-CQ_0w1ot.d.ts → plugins-BZvDqGx5.d.ts} +33 -3
  115. package/dist/poll-CjKsWZi8.js +89 -0
  116. package/dist/requests-BwD6MKEq.js +282 -0
  117. package/dist/requests-CJrUf465.d.ts +50 -0
  118. package/dist/review.js +2 -2
  119. package/dist/same-origin-BGet22CC.js +21 -0
  120. package/dist/scan-DzJNXqOk.js +165 -0
  121. package/dist/seo-Dq9q_QkO.js +551 -0
  122. package/dist/seo-panel-CfiY-TnT.js +124 -0
  123. package/dist/server.d.ts +2 -2
  124. package/dist/server.js +2 -105
  125. package/dist/sessions-panel-COvhPAzv.js +98 -0
  126. package/dist/{shortcut-U6ftVY06.js → shortcut-s_mjGeU8.js} +1 -44
  127. package/dist/{types-QJUajwWq.js → state-CjjZPjPJ.js} +13 -8
  128. package/dist/store/convex.d.ts +33 -0
  129. package/dist/store/convex.js +52 -0
  130. package/dist/{vitals-panel-Dvc5dnR-.js → store-CQqIIKTc.js} +1 -29
  131. package/dist/store-Ync9eb1G.js +67 -0
  132. package/dist/store.d.ts +76 -0
  133. package/dist/store.js +188 -0
  134. package/dist/{styles--slk86ZQ.js → styles-BA8ueHoV.js} +13 -3
  135. package/dist/styles-DKU_P8MH.js +139 -0
  136. package/dist/styles-DPpDPmzi.js +68 -0
  137. package/dist/tokens-panel-CbMQfasZ.js +142 -0
  138. package/dist/types-B-ulf2Jp.js +8 -0
  139. package/dist/types-BIgGf-0C.d.ts +25 -0
  140. package/dist/types-BIkI-qN8.js +30 -0
  141. package/dist/{types-DADBRiGk.d.ts → types-Cxh4twqc.d.ts} +1 -1
  142. package/dist/types-DIdPfjtV.js +6 -0
  143. package/dist/types-DaJcsEjO.d.ts +44 -0
  144. package/dist/types-Dn68psVz.d.ts +118 -0
  145. package/dist/types-szkr2QOF.d.ts +39 -0
  146. package/dist/unlock-store-4V3vR4Eg.js +96 -0
  147. package/dist/variant-groups-TIfO3NIj.js +137 -0
  148. package/dist/variant-groups-aAIrcNK5.d.ts +36 -0
  149. package/dist/variants-panel-BDoSkwBJ.js +457 -0
  150. package/dist/variants-types-CcRf119M.d.ts +63 -0
  151. package/dist/variants.d.ts +43 -0
  152. package/dist/variants.js +83 -0
  153. package/dist/vitals-panel-BCmMUntW.js +30 -0
  154. package/dist/vite.d.ts +37 -0
  155. package/dist/vite.js +134 -0
  156. package/package.json +65 -5
  157. package/dist/define-hud-BBzsSl8b.d.ts +0 -36
@@ -0,0 +1,717 @@
1
+ import { i as definePlugin } from "../../plugins-DVy_vaYr.js";
2
+ import { FLAGS_COOKIE, FLAGS_STORAGE_KEY, FLAG_KEY, flagCookieString, isFlagScope, isFlagValue, readFlagOverrides, serializeFlagOverrides } from "../../flags.js";
3
+ import { a as matchEndpoint, c as readMockRegistry, d as validateScenarios, i as createMockResolver, l as scenarioInfo, n as MOCKS_DOCUMENT, o as nodeMockStatus, r as MOCK_SCENARIO_ID, s as parseEndpoint, t as MOCKS_COLLECTION, u as toMockActive } from "../../mocks-ESiRqk9o.js";
4
+ import { t as refuseCrossSite } from "../../same-origin-BGet22CC.js";
5
+ import { t as HudStoreError } from "../../types-BIkI-qN8.js";
6
+ import { t as file } from "../../file-xdSaQ2uR.js";
7
+ import { a as readCookie, c as timingSafeEqual } from "../../access-C7zlaqj6.js";
8
+ //#region src/plugins/data/auth/types.ts
9
+ async function listUsers(adapter) {
10
+ return typeof adapter.users === "function" ? adapter.users() : adapter.users;
11
+ }
12
+ /** The user with that id among the adapter's fixtures, else a bare `{ id, label: id }`. */
13
+ function knownUser(users, id) {
14
+ return users.find((user) => user.id === id) ?? {
15
+ id,
16
+ label: id
17
+ };
18
+ }
19
+ var HudAuthError = class extends Error {
20
+ status;
21
+ constructor(message, status = 400) {
22
+ super(message);
23
+ this.status = status;
24
+ this.name = "HudAuthError";
25
+ }
26
+ };
27
+ //#endregion
28
+ //#region src/plugins/data/flags-source.ts
29
+ /** A source that is just a list: the flags the app declares in code. */
30
+ function staticFlags(definitions) {
31
+ return { list: () => definitions };
32
+ }
33
+ //#endregion
34
+ //#region src/plugins/data/types.ts
35
+ /** The store collection overrides live in: `.hud/flags.json` with `file()`. */
36
+ const FLAGS_COLLECTION = "flags";
37
+ /** The one document in that collection: `{ overrides: { key: { value, scope } } }`. */
38
+ const FLAGS_DOCUMENT = "overrides";
39
+ //#endregion
40
+ //#region src/plugins/data/auth/cookies.ts
41
+ function cookieString(name, value, attributes = {}) {
42
+ const parts = [`${name}=${value}`, `Path=${attributes.path ?? "/"}`];
43
+ if (attributes.maxAge !== void 0) parts.push(`Max-Age=${attributes.maxAge}`);
44
+ if (attributes.httpOnly) parts.push("HttpOnly");
45
+ if (attributes.secure) parts.push("Secure");
46
+ parts.push(`SameSite=${attributes.sameSite ?? "Lax"}`);
47
+ return parts.join("; ");
48
+ }
49
+ /** A `Set-Cookie` that removes the cookie; attributes must match the one that set it. */
50
+ function clearCookieString(name, attributes = {}) {
51
+ return cookieString(name, "", {
52
+ ...attributes,
53
+ maxAge: 0
54
+ });
55
+ }
56
+ /** Whether the request reached a localhost origin, where `__Host-` and `Secure` cannot be used over http. */
57
+ function isLocalhost(request) {
58
+ try {
59
+ const { hostname } = new URL(request.url);
60
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+ /** The payload of a JWT, undecoded and unverified: enough to read `sub` for display. */
66
+ function decodeJwtPayload(token) {
67
+ if (!token) return null;
68
+ const parts = token.split(".");
69
+ const payload = parts[1];
70
+ if (parts.length !== 3 || !payload) return null;
71
+ try {
72
+ const text = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
73
+ const parsed = JSON.parse(text);
74
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+ const encoder = new TextEncoder();
80
+ function toBase64Url(bytes) {
81
+ let binary = "";
82
+ for (const byte of bytes) binary += String.fromCharCode(byte);
83
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
84
+ }
85
+ function encodeBase64Url(text) {
86
+ return toBase64Url(encoder.encode(text));
87
+ }
88
+ function decodeBase64Url(text) {
89
+ try {
90
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(text.length / 4) * 4, "=");
91
+ const binary = atob(padded);
92
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
93
+ return new TextDecoder("utf8", { fatal: true }).decode(bytes);
94
+ } catch {
95
+ return;
96
+ }
97
+ }
98
+ /** HMAC-SHA256 over `message` with a key derived from `secret`, base64url. */
99
+ async function hmac(secret, info, message) {
100
+ const material = await crypto.subtle.importKey("raw", encoder.encode(secret), "HKDF", false, ["deriveKey"]);
101
+ const key = await crypto.subtle.deriveKey({
102
+ name: "HKDF",
103
+ hash: "SHA-256",
104
+ salt: encoder.encode("@hansenexus/hud"),
105
+ info: encoder.encode(info)
106
+ }, material, {
107
+ name: "HMAC",
108
+ hash: "SHA-256",
109
+ length: 256
110
+ }, false, ["sign"]);
111
+ const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(message));
112
+ return toBase64Url(new Uint8Array(signature));
113
+ }
114
+ //#endregion
115
+ //#region src/plugins/data/auth/better-auth.ts
116
+ function isRecord$1(value) {
117
+ return typeof value === "object" && value !== null && !Array.isArray(value);
118
+ }
119
+ /** The signed-in user out of `getSession()`'s result: `{ user: { id, email } }`. */
120
+ function sessionUser(result) {
121
+ if (!isRecord$1(result) || !isRecord$1(result.user)) return null;
122
+ const { id, email } = result.user;
123
+ return {
124
+ ...typeof id === "string" ? { id } : {},
125
+ ...typeof email === "string" ? { email } : {}
126
+ };
127
+ }
128
+ /**
129
+ * Role switch for better-auth apps (proveno, mailnexus). Signing in runs the
130
+ * app's own `auth.api.signInEmail` for the fixture user's email and password
131
+ * and forwards the cookies better-auth sets; "signed in as" asks
132
+ * `auth.api.getSession` with the request's headers.
133
+ */
134
+ function betterAuth(options) {
135
+ const prefix = options.cookiePrefix ?? "better-auth";
136
+ const adapter = {
137
+ id: "better-auth",
138
+ label: "better-auth",
139
+ users: options.users,
140
+ async current(request) {
141
+ if (!options.auth.api.getSession) return null;
142
+ const session = sessionUser(await options.auth.api.getSession({ headers: request.headers }));
143
+ if (!session) return null;
144
+ const users = await listUsers(adapter);
145
+ const match = users.find((user) => user.id === session.id) ?? users.find((user) => session.email && user.email === session.email);
146
+ if (match) return match;
147
+ const id = session.id ?? session.email;
148
+ return id ? {
149
+ id,
150
+ label: session.email ?? id
151
+ } : null;
152
+ },
153
+ async signIn(user) {
154
+ if (!user.email || !user.password) throw new HudAuthError(`user "${user.id}" has no email and password to sign in with`);
155
+ const response = await options.auth.api.signInEmail({
156
+ body: {
157
+ email: user.email,
158
+ password: user.password
159
+ },
160
+ asResponse: true
161
+ });
162
+ if (!response.ok) throw new HudAuthError(`better-auth refused the sign-in (${response.status})`, 502);
163
+ return {
164
+ setCookie: response.headers.getSetCookie(),
165
+ storage: {}
166
+ };
167
+ },
168
+ async signOut(request) {
169
+ if (options.auth.api.signOut) {
170
+ const cookies = (await options.auth.api.signOut({
171
+ headers: request.headers,
172
+ asResponse: true
173
+ })).headers.getSetCookie();
174
+ if (cookies.length > 0) return {
175
+ setCookie: cookies,
176
+ storage: {}
177
+ };
178
+ }
179
+ const secure = !isLocalhost(request);
180
+ return {
181
+ setCookie: [clearCookieString(`${secure ? "__Secure-" : ""}${prefix}.session_token`, {
182
+ httpOnly: true,
183
+ secure
184
+ })],
185
+ storage: {}
186
+ };
187
+ }
188
+ };
189
+ return adapter;
190
+ }
191
+ //#endregion
192
+ //#region src/plugins/data/auth/convex-auth.ts
193
+ /** Convex Auth's cookie and `localStorage` key names (the Next.js and browser flavours). */
194
+ const CONVEX_AUTH_JWT_KEY = "__convexAuthJWT";
195
+ const CONVEX_AUTH_REFRESH_KEY = "__convexAuthRefreshToken";
196
+ function cookieNames(request) {
197
+ const secure = !isLocalhost(request);
198
+ const prefix = secure ? "__Host-" : "";
199
+ return {
200
+ jwt: `${prefix}${CONVEX_AUTH_JWT_KEY}`,
201
+ refresh: `${prefix}${CONVEX_AUTH_REFRESH_KEY}`,
202
+ secure
203
+ };
204
+ }
205
+ /** `${key}_${namespace}` with the namespace stripped to alphanumerics, as Convex Auth does. */
206
+ function convexAuthStorageKey(key, namespace) {
207
+ return `${key}_${namespace.replace(/[^a-zA-Z0-9]/g, "")}`;
208
+ }
209
+ /** The user id out of a Convex Auth JWT: `sub` is `<userId>|<sessionId>`. */
210
+ function convexAuthSubject(token) {
211
+ const sub = decodeJwtPayload(token)?.sub;
212
+ if (typeof sub !== "string" || !sub) return void 0;
213
+ const separator = sub.indexOf("|");
214
+ return separator > 0 ? sub.slice(0, separator) : sub;
215
+ }
216
+ /**
217
+ * Role switch for Convex Auth apps (fachwerk, lexilink-next). The app mints
218
+ * the session; the adapter puts the tokens where `@convex-dev/auth` reads
219
+ * them and reads `sub` back out of the JWT cookie for "signed in as".
220
+ */
221
+ function convexAuth(options) {
222
+ const writeCookies = options.cookies ?? true;
223
+ const namespace = options.storageNamespace;
224
+ const adapter = {
225
+ id: "convex-auth",
226
+ label: "Convex Auth",
227
+ users: options.users,
228
+ async current(request) {
229
+ const { jwt } = cookieNames(request);
230
+ const id = convexAuthSubject(readCookie(request.headers.get("cookie"), jwt));
231
+ return id ? knownUser(await listUsers(adapter), id) : null;
232
+ },
233
+ async signIn(user, request) {
234
+ const tokens = await options.mint(user);
235
+ if (!tokens?.token || !tokens.refreshToken) throw new HudAuthError("mint() returned no tokens", 502);
236
+ const { jwt, refresh, secure } = cookieNames(request);
237
+ const attributes = {
238
+ httpOnly: true,
239
+ secure,
240
+ sameSite: "Lax"
241
+ };
242
+ return {
243
+ setCookie: writeCookies ? [cookieString(jwt, tokens.token, attributes), cookieString(refresh, tokens.refreshToken, attributes)] : [],
244
+ storage: namespace ? {
245
+ [convexAuthStorageKey(CONVEX_AUTH_JWT_KEY, namespace)]: tokens.token,
246
+ [convexAuthStorageKey(CONVEX_AUTH_REFRESH_KEY, namespace)]: tokens.refreshToken
247
+ } : {}
248
+ };
249
+ },
250
+ async signOut(request) {
251
+ const { jwt, refresh, secure } = cookieNames(request);
252
+ const attributes = {
253
+ httpOnly: true,
254
+ secure,
255
+ sameSite: "Lax"
256
+ };
257
+ return {
258
+ setCookie: writeCookies ? [clearCookieString(jwt, attributes), clearCookieString(refresh, attributes)] : [],
259
+ storage: namespace ? {
260
+ [convexAuthStorageKey(CONVEX_AUTH_JWT_KEY, namespace)]: null,
261
+ [convexAuthStorageKey(CONVEX_AUTH_REFRESH_KEY, namespace)]: null
262
+ } : {}
263
+ };
264
+ }
265
+ };
266
+ return adapter;
267
+ }
268
+ //#endregion
269
+ //#region src/plugins/data/auth/cookie-impersonation.ts
270
+ /** Default cookie the impersonation is carried in. */
271
+ const IMPERSONATION_COOKIE = "hud-impersonate";
272
+ const DEFAULT_TTL_MS = 432e5;
273
+ function envSecret() {
274
+ const env = globalThis.process?.env;
275
+ return env?.HUD_ACCESS_SECRET || env?.HUD_ACCESS_PASSWORD || void 0;
276
+ }
277
+ function resolveSecret(secret) {
278
+ if (typeof secret === "function") return secret() || void 0;
279
+ return secret === void 0 ? envSecret() : secret || void 0;
280
+ }
281
+ const INFO = "hud-impersonate";
282
+ async function sign(secret, id, issuedAt) {
283
+ return hmac(secret, INFO, `${id}.${issuedAt}`);
284
+ }
285
+ /**
286
+ * The impersonation a request carries, or null. This is what the app's own
287
+ * auth layer calls to honour the switch: `readImpersonation(request)` and,
288
+ * when it names a user, treat the request as that user. With a secret the
289
+ * signature must verify; without one only an unsigned cookie is accepted.
290
+ */
291
+ async function readImpersonation(source, options = {}) {
292
+ const header = typeof source === "string" || !source ? source : source.headers.get("cookie");
293
+ const raw = readCookie(header, options.cookie ?? "hud-impersonate");
294
+ if (!raw) return null;
295
+ const [encodedId, issuedAtRaw, signature, ...rest] = raw.split(".");
296
+ if (!encodedId || !issuedAtRaw || rest.length > 0) return null;
297
+ const id = decodeBase64Url(encodedId);
298
+ const issuedAt = Number(issuedAtRaw);
299
+ if (!id || !Number.isSafeInteger(issuedAt) || issuedAt <= 0) return null;
300
+ const age = (options.now ?? Date.now()) - issuedAt;
301
+ if (age < 0 || age > (options.ttlMs ?? DEFAULT_TTL_MS)) return null;
302
+ const secret = resolveSecret(options.secret);
303
+ if (secret) {
304
+ if (!signature) return null;
305
+ const expected = await sign(secret, encodedId, issuedAtRaw);
306
+ return timingSafeEqual(signature, expected) ? {
307
+ id,
308
+ issuedAt,
309
+ signed: true
310
+ } : null;
311
+ }
312
+ return signature ? null : {
313
+ id,
314
+ issuedAt,
315
+ signed: false
316
+ };
317
+ }
318
+ /**
319
+ * Impersonation by cookie, for apps whose auth the HUD does not know (team-pulse,
320
+ * the Vite apps): picking a role sets `hud-impersonate=<user>` and the app's
321
+ * auth layer honours it through `readImpersonation()`. Self-contained: no
322
+ * session is minted anywhere, so it only works where the app chooses to read it.
323
+ */
324
+ function cookieImpersonation(options) {
325
+ const name = options.cookie ?? "hud-impersonate";
326
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
327
+ const readOptions = {
328
+ cookie: name,
329
+ ttlMs
330
+ };
331
+ if (options.secret !== void 0) readOptions.secret = options.secret;
332
+ const adapter = {
333
+ id: "cookie",
334
+ label: "Cookie impersonation",
335
+ users: options.users,
336
+ async current(request) {
337
+ const impersonation = await readImpersonation(request, readOptions);
338
+ if (!impersonation) return null;
339
+ return (options.getUser ? await options.getUser(impersonation.id) : knownUser(await listUsers(adapter), impersonation.id)) ?? {
340
+ id: impersonation.id,
341
+ label: impersonation.id
342
+ };
343
+ },
344
+ async signIn(user, request) {
345
+ if (options.getUser && !await options.getUser(user.id)) throw new HudAuthError(`unknown user "${user.id}"`, 404);
346
+ const encodedId = encodeBase64Url(user.id);
347
+ const issuedAt = String(Date.now());
348
+ const secret = resolveSecret(options.secret);
349
+ const value = secret ? `${encodedId}.${issuedAt}.${await sign(secret, encodedId, issuedAt)}` : `${encodedId}.${issuedAt}`;
350
+ return {
351
+ setCookie: [cookieString(name, value, {
352
+ maxAge: Math.floor(ttlMs / 1e3),
353
+ httpOnly: true,
354
+ secure: !isLocalhost(request),
355
+ sameSite: "Lax"
356
+ })],
357
+ storage: {}
358
+ };
359
+ },
360
+ async signOut(request) {
361
+ return {
362
+ setCookie: [clearCookieString(name, {
363
+ httpOnly: true,
364
+ secure: !isLocalhost(request)
365
+ })],
366
+ storage: {}
367
+ };
368
+ }
369
+ };
370
+ return adapter;
371
+ }
372
+ //#endregion
373
+ //#region src/plugins/data/server.ts
374
+ const NO_STORE = { "cache-control": "no-store" };
375
+ function isRecord(value) {
376
+ return typeof value === "object" && value !== null && !Array.isArray(value);
377
+ }
378
+ function failed(error, what) {
379
+ if (error instanceof HudStoreError || error instanceof HudAuthError) return Response.json({
380
+ ok: false,
381
+ error: error.message
382
+ }, { status: error.status });
383
+ console.error(`hud data: ${what} failed`, error);
384
+ return Response.json({
385
+ ok: false,
386
+ error: `${what} failed`
387
+ }, { status: 500 });
388
+ }
389
+ function json(body, setCookie = []) {
390
+ const res = Response.json(body, { headers: NO_STORE });
391
+ for (const cookie of setCookie) res.headers.append("set-cookie", cookie);
392
+ return res;
393
+ }
394
+ /** What the browser may know about a user: everything but the password. */
395
+ function publicUser({ password: _password, ...user }) {
396
+ return user;
397
+ }
398
+ /** The overrides out of the store's one document, dropping anything malformed. */
399
+ function toFlagOverrides(value) {
400
+ if (!isRecord(value) || !isRecord(value.overrides)) return [];
401
+ const overrides = [];
402
+ for (const [key, entry] of Object.entries(value.overrides)) {
403
+ if (!FLAG_KEY.test(key) || !isRecord(entry) || !isFlagValue(entry.value)) continue;
404
+ overrides.push({
405
+ key,
406
+ value: entry.value,
407
+ scope: isFlagScope(entry.scope) ? entry.scope : "cookie"
408
+ });
409
+ }
410
+ return overrides;
411
+ }
412
+ function toDocument(overrides) {
413
+ const document = {};
414
+ for (const { key, value, scope } of overrides) document[key] = {
415
+ value,
416
+ scope
417
+ };
418
+ return { overrides: document };
419
+ }
420
+ /** What the browser may know about a seed: everything but `run`. */
421
+ function seedInfo({ run: _run, ...seed }) {
422
+ return seed;
423
+ }
424
+ /** The seed's result as JSON; what does not serialise is described instead. */
425
+ function toSeedResult(value) {
426
+ if (value === void 0) return null;
427
+ try {
428
+ return JSON.parse(JSON.stringify(value)) ?? null;
429
+ } catch {
430
+ return String(value);
431
+ }
432
+ }
433
+ function validateSeeds(seeds) {
434
+ const byId = /* @__PURE__ */ new Map();
435
+ for (const seed of seeds) {
436
+ if (!MOCK_SCENARIO_ID.test(seed.id)) throw new Error(`hud data: seed id "${seed.id}" must match ${MOCK_SCENARIO_ID}`);
437
+ if (byId.has(seed.id)) throw new Error(`hud data: duplicate seed id "${seed.id}"`);
438
+ byId.set(seed.id, seed);
439
+ }
440
+ return byId;
441
+ }
442
+ /**
443
+ * Server half of `data()`: the role switch through the auth seam and
444
+ * feature-flag overrides through the storage seam. Carries `data.write`,
445
+ * which `access` hard-denies on production and grants on staging only when
446
+ * the app's matrix says so.
447
+ *
448
+ * ```ts
449
+ * dataServer({
450
+ * auth: cookieImpersonation({ users }),
451
+ * flags: [{ key: "new-checkout", value: false }],
452
+ * store: file(),
453
+ * })
454
+ * ```
455
+ */
456
+ function dataServer({ auth, flags, seeds, mocks, store = file() } = {}) {
457
+ const source = flags === void 0 ? void 0 : Array.isArray(flags) ? staticFlags(flags) : flags;
458
+ const seedTable = seeds === void 0 ? void 0 : validateSeeds(seeds);
459
+ const scenarios = mocks === void 0 ? void 0 : validateScenarios(mocks);
460
+ async function readActive() {
461
+ if (!scenarios) return {};
462
+ return toMockActive(await store.get(MOCKS_COLLECTION, MOCKS_DOCUMENT), scenarios);
463
+ }
464
+ async function writeActive(active) {
465
+ await store.set(MOCKS_COLLECTION, MOCKS_DOCUMENT, { active });
466
+ readMockRegistry()?.apply(active);
467
+ return json({
468
+ ok: true,
469
+ active
470
+ });
471
+ }
472
+ async function readOverrides() {
473
+ return toFlagOverrides(await store.get(FLAGS_COLLECTION, FLAGS_DOCUMENT));
474
+ }
475
+ async function writeOverrides(overrides) {
476
+ await store.set(FLAGS_COLLECTION, FLAGS_DOCUMENT, toDocument(overrides));
477
+ }
478
+ async function flagsResponse(overrides) {
479
+ return json({
480
+ ok: true,
481
+ overrides
482
+ }, [flagCookieString(overrides)]);
483
+ }
484
+ async function switched(current, result) {
485
+ return json({
486
+ ok: true,
487
+ current: current ? publicUser(current) : null,
488
+ storage: result.storage
489
+ }, result.setCookie);
490
+ }
491
+ return definePlugin({
492
+ id: "data",
493
+ capability: "data.write",
494
+ routes: {
495
+ "/": { GET: async (request) => {
496
+ try {
497
+ const overrides = source ? await readOverrides() : [];
498
+ return json({
499
+ ok: true,
500
+ auth: auth ? {
501
+ adapter: auth.id,
502
+ label: auth.label,
503
+ current: await auth.current(request).then((user) => user ? publicUser(user) : null),
504
+ users: (await listUsers(auth)).map(publicUser)
505
+ } : null,
506
+ flags: source ? {
507
+ definitions: [...await source.list(request)],
508
+ overrides
509
+ } : null,
510
+ seeds: seedTable ? { definitions: [...seedTable.values()].map(seedInfo) } : null,
511
+ mocks: scenarios ? {
512
+ scenarios: [...scenarios.values()].map((entry) => scenarioInfo(entry.scenario)),
513
+ active: await readActive(),
514
+ node: nodeMockStatus()
515
+ } : null
516
+ }, source ? [flagCookieString(overrides)] : []);
517
+ } catch (error) {
518
+ return failed(error, "state");
519
+ }
520
+ } },
521
+ "/role": {
522
+ POST: async (request) => {
523
+ const refusal = refuseCrossSite(request);
524
+ if (refusal) return refusal;
525
+ if (!auth) return Response.json({
526
+ ok: false,
527
+ error: "no auth adapter"
528
+ }, { status: 404 });
529
+ const body = await request.json().catch(() => null);
530
+ if (!isRecord(body) || typeof body.id !== "string" || !body.id) return Response.json({
531
+ ok: false,
532
+ error: "invalid role switch"
533
+ }, { status: 400 });
534
+ try {
535
+ const user = (await listUsers(auth)).find((candidate) => candidate.id === body.id);
536
+ if (!user) return Response.json({
537
+ ok: false,
538
+ error: "unknown user"
539
+ }, { status: 404 });
540
+ return switched(user, await auth.signIn(user, request));
541
+ } catch (error) {
542
+ return failed(error, "role switch");
543
+ }
544
+ },
545
+ DELETE: async (request) => {
546
+ const refusal = refuseCrossSite(request);
547
+ if (refusal) return refusal;
548
+ if (!auth) return Response.json({
549
+ ok: false,
550
+ error: "no auth adapter"
551
+ }, { status: 404 });
552
+ try {
553
+ return switched(null, await auth.signOut(request));
554
+ } catch (error) {
555
+ return failed(error, "sign out");
556
+ }
557
+ }
558
+ },
559
+ "/flags": { DELETE: async (request) => {
560
+ const refusal = refuseCrossSite(request);
561
+ if (refusal) return refusal;
562
+ if (!source) return Response.json({
563
+ ok: false,
564
+ error: "no flag source"
565
+ }, { status: 404 });
566
+ try {
567
+ await writeOverrides([]);
568
+ return flagsResponse([]);
569
+ } catch (error) {
570
+ return failed(error, "reset flags");
571
+ }
572
+ } },
573
+ "/seeds/:id": { POST: async (request, { params }) => {
574
+ const refusal = refuseCrossSite(request);
575
+ if (refusal) return refusal;
576
+ if (!seedTable) return Response.json({
577
+ ok: false,
578
+ error: "no seeds"
579
+ }, { status: 404 });
580
+ const seed = seedTable.get(params.id ?? "");
581
+ if (!seed) return Response.json({
582
+ ok: false,
583
+ error: "unknown seed"
584
+ }, { status: 404 });
585
+ const started = Date.now();
586
+ try {
587
+ const result = toSeedResult(await seed.run(request));
588
+ return json({
589
+ ok: true,
590
+ id: seed.id,
591
+ durationMs: Date.now() - started,
592
+ result
593
+ });
594
+ } catch (error) {
595
+ const message = error instanceof Error ? error.message : String(error);
596
+ return Response.json({
597
+ ok: false,
598
+ error: message,
599
+ durationMs: Date.now() - started
600
+ }, {
601
+ status: 500,
602
+ headers: NO_STORE
603
+ });
604
+ }
605
+ } },
606
+ "/mocks": { DELETE: async (request) => {
607
+ const refusal = refuseCrossSite(request);
608
+ if (refusal) return refusal;
609
+ if (!scenarios) return Response.json({
610
+ ok: false,
611
+ error: "no mocks"
612
+ }, { status: 404 });
613
+ try {
614
+ return await writeActive({});
615
+ } catch (error) {
616
+ return failed(error, "reset mocks");
617
+ }
618
+ } },
619
+ "/mocks/:id": {
620
+ PUT: async (request, { params }) => {
621
+ const refusal = refuseCrossSite(request);
622
+ if (refusal) return refusal;
623
+ if (!scenarios) return Response.json({
624
+ ok: false,
625
+ error: "no mocks"
626
+ }, { status: 404 });
627
+ const entry = scenarios.get(params.id ?? "");
628
+ if (!entry) return Response.json({
629
+ ok: false,
630
+ error: "unknown scenario"
631
+ }, { status: 404 });
632
+ try {
633
+ return await writeActive({
634
+ ...await readActive(),
635
+ [entry.scenario.endpoint]: entry.scenario.id
636
+ });
637
+ } catch (error) {
638
+ return failed(error, "activate scenario");
639
+ }
640
+ },
641
+ DELETE: async (request, { params }) => {
642
+ const refusal = refuseCrossSite(request);
643
+ if (refusal) return refusal;
644
+ if (!scenarios) return Response.json({
645
+ ok: false,
646
+ error: "no mocks"
647
+ }, { status: 404 });
648
+ const entry = scenarios.get(params.id ?? "");
649
+ if (!entry) return Response.json({
650
+ ok: false,
651
+ error: "unknown scenario"
652
+ }, { status: 404 });
653
+ try {
654
+ const active = await readActive();
655
+ if (active[entry.scenario.endpoint] !== entry.scenario.id) return await writeActive(active);
656
+ const { [entry.scenario.endpoint]: _off, ...rest } = active;
657
+ return await writeActive(rest);
658
+ } catch (error) {
659
+ return failed(error, "deactivate scenario");
660
+ }
661
+ }
662
+ },
663
+ "/flags/:key": {
664
+ PUT: async (request, { params }) => {
665
+ const refusal = refuseCrossSite(request);
666
+ if (refusal) return refusal;
667
+ if (!source) return Response.json({
668
+ ok: false,
669
+ error: "no flag source"
670
+ }, { status: 404 });
671
+ const key = params.key ?? "";
672
+ const body = await request.json().catch(() => null);
673
+ if (!FLAG_KEY.test(key) || !isRecord(body) || !isFlagValue(body.value) || body.scope !== void 0 && !isFlagScope(body.scope)) return Response.json({
674
+ ok: false,
675
+ error: "invalid flag override"
676
+ }, { status: 400 });
677
+ try {
678
+ const definition = (await source.list(request)).find((flag) => flag.key === key);
679
+ if (!definition) return Response.json({
680
+ ok: false,
681
+ error: "unknown flag"
682
+ }, { status: 404 });
683
+ const scope = isFlagScope(body.scope) ? body.scope : definition.scope ?? "cookie";
684
+ const overrides = (await readOverrides()).filter((override) => override.key !== key);
685
+ overrides.push({
686
+ key,
687
+ value: body.value,
688
+ scope
689
+ });
690
+ await writeOverrides(overrides);
691
+ return flagsResponse(overrides);
692
+ } catch (error) {
693
+ return failed(error, "set flag");
694
+ }
695
+ },
696
+ DELETE: async (request, { params }) => {
697
+ const refusal = refuseCrossSite(request);
698
+ if (refusal) return refusal;
699
+ if (!source) return Response.json({
700
+ ok: false,
701
+ error: "no flag source"
702
+ }, { status: 404 });
703
+ const key = params.key ?? "";
704
+ try {
705
+ const overrides = (await readOverrides()).filter((override) => override.key !== key);
706
+ await writeOverrides(overrides);
707
+ return flagsResponse(overrides);
708
+ } catch (error) {
709
+ return failed(error, "reset flag");
710
+ }
711
+ }
712
+ }
713
+ }
714
+ });
715
+ }
716
+ //#endregion
717
+ export { CONVEX_AUTH_JWT_KEY, CONVEX_AUTH_REFRESH_KEY, FLAGS_COLLECTION, FLAGS_COOKIE, FLAGS_DOCUMENT, FLAGS_STORAGE_KEY, FLAG_KEY, HudAuthError, IMPERSONATION_COOKIE, MOCKS_COLLECTION, MOCKS_DOCUMENT, MOCK_SCENARIO_ID, betterAuth, convexAuth, convexAuthStorageKey, convexAuthSubject, cookieImpersonation, createMockResolver, dataServer, flagCookieString, matchEndpoint, parseEndpoint, publicUser, readFlagOverrides, readImpersonation, readMockRegistry, seedInfo, serializeFlagOverrides, staticFlags, toFlagOverrides, toMockActive, toSeedResult, validateScenarios };