create-ailk 0.37.1 → 0.38.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 (230) hide show
  1. package/README.md +129 -0
  2. package/component-catalog.json +44 -6
  3. package/component-catalog.md +6 -5
  4. package/dist/add-module.js +16 -1
  5. package/dist/add-route.d.ts +2 -2
  6. package/dist/add-route.js +18 -11
  7. package/dist/cli.js +52 -0
  8. package/dist/declined-routes.d.ts +13 -0
  9. package/dist/declined-routes.js +74 -0
  10. package/dist/derive-architecture.d.ts +0 -6
  11. package/dist/derive-architecture.js +9 -15
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.js +3 -0
  14. package/dist/language-import.d.ts +93 -0
  15. package/dist/language-import.js +270 -43
  16. package/dist/lib/import-mdx.js +1 -1
  17. package/dist/lib/scaffold-render-sweep.d.ts +6 -3
  18. package/dist/lib/scaffold-render-sweep.js +8 -4
  19. package/dist/migrate-content.d.ts +6 -2
  20. package/dist/migrate-content.js +62 -5
  21. package/dist/module-architecture.js +139 -103
  22. package/dist/paid-sections.d.ts +13 -0
  23. package/dist/paid-sections.js +35 -5
  24. package/dist/programmatic.js +6 -16
  25. package/dist/remove-module.js +67 -0
  26. package/dist/routes.d.ts +103 -0
  27. package/dist/routes.js +708 -0
  28. package/dist/site-manifest.js +1 -1
  29. package/dist/site-roster.d.ts +2 -1
  30. package/dist/site-roster.js +30 -8
  31. package/dist/spoke-checkout.d.ts +28 -27
  32. package/dist/spoke-checkout.js +71 -102
  33. package/dist/surfaces.d.ts +18 -0
  34. package/dist/surfaces.js +47 -282
  35. package/dist/sync-routes.d.ts +14 -1
  36. package/dist/sync-routes.js +86 -5
  37. package/dist/topology.d.ts +15 -1
  38. package/dist/topology.js +20 -4
  39. package/dist/update.d.ts +17 -2
  40. package/dist/update.js +480 -77
  41. package/package.json +3 -3
  42. package/templates/README.md +1 -1
  43. package/templates/apps/mcp/CLAUDE.md +5 -3
  44. package/templates/apps/web/CLAUDE.md +62 -20
  45. package/templates/apps/web/account.config.tsx +101 -0
  46. package/templates/apps/web/app/[locale]/(authed)/account/appointments/[slug]/page.tsx +3 -161
  47. package/templates/apps/web/app/[locale]/(authed)/account/appointments/page.tsx +3 -139
  48. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +3 -406
  49. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/versions/[version]/file/route.ts +2 -190
  50. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +3 -182
  51. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +8 -420
  52. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +1 -1
  53. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +8 -214
  54. package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +8 -115
  55. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/route.ts +2 -80
  56. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/page.tsx +8 -121
  57. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +3 -154
  58. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +7 -149
  59. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +3 -143
  60. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/page.tsx +3 -126
  61. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +8 -302
  62. package/templates/apps/web/app/[locale]/(authed)/account/privacy/export/route.ts +2 -102
  63. package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +3 -240
  64. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +3 -131
  65. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +2 -24
  66. package/templates/apps/web/app/[locale]/(authed)/account/support/page.tsx +3 -60
  67. package/templates/apps/web/app/[locale]/layout.tsx +45 -28
  68. package/templates/apps/web/app/apple-icon.tsx +72 -0
  69. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +22 -12
  70. package/templates/apps/web/app/og/__tests__/__snapshots__/card.test.tsx.snap +3 -0
  71. package/templates/apps/web/app/og/__tests__/card.test.tsx +129 -0
  72. package/templates/apps/web/app/og/__tests__/route.test.ts +3 -4
  73. package/templates/apps/web/app/og/route.tsx +155 -72
  74. package/templates/apps/web/app/sitemap.xml/__tests__/site-listing.test.ts +12 -0
  75. package/templates/apps/web/i18n/request.ts +44 -1
  76. package/templates/apps/web/jest.config.cjs +13 -1
  77. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +11 -0
  78. package/templates/apps/web/lib/__tests__/fixtures/site-topology.ts +70 -0
  79. package/templates/apps/web/lib/__tests__/nav-label-keys.test.ts +14 -0
  80. package/templates/apps/web/lib/__tests__/profile-back-link.test.ts +148 -61
  81. package/templates/apps/web/lib/__tests__/served-pages.test.ts +77 -0
  82. package/templates/apps/web/lib/__tests__/server-api.test.ts +37 -5
  83. package/templates/apps/web/lib/__tests__/structured-data.test.tsx +26 -13
  84. package/templates/apps/web/lib/listings.tsx +2 -2
  85. package/templates/apps/web/lib/nav-label-keys.ts +16 -2
  86. package/templates/apps/web/lib/paid-section-contracts.ts +35 -6
  87. package/templates/apps/web/lib/paid-sections.generated.ts +8 -0
  88. package/templates/apps/web/lib/profile-back-link.ts +105 -32
  89. package/templates/apps/web/lib/served-pages.ts +95 -0
  90. package/templates/apps/web/lib/site-brand.tsx +3 -5
  91. package/templates/apps/web/messages/en.json +8 -684
  92. package/templates/apps/web/middleware.ts +3 -1
  93. package/templates/apps/web/next.config.mjs +27 -0
  94. package/templates/apps/web/package.json +1 -0
  95. package/templates/customizations.yaml +9 -0
  96. package/templates/package.json +3 -1
  97. package/templates/tools/lint-architecture.ts +164 -11
  98. package/versions.json +48 -47
  99. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/account-frame-sign-out.test.tsx +0 -175
  100. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/agreements-prompt.test.tsx +0 -301
  101. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +0 -515
  102. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/general.test.tsx +0 -883
  103. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +0 -758
  104. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +0 -264
  105. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +0 -167
  106. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +0 -730
  107. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-menu.test.tsx +0 -355
  108. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-popups.test.tsx +0 -97
  109. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/notifications.test.tsx +0 -375
  110. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/onboarding.test.tsx +0 -323
  111. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +0 -1208
  112. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/popups.test.tsx +0 -418
  113. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +0 -462
  114. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/rich-translator.ts +0 -63
  115. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/security.test.tsx +0 -406
  116. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/settings.test.tsx +0 -93
  117. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/support.test.tsx +0 -208
  118. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/thread.test.tsx +0 -340
  119. package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +0 -182
  120. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +0 -353
  121. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +0 -57
  122. package/templates/apps/web/app/[locale]/(authed)/account/agreements-actions.ts +0 -58
  123. package/templates/apps/web/app/[locale]/(authed)/account/agreements-gate.ts +0 -61
  124. package/templates/apps/web/app/[locale]/(authed)/account/agreements-prompt.tsx +0 -184
  125. package/templates/apps/web/app/[locale]/(authed)/account/appointments/__tests__/page.test.tsx +0 -426
  126. package/templates/apps/web/app/[locale]/(authed)/account/appointments/appointments-data.ts +0 -76
  127. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/pay-form.tsx +0 -65
  128. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/review-form.tsx +0 -172
  129. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/file-route.test.ts +0 -333
  130. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/page.test.tsx +0 -936
  131. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/pay.test.tsx +0 -193
  132. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/review.test.tsx +0 -476
  133. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-actions.ts +0 -184
  134. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-data.ts +0 -197
  135. package/templates/apps/web/app/[locale]/(authed)/account/billing/__tests__/offerings.test.ts +0 -99
  136. package/templates/apps/web/app/[locale]/(authed)/account/billing/offerings.ts +0 -123
  137. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +0 -303
  138. package/templates/apps/web/app/[locale]/(authed)/account/components/request-quote.tsx +0 -274
  139. package/templates/apps/web/app/[locale]/(authed)/account/error-row.tsx +0 -35
  140. package/templates/apps/web/app/[locale]/(authed)/account/for-you-labels.ts +0 -36
  141. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +0 -215
  142. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +0 -65
  143. package/templates/apps/web/app/[locale]/(authed)/account/general/account-name.ts +0 -36
  144. package/templates/apps/web/app/[locale]/(authed)/account/general/billing-anchor.tsx +0 -27
  145. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-actions.ts +0 -149
  146. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-details.tsx +0 -42
  147. package/templates/apps/web/app/[locale]/(authed)/account/general/deletion-request.tsx +0 -132
  148. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +0 -122
  149. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +0 -215
  150. package/templates/apps/web/app/[locale]/(authed)/account/general/photo-actions.ts +0 -73
  151. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-form.tsx +0 -107
  152. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-source.ts +0 -87
  153. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/__tests__/route.test.ts +0 -215
  154. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/member-thread-composer.tsx +0 -43
  155. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-data.ts +0 -88
  156. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-write.ts +0 -31
  157. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +0 -35
  158. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +0 -266
  159. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +0 -116
  160. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +0 -12
  161. package/templates/apps/web/app/[locale]/(authed)/account/new-actions.ts +0 -219
  162. package/templates/apps/web/app/[locale]/(authed)/account/new-menu.tsx +0 -365
  163. package/templates/apps/web/app/[locale]/(authed)/account/new-popups.tsx +0 -86
  164. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/actions.ts +0 -120
  165. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/onboarding-form.tsx +0 -322
  166. package/templates/apps/web/app/[locale]/(authed)/account/privacy/__tests__/export-route.test.ts +0 -173
  167. package/templates/apps/web/app/[locale]/(authed)/account/privacy/actions.ts +0 -103
  168. package/templates/apps/web/app/[locale]/(authed)/account/profile-actions.ts +0 -116
  169. package/templates/apps/web/app/[locale]/(authed)/account/retry-button.tsx +0 -27
  170. package/templates/apps/web/app/[locale]/(authed)/account/security/__tests__/hub-variant.test.tsx +0 -258
  171. package/templates/apps/web/app/[locale]/(authed)/account/security/security-panel.tsx +0 -130
  172. package/templates/apps/web/app/[locale]/(authed)/account/security/security-source.ts +0 -92
  173. package/templates/apps/web/app/[locale]/(authed)/account/settings-frame.tsx +0 -121
  174. package/templates/apps/web/app/[locale]/(authed)/account/sign-in-method.ts +0 -37
  175. package/templates/apps/web/app/[locale]/(authed)/account/support/support-form.tsx +0 -98
  176. package/templates/apps/web/app/[locale]/(authed)/account/support-actions.ts +0 -100
  177. package/templates/apps/web/app/[locale]/checkout/__tests__/pages.test.tsx +0 -139
  178. package/templates/apps/web/app/[locale]/checkout/__tests__/thank-you-account.test.tsx +0 -146
  179. package/templates/apps/web/app/[locale]/checkout/thank-you/page.tsx +0 -114
  180. package/templates/apps/web/app/[locale]/checkout/unavailable/page.tsx +0 -51
  181. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +0 -614
  182. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.count.test.tsx +0 -43
  183. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.deliverable.test.tsx +0 -214
  184. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.ending.test.tsx +0 -197
  185. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.invite.test.tsx +0 -286
  186. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.permalink.test.tsx +0 -520
  187. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.test.tsx +0 -376
  188. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.thanks-by-tier.test.tsx +0 -306
  189. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/account-invite.actions.test.ts +0 -69
  190. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/flow.actions.test.ts +0 -398
  191. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +0 -704
  192. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/save.actions.test.ts +0 -173
  193. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/two-route-tool.test.tsx +0 -141
  194. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/verify.test.tsx +0 -249
  195. package/templates/apps/web/app/[locale]/flows/[slug]/account-invite.actions.ts +0 -35
  196. package/templates/apps/web/app/[locale]/flows/[slug]/email-moment.ts +0 -92
  197. package/templates/apps/web/app/[locale]/flows/[slug]/flow.actions.ts +0 -177
  198. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +0 -472
  199. package/templates/apps/web/app/[locale]/flows/[slug]/page.tsx +0 -48
  200. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/LevelChart.tsx +0 -100
  201. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsCard.tsx +0 -99
  202. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +0 -820
  203. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsEmailStep.tsx +0 -203
  204. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.no-commerce.test.tsx +0 -194
  205. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.report.test.tsx +0 -284
  206. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/by-result.test.tsx +0 -302
  207. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/cards.test.tsx +0 -402
  208. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/landing.test.tsx +0 -293
  209. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/page.test.tsx +0 -485
  210. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/score.test.tsx +0 -231
  211. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/checkout-seam.ts +0 -74
  212. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/meeting-seam.ts +0 -36
  213. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/page.tsx +0 -420
  214. package/templates/apps/web/app/[locale]/flows/[slug]/save.actions.ts +0 -85
  215. package/templates/apps/web/app/[locale]/flows/[slug]/served-flow.ts +0 -91
  216. package/templates/apps/web/app/[locale]/flows/[slug]/start/page.tsx +0 -32
  217. package/templates/apps/web/app/[locale]/flows/[slug]/verify/page.tsx +0 -153
  218. package/templates/apps/web/app/[locale]/flows/[slug]/verify.actions.ts +0 -151
  219. package/templates/apps/web/app/[locale]/meet/confirmed/BookingHandOff.tsx +0 -128
  220. package/templates/apps/web/app/[locale]/meet/confirmed/__tests__/BookingHandOff.test.tsx +0 -126
  221. package/templates/apps/web/app/[locale]/purchase/__tests__/cancel.test.tsx +0 -162
  222. package/templates/apps/web/app/[locale]/purchase/__tests__/module-scope.test.ts +0 -68
  223. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +0 -411
  224. package/templates/apps/web/app/[locale]/purchase/cancel/page.tsx +0 -115
  225. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +0 -348
  226. package/templates/apps/web/lib/__tests__/account-config.test.ts +0 -704
  227. package/templates/apps/web/lib/account-config.ts +0 -678
  228. package/templates/apps/web/lib/checkout-config.ts +0 -16
  229. package/templates/apps/web/src/lib/__tests__/commerce-sections.test.ts +0 -57
  230. package/templates/apps/web/src/lib/commerce-sections.ts +0 -55
