@connextar/house 0.23.1 → 0.24.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 (186) hide show
  1. package/README.md +55 -13
  2. package/dist/analytics/browser.d.ts +1 -0
  3. package/dist/analytics/browser.d.ts.map +1 -1
  4. package/dist/analytics/browser.js +22 -5
  5. package/dist/analytics/browser.js.map +1 -1
  6. package/dist/analytics/config.d.ts +5 -0
  7. package/dist/analytics/config.d.ts.map +1 -1
  8. package/dist/analytics/config.js +4 -1
  9. package/dist/analytics/config.js.map +1 -1
  10. package/dist/analytics/posthog-extensions.d.ts +19 -0
  11. package/dist/analytics/posthog-extensions.d.ts.map +1 -0
  12. package/dist/analytics/posthog-extensions.js +19 -0
  13. package/dist/analytics/posthog-extensions.js.map +1 -0
  14. package/dist/analytics/react.d.ts.map +1 -1
  15. package/dist/analytics/react.js +4 -2
  16. package/dist/analytics/react.js.map +1 -1
  17. package/dist/analytics/redact.d.ts.map +1 -1
  18. package/dist/analytics/redact.js +6 -1
  19. package/dist/analytics/redact.js.map +1 -1
  20. package/dist/house.css +19 -0
  21. package/package.json +17 -3
  22. package/src/account/data-contract.ts +112 -0
  23. package/src/account/index.ts +11 -0
  24. package/src/admin/access.ts +267 -0
  25. package/src/admin/audit.ts +238 -0
  26. package/src/admin/bootstrap.ts +220 -0
  27. package/src/admin/client-index.ts +19 -0
  28. package/src/admin/client.tsx +187 -0
  29. package/src/admin/index.ts +91 -0
  30. package/src/admin/proof.ts +155 -0
  31. package/src/admin/second-factor-index.ts +16 -0
  32. package/src/admin/second-factor.ts +403 -0
  33. package/src/admin/testing-index.ts +13 -0
  34. package/src/admin/testing.ts +299 -0
  35. package/src/admin/view-as.ts +511 -0
  36. package/src/ai/config-index.ts +40 -0
  37. package/src/ai/config.ts +176 -0
  38. package/src/ai/images.ts +18 -0
  39. package/src/ai/index.ts +21 -0
  40. package/src/ai/pricing.ts +107 -0
  41. package/src/ai/provider.ts +403 -0
  42. package/src/analytics/browser.ts +400 -0
  43. package/src/analytics/client-index.ts +12 -0
  44. package/src/analytics/config.ts +89 -0
  45. package/src/analytics/index.ts +17 -0
  46. package/src/analytics/ingest.ts +81 -0
  47. package/src/analytics/posthog-extensions.ts +19 -0
  48. package/src/analytics/react-index.ts +16 -0
  49. package/src/analytics/react.tsx +241 -0
  50. package/src/analytics/redact.ts +146 -0
  51. package/src/analytics/server-index.ts +17 -0
  52. package/src/analytics/server.ts +277 -0
  53. package/src/auth/index.ts +30 -0
  54. package/src/auth/second-factor-index.ts +16 -0
  55. package/src/auth/second-factor-next.ts +136 -0
  56. package/src/auth/second-factor-routes.ts +40 -0
  57. package/src/auth/second-factor.ts +226 -0
  58. package/src/auth/step-up-client-index.ts +13 -0
  59. package/src/auth/step-up-client.ts +23 -0
  60. package/src/auth/step-up-index.ts +19 -0
  61. package/src/auth/step-up-routes.ts +99 -0
  62. package/src/auth/step-up.ts +432 -0
  63. package/src/auth/two-factor-policy.ts +112 -0
  64. package/src/changelog/changelog.tsx +367 -0
  65. package/src/changelog/index.ts +12 -0
  66. package/src/editor/block-handle.tsx +312 -0
  67. package/src/editor/blocks.ts +169 -0
  68. package/src/editor/bubble-toolbar.tsx +208 -0
  69. package/src/editor/collapsible.ts +159 -0
  70. package/src/editor/content-index.ts +1 -0
  71. package/src/editor/content.tsx +343 -0
  72. package/src/editor/editor.tsx +333 -0
  73. package/src/editor/emoji-index.ts +1 -0
  74. package/src/editor/emoji-picker.tsx +114 -0
  75. package/src/editor/emoji.ts +436 -0
  76. package/src/editor/index.ts +6 -0
  77. package/src/editor/sections.ts +83 -0
  78. package/src/editor/suggestion-popup.tsx +136 -0
  79. package/src/editor/suggestions.ts +309 -0
  80. package/src/editor/ui.tsx +171 -0
  81. package/src/errors/error-shell.tsx +72 -0
  82. package/src/errors/global-error-shell.tsx +116 -0
  83. package/src/errors/index.ts +2 -0
  84. package/src/grid/columns.ts +48 -0
  85. package/src/grid/compare.ts +35 -0
  86. package/src/grid/hidden-columns.ts +95 -0
  87. package/src/grid/index.ts +27 -0
  88. package/src/grid/use-grid.ts +282 -0
  89. package/src/grid/views.ts +70 -0
  90. package/src/guides/guide-article.tsx +92 -0
  91. package/src/guides/guide-figure-zoom.tsx +533 -0
  92. package/src/guides/guide-figure.tsx +68 -0
  93. package/src/guides/guide-toc.tsx +133 -0
  94. package/src/guides/guides-landing.tsx +57 -0
  95. package/src/guides/guides-search.tsx +160 -0
  96. package/src/guides/guides-shell.tsx +60 -0
  97. package/src/guides/guides-sidebar.tsx +93 -0
  98. package/src/guides/index.ts +28 -0
  99. package/src/guides/library.ts +165 -0
  100. package/src/health/health.ts +115 -0
  101. package/src/health/index.ts +11 -0
  102. package/src/internal/cx.ts +4 -0
  103. package/src/internal/next-link.ts +23 -0
  104. package/src/jobs/counts.ts +151 -0
  105. package/src/jobs/cron-auth.ts +60 -0
  106. package/src/jobs/health.ts +315 -0
  107. package/src/jobs/idle.ts +86 -0
  108. package/src/jobs/index.ts +120 -0
  109. package/src/jobs/job-health-list.tsx +316 -0
  110. package/src/jobs/next-index.ts +4 -0
  111. package/src/jobs/next.ts +65 -0
  112. package/src/jobs/prisma-index.ts +12 -0
  113. package/src/jobs/prisma.ts +170 -0
  114. package/src/jobs/prune.ts +79 -0
  115. package/src/jobs/react-index.ts +35 -0
  116. package/src/jobs/registry.ts +189 -0
  117. package/src/jobs/scheduler.ts +437 -0
  118. package/src/jobs/store.ts +212 -0
  119. package/src/jobs/windows.ts +157 -0
  120. package/src/maintenance/core.ts +270 -0
  121. package/src/maintenance/gate.ts +171 -0
  122. package/src/maintenance/index.ts +40 -0
  123. package/src/maintenance/page.ts +76 -0
  124. package/src/maintenance/proxy.ts +88 -0
  125. package/src/maintenance/react-index.ts +7 -0
  126. package/src/maintenance/react.tsx +190 -0
  127. package/src/maintenance/route.ts +82 -0
  128. package/src/maintenance/unavailable.ts +61 -0
  129. package/src/markdown/figure.tsx +132 -0
  130. package/src/markdown/figures.ts +237 -0
  131. package/src/markdown/guide.tsx +536 -0
  132. package/src/markdown/index.ts +53 -0
  133. package/src/markdown/table-view.tsx +74 -0
  134. package/src/markdown/table.ts +90 -0
  135. package/src/password/common.ts +58 -0
  136. package/src/password/estimate-index.ts +18 -0
  137. package/src/password/estimate.ts +715 -0
  138. package/src/password/index.ts +40 -0
  139. package/src/password/password-input.tsx +116 -0
  140. package/src/password/password-strength.tsx +157 -0
  141. package/src/password/reveal.ts +151 -0
  142. package/src/rate-limit/better-auth.ts +94 -0
  143. package/src/rate-limit/index.ts +32 -0
  144. package/src/rate-limit/keys.ts +110 -0
  145. package/src/rate-limit/limiter.ts +276 -0
  146. package/src/rate-limit/prisma-index.ts +12 -0
  147. package/src/rate-limit/prisma.ts +157 -0
  148. package/src/rate-limit/store.ts +47 -0
  149. package/src/release/changelog.ts +364 -0
  150. package/src/release/index.ts +32 -0
  151. package/src/release/version.ts +64 -0
  152. package/src/setup-guide/bits.tsx +420 -0
  153. package/src/setup-guide/card.tsx +358 -0
  154. package/src/setup-guide/class-names.ts +144 -0
  155. package/src/setup-guide/context.tsx +239 -0
  156. package/src/setup-guide/guide.ts +271 -0
  157. package/src/setup-guide/index.ts +76 -0
  158. package/src/setup-guide/launcher.tsx +207 -0
  159. package/src/setup-guide/strip.tsx +127 -0
  160. package/src/styles/house.css +403 -0
  161. package/src/trail/index.ts +12 -0
  162. package/src/trail/rules.ts +84 -0
  163. package/src/trail/trail.tsx +367 -0
  164. package/src/ux/errors.ts +32 -0
  165. package/src/ux/feedback.tsx +41 -0
  166. package/src/ux/index.ts +44 -0
  167. package/src/ux/navigation-index.ts +16 -0
  168. package/src/ux/navigation-progress.tsx +270 -0
  169. package/src/ux/optimistic.ts +415 -0
  170. package/src/ux/use-action.ts +155 -0
  171. package/src/ux/use-optimistic-list.ts +227 -0
  172. package/src/ux/use-optimistic-value.ts +136 -0
  173. package/src/web-search/index.ts +13 -0
  174. package/src/web-search/providers.ts +177 -0
  175. package/src/web-search/types.ts +98 -0
  176. package/src/whats-new/body.tsx +190 -0
  177. package/src/whats-new/index.ts +43 -0
  178. package/src/whats-new/seen.ts +40 -0
  179. package/src/whats-new/select.ts +230 -0
  180. package/src/whats-new/use-whats-new.ts +109 -0
  181. package/src/wizard/index.ts +61 -0
  182. package/src/wizard/invalid.ts +152 -0
  183. package/src/wizard/react-hook-form-index.ts +11 -0
  184. package/src/wizard/rhf-adapter.ts +67 -0
  185. package/src/wizard/rules.ts +137 -0
  186. package/src/wizard/wizard.tsx +442 -0
