create-ailk 0.22.0 → 0.23.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 (238) hide show
  1. package/component-catalog.json +149 -5
  2. package/component-catalog.md +7 -6
  3. package/dist/add-module.js +11 -9
  4. package/dist/add-route.d.ts +55 -1
  5. package/dist/add-route.js +294 -12
  6. package/dist/cli.js +27 -10
  7. package/dist/derive-architecture.d.ts +7 -5
  8. package/dist/derive-architecture.js +9 -32
  9. package/dist/lib/design-checks.js +4 -2
  10. package/dist/lib/env-catalog.js +0 -4
  11. package/dist/lib/npm-auth.d.ts +9 -0
  12. package/dist/lib/npm-auth.js +48 -0
  13. package/dist/lib/scaffold-render-sweep.d.ts +3 -2
  14. package/dist/lib/scaffold-render-sweep.js +5 -8
  15. package/dist/module-architecture.js +98 -10
  16. package/dist/paid-sections.d.ts +21 -2
  17. package/dist/paid-sections.js +69 -7
  18. package/dist/seed-flows.d.ts +4 -1
  19. package/dist/seed-flows.js +50 -4
  20. package/dist/spoke-checkout.d.ts +38 -35
  21. package/dist/spoke-checkout.js +66 -229
  22. package/dist/starter-grid.d.ts +0 -3
  23. package/dist/starter-grid.js +24 -14
  24. package/dist/surfaces.js +33 -12
  25. package/dist/sync-routes.d.ts +38 -1
  26. package/dist/sync-routes.js +184 -11
  27. package/dist/template-record.d.ts +1 -1
  28. package/dist/template-record.js +3 -2
  29. package/dist/update.js +10 -0
  30. package/package.json +3 -3
  31. package/site-templates/_base/content/en/NewsletterSignup/newsletter.mdx +4 -49
  32. package/site-templates/_base/content/en/Pricing/pricing.mdx +3 -21
  33. package/site-templates/marketing-site/TEMPLATE-MANIFEST.json +23 -20
  34. package/site-templates/marketing-site/TEMPLATE-MANIFEST.md +28 -14
  35. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.json +15 -39
  36. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.md +38 -34
  37. package/site-templates/marketing-site-free/content/en/NewsletterSignup/newsletter.mdx +6 -43
  38. package/site-templates/shapes/local-business-service/TEMPLATE-MANIFEST.json +14 -31
  39. package/site-templates/shapes/local-business-service/TEMPLATE-MANIFEST.md +26 -25
  40. package/site-templates/shapes/local-business-service/content/en/NewsletterSignup/newsletter.mdx +6 -43
  41. package/site-templates/shapes/organization-service/TEMPLATE-MANIFEST.json +14 -31
  42. package/site-templates/shapes/organization-service/TEMPLATE-MANIFEST.md +26 -25
  43. package/site-templates/shapes/organization-service/content/en/NewsletterSignup/newsletter.mdx +6 -43
  44. package/site-templates/shapes/person-service/TEMPLATE-MANIFEST.json +14 -31
  45. package/site-templates/shapes/person-service/TEMPLATE-MANIFEST.md +26 -25
  46. package/site-templates/shapes/person-service/content/en/NewsletterSignup/newsletter.mdx +6 -43
  47. package/templates/.env.example +9 -7
  48. package/templates/.github/workflows/ci.yml +13 -0
  49. package/templates/README.md +1 -0
  50. package/templates/_gitignore +4 -0
  51. package/templates/apps/api/.env.example +27 -0
  52. package/templates/apps/api/CLAUDE.md +77 -16
  53. package/templates/apps/api/package.json +1 -0
  54. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +2 -0
  55. package/templates/apps/api/src/bin/stripe-connections-rekey.ts +45 -0
  56. package/templates/apps/api/src/config/__tests__/stripe-connection-key.test.ts +185 -0
  57. package/templates/apps/api/src/config/index.ts +109 -0
  58. package/templates/apps/api/src/lib/__mocks__/prisma.ts +3 -0
  59. package/templates/apps/api/src/lib/__tests__/flow-rename-race.db.test.ts +116 -0
  60. package/templates/apps/api/src/lib/error-serializer.ts +74 -7
  61. package/templates/apps/api/src/lib/stripe.ts +74 -4
  62. package/templates/apps/api/src/lib/webhook-idempotency.ts +66 -2
  63. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +218 -0
  64. package/templates/apps/api/src/middleware/__tests__/write-budget.test.ts +174 -0
  65. package/templates/apps/api/src/middleware/rate-limit.ts +226 -4
  66. package/templates/apps/api/src/openapi/spec.ts +10 -7
  67. package/templates/apps/api/src/routes/billing/plan-checkout.ts +325 -0
  68. package/templates/apps/api/src/routes/checkout/__tests__/live-key.test.ts +11 -0
  69. package/templates/apps/api/src/routes/checkout/__tests__/offerings-authorization.test.ts +1300 -0
  70. package/templates/apps/api/src/routes/checkout/__tests__/session.test.ts +11 -0
  71. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +49 -0
  72. package/templates/apps/api/src/routes/checkout/session.ts +57 -25
  73. package/templates/apps/api/src/routes/checkout/sessions.ts +232 -82
  74. package/templates/apps/api/src/routes/consent/__tests__/account.test.ts +5 -5
  75. package/templates/apps/api/src/routes/consent/__tests__/sign-up-rate-limit.test.ts +160 -0
  76. package/templates/apps/api/src/routes/consent/account.ts +4 -2
  77. package/templates/apps/api/src/routes/content/__tests__/get-page.test.ts +2 -2
  78. package/templates/apps/api/src/routes/content/__tests__/offerings.test.ts +731 -0
  79. package/templates/apps/api/src/routes/content/__tests__/pricing.test.ts +753 -0
  80. package/templates/apps/api/src/routes/content/__tests__/shown-offerings.test.ts +762 -0
  81. package/templates/apps/api/src/routes/content/index.ts +16 -2
  82. package/templates/apps/api/src/routes/content/offerings.ts +184 -0
  83. package/templates/apps/api/src/routes/content/pricing.ts +176 -0
  84. package/templates/apps/api/src/routes/content/shown-offerings.ts +229 -0
  85. package/templates/apps/api/src/routes/leads/index.ts +17 -14
  86. package/templates/apps/api/src/routes/webhooks/README.md +66 -0
  87. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-offerings.test.ts +814 -0
  88. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-org-billing.test.ts +80 -68
  89. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +5 -5
  90. package/templates/apps/api/src/routes/webhooks/__tests__/stripe.test.ts +8 -2
  91. package/templates/apps/api/src/routes/webhooks/index.ts +23 -0
  92. package/templates/apps/api/src/routes/webhooks/stripe-offerings.ts +384 -0
  93. package/templates/apps/api/src/routes/webhooks/stripe.ts +91 -17
  94. package/templates/apps/api/src/server.ts +140 -51
  95. package/templates/apps/api/src/services/__tests__/checkout-plan.test.ts +313 -0
  96. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +51 -2
  97. package/templates/apps/api/src/services/__tests__/keyless-workspace-predicate.test.ts +234 -0
  98. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +374 -44
  99. package/templates/apps/api/src/services/__tests__/person.test.ts +232 -1
  100. package/templates/apps/api/src/services/__tests__/plan-offerings.test.ts +444 -0
  101. package/templates/apps/api/src/services/deliverable-fulfillment.ts +13 -5
  102. package/templates/apps/api/src/services/entitlements.ts +157 -1
  103. package/templates/apps/api/src/services/lead-routing.ts +113 -58
  104. package/templates/apps/api/src/services/offerings/__tests__/catalog.test.ts +295 -0
  105. package/templates/apps/api/src/services/offerings/__tests__/checkout-session-record.test.ts +268 -0
  106. package/templates/apps/api/src/services/offerings/__tests__/connection.test.ts +868 -0
  107. package/templates/apps/api/src/services/offerings/__tests__/fixtures.ts +416 -0
  108. package/templates/apps/api/src/services/offerings/__tests__/org-products.test.ts +396 -0
  109. package/templates/apps/api/src/services/offerings/__tests__/readers.test.ts +681 -0
  110. package/templates/apps/api/src/services/offerings/__tests__/source.test.ts +231 -0
  111. package/templates/apps/api/src/services/offerings/catalog.ts +308 -0
  112. package/templates/apps/api/src/services/offerings/checkout-authorization.ts +385 -0
  113. package/templates/apps/api/src/services/offerings/checkout-session-record.ts +192 -0
  114. package/templates/apps/api/src/services/offerings/connection.ts +1003 -0
  115. package/templates/apps/api/src/services/offerings/index.ts +614 -0
  116. package/templates/apps/api/src/services/offerings/source.ts +140 -0
  117. package/templates/apps/api/src/services/offerings/store.ts +150 -0
  118. package/templates/apps/api/src/services/person.ts +124 -9
  119. package/templates/apps/api/src/services/plan-offerings.ts +96 -30
  120. package/templates/apps/api/src/services/public-site-resolver.ts +19 -14
  121. package/templates/apps/mcp/CLAUDE.md +22 -14
  122. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +9 -4
  123. package/templates/apps/mcp/__tests__/get_offerings.test.ts +358 -0
  124. package/templates/apps/mcp/__tests__/get_pricing.test.ts +364 -0
  125. package/templates/apps/mcp/__tests__/http-transport.test.ts +4 -4
  126. package/templates/apps/mcp/__tests__/module-exclusion.test.ts +2 -2
  127. package/templates/apps/mcp/__tests__/server.test.ts +13 -11
  128. package/templates/apps/mcp/__tests__/start_purchase.test.ts +208 -12
  129. package/templates/apps/mcp/__tests__/tools/purchase.test.ts +11 -11
  130. package/templates/apps/mcp/src/lib/shown-offerings.ts +105 -0
  131. package/templates/apps/mcp/src/server.ts +5 -0
  132. package/templates/apps/mcp/src/tools/get_offerings.ts +47 -30
  133. package/templates/apps/mcp/src/tools/get_pricing.ts +40 -40
  134. package/templates/apps/mcp/src/tools/purchase.ts +30 -2
  135. package/templates/apps/mcp/src/workspace-server.ts +15 -0
  136. package/templates/apps/web/.env.example +10 -31
  137. package/templates/apps/web/CLAUDE.md +315 -42
  138. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/agreements-prompt.test.tsx +3 -3
  139. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +3 -3
  140. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +3 -3
  141. package/templates/apps/web/app/[locale]/careers/[slug]/[action]/page.tsx +189 -0
  142. package/templates/apps/web/app/[locale]/careers/[slug]/apply.actions.ts +4 -2
  143. package/templates/apps/web/app/[locale]/careers/[slug]/job-application-form.ts +8 -3
  144. package/templates/apps/web/app/[locale]/careers/[slug]/page.tsx +22 -144
  145. package/templates/apps/web/app/[locale]/careers/__tests__/apply.actions.test.ts +9 -0
  146. package/templates/apps/web/app/[locale]/careers/__tests__/careers-hub.test.tsx +172 -0
  147. package/templates/apps/web/app/[locale]/careers/__tests__/careers-set.test.tsx +149 -0
  148. package/templates/apps/web/app/[locale]/careers/__tests__/job-application-form.test.ts +22 -24
  149. package/templates/apps/web/app/[locale]/careers/__tests__/job-apply-page.test.tsx +140 -66
  150. package/templates/apps/web/app/[locale]/careers/__tests__/page-renderer-migration.test.tsx +57 -22
  151. package/templates/apps/web/app/[locale]/careers/page.tsx +129 -5
  152. package/templates/apps/web/app/[locale]/contact/__tests__/contact-magnet-page.test.tsx +119 -11
  153. package/templates/apps/web/app/[locale]/contact/__tests__/contact.actions.test.ts +28 -5
  154. package/templates/apps/web/app/[locale]/contact/contact.actions.ts +6 -2
  155. package/templates/apps/web/app/[locale]/contact/page.tsx +99 -92
  156. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +237 -5
  157. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.count.test.tsx +43 -0
  158. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.deliverable.test.tsx +200 -0
  159. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.ending.test.tsx +197 -0
  160. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +430 -0
  161. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/two-route-tool.test.tsx +21 -9
  162. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +352 -0
  163. package/templates/apps/web/app/[locale]/flows/[slug]/page.tsx +12 -73
  164. package/templates/apps/web/app/[locale]/flows/[slug]/start/page.tsx +10 -31
  165. package/templates/apps/web/app/[locale]/layout.tsx +55 -4
  166. package/templates/apps/web/app/[locale]/newsletter/__tests__/page.test.tsx +174 -104
  167. package/templates/apps/web/app/[locale]/newsletter/page.tsx +95 -58
  168. package/templates/apps/web/app/[locale]/pricing/__tests__/__snapshots__/unconnected.test.tsx.snap +7 -0
  169. package/templates/apps/web/app/[locale]/pricing/__tests__/offerings.test.tsx +599 -0
  170. package/templates/apps/web/app/[locale]/pricing/__tests__/page.test.tsx +216 -0
  171. package/templates/apps/web/app/[locale]/pricing/__tests__/unconnected.test.tsx +236 -0
  172. package/templates/apps/web/app/[locale]/pricing/page.tsx +367 -6
  173. package/templates/apps/web/app/[locale]/team/__tests__/team-routes.test.tsx +4 -1
  174. package/templates/apps/web/app/[locale]/unsubscribe/__tests__/unsubscribe-rsc-boundary.test.tsx +17 -0
  175. package/templates/apps/web/app/[locale]/unsubscribe/__tests__/unsubscribe.test.tsx +62 -3
  176. package/templates/apps/web/app/[locale]/unsubscribe/page.tsx +70 -18
  177. package/templates/apps/web/app/[locale]/unsubscribe/unsubscribe-button.tsx +30 -9
  178. package/templates/apps/web/app/api/offerings/checkout/[lookupKey]/route.ts +316 -0
  179. package/templates/apps/web/app/api/offerings/checkout/__tests__/route.test.ts +810 -0
  180. package/templates/apps/web/lib/__tests__/auth-routes.test.ts +27 -1
  181. package/templates/apps/web/lib/__tests__/deck-page.test.ts +2 -1
  182. package/templates/apps/web/lib/__tests__/in-page-magnet.test.ts +265 -0
  183. package/templates/apps/web/lib/__tests__/magnet-routes.test.ts +57 -0
  184. package/templates/apps/web/lib/__tests__/newsletter.actions.test.ts +293 -0
  185. package/templates/apps/web/lib/__tests__/offerings-pricing.test.ts +601 -0
  186. package/templates/apps/web/lib/__tests__/structured-data.test.tsx +67 -8
  187. package/templates/apps/web/lib/auth-routes.ts +36 -2
  188. package/templates/apps/web/lib/checkout-config.ts +9 -20
  189. package/templates/apps/web/lib/deck-page.ts +1 -0
  190. package/templates/apps/web/lib/deliverable-grant.ts +18 -0
  191. package/templates/apps/web/lib/in-page-magnet.ts +416 -0
  192. package/templates/apps/web/lib/magnet-routes.ts +42 -0
  193. package/templates/apps/web/lib/modules.generated.ts +9 -0
  194. package/templates/apps/web/lib/newsletter.actions.ts +202 -0
  195. package/templates/apps/web/lib/offerings-pricing.ts +326 -0
  196. package/templates/apps/web/lib/posting-title.ts +17 -0
  197. package/templates/apps/web/lib/sign-up-agreements.ts +4 -2
  198. package/templates/apps/web/messages/en.json +49 -15
  199. package/templates/apps/web/middleware.ts +12 -2
  200. package/templates/apps/web/security-headers.config.ts +17 -0
  201. package/templates/content/en/BlogList/blog.mdx +4 -71
  202. package/templates/content/en/BookCall/book-a-call.mdx +1 -41
  203. package/templates/content/en/BookCall/onsite-estimate.mdx +1 -17
  204. package/templates/content/en/BookCall/onsite-service.mdx +1 -17
  205. package/templates/content/en/BookCall/start-project.mdx +1 -17
  206. package/templates/content/en/ContactPage/contact.mdx +6 -63
  207. package/templates/content/en/HomePage/home.mdx +3 -21
  208. package/templates/database/CHANGELOG.md +31 -0
  209. package/templates/database/__tests__/in-page-magnets-migration.test.ts +161 -0
  210. package/templates/database/__tests__/offerings-checkout-session.db.test.ts +270 -0
  211. package/templates/database/__tests__/offerings-migration.test.ts +197 -0
  212. package/templates/database/__tests__/offerings-shown-price-ids-migration.test.ts +86 -0
  213. package/templates/database/__tests__/offerings.db.test.ts +303 -0
  214. package/templates/database/__tests__/seed.test.ts +31 -1
  215. package/templates/database/auth/schema.prisma +4 -0
  216. package/templates/database/config/schema.prisma +91 -0
  217. package/templates/database/migrations/20261020120000_offerings_data_model/migration.sql +146 -0
  218. package/templates/database/migrations/20261021120000_offerings_checkout_session/migration.sql +77 -0
  219. package/templates/database/migrations/20261022120000_in_page_magnets/migration.sql +45 -0
  220. package/templates/database/migrations/20261023120000_offerings_shown_price_ids/migration.sql +47 -0
  221. package/templates/database/migrations/20261024120000_organization_plan_checkout_session/migration.sql +16 -0
  222. package/templates/database/package.json +1 -1
  223. package/templates/database/seed.ts +30 -2
  224. package/versions.json +35 -35
  225. package/site-templates/marketing-site-free/content/en/Pricing/pricing.mdx +0 -199
  226. package/templates/apps/web/app/[locale]/downloads/__tests__/page-renderer-migration.test.tsx +0 -93
  227. package/templates/apps/web/app/[locale]/downloads/page.tsx +0 -37
  228. package/templates/apps/web/app/[locale]/newsletter/__tests__/newsletter.actions.test.ts +0 -139
  229. package/templates/apps/web/app/[locale]/newsletter/newsletter.actions.ts +0 -93
  230. package/templates/apps/web/app/api/checkout/[offering]/route.ts +0 -48
  231. package/templates/apps/web/app/api/checkout/__tests__/route.test.ts +0 -120
  232. package/templates/apps/web/app/api/checkout/__tests__/success-path.test.ts +0 -86
  233. package/templates/apps/web/app/api/webhooks/stripe/__tests__/route.test.ts +0 -92
  234. package/templates/apps/web/app/api/webhooks/stripe/route.ts +0 -31
  235. package/templates/apps/web/lib/__tests__/checkout.test.ts +0 -243
  236. package/templates/apps/web/lib/__tests__/meeting-slugs.test.ts +0 -120
  237. package/templates/apps/web/lib/checkout.ts +0 -93
  238. package/templates/apps/web/lib/meeting-slugs.ts +0 -63