@@ -1,173 +0,0 @@
1
- /**
2
- * Tests for Get your full report — `sendResultsEmailAction` (#11013 spec E,
3
- * D-F), the results page's email moment, which replaced "Email me this plan"
4
- * (`saveRecommendationAction`, #4842 D7 / #6786).
5
- *
6
- * AC-4 (the action half) — refuses a bad slug or body as `invalid_input`
7
- * without a call; `unavailable` on a refused bot check; on success calls
8
- * `flows.resultsEmail` once with the body and the visitor's IP init and
9
- * answers `{ ok: true }` — never an id. No `saveRecommendationAction`
10
- * export remains.
11
- * D7 — the shared status → kind map (`email-moment.ts`), never a throw.
12
- *
13
- * Mock shape: `checkout.actions.test.ts`'s (`@working-theory/api-client` +
14
- * `next/headers`).
15
- */
16
-
17
- import * as actions from "../save.actions.js";
18
- import { sendResultsEmailAction } from "../save.actions.js";
19
-
20
- // #9255 — the write bot check's verdict. `checkBotId` reads Vercel's
21
- // request context, which jest has none of, so every case decides it here.
22
- const checkBotIdMock = jest.fn();
23
- jest.mock("botid/server", () => ({
24
- checkBotId: (...args: unknown[]) => checkBotIdMock(...args),
25
- }));
26
-
27
- jest.mock("@working-theory/api-client", () => ({
28
- flows: {
29
- resultsEmail: jest.fn(),
30
- save: jest.fn(),
31
- },
32
- }));
33
-
34
- jest.mock("next/headers", () => ({
35
- __esModule: true,
36
- headers: jest.fn().mockResolvedValue({ get: () => null }),
37
- }));
38
-
39
- import { flows } from "@working-theory/api-client";
40
- import { headers } from "next/headers";
41
-
42
- const mockResultsEmail = flows.resultsEmail as jest.Mock;
43
- const mockSave = flows.save as jest.Mock;
44
- const mockHeaders = headers as jest.Mock;
45
-
46
- const SLUG = "ailk-recommender";
47
- const ANSWERS = { team_size: "agency", wants_seo: "yes" };
48
- const BODY = { answers: ANSWERS, email: "jane@example.com", locale: "en" };
49
-
50
- beforeEach(() => {
51
- jest.spyOn(console, "error").mockImplementation(() => undefined);
52
- });
53
-
54
- afterEach(() => {
55
- jest.clearAllMocks();
56
- jest.restoreAllMocks();
57
- mockHeaders.mockResolvedValue({ get: () => null });
58
- });
59
-
60
- describe("sendResultsEmailAction — AC-4 (the action half)", () => {
61
- it("calls flows.resultsEmail once with the body and answers { ok: true } with no id", async () => {
62
- mockResultsEmail.mockResolvedValueOnce({ ok: true, body: { sent: true } });
63
- await expect(sendResultsEmailAction(SLUG, BODY)).resolves.toEqual({ ok: true });
64
- expect(mockResultsEmail).toHaveBeenCalledTimes(1);
65
- expect(mockResultsEmail).toHaveBeenCalledWith(SLUG, BODY);
66
- expect(mockSave).not.toHaveBeenCalled();
67
- });
68
-
69
- it("forwards the stored session id when the body carries one", async () => {
70
- mockResultsEmail.mockResolvedValueOnce({ ok: true, body: { sent: true } });
71
- await sendResultsEmailAction(SLUG, { ...BODY, sessionId: "fs_1" });
72
- expect(mockResultsEmail).toHaveBeenCalledWith(SLUG, { ...BODY, sessionId: "fs_1" });
73
- });
74
-
75
- it("maps failures through the shared status → kind map and never throws", async () => {
76
- mockResultsEmail.mockResolvedValueOnce({ ok: false, status: 429, body: { retryAfterSeconds: 9 } });
77
- await expect(sendResultsEmailAction(SLUG, BODY)).resolves.toEqual({
78
- ok: false,
79
- kind: "rate_limited",
80
- retryAfterSeconds: 9,
81
- });
82
- mockResultsEmail.mockResolvedValueOnce({ ok: false, status: 409, body: null });
83
- await expect(sendResultsEmailAction(SLUG, BODY)).resolves.toEqual({ ok: false, kind: "not_configured" });
84
- mockResultsEmail.mockRejectedValueOnce(new Error("boom"));
85
- await expect(sendResultsEmailAction(SLUG, BODY)).resolves.toEqual({ ok: false, kind: "network" });
86
- expect(mockResultsEmail).toHaveBeenCalledTimes(3);
87
- });
88
-
89
- it.each([
90
- ["a bad email", SLUG, { ...BODY, email: "nope" }],
91
- ["an unknown body key", SLUG, { ...BODY, consents: { marketing: true } }],
92
- ["a bad slug", "Not A Slug", BODY],
93
- ])("%s is invalid_input with no call", async (_label, slug, body) => {
94
- await expect(sendResultsEmailAction(slug, body as typeof BODY)).resolves.toEqual({
95
- ok: false,
96
- kind: "invalid_input",
97
- });
98
- expect(mockResultsEmail).not.toHaveBeenCalled();
99
- expect(checkBotIdMock).not.toHaveBeenCalled();
100
- });
101
-
102
- it("forwards the visitor's x-forwarded-for on the outbound call (#4730)", async () => {
103
- mockHeaders.mockResolvedValueOnce({
104
- get: (name: string) => (name === "x-forwarded-for" ? "203.0.113.7" : null),
105
- });
106
- mockResultsEmail.mockResolvedValueOnce({ ok: true, body: { sent: true } });
107
- await sendResultsEmailAction(SLUG, BODY);
108
- expect(mockResultsEmail).toHaveBeenCalledWith(SLUG, BODY, {
109
- headers: { "x-forwarded-for": "203.0.113.7" },
110
- });
111
- });
112
-
113
- it("no saveRecommendationAction export remains", () => {
114
- expect(Object.keys(actions)).not.toContain("saveRecommendationAction");
115
- });
116
- });
117
-
118
- // #9255 D4 — the write bot check runs after the slug and body checks,
119
- // immediately before the write.
120
- describe("sendResultsEmailAction — the write bot check (#9255)", () => {
121
- const BOT = { isHuman: false, isBot: true, isVerifiedBot: false, bypassed: false };
122
- const HUMAN = { ...BOT, isHuman: true, isBot: false };
123
- const BOT_ENV_KEYS = ["VERCEL", "AILK_BOT_CHECK", "AILK_BOOKING_BOT_CHECK"] as const;
124
- const priorBotEnv = new Map(BOT_ENV_KEYS.map((name) => [name, process.env[name]]));
125
-
126
- let botLogSpies: jest.SpyInstance[] = [];
127
-
128
- beforeEach(() => {
129
- checkBotIdMock.mockReset();
130
- for (const name of BOT_ENV_KEYS) delete process.env[name];
131
- process.env.VERCEL = "1";
132
- botLogSpies = [
133
- jest.spyOn(console, "warn").mockImplementation(() => undefined),
134
- jest.spyOn(console, "error").mockImplementation(() => undefined),
135
- ];
136
- });
137
-
138
- afterEach(() => {
139
- for (const [name, value] of priorBotEnv) {
140
- if (value === undefined) delete process.env[name];
141
- else process.env[name] = value;
142
- }
143
- for (const spy of botLogSpies) spy.mockRestore();
144
- });
145
-
146
- it.each([
147
- ["a bot", () => checkBotIdMock.mockResolvedValue(BOT)],
148
- ["a check that fails", () => checkBotIdMock.mockRejectedValue(new Error("boom"))],
149
- ])("%s gets kind unavailable, and nothing is sent", async (_label, decide) => {
150
- decide();
151
- expect(await sendResultsEmailAction(SLUG, BODY)).toStrictEqual({ ok: false, kind: "unavailable" });
152
- expect(checkBotIdMock).toHaveBeenCalledTimes(1);
153
- expect(mockResultsEmail).not.toHaveBeenCalled();
154
- });
155
-
156
- it("a human sends exactly what the check off sends", async () => {
157
- checkBotIdMock.mockResolvedValue(HUMAN);
158
- mockResultsEmail.mockResolvedValue({ ok: true, status: 200, body: { sent: true } });
159
- delete process.env.VERCEL;
160
- await sendResultsEmailAction(SLUG, BODY);
161
- process.env.VERCEL = "1";
162
- expect(await sendResultsEmailAction(SLUG, BODY)).toEqual({ ok: true });
163
- expect(checkBotIdMock).toHaveBeenCalledTimes(1);
164
- expect(mockResultsEmail).toHaveBeenCalledTimes(2);
165
- expect(mockResultsEmail.mock.calls[1]).toEqual(mockResultsEmail.mock.calls[0]);
166
- });
167
-
168
- it("an invalid slug answers invalid_input with no check", async () => {
169
- checkBotIdMock.mockResolvedValue(BOT);
170
- expect(await sendResultsEmailAction("Not A Slug", BODY)).toEqual({ ok: false, kind: "invalid_input" });
171
- expect(checkBotIdMock).not.toHaveBeenCalled();
172
- });
173
- });
@@ -1,141 +0,0 @@
1
- // oss: false
2
- /**
3
- * #5053 — an interactive tool is two routes.
4
- *
5
- * The defect this convention closes is SILENT: a flow mounted at a bare
6
- * route renders fine, the walk works, and nothing surfaces that the tool is
7
- * invisible to search and to answer engines. So the assertions below are the
8
- * only thing standing between the convention and a quiet regression.
9
- *
10
- * Three claims are pinned here:
11
- * 1. The flow route carries `noindex, follow` — and gets it from
12
- * `flowRouteMetadata`, not from a robots line written into the route
13
- * (D4: mounted, not remembered). The source-level assertion is
14
- * deliberate: re-inlining the value would satisfy a value-only test
15
- * while losing the property the decision is actually about.
16
- * 2. The landing route sets no `robots` at all, so it indexes.
17
- * 3. The landing emits the `Assessment` page type's SINGLE-LAYER
18
- * `@type: "WebApplication"` — no `WebPage` envelope, no `mainEntity`
19
- * (D2, resting on #5019). The consuming site's two-layer shape is not
20
- * adopted, and this is what fails if someone adopts it.
21
- */
22
- import { readFileSync } from "node:fs";
23
- import { join } from "node:path";
24
-
25
- import { render } from "@testing-library/react";
26
- import type { FlowConfig } from "@working-theory/validation";
27
-
28
- const mockGet = jest.fn();
29
- jest.mock("@working-theory/api-client", () => ({
30
- __esModule: true,
31
- flows: { get: (...args: unknown[]) => mockGet(...args) },
32
- }));
33
-
34
- jest.mock("next/navigation", () => ({
35
- __esModule: true,
36
- notFound: () => {
37
- throw new Error("NEXT_NOT_FOUND");
38
- },
39
- }));
40
-
41
- jest.mock("next-intl/server", () => ({
42
- __esModule: true,
43
- getTranslations: async () => (key: string) => key,
44
- }));
45
-
46
- jest.mock("@working-theory/ui/sections", () => ({
47
- __esModule: true,
48
- SectionRenderer: () => null,
49
- }));
50
-
51
- import LandingPage, { generateMetadata as landingMetadata } from "../page";
52
- import { generateMetadata as flowMetadata } from "../start/page";
53
-
54
- const SLUG = "readiness-check";
55
-
56
- function fixtureConfig(): FlowConfig {
57
- return {
58
- slug: SLUG,
59
- defaultLocale: "en",
60
- steps: [
61
- {
62
- key: "team",
63
- type: "segmentation",
64
- copy: { title: { en: "How ready is your site?" } },
65
- questions: [
66
- {
67
- name: "team_size",
68
- options: [
69
- { value: "solo", label: { en: "Solo" } },
70
- { value: "agency", label: { en: "Agency" } },
71
- ],
72
- },
73
- ],
74
- },
75
- ],
76
- } as FlowConfig;
77
- }
78
-
79
- // #8840 D8 — both routes render through `magnet-page.tsx`, which shares one
80
- // slug's read for 15 seconds per instance; each test starts an hour later so
81
- // none sees another's read.
82
- let clock = 1_800_000_000_000;
83
- jest.spyOn(Date, "now").mockImplementation(() => clock);
84
-
85
- beforeEach(() => {
86
- clock += 60 * 60 * 1000;
87
- mockGet.mockReset();
88
- mockGet.mockResolvedValue({ ok: true, body: fixtureConfig() });
89
- });
90
-
91
- const params = Promise.resolve({ locale: "en", slug: SLUG });
92
-
93
- describe("the flow route", () => {
94
- it("carries noindex, follow", async () => {
95
- const metadata = await flowMetadata({ params });
96
- expect(metadata.robots).toEqual({ index: false, follow: true });
97
- });
98
-
99
- it("still carries noindex, follow when the flow is not configured", async () => {
100
- mockGet.mockResolvedValue({ ok: false, error: "flow_not_found" });
101
- const metadata = await flowMetadata({ params });
102
- expect(metadata.robots).toEqual({ index: false, follow: true });
103
- });
104
-
105
- // #8840 D8 — the route mounts the standard renderer, which mounts
106
- // `flowRouteMetadata`; neither writes the robots value itself.
107
- it("gets the value from flowRouteMetadata rather than writing it", () => {
108
- const strip = (file: string) =>
109
- readFileSync(join(__dirname, "..", file), "utf8")
110
- .replace(/\/\*[\s\S]*?\*\//g, "")
111
- .replace(/\/\/.*$/gm, "");
112
- const route = strip(join("start", "page.tsx"));
113
- const renderer = strip("magnet-page.tsx");
114
- expect(route).toContain("renderMagnetStartMetadata");
115
- expect(renderer).toContain("flowRouteMetadata");
116
- for (const code of [route, renderer]) {
117
- expect(code).not.toMatch(/robots/i);
118
- expect(code).not.toMatch(/noindex/i);
119
- }
120
- });
121
- });
122
-
123
- describe("the landing route", () => {
124
- it("sets no robots value, so it indexes", async () => {
125
- const metadata = await landingMetadata({ params });
126
- expect(metadata.robots).toBeUndefined();
127
- expect(metadata.title).toBe("How ready is your site?");
128
- });
129
-
130
- it("emits the single-layer WebApplication shape, with no WebPage envelope", async () => {
131
- const { container } = render(await LandingPage({ params }));
132
- const script = container.querySelector(
133
- 'script[type="application/ld+json"]',
134
- );
135
- const emitted = JSON.parse(script!.innerHTML) as Record<string, unknown>;
136
-
137
- expect(emitted["@type"]).toBe("WebApplication");
138
- expect(emitted).not.toHaveProperty("mainEntity");
139
- expect(emitted["name"]).toBe("How ready is your site?");
140
- });
141
- });
@@ -1,249 +0,0 @@
1
- /**
2
- * A magnet Lead's confirm page and action (#10826, spec
3
- * docs/specs/10826-the-four-conversions-as-completion-spec.md D5; AC-2).
4
- *
5
- * The page: `?lead=L&verify=N` renders one confirm button and calls no API
6
- * while it renders; `?confirmed=1` and `?error=…` render their cards.
7
- * The action: every bound argument is re-checked before any API call; the
8
- * limit and the bot check run first; the API's answer picks the redirect,
9
- * which is always same-site and never carries the nonce.
10
- */
11
- import { render, screen } from "@testing-library/react";
12
-
13
- import en from "../../../../../messages/en.json";
14
-
15
- const mockRedirect = jest.fn((url: string) => {
16
- throw new Error(`REDIRECT ${url}`);
17
- });
18
- const mockNotFound = jest.fn(() => {
19
- throw new Error("NOT_FOUND");
20
- });
21
- jest.mock("next/navigation", () => ({
22
- redirect: (url: string) => mockRedirect(url),
23
- notFound: () => mockNotFound(),
24
- }));
25
-
26
- const mockHeaders = jest.fn(
27
- async () => new Headers({ "x-forwarded-for": "203.0.113.9" }),
28
- );
29
- jest.mock("next/headers", () => ({
30
- headers: () => mockHeaders(),
31
- }));
32
-
33
- const mockRunBotCheck = jest.fn();
34
- // eslint-disable-next-line no-restricted-syntax -- BotID is an external service boundary; lib/bot-check.ts is its one wrapper.
35
- jest.mock("../../../../../lib/bot-check", () => ({
36
- runBotCheck: (...args: unknown[]) => mockRunBotCheck(...args),
37
- }));
38
-
39
- const mockVerifyLead = jest.fn();
40
- jest.mock("@working-theory/api-client", () => ({
41
- flows: { verifyLead: (...args: unknown[]) => mockVerifyLead(...args) },
42
- }));
43
-
44
- import { __resetRateLimit } from "../../../../../src/lib/rate-limit";
45
- import FlowVerifyPage from "../verify/page";
46
- import { confirmLeadEmailAction } from "../verify.actions";
47
-
48
- const SLUG = "growth-check";
49
- const LEAD = "lead_01920000-1082-7000-8000-000000000001";
50
- const NONCE = "N".repeat(43);
51
-
52
- async function renderPage(
53
- query: Record<string, string>,
54
- slug = SLUG,
55
- ): Promise<void> {
56
- render(
57
- await FlowVerifyPage({
58
- params: Promise.resolve({ locale: "en", slug }),
59
- searchParams: Promise.resolve(query),
60
- }),
61
- );
62
- }
63
-
64
- /** Run the action; answer the redirect URL, asserting it never carries the nonce. */
65
- async function redirectOf(
66
- args: [slug?: string, leadId?: string, nonce?: string, locale?: string] = [],
67
- ): Promise<string> {
68
- const [slug = SLUG, leadId = LEAD, nonce = NONCE, locale = "en"] = args;
69
- await expect(
70
- confirmLeadEmailAction(slug, leadId, nonce, locale),
71
- ).rejects.toThrow(/^REDIRECT /);
72
- const url = mockRedirect.mock.calls.at(-1)![0];
73
- if (nonce.length > 0) expect(url).not.toContain(nonce);
74
- return url;
75
- }
76
-
77
- const answer = (body: Record<string, unknown>) =>
78
- mockVerifyLead.mockResolvedValue({ ok: true, body });
79
-
80
- beforeEach(() => {
81
- jest.clearAllMocks();
82
- __resetRateLimit();
83
- mockRunBotCheck.mockResolvedValue("pass");
84
- answer({ outcome: "verified", landing: null });
85
- });
86
-
87
- describe("the confirm page (#10826 D5)", () => {
88
- it("renders one confirm button on ?lead=&verify= and calls no API while rendering", async () => {
89
- await renderPage({ lead: LEAD, verify: NONCE });
90
- expect(screen.getByTestId("flow-verify-confirm")).toBeInTheDocument();
91
- expect(screen.getByTestId("flow-verify-confirm-button")).toHaveTextContent(
92
- en.flowVerify.confirmButton,
93
- );
94
- expect(mockVerifyLead).not.toHaveBeenCalled();
95
- expect(mockRedirect).not.toHaveBeenCalled();
96
- expect(document.body.innerHTML).not.toContain(NONCE);
97
- });
98
-
99
- it("renders the confirmed card on ?confirmed=1", async () => {
100
- await renderPage({ confirmed: "1" });
101
- expect(screen.getByTestId("flow-verify-confirmed")).toHaveTextContent(
102
- en.flowVerify.confirmedHeading,
103
- );
104
- });
105
-
106
- it.each([
107
- ["?error=invalid", { error: "invalid" }],
108
- ["no query", {}],
109
- ["a lead id of the wrong shape", { lead: "x", verify: NONCE }],
110
- ["a 257-character nonce", { lead: LEAD, verify: "N".repeat(257) }],
111
- ])("renders the error card on %s", async (_label, query) => {
112
- await renderPage(query);
113
- expect(screen.getByTestId("flow-verify-error")).toHaveTextContent(
114
- en.flowVerify.errorHeading,
115
- );
116
- expect(mockVerifyLead).not.toHaveBeenCalled();
117
- });
118
-
119
- it("verify wins over confirmed, and confirmed over error", async () => {
120
- await renderPage({
121
- lead: LEAD,
122
- verify: NONCE,
123
- confirmed: "1",
124
- error: "invalid",
125
- });
126
- expect(screen.getByTestId("flow-verify-confirm")).toBeInTheDocument();
127
- });
128
-
129
- it("is a 404 for an unreadable slug", async () => {
130
- await expect(
131
- renderPage({ lead: LEAD, verify: NONCE }, "Bad_Slug"),
132
- ).rejects.toThrow("NOT_FOUND");
133
- });
134
- });
135
-
136
- describe("confirmLeadEmailAction (#10826 D5)", () => {
137
- it("posts the bound Lead id and nonce, forwarding the visitor's address", async () => {
138
- await redirectOf();
139
- expect(mockVerifyLead).toHaveBeenCalledWith(
140
- SLUG,
141
- { leadId: LEAD, nonce: NONCE },
142
- { headers: { "x-forwarded-for": "203.0.113.9" } },
143
- );
144
- });
145
-
146
- it("redirects a verified lead-link confirm to its landing", async () => {
147
- answer({ outcome: "verified", landing: "/pricing?plan=growth" });
148
- expect(await redirectOf()).toBe("/pricing?plan=growth");
149
- });
150
-
151
- it("redirects to the confirmed card on already_verified with no landing", async () => {
152
- answer({ outcome: "already_verified", landing: null });
153
- expect(await redirectOf()).toBe(`/flows/${SLUG}/verify?confirmed=1`);
154
- });
155
-
156
- it("redirects a user magnet's verified Lead to the sign-up landing (accountInviteHref)", async () => {
157
- answer({
158
- outcome: "verified",
159
- landing: null,
160
- signUpEmail: "a+b@x.example",
161
- });
162
- expect(await redirectOf()).toBe(
163
- "/sign-in?next=%2Faccount&email=a%2Bb%40x.example",
164
- );
165
- });
166
-
167
- it.each([
168
- "//evil.example",
169
- "/\\evil.example",
170
- "https://evil.example",
171
- "/\t/evil.example",
172
- "/\n/evil.example",
173
- "/ok path",
174
- "/ok\\..\\evil",
175
- ])("never redirects to a landing of %s (SEC-10826-5)", async (landing) => {
176
- answer({ outcome: "verified", landing });
177
- expect(await redirectOf()).toBe(`/flows/${SLUG}/verify?confirmed=1`);
178
- });
179
-
180
- it.each([
181
- ["expired", { ok: true, body: { outcome: "expired", landing: null } }],
182
- ["invalid", { ok: true, body: { outcome: "invalid", landing: null } }],
183
- ["a non-2xx", { ok: false, status: 503 }],
184
- ])("redirects to the error card on %s", async (_label, res) => {
185
- mockVerifyLead.mockResolvedValue(res);
186
- expect(await redirectOf()).toBe(`/flows/${SLUG}/verify?error=invalid`);
187
- });
188
-
189
- it("redirects to the error card when the call throws", async () => {
190
- mockVerifyLead.mockRejectedValue(new Error("boom"));
191
- expect(await redirectOf()).toBe(`/flows/${SLUG}/verify?error=invalid`);
192
- });
193
-
194
- it.each(["bot", "unavailable"])(
195
- "makes no API call when the bot check answers %s",
196
- async (verdict) => {
197
- mockRunBotCheck.mockResolvedValue(verdict);
198
- expect(await redirectOf()).toBe(`/flows/${SLUG}/verify?error=invalid`);
199
- expect(mockVerifyLead).not.toHaveBeenCalled();
200
- },
201
- );
202
-
203
- it("makes no API call once the visitor's limit (5 per 10 minutes) is spent", async () => {
204
- const vercel = process.env.VERCEL;
205
- process.env.VERCEL = "1";
206
- mockHeaders.mockImplementation(
207
- async () => new Headers({ "x-vercel-forwarded-for": "203.0.113.9" }),
208
- );
209
- try {
210
- for (let i = 0; i < 5; i++) await redirectOf();
211
- mockVerifyLead.mockClear();
212
- expect(await redirectOf()).toBe(`/flows/${SLUG}/verify?error=invalid`);
213
- expect(mockVerifyLead).not.toHaveBeenCalled();
214
- } finally {
215
- if (vercel === undefined) delete process.env.VERCEL;
216
- else process.env.VERCEL = vercel;
217
- mockHeaders.mockImplementation(
218
- async () => new Headers({ "x-forwarded-for": "203.0.113.9" }),
219
- );
220
- }
221
- });
222
-
223
- it.each([
224
- ["a traversal slug", ["x/../../v1/other"], "/?error=invalid"],
225
- [
226
- "a locale that is not enabled",
227
- [SLUG, LEAD, NONCE, "/evil.example"],
228
- `/flows/${SLUG}/verify?error=invalid`,
229
- ],
230
- [
231
- "a 257-character nonce",
232
- [SLUG, LEAD, "N".repeat(257)],
233
- `/flows/${SLUG}/verify?error=invalid`,
234
- ],
235
- ["an empty nonce", [SLUG, LEAD, ""], `/flows/${SLUG}/verify?error=invalid`],
236
- [
237
- "a Lead id of the wrong shape",
238
- [SLUG, "lead_x"],
239
- `/flows/${SLUG}/verify?error=invalid`,
240
- ],
241
- ] as const)(
242
- "refuses %s with no API call (SEC-10826-6)",
243
- async (_label, args, href) => {
244
- expect(await redirectOf([...args])).toBe(href);
245
- expect(mockVerifyLead).not.toHaveBeenCalled();
246
- expect(mockRunBotCheck).not.toHaveBeenCalled();
247
- },
248
- );
249
- });
@@ -1,35 +0,0 @@
1
- // oss: false
2
- "use server";
3
-
4
- /**
5
- * accountInviteLinkAction — the walk's "Track this in your account" link
6
- * (#8771 D5). The walk's client holds the email the visitor typed; this builds
7
- * the sign-in link that starts with that email prefilled, using #8757's
8
- * `accountInviteHref`. It is a Server Action, not client code, because
9
- * `accountInviteHref` reads the generated topology module, which lazily
10
- * imports `../auth` and must never reach a client bundle.
11
- *
12
- * It makes no API call and writes nothing — the invite email is sent by the
13
- * API at completion. No MCP twin: it builds a link from the visitor's own
14
- * email for a browser to follow (`WEB_ONLY_ACTIONS` in
15
- * `apps/mcp/__tests__/parity.test.ts`).
16
- *
17
- * Answers `null` for an email the hint schema refuses, a locale that cannot be
18
- * read, or a site with no sign-in — the walk then shows no link.
19
- */
20
- import { accountEmailHintSchema } from "@working-theory/validation";
21
- import { getLocale } from "next-intl/server";
22
-
23
- import { accountInviteHref } from "../../../../lib/account-invite";
24
-
25
- export async function accountInviteLinkAction(
26
- email: string,
27
- ): Promise<string | null> {
28
- const hint = accountEmailHintSchema.safeParse(email);
29
- if (!hint.success) return null;
30
- try {
31
- return accountInviteHref(await getLocale(), hint.data);
32
- } catch {
33
- return null;
34
- }
35
- }
@@ -1,92 +0,0 @@
1
- // oss: false
2
- /**
3
- * email-moment.ts — the helpers the recommender's two email-moment Server
4
- * Actions share (#4842 D7): `sendResultsEmailAction` (`save.actions.ts`,
5
- * shipped with the results page; #11013 D-F) and `startCheckoutAction`
6
- * (`checkout.actions.ts`, commerce's). Split out of `checkout.actions.ts` by
7
- * #6786 so the save half ships without the checkout half; a `"use server"`
8
- * file may export only async functions, so the shared sync helpers live here.
9
- *
10
- * Both actions mirror `submitFlowStepAction`'s idiom exactly: the visitor-IP
11
- * forwarding helper (duplicated here — the `flow.actions.ts` original is
12
- * module-private and that file is this unit's regression floor), a status →
13
- * kind map, and NEVER a throw to the client. Logging is PII-safe: slug + kind
14
- * only — the email is never logged.
15
- */
16
- import type { FlowSaveInput } from "@working-theory/validation";
17
- import { headers } from "next/headers";
18
-
19
- export type EmailMomentFailureKind =
20
- | "invalid_input"
21
- | "not_configured"
22
- | "rate_limited"
23
- | "unavailable"
24
- | "network";
25
-
26
- export interface EmailMomentFailure {
27
- ok: false;
28
- kind: EmailMomentFailureKind;
29
- retryAfterSeconds?: number;
30
- }
31
-
32
- /**
33
- * Reads the visitor's real IP from THIS action's own incoming request —
34
- * never from the browser-supplied payload — preferring `x-forwarded-for`
35
- * and falling back to `x-real-ip`. Returns `undefined` rather than throwing
36
- * on any failure (a local copy of `flow.actions.ts`'s helper, #4730).
37
- */
38
- export async function resolveVisitorIpInit(): Promise<
39
- { headers: Record<string, string> } | undefined
40
- > {
41
- try {
42
- const incoming = await headers();
43
- const visitorIp =
44
- incoming.get("x-forwarded-for") ?? incoming.get("x-real-ip");
45
- return visitorIp
46
- ? { headers: { "x-forwarded-for": visitorIp } }
47
- : undefined;
48
- } catch {
49
- return undefined;
50
- }
51
- }
52
-
53
- /** PII-safe error identity for logs — the `recommender.ts` idiom (`err.name` only). */
54
- export function errorName(err: unknown): string {
55
- return err instanceof Error ? err.name : "unknown";
56
- }
57
-
58
- /** The shared `status → kind` map (D7). Never throws. */
59
- export function failureFor(res: {
60
- status: number;
61
- body: unknown;
62
- }): EmailMomentFailure {
63
- if (res.status === 400) return { ok: false, kind: "invalid_input" };
64
- if (res.status === 409) return { ok: false, kind: "not_configured" };
65
- if (res.status === 429) {
66
- const body = res.body as { retryAfterSeconds?: number } | null;
67
- return {
68
- ok: false,
69
- kind: "rate_limited",
70
- ...(typeof body?.retryAfterSeconds === "number"
71
- ? { retryAfterSeconds: body.retryAfterSeconds }
72
- : {}),
73
- };
74
- }
75
- return { ok: false, kind: "unavailable" };
76
- }
77
-
78
- /**
79
- * exactOptionalPropertyTypes-safe rebuild of the parsed body: Zod's inferred
80
- * optional fields type as `T | undefined`, which does not structurally match
81
- * the api-client's `sessionId?: string` / `locale?: string` — so an absent
82
- * optional key is OMITTED rather than sent as an explicit `undefined`.
83
- */
84
- export function emailMomentFields(parsed: FlowSaveInput): FlowSaveInput {
85
- const { answers, email, locale, sessionId } = parsed;
86
- return {
87
- answers,
88
- email,
89
- ...(locale !== undefined ? { locale } : {}),
90
- ...(sessionId !== undefined ? { sessionId } : {}),
91
- };
92
- }