@sssb/kit 0.0.0 → 0.2.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 (214) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +209 -5
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +312 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +270 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +94 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
@@ -0,0 +1,320 @@
1
+ import type { TourAction, TourMiss } from './contracts'
2
+
3
+ /**
4
+ * The tour DRIVER: a ghost cursor that works on any screen. Scripts (./contracts.ts) are declarative;
5
+ * this animates a fake cursor to REAL elements, fires real clicks (React handles them normally), and
6
+ * types into real fields character by character with native setters, so controlled components update.
7
+ *
8
+ * Ported from the tourable-prototype template's `src/tour/driver.js`. What the port keeps, because it
9
+ * is what makes a walkthrough watchable rather than a screen recording:
10
+ *
11
+ * - Clicks pause about half a second between the click animation and the actual click. There is no
12
+ * page-load delay to pace the viewer, so the driver supplies one.
13
+ * - The cursor hides while typing (it would cover the text) and reappears on its next move.
14
+ * - Cancellation is checked INSIDE actions, before every real click and every typed character, so
15
+ * Back or Exit mid-script can never let a stale click land on the next step's screen.
16
+ * - `isDriving()` is true while a script runs. The engine uses it to tell driver-initiated navigation
17
+ * from the viewer's own (the derail guard) and to hide the cursor when the VIEWER scrolls.
18
+ *
19
+ * What the port CHANGES, and why:
20
+ *
21
+ * - **Selectors are awaited, not sampled.** The source queried the DOM immediately; here every action
22
+ * polls for its target up to a real-time deadline. A tour is also a CI walkthrough run at ~50x
23
+ * speed, where the app has not necessarily re-rendered by the time the next action starts.
24
+ * - **A miss is recorded, not swallowed.** The source kept the tour alive by ignoring a missing
25
+ * element. This keeps the tour alive too (a viewer must never be stranded) but reports every
26
+ * unresolved target, which is how a screen change that breaks a tour fails the build.
27
+ * - **`emit` is gone.** The source had a bridge to app-level actions; here the world has its own UI —
28
+ * the Simulator panel — so a tour drives it by clicking real controls (the `panel` action), which
29
+ * is both better to watch and the reason SSSB needs to learn no app vocabulary.
30
+ * - **Speed is a value, not a window global.** `setDriverSpeed` is wired to the Tours tab's Fast
31
+ * switch, which is also how CI runs a tour in seconds.
32
+ */
33
+
34
+ /** The ghost cursor's element ids — rendered by ./tour-overlay.tsx, moved from here. */
35
+ export const CURSOR_ID = 'sssb-tour-cursor'
36
+ export const CURSOR_RING_ID = 'sssb-tour-cursor-ring'
37
+
38
+ // Bumped by every cancelScript(); an in-flight script whose token is stale stops at its next check.
39
+ let token = 0
40
+ // Depth rather than a boolean: an `advance` script can start while an entry script is unwinding.
41
+ let driving = 0
42
+ // Fast-forward: finish the current script near-instantly instead of cancelling it (Next mid-script
43
+ // must never leave a form half-filled).
44
+ let fastForwarding = false
45
+ let speedScale = 1
46
+
47
+ /** Scale every delay. 1 = presentation pace; the Tours tab's Fast switch drops it to a preview
48
+ * crawl, which is also how the CI walkthrough runs a whole tour in a few seconds. */
49
+ export function setDriverSpeed(scale: number) {
50
+ speedScale = scale
51
+ }
52
+
53
+ export function cancelScript() {
54
+ token += 1
55
+ }
56
+
57
+ export function isDriving(): boolean {
58
+ return driving > 0
59
+ }
60
+
61
+ /** Called when the viewer presses Next mid-script: the script completes instantly, then the tour moves
62
+ * on. Cancelling instead would strand a half-typed form on screen. */
63
+ export function requestFastForward() {
64
+ if (driving > 0) fastForwarding = true
65
+ }
66
+
67
+ // Real-time deadlines (NOT scaled): how long an action waits for its target before calling it a miss.
68
+ // Interactive actions want a short leash; `expect`/`expectText` are deliberately "wait for the world to
69
+ // catch up" actions, so they wait for an autonomous actor or a job to land.
70
+ const FIND_TIMEOUT_MS = 2_500
71
+ const EXPECT_TIMEOUT_MS = 8_000
72
+ const POLL_MS = 60
73
+
74
+ const sleep = (ms: number) =>
75
+ new Promise((resolve) => setTimeout(resolve, Math.max(1, ms * (fastForwarding ? 0.01 : speedScale))))
76
+ /** A real-time wait, immune to the speed control — used only for polling the DOM. */
77
+ const realSleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
78
+
79
+ const query = (selector: string): HTMLElement | null => document.querySelector<HTMLElement>(selector)
80
+ const cursor = () => document.getElementById(CURSOR_ID)
81
+
82
+ interface ScriptContext {
83
+ alive: () => boolean
84
+ miss: (action: string, target: string) => void
85
+ }
86
+
87
+ /** Poll for a selector until the deadline. Returns null (and stays silent) — callers decide whether a
88
+ * missing element is a miss, because `panel` legitimately probes for an element that may not be there. */
89
+ async function waitFor(ctx: ScriptContext, selector: string, timeoutMs: number): Promise<HTMLElement | null> {
90
+ const deadline = Date.now() + timeoutMs
91
+ for (;;) {
92
+ const el = query(selector)
93
+ if (el) return el
94
+ if (!ctx.alive() || Date.now() > deadline) return null
95
+ await realSleep(POLL_MS)
96
+ }
97
+ }
98
+
99
+ /** Resolve a target an action REQUIRES: a failure is recorded as a miss and the action no-ops. */
100
+ async function resolve(ctx: ScriptContext, action: string, selector: string): Promise<HTMLElement | null> {
101
+ const el = await waitFor(ctx, selector, FIND_TIMEOUT_MS)
102
+ if (!el && ctx.alive()) ctx.miss(action, selector)
103
+ return el
104
+ }
105
+
106
+ function place(el: Element) {
107
+ const c = cursor()
108
+ if (!c) return
109
+ const rect = el.getBoundingClientRect()
110
+ c.style.opacity = '1'
111
+ // Aim at the element's middle, but never more than 140px in — on a full-width row the cursor
112
+ // should sit where a hand would reach, not in the far distance.
113
+ c.style.transform = `translate(${rect.left + Math.min(rect.width / 2, 140)}px, ${rect.top + rect.height / 2}px)`
114
+ }
115
+
116
+ function scrollIntoView(el: Element) {
117
+ try {
118
+ el.scrollIntoView({ block: 'center', behavior: 'smooth' })
119
+ } catch {
120
+ // jsdom/happy-dom have no layout — the tour is still driveable without the scroll.
121
+ }
122
+ }
123
+
124
+ /** Glide to an element: scroll it to the middle of the screen, then move the cursor onto it. */
125
+ async function moveTo(ctx: ScriptContext, action: string, selector: string): Promise<HTMLElement | null> {
126
+ const el = await resolve(ctx, action, selector)
127
+ if (!el || !ctx.alive()) return null
128
+ scrollIntoView(el)
129
+ await sleep(380)
130
+ if (!ctx.alive()) return null
131
+ place(el)
132
+ await sleep(650)
133
+ return ctx.alive() ? el : null
134
+ }
135
+
136
+ /** The click halo. Web Animations API rather than a stylesheet: SSSB components ship no global CSS. */
137
+ async function ripple() {
138
+ const ring = document.getElementById(CURSOR_RING_ID)
139
+ ring?.animate(
140
+ [
141
+ { opacity: 1, transform: 'scale(0.35)' },
142
+ { opacity: 0.8, transform: 'scale(1.45)', offset: 0.55 },
143
+ { opacity: 0, transform: 'scale(1.95)' },
144
+ ],
145
+ { duration: 700, easing: 'cubic-bezier(.15,.6,.25,1)' },
146
+ )
147
+ await sleep(380)
148
+ }
149
+
150
+ /** Set a value the way a user would, so React's onChange sees it: the native setter bypasses React's
151
+ * value tracker, which would otherwise swallow the input event as a no-op. */
152
+ function setNativeValue(el: HTMLElement, value: string) {
153
+ const proto =
154
+ el.tagName === 'SELECT'
155
+ ? window.HTMLSelectElement
156
+ : el.tagName === 'TEXTAREA'
157
+ ? window.HTMLTextAreaElement
158
+ : window.HTMLInputElement
159
+ const setter = Object.getOwnPropertyDescriptor(proto.prototype, 'value')?.set
160
+ if (setter) setter.call(el, value)
161
+ else (el as HTMLInputElement).value = value
162
+ }
163
+
164
+ async function clickAction(ctx: ScriptContext, selector: string) {
165
+ const el = await moveTo(ctx, 'click', selector)
166
+ if (!el) return
167
+ await ripple()
168
+ await sleep(500) // let the viewer register the click before anything on screen changes
169
+ if (!ctx.alive()) return // Back/Exit was pressed: this click must not land
170
+ el.click()
171
+ await sleep(720) // breathing room after the change
172
+ }
173
+
174
+ async function typeAction(ctx: ScriptContext, selector: string, text: string) {
175
+ const el = await moveTo(ctx, 'type', selector)
176
+ if (!el) return
177
+ el.focus()
178
+ const c = cursor()
179
+ if (c) c.style.opacity = '0' // the cursor would cover the text being typed
180
+ for (let i = 1; i <= text.length; i += 1) {
181
+ if (!ctx.alive()) return
182
+ setNativeValue(el, text.slice(0, i))
183
+ el.dispatchEvent(new Event('input', { bubbles: true }))
184
+ await sleep(26)
185
+ }
186
+ await sleep(240)
187
+ }
188
+
189
+ async function selectAction(ctx: ScriptContext, selector: string, value: string) {
190
+ const el = await moveTo(ctx, 'select', selector)
191
+ if (!el) return
192
+ await ripple()
193
+ if (!ctx.alive()) return
194
+ setNativeValue(el, value)
195
+ el.dispatchEvent(new Event('change', { bubbles: true }))
196
+ await sleep(420)
197
+ }
198
+
199
+ /**
200
+ * Drive the Simulator panel through its own controls. Expanding is conditional (the panel remembers
201
+ * whether the viewer left it open), so this probes for the panel WITHOUT recording a miss — only the
202
+ * tab itself is required.
203
+ */
204
+ async function panelAction(ctx: ScriptContext, tab?: string) {
205
+ const expanded = () => query('[data-testid="simulator-panel"]')
206
+ if (tab === undefined) {
207
+ if (expanded()) await clickAction(ctx, '[data-testid="simulator-collapse"]')
208
+ return
209
+ }
210
+ if (!expanded()) {
211
+ await clickAction(ctx, '[data-testid="simulator-pill"]')
212
+ // The panel mounts on click; wait for it rather than racing the render.
213
+ await waitFor(ctx, '[data-testid="simulator-panel"]', FIND_TIMEOUT_MS)
214
+ }
215
+ await clickAction(ctx, `[data-testid="simulator-tab-${tab}"]`)
216
+ }
217
+
218
+ async function expectAction(ctx: ScriptContext, selector: string) {
219
+ const el = await waitFor(ctx, selector, EXPECT_TIMEOUT_MS)
220
+ if (!el) {
221
+ if (ctx.alive()) ctx.miss('expect', selector)
222
+ return
223
+ }
224
+ scrollIntoView(el)
225
+ await sleep(300)
226
+ }
227
+
228
+ async function expectTextAction(ctx: ScriptContext, selector: string, needle: string) {
229
+ const deadline = Date.now() + EXPECT_TIMEOUT_MS
230
+ for (;;) {
231
+ const el = query(selector)
232
+ if (el?.textContent?.includes(needle)) {
233
+ scrollIntoView(el)
234
+ await sleep(300)
235
+ return
236
+ }
237
+ if (!ctx.alive()) return
238
+ if (Date.now() > deadline) {
239
+ ctx.miss('expectText', `${selector} — ${needle}`)
240
+ return
241
+ }
242
+ await realSleep(POLL_MS)
243
+ }
244
+ }
245
+
246
+ async function runAction(ctx: ScriptContext, action: TourAction) {
247
+ switch (action[0]) {
248
+ case 'move': {
249
+ await moveTo(ctx, 'move', action[1])
250
+ return
251
+ }
252
+ case 'click':
253
+ return clickAction(ctx, action[1])
254
+ case 'type':
255
+ return typeAction(ctx, action[1], action[2])
256
+ case 'select':
257
+ return selectAction(ctx, action[1], action[2])
258
+ case 'panel':
259
+ return panelAction(ctx, action[1])
260
+ case 'expect':
261
+ return expectAction(ctx, action[1])
262
+ case 'expectText':
263
+ return expectTextAction(ctx, action[1], action[2])
264
+ case 'scrollTo': {
265
+ const el = await resolve(ctx, 'scrollTo', action[1])
266
+ if (!el || !ctx.alive()) return
267
+ scrollIntoView(el)
268
+ await sleep(600)
269
+ if (ctx.alive()) place(el)
270
+ return
271
+ }
272
+ case 'scrollTop': {
273
+ try {
274
+ window.scrollTo({ top: 0, behavior: 'smooth' })
275
+ } catch {
276
+ window.scrollTo(0, 0)
277
+ }
278
+ await sleep(400)
279
+ return
280
+ }
281
+ case 'pause':
282
+ await sleep(action[1])
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Run one script to completion. Never throws: a tour that dies mid-step strands the viewer, so an
288
+ * action that blows up is reported through `onMiss` and the story carries on.
289
+ */
290
+ export async function runScript(script: readonly TourAction[] | undefined, onMiss: (miss: TourMiss) => void) {
291
+ if (!script || script.length === 0) {
292
+ hideCursor()
293
+ return
294
+ }
295
+ const mine = (token += 1)
296
+ const ctx: ScriptContext = {
297
+ alive: () => mine === token,
298
+ miss: (action, target) => onMiss({ action, target }),
299
+ }
300
+ driving += 1
301
+ try {
302
+ await sleep(350) // let the step's screen render before the cursor arrives
303
+ for (const action of script) {
304
+ if (!ctx.alive()) return
305
+ try {
306
+ await runAction(ctx, action)
307
+ } catch (error) {
308
+ ctx.miss(action[0], `${String(action[1] ?? '')} (${error instanceof Error ? error.message : 'failed'})`)
309
+ }
310
+ }
311
+ } finally {
312
+ driving -= 1
313
+ if (driving === 0) fastForwarding = false
314
+ }
315
+ }
316
+
317
+ export function hideCursor() {
318
+ const c = cursor()
319
+ if (c) c.style.opacity = '0'
320
+ }
@@ -0,0 +1,226 @@
1
+ 'use client'
2
+
3
+ import { Box, Button, Group, Stack, Text, UnstyledButton } from '@mantine/core'
4
+ import { useTranslations } from 'next-intl'
5
+ import type { ReactNode } from 'react'
6
+ import type { TourMiss } from './contracts'
7
+ import { CURSOR_ID, CURSOR_RING_ID } from './driver'
8
+
9
+ /**
10
+ * Everything a running tour puts ON TOP of the app: the ghost cursor the driver moves, the vignette
11
+ * backdrop a spotlight dims the page with, the narration bar, and the end-of-run report.
12
+ *
13
+ * Deliberately one component: all four are the same overlay layer, they share a z-index budget, and a
14
+ * host should mount ONE node beside the Simulator panel rather than remember four.
15
+ *
16
+ * Z-INDEX BUDGET (the panel's pill sits at 1000): backdrop 1100, spotlit target 1150 (set inline by
17
+ * the engine), cursor 1300, bar 1200. The cursor stays above the bar so it can visibly travel over it.
18
+ */
19
+
20
+ export interface TourOverlayProps {
21
+ /** A tour is running: the bar and the cursor exist. */
22
+ active: boolean
23
+ /** Zero-based index of the step being narrated, and how many there are. */
24
+ stepIndex: number
25
+ total: number
26
+ /** The step's narration, already translated (rich text: the app's catalog may bold a term). */
27
+ narration: ReactNode
28
+ /** An `advance` script is mid-flight — the buttons lock so a double Next cannot skip a beat. */
29
+ advancing: boolean
30
+ /** Whether a spotlight is currently lit (the engine only reports true once its target exists). */
31
+ spotlit: boolean
32
+ /** Targets this run has asked for and not found. Shown as they happen, so an author sees the break
33
+ * where it happened rather than in a log. */
34
+ misses: TourMiss[]
35
+ /** The viewer navigated away from the tour's storyline under their own steam. */
36
+ derailed: boolean
37
+ /** Set when the run ends (finished or exited) — the strip CI reads to decide whether the tour is
38
+ * still true. Cleared by the viewer. */
39
+ report: { steps: number; misses: TourMiss[] } | null
40
+ onNext: () => void
41
+ onBack: () => void
42
+ onExit: () => void
43
+ onResume: () => void
44
+ onDismissReport: () => void
45
+ }
46
+
47
+ const barStyle = {
48
+ position: 'fixed',
49
+ left: 0,
50
+ right: 0,
51
+ bottom: 0,
52
+ zIndex: 1200,
53
+ background: '#1a1b1e',
54
+ color: '#f8f9fa',
55
+ borderTop: '1px solid #373a40',
56
+ boxShadow: '0 -6px 30px rgba(0,0,0,0.35)',
57
+ padding: '10px 16px',
58
+ } as const
59
+
60
+ export function TourOverlay({
61
+ active,
62
+ stepIndex,
63
+ total,
64
+ narration,
65
+ advancing,
66
+ spotlit,
67
+ misses,
68
+ derailed,
69
+ report,
70
+ onNext,
71
+ onBack,
72
+ onExit,
73
+ onResume,
74
+ onDismissReport,
75
+ }: TourOverlayProps) {
76
+ const t = useTranslations('simulator')
77
+
78
+ return (
79
+ <>
80
+ {/* The vignette. Pointer-events off: it dims, it never intercepts — the driver still has to
81
+ click through it, and so does anyone who wants to poke at the highlighted thing. */}
82
+ {active && spotlit ? (
83
+ <Box
84
+ data-testid="tour-spotlight"
85
+ style={{
86
+ position: 'fixed',
87
+ inset: 0,
88
+ zIndex: 1100,
89
+ background: 'rgba(16,30,42,0.66)',
90
+ pointerEvents: 'none',
91
+ }}
92
+ />
93
+ ) : null}
94
+
95
+ {/* The ghost cursor. Positioned only by the driver (transform), so React never re-renders
96
+ on movement; the transition is what makes it glide rather than teleport. */}
97
+ {active ? (
98
+ <Box
99
+ id={CURSOR_ID}
100
+ aria-hidden
101
+ style={{
102
+ position: 'fixed',
103
+ top: 0,
104
+ left: 0,
105
+ zIndex: 1300,
106
+ opacity: 0,
107
+ pointerEvents: 'none',
108
+ transition: 'transform .68s cubic-bezier(.3,.75,.3,1), opacity .3s',
109
+ filter: 'drop-shadow(0 2px 7px rgba(16,30,42,.45))',
110
+ }}
111
+ >
112
+ <svg width="33" height="33" viewBox="0 0 24 24">
113
+ <path d="M5 3l14 8-6.5 1.5L9 19z" fill="#14232f" stroke="#fff" strokeWidth="1.6" />
114
+ </svg>
115
+ <Box
116
+ id={CURSOR_RING_ID}
117
+ style={{
118
+ position: 'absolute',
119
+ top: -9,
120
+ left: -9,
121
+ width: 50,
122
+ height: 50,
123
+ borderRadius: '50%',
124
+ border: '3.5px solid #fcc419',
125
+ background: 'rgba(252,196,25,0.18)',
126
+ opacity: 0,
127
+ }}
128
+ />
129
+ </Box>
130
+ ) : null}
131
+
132
+ {active ? (
133
+ <Box component="aside" aria-label={t('tourBarLabel')} data-testid="tour-bar" style={barStyle}>
134
+ <Group gap="md" wrap="nowrap" align="center">
135
+ <Text
136
+ size="xs"
137
+ fw={800}
138
+ data-testid="tour-progress"
139
+ data-step={stepIndex + 1}
140
+ data-total={total}
141
+ style={{ flexShrink: 0, background: '#373a40', borderRadius: 8, padding: '4px 8px' }}
142
+ >
143
+ {t('tourProgress', { step: stepIndex + 1, total })}
144
+ </Text>
145
+ {/* Constant-ish height with its own scroll, so the buttons never move under a
146
+ longer step. 120px is five lines at the narrow end of the layout (panel
147
+ open on a small laptop), which is as long as narration should ever be. */}
148
+ <Stack gap={4} style={{ flex: 1, minWidth: 0, maxHeight: 120, overflowY: 'auto' }}>
149
+ <Text size="sm" c="gray.2" data-testid="tour-narration">
150
+ {narration}
151
+ </Text>
152
+ {derailed ? (
153
+ <Text size="xs" c="yellow.4" data-testid="tour-derailed">
154
+ {t('tourDerailedHint')}
155
+ </Text>
156
+ ) : null}
157
+ {misses.map((miss) => (
158
+ <Text key={`${miss.action}:${miss.target}`} size="xs" c="red.4" data-testid="tour-miss">
159
+ {t('tourMiss', { action: miss.action, target: miss.target })}
160
+ </Text>
161
+ ))}
162
+ </Stack>
163
+ <Group gap="xs" wrap="nowrap" style={{ flexShrink: 0 }}>
164
+ {derailed ? (
165
+ <Button size="xs" variant="default" data-testid="tour-resume" onClick={onResume}>
166
+ {t('tourResume')}
167
+ </Button>
168
+ ) : null}
169
+ <UnstyledButton
170
+ data-testid="tour-exit"
171
+ onClick={onExit}
172
+ style={{ fontSize: 12, color: '#909296', textDecoration: 'underline' }}
173
+ >
174
+ {t('tourExit')}
175
+ </UnstyledButton>
176
+ <Button
177
+ size="xs"
178
+ variant="default"
179
+ data-testid="tour-back"
180
+ disabled={stepIndex === 0 || advancing}
181
+ onClick={onBack}
182
+ >
183
+ {t('tourBack')}
184
+ </Button>
185
+ <Button size="xs" data-testid="tour-next" loading={advancing} onClick={onNext}>
186
+ {stepIndex >= total - 1 ? t('tourFinish') : t('tourNext')}
187
+ </Button>
188
+ </Group>
189
+ </Group>
190
+ </Box>
191
+ ) : null}
192
+
193
+ {/* The run report. It outlives the tour on purpose: a presenter sees "that ran clean", and
194
+ the CI walkthrough asserts data-misses="0" here after clicking the story to its end. */}
195
+ {report ? (
196
+ <Box role="status" data-testid="tour-report" data-misses={report.misses.length} style={barStyle}>
197
+ <Group gap="md" wrap="nowrap" align="center">
198
+ <Stack gap={2} style={{ flex: 1, minWidth: 0 }}>
199
+ <Text size="sm" fw={700} c={report.misses.length === 0 ? 'teal.4' : 'red.4'}>
200
+ {report.misses.length === 0
201
+ ? t('tourReportClean', { steps: report.steps })
202
+ : t('tourReportProblems', {
203
+ steps: report.steps,
204
+ count: report.misses.length,
205
+ })}
206
+ </Text>
207
+ {report.misses.map((miss) => (
208
+ <Text
209
+ key={`${miss.action}:${miss.target}`}
210
+ size="xs"
211
+ c="red.4"
212
+ data-testid="tour-report-miss"
213
+ >
214
+ {t('tourMiss', { action: miss.action, target: miss.target })}
215
+ </Text>
216
+ ))}
217
+ </Stack>
218
+ <Button size="xs" variant="default" data-testid="tour-report-dismiss" onClick={onDismissReport}>
219
+ {t('tourReportDismiss')}
220
+ </Button>
221
+ </Group>
222
+ </Box>
223
+ ) : null}
224
+ </>
225
+ )
226
+ }