@@ -0,0 +1,241 @@
1
+ "use client";
2
+
3
+ import { usePathname } from "next/navigation.js";
4
+ import * as React from "react";
5
+
6
+ import { cx } from "../internal/cx.js";
7
+ import type { AnalyticsConsent, BrowserAnalytics, PostHogLike } from "./browser.js";
8
+ import { NOT_MEASURED_ATTRIBUTE, RECORDABLE_ATTRIBUTE } from "./config.js";
9
+
10
+ /**
11
+ * The components: the cookie card and everything it drives, the pre-paint script, the "Cookie settings" button, the
12
+ * markers a page renders to say whether it may be measured, and a hook for the settings page's own consent card.
13
+ *
14
+ * Each takes the app's `BrowserAnalytics` — built once in a plain module and imported by the app's own client
15
+ * wrapper, since a definition holding functions cannot cross from a server component to a client one.
16
+ */
17
+
18
+ const subscribeToNothing = () => () => {};
19
+
20
+ /** The page this document was first loaded on was tagged — read once, before any client navigation. */
21
+ const documentBeganTagged = (browser: BrowserAnalytics) =>
22
+ typeof window !== "undefined" && browser.analytics.isTaggedPath(window.location.pathname);
23
+
24
+ export interface CookieCardProps {
25
+ answer(consent: AnalyticsConsent): void;
26
+ reopened: boolean;
27
+ }
28
+
29
+ export const SITE_ANALYTICS_LABELS = {
30
+ title: "Cookies",
31
+ body: "We'd like to measure how people use these pages, to make them better. Nothing is measured inside your account, and nothing is sold.",
32
+ accept: "Accept",
33
+ reject: "Reject",
34
+ };
35
+
36
+ export const SITE_ANALYTICS_CLASS_NAMES = {
37
+ root: "fixed inset-x-4 bottom-4 z-50 mx-auto max-w-xl rounded-lg border border-border bg-card p-4 text-sm text-foreground shadow-lg",
38
+ title: "font-semibold",
39
+ body: "mt-1 text-muted-foreground",
40
+ actions: "mt-3 flex flex-wrap justify-end gap-2",
41
+ reject: "rounded-md border border-border px-3 py-1.5 font-medium hover:bg-muted",
42
+ accept: "rounded-md bg-primary px-3 py-1.5 font-medium text-primary-foreground hover:opacity-90",
43
+ };
44
+
45
+ export interface SiteAnalyticsProps {
46
+ browser: BrowserAnalytics;
47
+ /** The GTM container. Empty: no GTM. */
48
+ containerId?: string;
49
+ /** The PostHog project key; whether PostHog is on. Empty: off. */
50
+ posthogKey?: string;
51
+ /** posthog-js's instance, which `instrumentation-client.ts` initialised. */
52
+ posthog?: PostHogLike | null;
53
+ /**
54
+ * The event a click on a same-origin link to a private page is: `begin_sign_up` for `/sign-up`. Null for none.
55
+ * The click leaves the public pages with a full load, so GTM is not carried into the app.
56
+ */
57
+ leavingEvent?: (pathname: string) => string | null;
58
+ /** The app's own card. Default: the house's, on the theme tokens. */
59
+ renderCard?: (props: CookieCardProps) => React.ReactNode;
60
+ labels?: Partial<typeof SITE_ANALYTICS_LABELS>;
61
+ classNames?: Partial<typeof SITE_ANALYTICS_CLASS_NAMES>;
62
+ }
63
+
64
+ /**
65
+ * In the root layout, once. It asks — on a page where measuring could happen, and only there — and loads GTM after a
66
+ * yes on a tagged page, starts and stops replay as the page changes, and makes leaving the public pages a full load.
67
+ */
68
+ export function SiteAnalytics({
69
+ browser,
70
+ containerId = "",
71
+ posthogKey = "",
72
+ posthog,
73
+ leavingEvent,
74
+ renderCard,
75
+ labels,
76
+ classNames,
77
+ }: SiteAnalyticsProps) {
78
+ const { analytics } = browser;
79
+ const pathname = usePathname() ?? "/";
80
+ const tagged = analytics.isTaggedPath(pathname);
81
+ const recordable = React.useSyncExternalStore(browser.subscribeToRecordable, browser.pageIsRecordable, () => false);
82
+ const askHere = tagged || (Boolean(posthogKey) && analytics.recordablePath(pathname) && recordable);
83
+ const consent = React.useSyncExternalStore(browser.subscribeToConsent, browser.readConsent, () => null);
84
+ const optedOut = React.useSyncExternalStore(subscribeToNothing, browser.browserOptsOut, () => false);
85
+ const [reopened, setReopened] = React.useState(false);
86
+ const asking = reopened || (consent === null && !optedOut);
87
+ const beganTagged = React.useRef(documentBeganTagged(browser));
88
+
89
+ React.useEffect(() => {
90
+ const ask = () => setReopened(true);
91
+ window.addEventListener(analytics.cookieSettingsEvent, ask);
92
+ return () => window.removeEventListener(analytics.cookieSettingsEvent, ask);
93
+ }, [analytics.cookieSettingsEvent]);
94
+
95
+ React.useEffect(() => {
96
+ if (!containerId || consent !== "granted" || !tagged || optedOut) return;
97
+ // A document that began on a private page reloads rather than loading GTM into it.
98
+ if (beganTagged.current) browser.loadGtm(containerId);
99
+ else window.location.reload();
100
+ }, [browser, containerId, consent, tagged, optedOut]);
101
+
102
+ React.useEffect(() => {
103
+ browser.syncRecording(posthog);
104
+ }, [browser, posthog, consent, pathname, recordable]);
105
+
106
+ React.useEffect(() => {
107
+ // Arriving on a private page — untagged, or marked private — with GTM loaded: drop it with a full load. The new
108
+ // document does not load GTM, so this happens once.
109
+ if ((!analytics.isTaggedPath(pathname) || browser.pageIsPrivate()) && browser.isGtmLoaded()) {
110
+ window.location.reload();
111
+ }
112
+ }, [analytics, browser, pathname]);
113
+
114
+ React.useEffect(() => {
115
+ function onClick(event: MouseEvent) {
116
+ if (event.defaultPrevented || event.button !== 0) return;
117
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
118
+ if (!browser.isGtmLoaded() || !(event.target instanceof Element)) return;
119
+ const anchor = event.target.closest("a[href]");
120
+ if (!(anchor instanceof HTMLAnchorElement) || anchor.hasAttribute("download")) return;
121
+ if (anchor.target && anchor.target !== "_self") return;
122
+ const url = new URL(anchor.href, window.location.href);
123
+ if (url.origin !== window.location.origin || analytics.isTaggedPath(url.pathname)) return;
124
+ const name = leavingEvent?.(url.pathname) ?? null;
125
+ if (name) {
126
+ browser.track(name, {
127
+ cta_text: anchor.textContent?.trim() || undefined,
128
+ cta_location: browser.ctaLocation(anchor),
129
+ });
130
+ }
131
+ event.preventDefault();
132
+ window.location.assign(url.href);
133
+ }
134
+ document.addEventListener("click", onClick, true);
135
+ return () => document.removeEventListener("click", onClick, true);
136
+ }, [analytics, browser, leavingEvent]);
137
+
138
+ if ((!containerId && !posthogKey) || !asking || !askHere) return null;
139
+
140
+ function answer(choice: AnalyticsConsent) {
141
+ setReopened(false);
142
+ const wasLoaded = browser.isGtmLoaded();
143
+ browser.writeConsent(choice);
144
+ if (choice === "denied" && wasLoaded) {
145
+ browser.withdrawConsent();
146
+ window.location.reload();
147
+ }
148
+ }
149
+
150
+ if (renderCard) return <>{renderCard({ answer, reopened })}</>;
151
+ const words = { ...SITE_ANALYTICS_LABELS, ...labels };
152
+ const c = { ...SITE_ANALYTICS_CLASS_NAMES, ...classNames };
153
+ return (
154
+ <section aria-label={words.title} data-cookie-card="" data-reopened={reopened ? "" : undefined} className={c.root}>
155
+ <p className={c.title}>{words.title}</p>
156
+ <p className={c.body}>{words.body}</p>
157
+ <div className={c.actions}>
158
+ <button type="button" className={c.reject} onClick={() => answer("denied")}>
159
+ {words.reject}
160
+ </button>
161
+ <button type="button" className={c.accept} onClick={() => answer("granted")}>
162
+ {words.accept}
163
+ </button>
164
+ </div>
165
+ </section>
166
+ );
167
+ }
168
+
169
+ /** In `<head>`: marks the document before paint once an answer is known, so the card never flashes. */
170
+ export function ConsentKnownScript({
171
+ browser,
172
+ containerId = "",
173
+ posthogKey = "",
174
+ nonce,
175
+ }: {
176
+ browser: BrowserAnalytics;
177
+ containerId?: string;
178
+ posthogKey?: string;
179
+ nonce?: string;
180
+ }) {
181
+ if (!containerId && !posthogKey) return null;
182
+ return <script nonce={nonce} dangerouslySetInnerHTML={{ __html: browser.consentKnownScript }} />;
183
+ }
184
+
185
+ /** The footer's "Cookie settings": asks again. */
186
+ export function CookieSettingsButton({
187
+ browser,
188
+ className,
189
+ children = "Cookie settings",
190
+ }: {
191
+ browser: BrowserAnalytics;
192
+ className?: string;
193
+ children?: React.ReactNode;
194
+ }) {
195
+ return (
196
+ <button type="button" className={cx(className)} onClick={() => browser.reopenConsent()}>
197
+ {children}
198
+ </button>
199
+ );
200
+ }
201
+
202
+ /**
203
+ * On a signed-in page the app lets be measured (`recordablePath`), for an ordinary member: render it for them, and
204
+ * never for an administrator or during a view. Without it the page is not measured.
205
+ */
206
+ export function RecordingAllowed({ browser }: { browser: BrowserAnalytics }) {
207
+ React.useEffect(() => {
208
+ browser.recordableChanged();
209
+ return () => {
210
+ // After unmount the marker is gone; tell the listeners on the next tick, when the DOM says so.
211
+ queueMicrotask(() => browser.recordableChanged());
212
+ };
213
+ }, [browser]);
214
+ return <span hidden {...{ [RECORDABLE_ATTRIBUTE]: "" }} />;
215
+ }
216
+
217
+ /**
218
+ * On a page that must never be measured, however it was reached and whoever accepted: an administrator reading the
219
+ * internal changelog at a public address, say. `ViewingAsBanner` already carries its own marker.
220
+ */
221
+ export function NotMeasured() {
222
+ return <span hidden {...{ [NOT_MEASURED_ATTRIBUTE]: "" }} />;
223
+ }
224
+
225
+ /** For the settings page's own consent card: the answer, whether the browser said no for everybody, and a setter. */
226
+ export function useAnalyticsConsent(browser: BrowserAnalytics) {
227
+ const consent = React.useSyncExternalStore(browser.subscribeToConsent, browser.readConsent, () => null);
228
+ const optedOut = React.useSyncExternalStore(subscribeToNothing, browser.browserOptsOut, () => false);
229
+ const setConsent = React.useCallback(
230
+ (choice: AnalyticsConsent) => {
231
+ const wasLoaded = browser.isGtmLoaded();
232
+ browser.writeConsent(choice);
233
+ if (choice === "denied" && wasLoaded) {
234
+ browser.withdrawConsent();
235
+ window.location.reload();
236
+ }
237
+ },
238
+ [browser],
239
+ );
240
+ return { consent: optedOut ? ("denied" as const) : consent, optedOut, setConsent };
241
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Redaction: what analytics and error reports may say about an address, a message or a stack.
3
+ *
4
+ * The union of the three copies' rules, each the strictest: Quickie's token paths (encoded forms too) and generic
5
+ * record ids, PharmaLine's named id segments and its full redaction of paths, and the email, long-number and UK
6
+ * postcode rules both of them had and AltEd lacked. Every query value is replaced. The app supplies its own words:
7
+ * which path prefixes carry a token, which query parameters are sensitive, which collections take an id.
8
+ */
9
+
10
+ export interface RedactionRules {
11
+ /** Path prefixes whose next segment is a secret: `/i/<token>`, `/api/calendar/<token>`. Longest first is not needed. */
12
+ tokenPathPrefixes?: readonly string[];
13
+ /** Query parameters to redact even where a value is only half a URL — `?token=`, `&email=`. */
14
+ sensitiveQueryParams?: readonly string[];
15
+ /** Collections whose next segment is a record id that is not a cuid or UUID: `/patients/<id>`. */
16
+ idSegments?: readonly string[];
17
+ /** Segments after an id collection that are pages, not ids: `new`, `import`. */
18
+ idSegmentExceptions?: readonly string[];
19
+ /** Anything else the app must never send: `[/\bNHS\s?\d{10}\b/g, "[nhs-number]"]`. */
20
+ patterns?: readonly (readonly [RegExp, string])[];
21
+ }
22
+
23
+ export interface Redactor {
24
+ /** Every rule, over any text: a message, a stack line, a property value. */
25
+ redact(text: string): string;
26
+ /**
27
+ * An address as analytics may keep it: this site's — the redacted path, no query, no fragment; anybody else's —
28
+ * the origin alone; a bare path — redacted.
29
+ */
30
+ cleanUrl(value: string, ownOrigin: string): string;
31
+ /** `redact` over every string, and every key, in plain objects and arrays. Dates, classes and the rest stay. */
32
+ redactDeep<T>(value: T): T;
33
+ }
34
+
35
+ export const TOKEN_PLACEHOLDER = ":token";
36
+ export const REDACTED = ":redacted";
37
+
38
+ const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
39
+
40
+ /** Prisma's `cuid()` (25 characters, starting with `c`) and UUIDs, as a whole path segment. */
41
+ const RECORD_ID =
42
+ /(\/)(?:c[a-z0-9]{24}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?=[/?#\s"'\\]|$)/gi;
43
+ const QUERY_VALUE = /([?&][\w.%-]+=)[^&#\s"'\\]+/g;
44
+ const EMAIL = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g;
45
+ /**
46
+ * Ten digits or more — a card, a phone number, an account — standing on its own. A run glued to letters, digits'
47
+ * neighbours or a hyphen is part of an identifier (a cuid's `l8091234567x`, a UUID's last group), and is left alone:
48
+ * 0.23.0 and 0.23.1 cut ids apart (`cmh2x7q9a0000l[number]x`), which server events and stacks are keyed by.
49
+ */
50
+ const LONG_NUMBER = /(?<![\w-])(?!\d{8}-\d{4}-\d{4}-\d{4}-\d{12}\b)\+?\d(?:[\s-]?\d){9,}(?![A-Za-z_])/g;
51
+ const POSTCODE = /\b[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}\b/gi;
52
+ const PLACEHOLDER_ORIGIN = "https://placeholder.invalid";
53
+ const MAX_DEPTH = 32;
54
+
55
+ const isPlainObject = (value: unknown): value is Record<string, unknown> => {
56
+ if (value === null || typeof value !== "object") return false;
57
+ const prototype: unknown = Object.getPrototypeOf(value);
58
+ return prototype === Object.prototype || prototype === null;
59
+ };
60
+
61
+ export function createRedactor(rules: RedactionRules = {}): Redactor {
62
+ const prefixes = [...(rules.tokenPathPrefixes ?? [])].sort((a, b) => b.length - a.length);
63
+ const params = rules.sensitiveQueryParams ?? [];
64
+ const segments = rules.idSegments ?? [];
65
+ const exceptions = rules.idSegmentExceptions ?? ["new", "import"];
66
+
67
+ for (const prefix of prefixes) {
68
+ if (!prefix.startsWith("/") || prefix.endsWith("/")) {
69
+ throw new Error(`[analytics] a token path prefix starts with "/" and does not end with one: "${prefix}".`);
70
+ }
71
+ }
72
+
73
+ const PATH_START = String.raw`(^|[\s"'\x60=(<>,;[{]|[a-z][a-z0-9+.-]*:\/\/[^/\s"'\x60<>?#]*)`;
74
+ // A route pattern's placeholder (`[token]`, `:token`) is not a token, and stays.
75
+ const SEGMENT = String.raw`(?![[:])[^/?#\s"'\x60<>)\]},;&]+`;
76
+ const tokenPath = prefixes.length
77
+ ? new RegExp(`${PATH_START}(${prefixes.map(escape).join("|")})/${SEGMENT}`, "gi")
78
+ : null;
79
+ const ENCODED_PATH_START = String.raw`(^|=|%3D|[\s"'\x60]|%3A%2F%2F[^%/?#&\s"'\x60]*)`;
80
+ const ENCODED_SEGMENT = String.raw`[^%/?#&\s"'\x60<>]+`;
81
+ const encodedTokenPath = prefixes.length
82
+ ? new RegExp(
83
+ `${ENCODED_PATH_START}(${prefixes.map((p) => escape(p).replace(/\//g, "%2F")).join("|")})%2F${ENCODED_SEGMENT}`,
84
+ "gi",
85
+ )
86
+ : null;
87
+ const names = params.map(escape).join("|");
88
+ const sensitiveParam = params.length ? new RegExp(String.raw`([?&;#])(${names})=[^&#\s"'\x60<>]*`, "gi") : null;
89
+ const encodedSensitiveParam = params.length
90
+ ? new RegExp(String.raw`(%3F|%26)(${names})%3D(?:(?!%26)[^&#\s"'\x60<>])*`, "gi")
91
+ : null;
92
+ const idSegment = segments.length
93
+ ? new RegExp(
94
+ String.raw`(\/(?:${segments.map(escape).join("|")})\/)(?!(?:${exceptions.map(escape).join("|")})(?:[/?#\s"'\\]|$))[^/?#\s"'\\]+`,
95
+ "gi",
96
+ )
97
+ : null;
98
+
99
+ function redact(text: string): string {
100
+ let out = text;
101
+ if (tokenPath) out = out.replace(tokenPath, `$1$2/${TOKEN_PLACEHOLDER}`);
102
+ if (encodedTokenPath) out = out.replace(encodedTokenPath, `$1$2%2F${TOKEN_PLACEHOLDER}`);
103
+ if (sensitiveParam) out = out.replace(sensitiveParam, `$1$2=${REDACTED}`);
104
+ if (encodedSensitiveParam) out = out.replace(encodedSensitiveParam, `$1$2%3D${REDACTED}`);
105
+ out = out.replace(RECORD_ID, "$1[id]");
106
+ if (idSegment) out = out.replace(idSegment, "$1[id]");
107
+ out = out
108
+ .replace(QUERY_VALUE, "$1[redacted]")
109
+ .replace(EMAIL, "[email]")
110
+ .replace(LONG_NUMBER, "[number]")
111
+ .replace(POSTCODE, "[postcode]");
112
+ for (const [pattern, replacement] of rules.patterns ?? []) {
113
+ out = out.replace(
114
+ new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`),
115
+ replacement,
116
+ );
117
+ }
118
+ return out;
119
+ }
120
+
121
+ function cleanUrl(value: string, ownOrigin: string): string {
122
+ let url: URL;
123
+ try {
124
+ url = new URL(value, PLACEHOLDER_ORIGIN);
125
+ } catch {
126
+ return redact(value);
127
+ }
128
+ if (url.origin === PLACEHOLDER_ORIGIN) return redact(url.pathname);
129
+ if (url.origin !== ownOrigin) return url.origin;
130
+ return url.origin + redact(url.pathname);
131
+ }
132
+
133
+ function redactDeep<T>(value: T, depth = 0): T {
134
+ if (typeof value === "string") return redact(value) as T;
135
+ if (depth > MAX_DEPTH) return value;
136
+ if (Array.isArray(value)) return (value as unknown[]).map((item) => redactDeep(item, depth + 1)) as T;
137
+ if (isPlainObject(value)) {
138
+ const copy: Record<string, unknown> = {};
139
+ for (const [key, item] of Object.entries(value)) copy[redact(key)] = redactDeep(item, depth + 1);
140
+ return copy as T;
141
+ }
142
+ return value;
143
+ }
144
+
145
+ return { redact, cleanUrl, redactDeep: (value) => redactDeep(value) };
146
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `@connextar/house/analytics/server` — error reports (`onRequestError` and handled 500s), product events, and GA4's
3
+ * server-side `sign_up`. Imports no browser package, no PostHog and no Next: each is handed in.
4
+ */
5
+ export {
6
+ createServerAnalytics,
7
+ measurementProtocol,
8
+ readGaCookies,
9
+ registeredErrorReporter,
10
+ signUpMethod,
11
+ type GaCookies,
12
+ type MeasurementProtocolOptions,
13
+ type PostHogServerLike,
14
+ type ServerAnalytics,
15
+ type ServerAnalyticsOptions,
16
+ type SignUpContext,
17
+ } from "./server.js";
@@ -0,0 +1,277 @@
1
+ import type { Analytics } from "./config.js";
2
+
3
+ /**
4
+ * The server half: error reports, product events and GA4's server-side `sign_up`.
5
+ *
6
+ * Imports no browser package, no PostHog and no Next: the app passes its `posthog-node` client (`posthog`) and Next's
7
+ * `after` (`after`), so this runs wherever the app's server code does and the versions stay the app's.
8
+ *
9
+ * - **Errors** — `onRequestError` and the handled 500s — are sent anonymous (no distinct id, no person profile),
10
+ * with the message and every stack frame redacted, and a Prisma error reduced to its code: a Prisma message quotes
11
+ * the query's values. Quickie's frames are taken only after the original `name: message` head, so a message line that
12
+ * looks like ` at 12 High Street` cannot pass as a frame. AltEd reduced nothing and redacted only tokens.
13
+ * - **Events** keyed by a person are refused while viewing as somebody (senco's rule — Quickie's had none) and for a
14
+ * request that sends `Sec-GPC: 1`, and their properties are redacted.
15
+ * - **`sign_up` by Measurement Protocol** only on a production host, never with `Sec-GPC: 1` (AltEd lacked it), and
16
+ * only with both Google cookies — a stray `_ga` from another site is not a session (AltEd accepted it). Clearing
17
+ * them on a no is what withdraws it.
18
+ */
19
+
20
+ /** The parts of posthog-node's client this calls. */
21
+ export interface PostHogServerLike {
22
+ captureExceptionImmediate(
23
+ error: unknown,
24
+ distinctId?: string,
25
+ properties?: Record<string, unknown>,
26
+ ): Promise<unknown>;
27
+ capture(event: { distinctId: string; event: string; properties?: Record<string, unknown> }): void;
28
+ flush(): Promise<unknown>;
29
+ }
30
+
31
+ export interface ServerAnalyticsOptions {
32
+ analytics: Analytics;
33
+ /** The app's posthog-node client, or null when analytics is off. Called each time, so the env can turn it off. */
34
+ posthog: () => PostHogServerLike | null | undefined;
35
+ /** Whether this request is a "view as". Fail-closed: one that throws counts as yes. */
36
+ isViewingAs?: () => boolean | Promise<boolean>;
37
+ /** The request's headers, for `Sec-GPC`: Next's `headers`. Outside a request, return null. */
38
+ requestHeaders?: () => Pick<Headers, "get"> | null | undefined | Promise<Pick<Headers, "get"> | null | undefined>;
39
+ /** Next's `after`, to send once the response has gone. Default: sent at once, not awaited. */
40
+ after?: (task: () => Promise<void>) => void;
41
+ logger?: { error(message: string, ...detail: unknown[]): void };
42
+ }
43
+
44
+ const MESSAGE_LIMIT = 1000;
45
+ const FRAME = /^\s+at /;
46
+
47
+ export type ServerAnalytics = ReturnType<typeof createServerAnalytics>;
48
+
49
+ export function createServerAnalytics(options: ServerAnalyticsOptions) {
50
+ const { analytics } = options;
51
+ const logger = options.logger ?? console;
52
+
53
+ function safeMessage(source: Error): string {
54
+ if (source.name.startsWith("PrismaClient") || source.constructor?.name?.startsWith("PrismaClient")) {
55
+ const code = (source as Error & { code?: unknown }).code;
56
+ return typeof code === "string" && /^[A-Z]\d{3,4}$/.test(code)
57
+ ? `Prisma ${code}`
58
+ : "Prisma error (message withheld)";
59
+ }
60
+ return analytics.redact(source.message).slice(0, MESSAGE_LIMIT);
61
+ }
62
+
63
+ /** A copy of the error that is safe to send: its name, a redacted message, and redacted frames only. */
64
+ function redactedError(error: unknown): Error {
65
+ const source = error instanceof Error ? error : new Error(String(error));
66
+ const copy = new Error(safeMessage(source));
67
+ copy.name = source.name;
68
+ if (source.stack) {
69
+ const head = source.message ? `${source.name}: ${source.message}` : source.name;
70
+ const body = source.stack.startsWith(head) ? source.stack.slice(head.length) : source.stack;
71
+ const frames = body.split("\n").filter((line) => FRAME.test(line));
72
+ copy.stack = [`${copy.name}: ${copy.message}`, ...frames.map((line) => analytics.redact(line))].join("\n");
73
+ } else {
74
+ copy.stack = `${copy.name}: ${copy.message}`;
75
+ }
76
+ return copy;
77
+ }
78
+
79
+ async function reportServerError(error: unknown, properties: Record<string, unknown> = {}): Promise<void> {
80
+ const posthog = options.posthog();
81
+ if (!posthog) return;
82
+ try {
83
+ await posthog.captureExceptionImmediate(redactedError(error), undefined, {
84
+ ...analytics.redactDeep(properties),
85
+ $process_person_profile: false,
86
+ });
87
+ } catch (failure) {
88
+ logger.error("[analytics] an error report failed", failure);
89
+ }
90
+ }
91
+
92
+ function later(task: () => Promise<void>): void {
93
+ if (options.after) {
94
+ try {
95
+ options.after(task);
96
+ return;
97
+ } catch {
98
+ // Outside a request scope `after` throws: send now instead.
99
+ }
100
+ }
101
+ void task();
102
+ }
103
+
104
+ /** For `handleError`'s 500s: sent once the response has gone. */
105
+ function reportServerErrorAfterResponse(error: unknown, properties: Record<string, unknown> = {}): void {
106
+ if (!options.posthog()) return;
107
+ later(() => reportServerError(error, properties));
108
+ }
109
+
110
+ /** `export const onRequestError = server.onRequestError` in `instrumentation.ts`: the route pattern, never the URL. */
111
+ async function onRequestError(
112
+ error: unknown,
113
+ request: { method?: string },
114
+ context: { routePath?: string; routeType?: string },
115
+ ): Promise<void> {
116
+ await reportServerError(error, {
117
+ source: "server",
118
+ route: context.routePath,
119
+ route_type: context.routeType,
120
+ method: request.method,
121
+ });
122
+ }
123
+
124
+ async function refused(): Promise<boolean> {
125
+ try {
126
+ if (options.isViewingAs && (await options.isViewingAs())) return true;
127
+ } catch {
128
+ return true;
129
+ }
130
+ try {
131
+ const headers = await options.requestHeaders?.();
132
+ if (headers?.get("sec-gpc") === "1") return true;
133
+ } catch {
134
+ // Outside a request: no header to honour.
135
+ }
136
+ return false;
137
+ }
138
+
139
+ /** A product event for a person, its properties redacted; never during a view or against `Sec-GPC: 1`. */
140
+ async function captureServerEvent(distinctId: string, event: string, properties?: Record<string, unknown>) {
141
+ const posthog = options.posthog();
142
+ if (!posthog || (await refused())) return;
143
+ try {
144
+ posthog.capture({ distinctId, event, properties: properties && analytics.redactDeep(properties) });
145
+ await posthog.flush();
146
+ } catch (error) {
147
+ logger.error("[analytics] a server event failed", error);
148
+ }
149
+ }
150
+
151
+ function captureServerEventAfterResponse(distinctId: string, event: string, properties?: Record<string, unknown>) {
152
+ if (!options.posthog()) return;
153
+ later(() => captureServerEvent(distinctId, event, properties));
154
+ }
155
+
156
+ return {
157
+ redactedError,
158
+ reportServerError,
159
+ reportServerErrorAfterResponse,
160
+ onRequestError,
161
+ captureServerEvent,
162
+ captureServerEventAfterResponse,
163
+ /** For `register()`: puts the after-response reporter where the app's `handleError` finds it. */
164
+ registerErrorReporter(target: object = globalThis): void {
165
+ Object.assign(target, { [analytics.errorReporterSymbol]: reportServerErrorAfterResponse });
166
+ },
167
+ };
168
+ }
169
+
170
+ /** The reporter `registerErrorReporter` put on `globalThis`, for `handleError` — a no-op until it is registered. */
171
+ export function registeredErrorReporter(
172
+ analytics: Analytics,
173
+ target: object = globalThis,
174
+ ): (error: unknown, properties?: Record<string, unknown>) => void {
175
+ const found = (target as Record<symbol, unknown>)[analytics.errorReporterSymbol];
176
+ return typeof found === "function"
177
+ ? (found as (error: unknown, properties?: Record<string, unknown>) => void)
178
+ : () => {};
179
+ }
180
+
181
+ // ── GA4 Measurement Protocol ─────────────────────────────────────────────────
182
+
183
+ const ENDPOINT = "https://www.google-analytics.com/mp/collect";
184
+
185
+ export interface GaCookies {
186
+ clientId: string;
187
+ sessionId: string;
188
+ }
189
+
190
+ function cookieValue(cookieHeader: string, name: string): string | undefined {
191
+ for (const part of cookieHeader.split(";")) {
192
+ const index = part.indexOf("=");
193
+ if (index <= 0 || part.slice(0, index).trim() !== name) continue;
194
+ const raw = part.slice(index + 1).trim();
195
+ try {
196
+ return decodeURIComponent(raw);
197
+ } catch {
198
+ return raw;
199
+ }
200
+ }
201
+ return undefined;
202
+ }
203
+
204
+ /** `_ga`'s client id and the `_ga_<id>` session — both, or null. */
205
+ export function readGaCookies(cookieHeader: string, measurementId: string): GaCookies | null {
206
+ const ga = cookieValue(cookieHeader, "_ga")?.match(/^GA\d\.\d+\.(\d+\.\d+)$/);
207
+ if (!ga) return null;
208
+ const session = cookieValue(cookieHeader, `_ga_${measurementId.replace(/^G-/, "")}`);
209
+ const sessionId = session?.match(/^GS1\.\d+\.(\d+)\./)?.[1] ?? session?.match(/^GS2\.\d+\.s(\d+)/)?.[1];
210
+ if (!sessionId) return null;
211
+ return { clientId: ga[1]!, sessionId };
212
+ }
213
+
214
+ /** How the account was made, from the Better Auth route that made it. */
215
+ export function signUpMethod(path: string | undefined, providerId?: string): string {
216
+ if (path === "/sign-up/email") return "password";
217
+ if (path?.startsWith("/magic-link")) return "magic_link";
218
+ if (path?.startsWith("/callback") || path?.startsWith("/oauth2/callback")) return providerId ?? "social";
219
+ if (path?.startsWith("/passkey")) return "passkey";
220
+ return "other";
221
+ }
222
+
223
+ /** Better Auth's endpoint context, as `databaseHooks.user.create.after` receives it. */
224
+ export interface SignUpContext {
225
+ path?: string;
226
+ params?: Record<string, string | undefined>;
227
+ headers?: Headers | Pick<Headers, "get">;
228
+ request?: Request;
229
+ }
230
+
231
+ export interface MeasurementProtocolOptions {
232
+ measurementId: string | undefined;
233
+ apiSecret: string | undefined;
234
+ /** The hosts a sign-up counts on: production's. A preview or a laptop never sends one. */
235
+ productionHosts: readonly string[];
236
+ fetch?: typeof fetch;
237
+ logger?: { error(message: string, ...detail: unknown[]): void };
238
+ }
239
+
240
+ /** `databaseHooks.user.create.after: async (_user, context) => recordSignUp(context)`. Never throws. */
241
+ export function measurementProtocol(options: MeasurementProtocolOptions) {
242
+ const hosts = new Set(options.productionHosts);
243
+ const logger = options.logger ?? console;
244
+ return {
245
+ async recordSignUp(context: SignUpContext | null | undefined): Promise<void> {
246
+ const { measurementId, apiSecret } = options;
247
+ if (!measurementId || !apiSecret || !context) return;
248
+ try {
249
+ const headers = context.headers ?? context.request?.headers;
250
+ if (!headers || !hosts.has(headers.get("host") ?? "")) return;
251
+ if (headers.get("sec-gpc") === "1") return;
252
+ const cookies = readGaCookies(headers.get("cookie") ?? "", measurementId);
253
+ if (!cookies) return;
254
+ const url = `${ENDPOINT}?measurement_id=${encodeURIComponent(measurementId)}&api_secret=${encodeURIComponent(apiSecret)}`;
255
+ await (options.fetch ?? fetch)(url, {
256
+ method: "POST",
257
+ body: JSON.stringify({
258
+ client_id: cookies.clientId,
259
+ events: [
260
+ {
261
+ name: "sign_up",
262
+ params: {
263
+ method: signUpMethod(context.path, context.params?.id),
264
+ engagement_time_msec: 1,
265
+ session_id: cookies.sessionId,
266
+ },
267
+ },
268
+ ],
269
+ }),
270
+ signal: AbortSignal.timeout(2000),
271
+ });
272
+ } catch (error) {
273
+ logger.error("[analytics] could not record a sign-up", error);
274
+ }
275
+ },
276
+ };
277
+ }