@@ -0,0 +1,231 @@
1
+ /**
2
+ * services/offerings/source.ts — the paged Stripe catalog source (#8922, spec
3
+ * docs/specs/8922-the-may-sell-product-list-spec.md D2, AC-6): built lazily,
4
+ * paged through both lists concurrently, bounded by calls and by time, and
5
+ * never reading a disconnected or unusable connection as an empty catalog.
6
+ *
7
+ * `connection.js`'s `stripeClientForOrganization` is mocked to answer each
8
+ * case's client, so no key is decrypted and no Stripe call is made.
9
+ */
10
+ const mockStripeClientForOrganization = jest.fn();
11
+ // eslint-disable-next-line no-restricted-syntax -- connection.ts's per-key client is the Stripe HTTP boundary (#8907 D12); each case answers its own client
12
+ jest.mock("../connection.js", () => ({
13
+ stripeClientForOrganization: (...args: unknown[]) => mockStripeClientForOrganization(...args),
14
+ }));
15
+
16
+ const mockWarn = jest.fn();
17
+ jest.mock("@working-theory/observability", () => ({
18
+ logger: { warn: (...args: unknown[]) => mockWarn(...args), error: jest.fn(), info: jest.fn(), debug: jest.fn() },
19
+ }));
20
+
21
+ import { OFFERINGS_CATALOG_PRICES_MAX, OFFERINGS_CATALOG_PRODUCTS_MAX } from "../catalog.js";
22
+ import {
23
+ OFFERINGS_CATALOG_READ_TIMEOUT_MS,
24
+ OfferingsCatalogUnavailableError,
25
+ stripeCatalogSourceFor,
26
+ } from "../source.js";
27
+
28
+ const ORG = "org_01920000-8922-7000-8000-0000000000a1";
29
+
30
+ type Params = { active?: boolean; limit?: number; starting_after?: string };
31
+ type Page = { data: Array<{ id: string }>; has_more: boolean };
32
+
33
+ /** A list call answering `pages[i]` on its i-th call, then an empty last page. */
34
+ function pagedList(prefix: string, sizes: number[]) {
35
+ let call = 0;
36
+ let next = 0;
37
+ return jest.fn(async (_params: Params): Promise<Page> => {
38
+ const size = sizes[call] ?? 0;
39
+ const hasMore = call < sizes.length - 1;
40
+ call += 1;
41
+ const data = Array.from({ length: size }, () => ({ id: `${prefix}_${next++}` }));
42
+ return { data, has_more: hasMore };
43
+ });
44
+ }
45
+
46
+ /** A list call that answers `size` fresh items with `has_more: true`, forever. */
47
+ function endlessList(prefix: string, size: number) {
48
+ let next = 0;
49
+ return jest.fn(async (_params: Params): Promise<Page> => ({
50
+ data: Array.from({ length: size }, () => ({ id: `${prefix}_${next++}` })),
51
+ has_more: true,
52
+ }));
53
+ }
54
+
55
+ function clientOf(products: jest.Mock, prices: jest.Mock) {
56
+ return { products: { list: products }, prices: { list: prices } };
57
+ }
58
+
59
+ function connect(client: unknown): void {
60
+ mockStripeClientForOrganization.mockResolvedValue({ kind: "ok", client, mode: "test" });
61
+ }
62
+
63
+ beforeEach(() => {
64
+ jest.useRealTimers();
65
+ mockStripeClientForOrganization.mockReset();
66
+ mockWarn.mockReset();
67
+ });
68
+
69
+ describe("stripeCatalogSourceFor (#8922 D2, AC-6)", () => {
70
+ it("does nothing until listActiveCatalog is called", () => {
71
+ const source = stripeCatalogSourceFor(ORG);
72
+ expect(typeof source.listActiveCatalog).toBe("function");
73
+ expect(mockStripeClientForOrganization).not.toHaveBeenCalled();
74
+ });
75
+
76
+ it("pages each list with starting_after until has_more is false, concurrently", async () => {
77
+ const products = pagedList("prod", [100, 100, 50]);
78
+ const prices = pagedList("price", [100, 20]);
79
+ let productsFirstPageResolved = false;
80
+ const productsList = jest.fn(async (params: Params) => {
81
+ const page = await products(params);
82
+ productsFirstPageResolved = true;
83
+ return page;
84
+ });
85
+ let pricesStartedBeforeProductsResolved = false;
86
+ const pricesList = jest.fn(async (params: Params) => {
87
+ if (pricesList.mock.calls.length === 1) pricesStartedBeforeProductsResolved = !productsFirstPageResolved;
88
+ return prices(params);
89
+ });
90
+ connect(clientOf(productsList, pricesList));
91
+
92
+ const catalog = await stripeCatalogSourceFor(ORG).listActiveCatalog();
93
+
94
+ expect(mockStripeClientForOrganization).toHaveBeenCalledWith(ORG);
95
+ expect(productsList.mock.calls.map(([p]) => p)).toEqual([
96
+ { active: true, limit: 100 },
97
+ { active: true, limit: 100, starting_after: "prod_99" },
98
+ { active: true, limit: 100, starting_after: "prod_199" },
99
+ ]);
100
+ expect(catalog.products).toHaveLength(250);
101
+ expect(catalog.products.map((p) => p.id)).toEqual(Array.from({ length: 250 }, (_, i) => `prod_${i}`));
102
+ expect(pricesList.mock.calls.map(([p]) => p)).toEqual([
103
+ { active: true, limit: 100 },
104
+ { active: true, limit: 100, starting_after: "price_99" },
105
+ ]);
106
+ expect(catalog.prices).toHaveLength(120);
107
+ expect(pricesStartedBeforeProductsResolved).toBe(true);
108
+ expect(mockWarn).not.toHaveBeenCalled();
109
+ });
110
+
111
+ it("stops at the caps: 10 product calls and 30 price calls of full pages", async () => {
112
+ const products = endlessList("prod", 100);
113
+ const prices = endlessList("price", 100);
114
+ connect(clientOf(products, prices));
115
+ const catalog = await stripeCatalogSourceFor(ORG).listActiveCatalog();
116
+ expect(products).toHaveBeenCalledTimes(OFFERINGS_CATALOG_PRODUCTS_MAX / 100);
117
+ expect(prices).toHaveBeenCalledTimes(OFFERINGS_CATALOG_PRICES_MAX / 100);
118
+ expect(catalog.products).toHaveLength(1000);
119
+ expect(catalog.prices).toHaveLength(3000);
120
+ // Cut off with more to read: logged once, with the Organization alone (SEC-8922-7).
121
+ expect(mockWarn).toHaveBeenCalledTimes(1);
122
+ expect(mockWarn).toHaveBeenCalledWith({ organizationId: ORG, reason: "catalog_truncated" }, expect.any(String));
123
+ });
124
+
125
+ it("bounds by calls, not items: pages of one item still stop at 10 and 30 calls", async () => {
126
+ const products = endlessList("prod", 1);
127
+ const prices = endlessList("price", 1);
128
+ connect(clientOf(products, prices));
129
+ const catalog = await stripeCatalogSourceFor(ORG).listActiveCatalog();
130
+ expect(products).toHaveBeenCalledTimes(10);
131
+ expect(prices).toHaveBeenCalledTimes(30);
132
+ expect(catalog.products).toHaveLength(10);
133
+ expect(catalog.prices).toHaveLength(30);
134
+ });
135
+
136
+ it("ends a loop on an empty page that still says has_more", async () => {
137
+ const products = jest.fn(async (): Promise<Page> => ({ data: [], has_more: true }));
138
+ const prices = pagedList("price", [3]);
139
+ connect(clientOf(products, prices));
140
+ const catalog = await stripeCatalogSourceFor(ORG).listActiveCatalog();
141
+ expect(products).toHaveBeenCalledTimes(1);
142
+ expect(catalog.products).toEqual([]);
143
+ });
144
+
145
+ it("ends a loop on a page whose last id repeats the starting_after it was asked with", async () => {
146
+ const products = jest.fn(async (params: Params): Promise<Page> => ({
147
+ data: [{ id: params.starting_after ?? "prod_a" }],
148
+ has_more: true,
149
+ }));
150
+ const prices = pagedList("price", [1]);
151
+ connect(clientOf(products, prices));
152
+ const catalog = await stripeCatalogSourceFor(ORG).listActiveCatalog();
153
+ expect(products.mock.calls.map(([p]) => p)).toEqual([
154
+ { active: true, limit: 100 },
155
+ { active: true, limit: 100, starting_after: "prod_a" },
156
+ ]);
157
+ expect(catalog.products).toEqual([{ id: "prod_a" }, { id: "prod_a" }]);
158
+ });
159
+
160
+ it.each(["none", "unusable"] as const)(
161
+ "rejects a %s connection with OfferingsCatalogUnavailableError and no list call",
162
+ async (kind) => {
163
+ mockStripeClientForOrganization.mockResolvedValue({ kind });
164
+ const products = jest.fn();
165
+ const err = await stripeCatalogSourceFor(ORG)
166
+ .listActiveCatalog()
167
+ .catch((e: unknown) => e);
168
+ expect(err).toBeInstanceOf(OfferingsCatalogUnavailableError);
169
+ expect((err as Error).message).toBe("The Offerings catalog source is unavailable");
170
+ expect((err as { cause?: unknown }).cause).toBeUndefined();
171
+ expect(products).not.toHaveBeenCalled();
172
+ },
173
+ );
174
+
175
+ it("rejects a hung page after the timeout, starts no call after it, and leaves no unhandled rejection", async () => {
176
+ jest.useFakeTimers();
177
+ const unhandled = jest.fn();
178
+ process.on("unhandledRejection", unhandled);
179
+ try {
180
+ let rejectHung: (err: Error) => void = () => undefined;
181
+ const products = jest.fn(
182
+ () =>
183
+ new Promise<Page>((_resolve, reject) => {
184
+ rejectHung = reject;
185
+ }),
186
+ );
187
+ const prices = jest.fn(
188
+ () =>
189
+ new Promise<Page>((resolve) => {
190
+ setTimeout(() => resolve({ data: [{ id: "price_late" }], has_more: true }), OFFERINGS_CATALOG_READ_TIMEOUT_MS + 1000);
191
+ }),
192
+ );
193
+ connect(clientOf(products, prices));
194
+
195
+ const read = stripeCatalogSourceFor(ORG).listActiveCatalog();
196
+ const settled = read.catch((e: unknown) => e);
197
+ await jest.advanceTimersByTimeAsync(OFFERINGS_CATALOG_READ_TIMEOUT_MS);
198
+ expect(await settled).toBeInstanceOf(OfferingsCatalogUnavailableError);
199
+
200
+ // The late page resolves after the timeout: no further call is started.
201
+ await jest.advanceTimersByTimeAsync(2000);
202
+ expect(prices).toHaveBeenCalledTimes(1);
203
+ // The hung page rejects after the timeout: never an unhandled rejection.
204
+ rejectHung(new Error("late failure"));
205
+ await jest.advanceTimersByTimeAsync(0);
206
+ jest.useRealTimers();
207
+ await new Promise((resolve) => setImmediate(resolve));
208
+ expect(unhandled).not.toHaveBeenCalled();
209
+ expect(products).toHaveBeenCalledTimes(1);
210
+ } finally {
211
+ process.off("unhandledRejection", unhandled);
212
+ }
213
+ });
214
+
215
+ it("rejects with the Stripe error object itself", async () => {
216
+ const stripeError = new Error("Invalid API Key provided: rk_test_********************abcd");
217
+ const products = jest.fn(async () => Promise.reject(stripeError));
218
+ const prices = pagedList("price", [1]);
219
+ connect(clientOf(products, prices));
220
+ await expect(stripeCatalogSourceFor(ORG).listActiveCatalog()).rejects.toBe(stripeError);
221
+ });
222
+
223
+ it("requests the client again on every read, never reusing one", async () => {
224
+ connect(clientOf(pagedList("prod", [1]), pagedList("price", [1])));
225
+ const source = stripeCatalogSourceFor(ORG);
226
+ await source.listActiveCatalog();
227
+ connect(clientOf(pagedList("prod", [1]), pagedList("price", [1])));
228
+ await source.listActiveCatalog();
229
+ expect(mockStripeClientForOrganization).toHaveBeenCalledTimes(2);
230
+ });
231
+ });
@@ -0,0 +1,308 @@
1
+ /**
2
+ * The one Offerings normalizer (#8876, spec
3
+ * docs/specs/8876-the-offerings-data-model-typed-spec.md D5) — turns a
4
+ * seller's Stripe Products and Prices into the typed shape every Offerings
5
+ * surface consumes, and names why each other Product is held out.
6
+ *
7
+ * Stripe text is seller-authored and untrusted (contract
8
+ * docs/specs/8879-the-offerings-security-contract-key-spec.md §3.6). It is
9
+ * normalized here once (T1) and parsed by `@working-theory/validation`'s
10
+ * Offerings schemas before any surface sees it. Only the fields the contract
11
+ * lists are read: a Product's `images` and `url`, a Price's `nickname` and
12
+ * `statement_descriptor`, and every other metadata key never reach the
13
+ * output.
14
+ *
15
+ * The lookup key is split only by `parseLookupKey` (G1), and a Price's period
16
+ * read only by `periodOfStripePrice` (G3).
17
+ *
18
+ * `normalizeCatalog` is pure: no I/O, no clock, no logging.
19
+ */
20
+ import {
21
+ LOOKUP_KEY_PERIODS,
22
+ OFFERINGS_AMOUNT_MAX,
23
+ OFFERINGS_DESCRIPTION_MAX,
24
+ OFFERINGS_FEATURES_MAX,
25
+ OFFERINGS_FEATURE_MAX,
26
+ OFFERINGS_NAME_MAX,
27
+ OFFERINGS_NOTE_MAX,
28
+ OFFERINGS_UNIT_LABEL_MAX,
29
+ offeringsHeldProductSchema,
30
+ offeringsSnapshotProductSchema,
31
+ offeringsStripeIdSchema,
32
+ parseLookupKey,
33
+ periodOfStripePrice,
34
+ type OfferingsGroup,
35
+ type OfferingsHeldProduct,
36
+ type OfferingsHeldReason,
37
+ type OfferingsPrice,
38
+ type OfferingsSnapshotProduct,
39
+ } from "@working-theory/validation";
40
+
41
+ /** The most Products and Prices a source pages through, and the normalizer reads. */
42
+ export const OFFERINGS_CATALOG_PRODUCTS_MAX = 1000;
43
+ export const OFFERINGS_CATALOG_PRICES_MAX = 3000;
44
+
45
+ /**
46
+ * A Stripe Product as the normalizer reads it. Every field is `unknown`, so a
47
+ * Stripe SDK object fits with no import and nothing is trusted.
48
+ */
49
+ export interface CatalogProduct {
50
+ readonly id?: unknown;
51
+ readonly active?: unknown;
52
+ readonly name?: unknown;
53
+ readonly description?: unknown;
54
+ readonly marketing_features?: unknown;
55
+ readonly unit_label?: unknown;
56
+ readonly metadata?: unknown;
57
+ }
58
+
59
+ /** A Stripe Price as the normalizer reads it. */
60
+ export interface CatalogPrice {
61
+ readonly id?: unknown;
62
+ readonly active?: unknown;
63
+ readonly product?: unknown;
64
+ readonly lookup_key?: unknown;
65
+ readonly type?: unknown;
66
+ readonly recurring?: unknown;
67
+ readonly billing_scheme?: unknown;
68
+ readonly unit_amount?: unknown;
69
+ readonly currency?: unknown;
70
+ }
71
+
72
+ export interface OfferingsCatalog {
73
+ products: CatalogProduct[];
74
+ prices: CatalogPrice[];
75
+ }
76
+
77
+ /**
78
+ * Where a seller's catalog comes from. #8857 implements it with the per-key
79
+ * client, paginated (#8054), stopping at the two caps above.
80
+ */
81
+ export interface OfferingsCatalogSource {
82
+ listActiveCatalog(): Promise<OfferingsCatalog>;
83
+ }
84
+
85
+ export interface NormalizedCatalog {
86
+ offerings: OfferingsSnapshotProduct[];
87
+ held: OfferingsHeldProduct[];
88
+ }
89
+
90
+ // Unicode Cc, Cf, Zl, Zp and Cs (lone surrogates) — T1's stripped categories.
91
+ const STRIPPED = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/gu;
92
+
93
+ function isRecord(value: unknown): value is Record<string, unknown> {
94
+ return value !== null && typeof value === "object" && !Array.isArray(value);
95
+ }
96
+
97
+ /**
98
+ * T1: strip the categories (`\n` kept only when `keepNewlines`), NFC, trim,
99
+ * and cut to `max` code points. A non-string, or nothing left, is `null`.
100
+ * Exported for the Offerings session read's line-item names (#8931 D9).
101
+ */
102
+ export function normalizeText(value: unknown, max: number, keepNewlines = false): string | null {
103
+ if (typeof value !== "string") return null;
104
+ const stripped = value.replace(STRIPPED, (ch) => (keepNewlines && ch === "\n" ? ch : ""));
105
+ const text = [...stripped.normalize("NFC").trim()].slice(0, max).join("").trimEnd();
106
+ return text.length > 0 ? text : null;
107
+ }
108
+
109
+ /**
110
+ * The Offerings product marker (contract G6, A9): any non-empty
111
+ * `metadata.ailk_group`. Deliberately wider than the group check below, so a
112
+ * malformed group such as `Plan` is held out of Offerings and still refused
113
+ * on the env checkout path (#8861).
114
+ */
115
+ export function isOfferingsProduct(product: CatalogProduct): boolean {
116
+ return isRecord(product.metadata) && typeof product.metadata.ailk_group === "string"
117
+ && product.metadata.ailk_group.length > 0;
118
+ }
119
+
120
+ function metadataOf(product: CatalogProduct): Record<string, unknown> {
121
+ return isRecord(product.metadata) ? product.metadata : {};
122
+ }
123
+
124
+ function groupOf(product: CatalogProduct): OfferingsGroup | null {
125
+ const group = metadataOf(product).ailk_group;
126
+ return group === "plan" || group === "addon" ? group : null;
127
+ }
128
+
129
+ /** `metadata.ailk_order` when it is 1–4 digits, else `null` (sorts last). */
130
+ function orderOf(product: CatalogProduct): number | null {
131
+ const order = metadataOf(product).ailk_order;
132
+ return typeof order === "string" && /^[0-9]{1,4}$/.test(order) ? Number(order) : null;
133
+ }
134
+
135
+ function featuresOf(product: CatalogProduct): string[] {
136
+ if (!Array.isArray(product.marketing_features)) return [];
137
+ return product.marketing_features
138
+ .map((feature: unknown) =>
139
+ isRecord(feature) ? normalizeText(feature.name, OFFERINGS_FEATURE_MAX) : null,
140
+ )
141
+ .filter((name): name is string => name !== null)
142
+ .slice(0, OFFERINGS_FEATURES_MAX);
143
+ }
144
+
145
+ function productIdOfPrice(price: CatalogPrice): unknown {
146
+ return isRecord(price.product) ? price.product.id : price.product;
147
+ }
148
+
149
+ function isStripeId(value: unknown): value is string {
150
+ return offeringsStripeIdSchema.safeParse(value).success;
151
+ }
152
+
153
+ /** One Price as a sellable offering price (G3), or `null`. */
154
+ function sellablePrice(price: CatalogPrice): OfferingsPrice | null {
155
+ const parsed = parseLookupKey(price.lookup_key);
156
+ const period = periodOfStripePrice(price);
157
+ if (!parsed || parsed.period !== period) return null;
158
+ if (price.billing_scheme !== "per_unit") return null;
159
+ const amount = price.unit_amount;
160
+ if (typeof amount !== "number" || !Number.isInteger(amount) || amount < 0 || amount > OFFERINGS_AMOUNT_MAX) {
161
+ return null;
162
+ }
163
+ if (typeof price.currency !== "string" || !/^[a-z]{3}$/.test(price.currency)) return null;
164
+ if (isRecord(price.recurring) && price.recurring.usage_type === "metered") return null;
165
+ return {
166
+ priceId: price.id as string,
167
+ lookupKey: price.lookup_key as string,
168
+ plan: parsed.plan,
169
+ period: parsed.period,
170
+ interval: isRecord(price.recurring) && price.type === "recurring"
171
+ ? (price.recurring.interval as "month" | "year")
172
+ : null,
173
+ amount,
174
+ currency: price.currency,
175
+ };
176
+ }
177
+
178
+ /** Compare two strings by code point (not UTF-16 unit). */
179
+ function compareCodePoints(a: string, b: string): number {
180
+ const x = [...a];
181
+ const y = [...b];
182
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
183
+ const d = x[i]!.codePointAt(0)! - y[i]!.codePointAt(0)!;
184
+ if (d !== 0) return d;
185
+ }
186
+ return x.length - y.length;
187
+ }
188
+
189
+ /** D5 step 5: plan before addon, `ailkOrder` (null last), name, then id. */
190
+ function compareOfferings(a: OfferingsSnapshotProduct, b: OfferingsSnapshotProduct): number {
191
+ if (a.ailkGroup !== b.ailkGroup) return a.ailkGroup === "plan" ? -1 : 1;
192
+ if (a.ailkOrder !== b.ailkOrder) {
193
+ if (a.ailkOrder === null) return 1;
194
+ if (b.ailkOrder === null) return -1;
195
+ return a.ailkOrder - b.ailkOrder;
196
+ }
197
+ return compareCodePoints(a.name, b.name) || compareCodePoints(a.productId, b.productId);
198
+ }
199
+
200
+ type Candidate =
201
+ | { productId: string; name: string; held: OfferingsHeldReason }
202
+ | { productId: string; name: string; offering: OfferingsSnapshotProduct };
203
+
204
+ /**
205
+ * Normalize one seller's catalog (D5). Reads at most
206
+ * `OFFERINGS_CATALOG_PRODUCTS_MAX` Products and `OFFERINGS_CATALOG_PRICES_MAX`
207
+ * Prices; an inactive Product, a Product or Price whose id is not a Stripe
208
+ * id, and a repeat of a Product or Price id already read, is left out of both
209
+ * lists. Every other Product is either an
210
+ * offering or held with its reason. One Product that fails its parse is held
211
+ * `invalid`, never failing the catalog.
212
+ */
213
+ export function normalizeCatalog(input: OfferingsCatalog): NormalizedCatalog {
214
+ // A Product id the source answers twice (a paging bug) counts once.
215
+ const seen = new Set<unknown>();
216
+ const products = input.products
217
+ .slice(0, OFFERINGS_CATALOG_PRODUCTS_MAX)
218
+ .filter((p) => p.active === true && isStripeId(p.id) && !seen.has(p.id) && seen.add(p.id));
219
+ const pricesByProduct = new Map<string, CatalogPrice[]>();
220
+ const seenPrices = new Set<unknown>();
221
+ for (const price of input.prices.slice(0, OFFERINGS_CATALOG_PRICES_MAX)) {
222
+ const productId = productIdOfPrice(price);
223
+ if (price.active !== true || !isStripeId(price.id) || typeof productId !== "string") continue;
224
+ if (seenPrices.has(price.id)) continue;
225
+ seenPrices.add(price.id);
226
+ const list = pricesByProduct.get(productId) ?? [];
227
+ list.push(price);
228
+ pricesByProduct.set(productId, list);
229
+ }
230
+
231
+ // G4: every plan any active Product's Prices carry, by Product — two
232
+ // Products carrying one plan hold both, whatever else holds them.
233
+ const plansByProduct = new Map<string, Set<string>>();
234
+ const productsByPlan = new Map<string, Set<string>>();
235
+ for (const product of products) {
236
+ const id = product.id as string;
237
+ const plans = new Set(
238
+ (pricesByProduct.get(id) ?? [])
239
+ .map((price) => parseLookupKey(price.lookup_key)?.plan)
240
+ .filter((plan): plan is string => plan !== undefined),
241
+ );
242
+ plansByProduct.set(id, plans);
243
+ for (const plan of plans) {
244
+ const holders = productsByPlan.get(plan) ?? new Set<string>();
245
+ holders.add(id);
246
+ productsByPlan.set(plan, holders);
247
+ }
248
+ }
249
+
250
+ const candidates: Candidate[] = products.map((product) => {
251
+ const productId = product.id as string;
252
+ const name = normalizeText(product.name, OFFERINGS_NAME_MAX) ?? "";
253
+ const group = groupOf(product);
254
+ if (group === null) return { productId, name, held: "group_invalid" };
255
+ if (name === "") return { productId, name, held: "name_missing" };
256
+
257
+ const active = pricesByProduct.get(productId) ?? [];
258
+ const sellable = active.map(sellablePrice);
259
+ if (sellable.length === 0 || sellable.some((price) => price === null)) {
260
+ return { productId, name, held: "needs_lookup_key" };
261
+ }
262
+ const prices = sellable as OfferingsPrice[];
263
+ const plan = prices[0]!.plan;
264
+ const periods = new Set(prices.map((price) => price.period));
265
+ if (prices.some((price) => price.plan !== plan) || periods.size !== prices.length) {
266
+ return { productId, name, held: "needs_lookup_key" };
267
+ }
268
+ if ([...plansByProduct.get(productId)!].some((p) => productsByPlan.get(p)!.size > 1)) {
269
+ return { productId, name, held: "plan_conflict" };
270
+ }
271
+
272
+ const metadata = metadataOf(product);
273
+ const offering = offeringsSnapshotProductSchema.safeParse({
274
+ productId,
275
+ plan,
276
+ name,
277
+ description: normalizeText(product.description, OFFERINGS_DESCRIPTION_MAX, true),
278
+ marketingFeatures: featuresOf(product),
279
+ unitLabel: normalizeText(product.unit_label, OFFERINGS_UNIT_LABEL_MAX),
280
+ note: normalizeText(metadata.ailk_note, OFFERINGS_NOTE_MAX),
281
+ termsNote: normalizeText(metadata.ailk_terms_note, OFFERINGS_NOTE_MAX),
282
+ ailkGroup: group,
283
+ ailkOrder: orderOf(product),
284
+ prices: [...prices].sort(
285
+ (a, b) => LOOKUP_KEY_PERIODS.indexOf(a.period) - LOOKUP_KEY_PERIODS.indexOf(b.period),
286
+ ),
287
+ });
288
+ return offering.success
289
+ ? { productId, name, offering: offering.data }
290
+ : { productId, name, held: "invalid" };
291
+ });
292
+
293
+ const offerings: OfferingsSnapshotProduct[] = [];
294
+ const held: OfferingsHeldProduct[] = [];
295
+ for (const candidate of candidates) {
296
+ if ("offering" in candidate) {
297
+ offerings.push(candidate.offering);
298
+ continue;
299
+ }
300
+ const parsed = offeringsHeldProductSchema.safeParse({
301
+ productId: candidate.productId,
302
+ name: candidate.name,
303
+ reason: candidate.held,
304
+ });
305
+ if (parsed.success) held.push(parsed.data);
306
+ }
307
+ return { offerings: offerings.sort(compareOfferings), held };
308
+ }