@velastack/patterns 0.4.1 → 0.4.3

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 (137) hide show
  1. package/dist/chunks/{_layout-kkgN0IF7.js → _layout-D-FzWqn0.js} +2 -2
  2. package/dist/chunks/{_layout-kkgN0IF7.js.map → _layout-D-FzWqn0.js.map} +1 -1
  3. package/dist/chunks/_page-C7kGoW7_.js +6 -0
  4. package/dist/chunks/_page-C7kGoW7_.js.map +1 -0
  5. package/dist/chunks/_page-e_I-fdSR.js +6 -0
  6. package/dist/chunks/_page-e_I-fdSR.js.map +1 -0
  7. package/dist/chunks/auth-pages-B52ei-4z.js +291 -0
  8. package/dist/chunks/auth-pages-B52ei-4z.js.map +1 -0
  9. package/dist/chunks/{collections-Dz2fvKnz.js → collections-zzZ_HQxB.js} +2 -2
  10. package/dist/chunks/{collections-Dz2fvKnz.js.map → collections-zzZ_HQxB.js.map} +1 -1
  11. package/dist/chunks/{compose-handle-D_Rz3Fzo.js → compose-handle-BDlZ7Pif.js} +2 -2
  12. package/dist/chunks/{compose-handle-D_Rz3Fzo.js.map → compose-handle-BDlZ7Pif.js.map} +1 -1
  13. package/dist/chunks/{config-target-Dx3w6WSk.js → config-target-rHgjaA8u.js} +2 -2
  14. package/dist/chunks/{config-target-Dx3w6WSk.js.map → config-target-rHgjaA8u.js.map} +1 -1
  15. package/dist/chunks/{constants-BjyMU5s8.js → constants-Rq8SCXwH.js} +2 -2
  16. package/dist/chunks/{constants-BjyMU5s8.js.map → constants-Rq8SCXwH.js.map} +1 -1
  17. package/dist/chunks/dispatch-D4TN9pdW.js +6 -0
  18. package/dist/chunks/dispatch-D4TN9pdW.js.map +1 -0
  19. package/dist/chunks/{env-vars-C1NUX-bf.js → env-vars-CcE6ODqC.js} +4 -4
  20. package/dist/chunks/{env-vars-C1NUX-bf.js.map → env-vars-CcE6ODqC.js.map} +1 -1
  21. package/dist/chunks/{format-result-DZ8De8KY.js → format-result-BVoLVknk.js} +2 -2
  22. package/dist/chunks/format-result-BVoLVknk.js.map +1 -0
  23. package/dist/chunks/{generate-DeaBlnK6.js → generate-B6Odfk5f.js} +2 -2
  24. package/dist/chunks/{generate-DeaBlnK6.js.map → generate-B6Odfk5f.js.map} +1 -1
  25. package/dist/chunks/{generate-WMJo3QGZ.js → generate-Bg0E3eWm.js} +2 -2
  26. package/dist/chunks/{generate-WMJo3QGZ.js.map → generate-Bg0E3eWm.js.map} +1 -1
  27. package/dist/chunks/{generate-Gcc8iRkZ.js → generate-CFqpRi9D.js} +3 -3
  28. package/dist/chunks/{generate-Gcc8iRkZ.js.map → generate-CFqpRi9D.js.map} +1 -1
  29. package/dist/chunks/{generate-BW3l5Fxw.js → generate-CZGHByV3.js} +2 -2
  30. package/dist/chunks/{generate-BW3l5Fxw.js.map → generate-CZGHByV3.js.map} +1 -1
  31. package/dist/chunks/{generate.runtime-IlBCcXvv.js → generate.runtime-5rIc-RNL.js} +7 -7
  32. package/dist/chunks/{generate.runtime-IlBCcXvv.js.map → generate.runtime-5rIc-RNL.js.map} +1 -1
  33. package/dist/chunks/{generate.runtime-BgTz41Zg.js → generate.runtime-BK3mR0Rj.js} +92 -140
  34. package/dist/chunks/generate.runtime-BK3mR0Rj.js.map +1 -0
  35. package/dist/chunks/generate.runtime-Bcrht4M9.js +42 -0
  36. package/dist/chunks/generate.runtime-Bcrht4M9.js.map +1 -0
  37. package/dist/chunks/{generate.runtime-cwvAoKoH.js → generate.runtime-BpMN5Uq-.js} +3 -3
  38. package/dist/chunks/{generate.runtime-cwvAoKoH.js.map → generate.runtime-BpMN5Uq-.js.map} +1 -1
  39. package/dist/chunks/{generate.runtime-DD51OSuL.js → generate.runtime-CAn1qIQ_.js} +4 -4
  40. package/dist/chunks/{generate.runtime-DD51OSuL.js.map → generate.runtime-CAn1qIQ_.js.map} +1 -1
  41. package/dist/chunks/{generate.runtime-CuNhY5hn.js → generate.runtime-CEqLgLT9.js} +16 -11
  42. package/dist/chunks/generate.runtime-CEqLgLT9.js.map +1 -0
  43. package/dist/chunks/{generate.runtime-B1jVAnDI.js → generate.runtime-CK10Mum5.js} +8 -8
  44. package/dist/chunks/{generate.runtime-B1jVAnDI.js.map → generate.runtime-CK10Mum5.js.map} +1 -1
  45. package/dist/chunks/{generate.runtime-DqD3PW-W.js → generate.runtime-CZ46nkSL.js} +3 -3
  46. package/dist/chunks/{generate.runtime-DqD3PW-W.js.map → generate.runtime-CZ46nkSL.js.map} +1 -1
  47. package/dist/chunks/{generate.runtime-CslAvllQ.js → generate.runtime-CbE9RHcf.js} +5 -5
  48. package/dist/chunks/generate.runtime-CbE9RHcf.js.map +1 -0
  49. package/dist/chunks/{generate.runtime-CCr1lvo4.js → generate.runtime-CpMKXBkn.js} +7 -7
  50. package/dist/chunks/{generate.runtime-CCr1lvo4.js.map → generate.runtime-CpMKXBkn.js.map} +1 -1
  51. package/dist/chunks/{generate.runtime-6FXJM8hT.js → generate.runtime-CqncBFNg.js} +5 -5
  52. package/dist/chunks/{generate.runtime-6FXJM8hT.js.map → generate.runtime-CqncBFNg.js.map} +1 -1
  53. package/dist/chunks/{generate.runtime-C6bSvGMb.js → generate.runtime-DHHlYfTD.js} +6 -6
  54. package/dist/chunks/{generate.runtime-C6bSvGMb.js.map → generate.runtime-DHHlYfTD.js.map} +1 -1
  55. package/dist/chunks/generate.runtime-DJ9MVVPC.js +325 -0
  56. package/dist/chunks/generate.runtime-DJ9MVVPC.js.map +1 -0
  57. package/dist/chunks/generate.runtime-DJHUBL4Z.js +68 -0
  58. package/dist/chunks/generate.runtime-DJHUBL4Z.js.map +1 -0
  59. package/dist/chunks/{generate.runtime-CnPraLKv.js → generate.runtime-DVB7uuht.js} +4 -4
  60. package/dist/chunks/{generate.runtime-CnPraLKv.js.map → generate.runtime-DVB7uuht.js.map} +1 -1
  61. package/dist/chunks/{generate.runtime-kvxmTlQb.js → generate.runtime-Db0HZyj3.js} +3 -3
  62. package/dist/chunks/{generate.runtime-kvxmTlQb.js.map → generate.runtime-Db0HZyj3.js.map} +1 -1
  63. package/dist/chunks/{generate.runtime-D_sQOeQa.js → generate.runtime-Djas9UNy.js} +6 -6
  64. package/dist/chunks/{generate.runtime-D_sQOeQa.js.map → generate.runtime-Djas9UNy.js.map} +1 -1
  65. package/dist/chunks/{generate.runtime-Ce_rwzNa.js → generate.runtime-Dl6OQ7pe.js} +4 -4
  66. package/dist/chunks/{generate.runtime-Ce_rwzNa.js.map → generate.runtime-Dl6OQ7pe.js.map} +1 -1
  67. package/dist/chunks/{generate.runtime-1-91UmM8.js → generate.runtime-DoZJHtZh.js} +4 -4
  68. package/dist/chunks/{generate.runtime-1-91UmM8.js.map → generate.runtime-DoZJHtZh.js.map} +1 -1
  69. package/dist/chunks/{generate.runtime-C8zJRNYG.js → generate.runtime-E-zoeSKW.js} +5 -5
  70. package/dist/chunks/{generate.runtime-C8zJRNYG.js.map → generate.runtime-E-zoeSKW.js.map} +1 -1
  71. package/dist/chunks/{generate.runtime-pVLzzpUM.js → generate.runtime-EQnytCFL.js} +40 -40
  72. package/dist/chunks/generate.runtime-EQnytCFL.js.map +1 -0
  73. package/dist/chunks/generate.runtime-IWEhGhWY.js +218 -0
  74. package/dist/chunks/generate.runtime-IWEhGhWY.js.map +1 -0
  75. package/dist/chunks/{generate.runtime-CYagyR5c.js → generate.runtime-a3R4hqFy.js} +6 -6
  76. package/dist/chunks/{generate.runtime-CYagyR5c.js.map → generate.runtime-a3R4hqFy.js.map} +1 -1
  77. package/dist/chunks/{generate.runtime-zJpEufTc.js → generate.runtime-aQnBmH8D.js} +9 -9
  78. package/dist/chunks/generate.runtime-aQnBmH8D.js.map +1 -0
  79. package/dist/chunks/{generate.runtime-Dtgw9IQO.js → generate.runtime-axm9wcQv.js} +5 -5
  80. package/dist/chunks/{generate.runtime-Dtgw9IQO.js.map → generate.runtime-axm9wcQv.js.map} +1 -1
  81. package/dist/chunks/{generate.runtime-DHBRyMAq.js → generate.runtime-hTKzxH2M.js} +5 -5
  82. package/dist/chunks/{generate.runtime-DHBRyMAq.js.map → generate.runtime-hTKzxH2M.js.map} +1 -1
  83. package/dist/chunks/{generate.runtime-BA3tDKnn.js → generate.runtime-kciwaXxh.js} +5 -5
  84. package/dist/chunks/{generate.runtime-BA3tDKnn.js.map → generate.runtime-kciwaXxh.js.map} +1 -1
  85. package/dist/chunks/{generate.runtime-B_UVGa3q.js → generate.runtime-koQxLywh.js} +5 -5
  86. package/dist/chunks/{generate.runtime-B_UVGa3q.js.map → generate.runtime-koQxLywh.js.map} +1 -1
  87. package/dist/chunks/{generate.runtime-DM4o_QYY.js → generate.runtime-rs1ZOIET.js} +5 -5
  88. package/dist/chunks/{generate.runtime-DM4o_QYY.js.map → generate.runtime-rs1ZOIET.js.map} +1 -1
  89. package/dist/chunks/{generate.runtime-DV3WmZtb.js → generate.runtime-uLUiPgqx.js} +6 -6
  90. package/dist/chunks/{generate.runtime-DV3WmZtb.js.map → generate.runtime-uLUiPgqx.js.map} +1 -1
  91. package/dist/chunks/{modify-file-BlDeeurK.js → modify-file-DK-tCH9k.js} +3 -3
  92. package/dist/chunks/{modify-file-BlDeeurK.js.map → modify-file-DK-tCH9k.js.map} +1 -1
  93. package/dist/chunks/modify-nav-user-BLyrW2sK.js +71 -0
  94. package/dist/chunks/modify-nav-user-BLyrW2sK.js.map +1 -0
  95. package/dist/chunks/{modify-svelte-config-remote-p0TfVzxm.js → modify-svelte-config-remote-DhuRX4FI.js} +2 -2
  96. package/dist/chunks/{modify-svelte-config-remote-p0TfVzxm.js.map → modify-svelte-config-remote-DhuRX4FI.js.map} +1 -1
  97. package/dist/chunks/modify-user-signup-BbqTiUuA.js +54 -0
  98. package/dist/chunks/modify-user-signup-BbqTiUuA.js.map +1 -0
  99. package/dist/chunks/{pocketbase-Dry6ry17.js → pocketbase-CgwbH1gI.js} +2 -2
  100. package/dist/chunks/{pocketbase-Dry6ry17.js.map → pocketbase-CgwbH1gI.js.map} +1 -1
  101. package/dist/chunks/{shared-CZC4d7Uj.js → shared-Cc_ns5-y.js} +2 -2
  102. package/dist/chunks/{shared-CZC4d7Uj.js.map → shared-Cc_ns5-y.js.map} +1 -1
  103. package/dist/chunks/{site-BwCA18Sv.js → site-lj0CDdQ1.js} +2 -2
  104. package/dist/chunks/{site-BwCA18Sv.js.map → site-lj0CDdQ1.js.map} +1 -1
  105. package/dist/chunks/{table-core-AjBpYi-y.js → table-core-DhDqT03G.js} +2 -2
  106. package/dist/chunks/{table-core-AjBpYi-y.js.map → table-core-DhDqT03G.js.map} +1 -1
  107. package/dist/chunks/{test-setup-DEmWd9Ul.js → test-setup-B9fQ5L_-.js} +5 -5
  108. package/dist/chunks/{test-setup-DEmWd9Ul.js.map → test-setup-B9fQ5L_-.js.map} +1 -1
  109. package/dist/chunks/{ts-morph-helpers-CDW4lhox.js → ts-morph-helpers-Bepc-Es2.js} +27 -23
  110. package/dist/chunks/ts-morph-helpers-Bepc-Es2.js.map +1 -0
  111. package/dist/chunks/{ui-X698F10c.js → ui-CuCsupFq.js} +3 -3
  112. package/dist/chunks/{ui-X698F10c.js.map → ui-CuCsupFq.js.map} +1 -1
  113. package/dist/chunks/{unmodify-load-CyGzC1Hu.js → unmodify-load-Bl5vXQiL.js} +2 -2
  114. package/dist/chunks/{unmodify-load-CyGzC1Hu.js.map → unmodify-load-Bl5vXQiL.js.map} +1 -1
  115. package/dist/chunks/whatsapp-CguKGTtw.js +105 -0
  116. package/dist/chunks/whatsapp-CguKGTtw.js.map +1 -0
  117. package/dist/chunks/{write-result-B68lvI57.js → write-result-DiZsCS_y.js} +5 -5
  118. package/dist/chunks/{write-result-B68lvI57.js.map → write-result-DiZsCS_y.js.map} +1 -1
  119. package/dist/index.d.ts +134 -1
  120. package/dist/index.js +2240 -2005
  121. package/dist/index.js.map +1 -1
  122. package/package.json +2 -2
  123. package/dist/chunks/dispatch-CXOXPLFk.js +0 -6
  124. package/dist/chunks/dispatch-CXOXPLFk.js.map +0 -1
  125. package/dist/chunks/format-result-DZ8De8KY.js.map +0 -1
  126. package/dist/chunks/generate.runtime-BO778G0r.js +0 -188
  127. package/dist/chunks/generate.runtime-BO778G0r.js.map +0 -1
  128. package/dist/chunks/generate.runtime-BgTz41Zg.js.map +0 -1
  129. package/dist/chunks/generate.runtime-CexC1Oky.js +0 -269
  130. package/dist/chunks/generate.runtime-CexC1Oky.js.map +0 -1
  131. package/dist/chunks/generate.runtime-CslAvllQ.js.map +0 -1
  132. package/dist/chunks/generate.runtime-CuNhY5hn.js.map +0 -1
  133. package/dist/chunks/generate.runtime-pVLzzpUM.js.map +0 -1
  134. package/dist/chunks/generate.runtime-zJpEufTc.js.map +0 -1
  135. package/dist/chunks/nav-user-BRIHOOpG.js +0 -6
  136. package/dist/chunks/nav-user-BRIHOOpG.js.map +0 -1
  137. package/dist/chunks/ts-morph-helpers-CDW4lhox.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velastack/patterns",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Registry of VelaStack patterns: generators and modifications applied to SvelteKit projects by the VelaStack CLI.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -98,7 +98,7 @@
98
98
  "@types/node": "^26.5.1",
99
99
  "@types/pluralize": "^0.0.33",
100
100
  "@velastack/kit": "^0.4.0",
101
- "@velastack/pocketbase": "^0.4.0",
101
+ "@velastack/pocketbase": "^0.4.2",
102
102
  "@velastack/pocketbase-codegen": "^0.1.0",
103
103
  "change-case": "^5.4.4",
104
104
  "cross-spawn": "^7.0.6",
@@ -1,6 +0,0 @@
1
- //#region src/patterns/enable/subscriptions/preview-modifies/src/lib/components/app-sidebar.svelte?raw
2
- var e = "<script lang=\"ts\" module>\n import HomeIcon from '@lucide/svelte/icons/home';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n<\/script>\n\n<script lang=\"ts\">\n import favicon from '#lib/assets/favicon.svg';\n import { site } from '#lib/site.js';\n\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n import * as Sidebar from '#lib/components/ui/sidebar/index.js';\n import type { ComponentProps } from 'svelte';\n\n let {\n user,\n // [!code highlight:1]\n subscription = null,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & {\n user: any;\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <Sidebar.MenuItem>\n <Sidebar.MenuButton size=\"lg\">\n {#snippet child({ props })}\n <a href=\"/dashboard\" {...props}>\n <div\n class=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n >\n <img src={favicon} alt=\"logo\" class=\"size-6\" />\n </div>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{site.name}</span>\n </div>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} {subscription} />\n </Sidebar.Footer>\n</Sidebar.Root>\n", t = "<script lang=\"ts\">\n import { toggleMode, mode } from \"mode-watcher\";\n import ChevronsUpDownIcon from \"@lucide/svelte/icons/chevrons-up-down\";\n import Settings2Icon from \"@lucide/svelte/icons/settings-2\";\n import CreditCardIcon from \"@lucide/svelte/icons/credit-card\";\n import LogOutIcon from \"@lucide/svelte/icons/log-out\";\n import MoonIcon from \"@lucide/svelte/icons/moon\";\n import SunIcon from \"@lucide/svelte/icons/sun\";\n import * as Avatar from \"#lib/components/ui/avatar/index.js\";\n import * as DropdownMenu from \"#lib/components/ui/dropdown-menu/index.js\";\n import * as Sidebar from \"#lib/components/ui/sidebar/index.js\";\n\n let data = {\n navUser: [\n {\n title: \"Settings\",\n url: \"/settings\",\n icon: Settings2Icon,\n },\n {\n title: \"Billing\",\n url: \"/billing\",\n icon: CreditCardIcon,\n },\n ],\n };\n\n let {\n user,\n // [!code highlight:1]\n subscription = null,\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n\n // [!code highlight:1]\n const planLabel = $derived(subscription?.productName ?? \"Free\");\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image\n src=\"/api/files/users/{user.id}/{user.avatar}\"\n alt={user.name}\n />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() ||\n user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">\n {user.name || user.email}\n </span>\n <!-- [!code highlight:3] -->\n <span class=\"truncate text-xs text-muted-foreground\">\n {planLabel}\n </span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? \"bottom\" : \"right\"}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image\n src=\"/api/files/users/{user.id}/{user.avatar}\"\n alt={user.name}\n />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() ||\n user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">\n {user.name || user.email}\n </span>\n <!-- [!code highlight:3] -->\n <span class=\"truncate text-xs\">\n {planLabel}\n </span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === \"dark\"}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a\n href={item.url}\n class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\"\n >\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button\n type=\"submit\"\n class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\"\n >\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", n = "// [!code highlight:33]\nasync function loadActiveSubscription(locals: App.Locals, userId: string) {\n const subscriptions = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\n 'user = {:user} && (status = \"active\" || status = \"trialing\")',\n { user: userId },\n ),\n expand: \"price\",\n sort: \"-created\",\n })\n .catch(() => []);\n\n const sub = subscriptions[0];\n if (!sub) return null;\n\n const price = sub.expand?.price;\n let productName: string | null = null;\n if (price?.product) {\n const product = await locals.admin\n .collection(\"stripe_products\")\n .getOne(price.product)\n .catch(() => null);\n productName = product?.name ?? null;\n }\n\n return {\n id: sub.id,\n status: sub.status as string,\n productName,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n };\n}\n\nexport const load = async ({ locals }) => {\n const user = locals.pb.authStore.record!;\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n // [!code highlight:1]\n const subscription = await loadActiveSubscription(locals, user.id);\n\n // [!code highlight:1]\n return { user, breadcrumbs, subscription };\n};\n", r = "<script lang=\"ts\">\n import * as Sidebar from \"#lib/components/ui/sidebar/index.js\";\n import { Separator } from \"#lib/components/ui/separator/index.js\";\n import AppSidebar from \"#lib/components/app-sidebar.svelte\";\n import * as Breadcrumb from \"#lib/components/ui/breadcrumb/index.js\";\n import { page } from \"$app/state\";\n\n let breadcrumbs = $derived(page.data.breadcrumbs || []) as {\n title: string;\n url: string;\n }[];\n let { data, children } = $props();\n<\/script>\n\n<div class=\"min-h-dvh dashboard\">\n <Sidebar.Provider>\n <!-- [!code highlight:5] -->\n <AppSidebar\n user={data.user}\n \n subscription={data.subscription}\n />\n <Sidebar.Inset>\n <header class=\"flex h-16 shrink-0 items-center gap-2\">\n <div class=\"flex items-center gap-2 px-4\">\n <Sidebar.Trigger class=\"-ml-1\" />\n <Separator\n orientation=\"vertical\"\n class=\"mr-2 data-[orientation=vertical]:h-4\"\n />\n {#if breadcrumbs.length > 0}\n <Breadcrumb.Root>\n <Breadcrumb.List>\n {#if breadcrumbs.length > 1}\n {#each breadcrumbs.slice(0, -1) as breadcrumb}\n <Breadcrumb.Item>\n <Breadcrumb.Link href={breadcrumb.url}\n >{breadcrumb.title}</Breadcrumb.Link\n >\n </Breadcrumb.Item>\n <Breadcrumb.Separator />\n {/each}\n {/if}\n <Breadcrumb.Page>\n {breadcrumbs[breadcrumbs.length - 1].title}\n </Breadcrumb.Page>\n </Breadcrumb.List>\n </Breadcrumb.Root>\n {/if}\n </div>\n </header>\n <div class=\"flex flex-1 flex-col p-4 pt-0\">\n {@render children?.()}\n </div>\n </Sidebar.Inset>\n </Sidebar.Provider>\n</div>\n\n<style>\n :global(body:has(div.dashboard)) {\n background-color: var(--color-sidebar);\n }\n</style>\n", i = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"#lib/stripe.js\";\n\ntype RecurringInfo = {\n interval: string;\n interval_count: number;\n trial_period_days?: number | null;\n};\n\nfunction parseRecurring(value: unknown): RecurringInfo | null {\n if (!value) return null;\n if (typeof value === \"object\") return value as RecurringInfo;\n try {\n return JSON.parse(value as string) as RecurringInfo;\n } catch {\n return null;\n }\n}\n\nconst ACTIVE_SUBSCRIPTION_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n];\n\nexport const load = async ({ locals, depends, parent }) => {\n const { user } = await parent();\n depends(\"app:billing\");\n\n let customer;\n try {\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n locals.admin.filter(\"user = {:user}\", { user: user.id }),\n );\n } catch {\n // The link-stripe-customer workflow started at signup has not finished.\n return {\n paymentMethods: [],\n user,\n billingReady: false,\n hasDefaultPaymentMethod: false,\n activeSubscription: null,\n availablePlans: [],\n };\n }\n\n const stripeCustomer = await stripe.customers.retrieve(customer.id);\n if (stripeCustomer.deleted) {\n return error(400, \"Customer not found\");\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n const subscriptionRecords = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\"user = {:user}\", { user: user.id }),\n expand: \"price\",\n sort: \"-created\",\n });\n\n const recurringPrices = await locals.admin\n .collection(\"stripe_prices\")\n .getFullList({\n filter: locals.admin.filter(\"type = {:type} && active = true\", {\n type: \"recurring\",\n }),\n });\n\n const productIds: string[] = Array.from(\n new Set(\n recurringPrices\n .map((p) => p.product)\n .filter((id): id is string => Boolean(id)),\n ),\n );\n const productMap = new Map<string, string>();\n if (productIds.length > 0) {\n const products = await locals.admin\n .collection(\"stripe_products\")\n .getFullList({\n filter: productIds.map((id) => `id = \"${id}\"`).join(\" || \"),\n });\n for (const product of products) {\n productMap.set(product.id, product.name ?? product.id);\n }\n }\n\n const availablePlans = recurringPrices.map((price) => ({\n id: price.id,\n productName:\n (price.product && productMap.get(price.product)) ?? price.product ?? \"\",\n unitAmount: (price.unit_amount ?? 0) as number,\n currency: (price.currency ?? \"\") as string,\n recurring: parseRecurring(price.recurring),\n }));\n\n const subscriptions = subscriptionRecords.map((sub) => {\n const expanded = sub.expand?.price;\n return {\n id: sub.id,\n status: sub.status as string,\n currentPeriodStart: (sub.current_period_start as string | null) ?? null,\n currentPeriodEnd: (sub.current_period_end as string | null) ?? null,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n canceledAt: (sub.canceled_at as string | null) || null,\n priceId: sub.price as string,\n productName: expanded\n ? ((expanded.product && productMap.get(expanded.product)) ??\n expanded.product ??\n null)\n : null,\n unitAmount: expanded ? ((expanded.unit_amount ?? null) as number | null) : null,\n currency: expanded ? ((expanded.currency ?? null) as string | null) : null,\n recurring: expanded ? parseRecurring(expanded.recurring) : null,\n };\n });\n\n const activeSubscription =\n subscriptions.find((s) => ACTIVE_SUBSCRIPTION_STATUSES.includes(s.status)) ||\n null;\n\n // If the active plan isn't in the list (e.g., price was deactivated), include\n // it so it can still be shown as the current plan.\n if (\n activeSubscription &&\n !availablePlans.some((p) => p.id === activeSubscription.priceId)\n ) {\n availablePlans.push({\n id: activeSubscription.priceId,\n productName: activeSubscription.productName ?? \"\",\n unitAmount: activeSubscription.unitAmount ?? 0,\n currency: activeSubscription.currency ?? \"\",\n recurring: activeSubscription.recurring,\n });\n }\n\n availablePlans.sort((a, b) => a.unitAmount - b.unitAmount);\n\n return {\n billingReady: true,\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card!.brand,\n last4: pm.card!.last4,\n expMonth: pm.card!.exp_month,\n expYear: pm.card!.exp_year,\n isDefault: pm.id === customer.default_payment_method,\n })),\n user,\n hasDefaultPaymentMethod: Boolean(customer.default_payment_method),\n activeSubscription,\n availablePlans,\n };\n};\n\nasync function getUserCustomer(locals: App.Locals) {\n const userId = locals.pb.authStore.record?.id;\n if (!userId) {\n return error(401, \"Unauthorized\");\n }\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${userId}\"`);\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n return customer;\n}\n\n// A subscription can be updated in-place unless it has fully terminated.\nconst UPDATABLE_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n \"paused\",\n];\n\nasync function findUpdatableSubscription(\n locals: App.Locals,\n userId: string,\n) {\n const filterClause = UPDATABLE_STATUSES.map(\n (s) => `status = \"${s}\"`,\n ).join(\" || \");\n const subs = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(`user = {:user} && (${filterClause})`, {\n user: userId,\n }),\n sort: \"-created\",\n });\n return subs[0] ?? null;\n}\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n selectPlan: async ({ locals, request }) => {\n const formData = await request.formData();\n const priceId = formData.get(\"priceId\") as string;\n if (!priceId) return error(400, \"Price ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // If an updatable subscription already exists, change its price in place\n // rather than creating a duplicate. Covers switch, resume-to-different-plan,\n // and races where the webhook hasn't delivered the existing sub yet.\n const existing = await findUpdatableSubscription(locals, userId);\n if (existing) {\n const stripeSub = await stripe.subscriptions.retrieve(existing.id);\n const item = stripeSub.items.data[0];\n if (!item) return error(500, \"Subscription has no items\");\n\n await stripe.subscriptions.update(existing.id, {\n items: [{ id: item.id, price: priceId }],\n proration_behavior: \"create_prorations\",\n cancel_at_period_end: false,\n });\n return;\n }\n\n const customer = await getUserCustomer(locals);\n if (!customer.default_payment_method) {\n return error(400, \"Add a default payment method before subscribing\");\n }\n\n await stripe.subscriptions.create({\n customer: customer.id,\n items: [{ price: priceId }],\n default_payment_method: customer.default_payment_method,\n payment_behavior: \"error_if_incomplete\",\n off_session: true,\n });\n },\n cancelSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // Verify the subscription belongs to this user before touching Stripe.\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: true,\n });\n },\n resumeSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n },\n};\n", a = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import * as Card from '#lib/components/ui/card/index.js';\n import { Badge } from '#lib/components/ui/badge/index.js';\n import * as AlertDialog from '#lib/components/ui/alert-dialog/index.js';\n import SetupButton from '#lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check, Package } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate, refreshAll } from '$app/navigation';\n import { untrack } from 'svelte';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let availablePlans = $derived(data.availablePlans);\n let hasDefaultPaymentMethod = $derived(data.hasDefaultPaymentMethod);\n\n // Local, mutable mirror of the server-side subscription. We optimistically\n // update it on user actions so the UI reflects the change immediately; the\n // $effect re-syncs from the server after the webhook has had a chance to\n // fire (refreshAll runs on a short delay below).\n let activeSubscription = $state(untrack(() => data.activeSubscription));\n $effect(() => {\n activeSubscription = data.activeSubscription;\n });\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n let showCancelDialog = $state(false);\n let isSubscribing = $state<string | null>(null);\n let isCanceling = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n\n function formatAmount(amount: number | null, currency: string | null) {\n if (amount === null || !currency) return '—';\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: currency.toUpperCase()\n }).format(amount / 100);\n }\n\n function formatInterval(recurring: { interval: string; interval_count: number } | null) {\n if (!recurring) return '';\n if (recurring.interval_count === 1) return `/ ${recurring.interval}`;\n return `every ${recurring.interval_count} ${recurring.interval}s`;\n }\n\n function formatDate(iso: string | null) {\n if (!iso) return '—';\n return new Date(iso).toLocaleDateString(undefined, {\n year: 'numeric',\n month: 'short',\n day: 'numeric'\n });\n }\n\n async function selectPlan(priceId: string, successMessage: string) {\n if (!hasDefaultPaymentMethod) {\n toast.error('Add a default payment method first');\n return;\n }\n const previous = activeSubscription;\n const plan = availablePlans.find((p) => p.id === priceId);\n if (plan) {\n activeSubscription = previous\n ? {\n ...previous,\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false\n }\n : {\n id: 'pending',\n status: 'active',\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false,\n currentPeriodStart: null,\n currentPeriodEnd: null,\n canceledAt: null\n };\n }\n\n isSubscribing = priceId;\n try {\n const formData = new FormData();\n formData.append('priceId', priceId);\n\n const res = await fetch('?/selectPlan', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`selectPlan failed: ${res.status}`);\n }\n\n toast.success(successMessage);\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error selecting plan:', err);\n toast.error('Failed to update plan');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function subscribe(priceId: string) {\n await selectPlan(priceId, 'Subscription started');\n }\n\n async function switchPlan(priceId: string) {\n await selectPlan(priceId, 'Subscription updated');\n }\n\n async function resumeSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isSubscribing = activeSubscription.priceId;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: false };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/resumeSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Resume failed: ${res.status}`);\n }\n\n toast.success('Subscription resumed');\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error resuming subscription:', err);\n toast.error('Failed to resume subscription');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function handleCancelSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isCanceling = true;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: true };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/cancelSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Cancel failed: ${res.status}`);\n }\n\n toast.success('Subscription will cancel at period end');\n showCancelDialog = false;\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error canceling subscription:', err);\n toast.error('Failed to cancel subscription');\n activeSubscription = previous;\n } finally {\n isCanceling = false;\n }\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if !data.billingReady}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">Setting up billing</p>\n <p class=\"text-sm\">This takes a moment after signing up. Refresh to check again.</p>\n </div>\n {:else if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n {#if data.billingReady}\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n {/if}\n </Card.Root>\n </div>\n </div>\n\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Plan</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">Manage your subscription.</p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if availablePlans.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <Package class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No plans available</p>\n <p class=\"text-sm\">Check back soon.</p>\n </div>\n {:else}\n {#if !hasDefaultPaymentMethod}\n <p class=\"text-muted-foreground mb-4 rounded-md border border-dashed p-3 text-sm\">\n Add a default payment method above to subscribe.\n </p>\n {/if}\n <div class=\"space-y-4\">\n {#each availablePlans as plan (plan.id)}\n {@const isCurrent = activeSubscription?.priceId === plan.id}\n <div\n class=\"flex items-center justify-between rounded-lg border p-4 transition-colors {isCurrent\n ? 'border-primary ring-primary ring-1'\n : 'border-border hover:bg-accent/50'}\"\n >\n <div class=\"flex items-center gap-4\">\n <div class=\"bg-muted flex size-12 items-center justify-center rounded-lg\">\n <Package class=\"size-5\" />\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">{plan.productName}</p>\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Badge variant=\"outline\">Pending cancellation</Badge>\n {:else if activeSubscription.status === 'trialing'}\n <Badge variant=\"secondary\">Trial</Badge>\n {:else if activeSubscription.status === 'past_due'}\n <Badge variant=\"destructive\">Past due</Badge>\n {:else}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Current\n </Badge>\n {/if}\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(plan.unitAmount, plan.currency)}\n {formatInterval(plan.recurring)}\n {#if isCurrent && activeSubscription?.currentPeriodEnd}\n <span>\n &bull;\n {activeSubscription.cancelAtPeriodEnd ? 'Cancels on' : 'Renews on'}\n {formatDate(activeSubscription.currentPeriodEnd)}\n </span>\n {/if}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={isSubscribing === plan.id}\n onclick={resumeSubscription}\n >\n {isSubscribing === plan.id ? 'Resuming...' : 'Resume'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => (showCancelDialog = true)}\n >\n Cancel subscription\n </Button>\n {/if}\n {:else if activeSubscription}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => switchPlan(plan.id)}\n >\n {isSubscribing === plan.id ? 'Switching...' : 'Switch'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => subscribe(plan.id)}\n >\n {isSubscribing === plan.id ? 'Subscribing...' : 'Subscribe'}\n </Button>\n {/if}\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Cancel Subscription Dialog -->\n<AlertDialog.Root bind:open={showCancelDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Cancel Subscription</AlertDialog.Title>\n <AlertDialog.Description>\n Your subscription will remain active until the end of the current billing period, then\n cancel automatically.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={() => (showCancelDialog = false)}>\n Keep Subscription\n </AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleCancelSubscription} disabled={isCanceling}>\n {isCanceling ? 'Canceling...' : 'Cancel at Period End'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", o = "import type Stripe from 'stripe';\nimport { handlePaymentIntentSucceeded } from './payment-intent/succeeded';\nimport { handlePaymentMethodAttached } from './payment-method/attached';\nimport { handleSubscriptionCreated } from './subscription/created';\nimport { handleSubscriptionUpdated } from './subscription/updated';\nimport { handleSubscriptionDeleted } from './subscription/deleted';\n\n/**\n * Routes a verified Stripe event to its handler. Runs inside the stripe-event\n * workflow, so a handler that throws is retried with backoff rather than lost.\n */\nexport async function dispatchStripeEvent(event: Stripe.Event, locals: App.Locals) {\n switch (event.type) {\n case 'payment_intent.succeeded':\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n case 'payment_method.attached':\n await handlePaymentMethodAttached(event.data.object, locals);\n break;\n\n case 'customer.subscription.created':\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case 'customer.subscription.updated':\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case 'customer.subscription.deleted':\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n}\n";
3
- //#endregion
4
- export { n as a, r as i, a as n, t as o, i as r, e as s, o as t };
5
-
6
- //# sourceMappingURL=dispatch-CXOXPLFk.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"dispatch-CXOXPLFk.js","names":["app_sidebar_default","nav_user_default","_layout_server_default","_layout_default","_page_server_default","_page_default","dispatch_default"],"sources":[],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"format-result-DZ8De8KY.js","names":["path","prettier","sveltePlugin","canFormatFile","file","dependsOnPrettier","pkg","readFileSync","root","usesPrettier","target","projectOptions","context","resolved","plugins","plugin","MAX_FORMAT_PASSES","formatSource","options","filePath","created","content","format","source","formatted","pass","again","formatFile","formatFiles","files","formatResult","creates","modifies","result"],"sources":["../../src/core/format-result.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport prettier from \"prettier\";\nimport type { File, Options, Result } from \"./types\";\nimport sveltePlugin from \"prettier-plugin-svelte\";\n\n/** What the formatter needs to know about the run: where the project is, and whether it exists at all. */\nexport type FormatContext = Pick<Options, \"env\" | \"root\">;\n\nfunction canFormatFile(file: File): boolean {\n return (\n file.language === \"ts\" ||\n file.language === \"js\" ||\n file.language === \"svelte\" ||\n file.path.endsWith(\".json\")\n );\n}\n\nfunction dependsOnPrettier(root: string): boolean {\n try {\n const pkg = JSON.parse(\n readFileSync(path.join(root, \"package.json\"), \"utf8\"),\n ) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return Boolean(pkg.dependencies?.prettier || pkg.devDependencies?.prettier);\n } catch {\n return false;\n }\n}\n\n/**\n * Whether the project formats with prettier: it depends on it, or prettier\n * finds a config file for the target (a monorepo may keep one at its root).\n * A project with neither, like a bare `sv create`, has a style of its own\n * that prettier's defaults would rewrite in every file a pattern edits.\n */\nasync function usesPrettier(root: string, target: string): Promise<boolean> {\n if (dependsOnPrettier(root)) return true;\n return (await prettier.resolveConfigFile(target)) !== null;\n}\n\n/**\n * The target project's own prettier settings (`.prettierrc`, `.editorconfig`,\n * `package.json#prettier`), so pattern output matches what `npm run lint`\n * expects there; `null` when the project does not use prettier. Preview runs\n * have no project and use prettier's defaults.\n *\n * The svelte plugin is always supplied as a module: a project's config names\n * it by string, which would resolve relative to this package instead.\n */\nasync function projectOptions(\n file: Pick<File, \"path\">,\n context?: FormatContext,\n): Promise<prettier.Options | null> {\n if (context?.env !== \"runtime\" || !context.root) return {};\n const target = path.isAbsolute(file.path)\n ? file.path\n : path.join(context.root, file.path);\n if (!(await usesPrettier(context.root, target))) return null;\n const resolved = await prettier.resolveConfig(target, { editorconfig: true });\n if (!resolved) return {};\n const plugins = (resolved.plugins ?? []).filter(\n (plugin) => plugin !== \"prettier-plugin-svelte\",\n );\n return { ...resolved, plugins };\n}\n\nconst MAX_FORMAT_PASSES = 3;\n\n/**\n * Formats one source text the way pattern output is formatted; the content\n * comes back unchanged when prettier cannot parse it, or when the project\n * does not use prettier and the file is not `created`. A file a generator\n * created is formatted either way, with prettier's defaults if need be: it\n * relies on formatting for its indentation and has no style of its own to\n * keep. Also used for component files that arrive on disk from\n * `shadcn-svelte add` or the bundled components, so `npm run lint` in the\n * project stays clean after an install.\n */\nexport async function formatSource(\n content: string,\n filePath: string,\n context?: FormatContext,\n { created = false }: { created?: boolean } = {},\n): Promise<string> {\n try {\n const options =\n (await projectOptions({ path: filePath }, context)) ??\n (created ? {} : null);\n if (!options) return content;\n const format = (source: string) =>\n prettier.format(source, {\n ...options,\n filepath: filePath,\n plugins: [...(options.plugins ?? []), sveltePlugin],\n });\n // Prettier is not always idempotent: a long one-line member chain\n // (`await context.admin.collection(\"x\").create({ ... })`) comes out broken\n // across lines on the first pass and joined on the second, which the\n // project's `prettier --check` would flag. Format until it settles.\n let formatted = await format(content);\n for (let pass = 1; pass < MAX_FORMAT_PASSES; pass++) {\n const again = await format(formatted);\n if (again === formatted) break;\n formatted = again;\n }\n return formatted;\n } catch {\n return content;\n }\n}\n\nasync function formatFile(\n file: File,\n context: FormatContext | undefined,\n created: boolean,\n): Promise<File> {\n if (file.status !== \"success\" || !canFormatFile(file)) {\n return file;\n }\n return {\n ...file,\n content: await formatSource(file.content, file.path, context, { created }),\n };\n}\n\nasync function formatFiles(\n files: File[],\n context: FormatContext | undefined,\n created: boolean,\n): Promise<File[]> {\n return Promise.all(files.map((file) => formatFile(file, context, created)));\n}\n\nexport async function formatResult(\n result: Result,\n context?: FormatContext,\n): Promise<Result> {\n const [creates, modifies] = await Promise.all([\n formatFiles(result.creates, context, true),\n formatFiles(result.modifies, context, false),\n ]);\n\n return {\n ...result,\n creates,\n modifies,\n };\n}\n"],"mappings":";;;;;AASA,SAASG,EAAc,GAAqB;CAC1C,OACEC,EAAK,aAAa,QAClBA,EAAK,aAAa,QAClBA,EAAK,aAAa,YAClBA,EAAK,KAAK,SAAS,OAAO;AAE9B;AAEA,SAASC,EAAkB,GAAuB;CAChD,IAAI;EACF,IAAMC,IAAM,KAAK,MAC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AAOE,CAAS;GACpC,IAAIE,MAAUF,GAAW;GACzB,IAAYE;EACd;EACA,OAAOF;CACT,QAAQ;EACN,OAAOH;CACT;AACF;AAEA,eAAeM,EACb,GACA,GACA,GACe;CAIf,OAHIvB,EAAK,WAAW,aAAa,CAACD,EAAcC,CAAI,IAC3CA,IAEF;EACL,GAAGA;EACH,SAAS,MAAMa,EAAab,EAAK,SAASA,EAAK,MAAMQ,GAAS,EAAE,WAAQ,CAAC;CAC3E;AACF;AAEA,eAAegB,EACb,GACA,GACA,GACiB;CACjB,OAAO,QAAQ,IAAIC,EAAM,KAAK,MAASF,EAAWvB,GAAMQ,GAASQ,CAAO,CAAC,CAAC;AAC5E;AAEA,eAAsBU,EACpB,GACA,GACiB;CACjB,IAAM,CAACC,GAASC,KAAY,MAAM,QAAQ,IAAI,CAC5CJ,EAAYK,EAAO,SAASrB,GAAS,EAAI,GACzCgB,EAAYK,EAAO,UAAUrB,GAAS,EAAK,CAC7C,CAAC;CAED,OAAO;EACL,GAAGqB;EACH;EACA;CACF;AACF"}
@@ -1,188 +0,0 @@
1
- import { t as e } from "./dedent-Gq6Krl4n.js";
2
- import { n as t } from "./logger-CQONztPm.js";
3
- import { n, r, t as i } from "./nav-user-BRIHOOpG.js";
4
- import { t as a } from "./shared-CZC4d7Uj.js";
5
- import { _ as o, o as s, u as c } from "./ts-morph-helpers-CDW4lhox.js";
6
- import { modifyOutcomeToFile as l } from "./modify-file-BlDeeurK.js";
7
- import { t as u } from "./svelte-file-B3RfgVdt.js";
8
- import d from "node:fs";
9
- import f from "node:path";
10
- import { SyntaxKind as p } from "ts-morph";
11
- //#region src/patterns/disable/subscriptions/modifies/modify-webhook-server.ts
12
- var m = /* @__PURE__ */ new Set([
13
- "customer.subscription.created",
14
- "customer.subscription.updated",
15
- "customer.subscription.deleted"
16
- ]);
17
- function h(e) {
18
- if (!d.existsSync(e)) return {
19
- status: "success",
20
- changed: !1
21
- };
22
- let t = d.readFileSync(e, "utf8");
23
- if (!t.includes("handleSubscriptionCreated")) return {
24
- status: "success",
25
- changed: !1
26
- };
27
- let { source: n } = o(t, (e) => {
28
- c(e, "./subscription/created"), c(e, "./subscription/updated"), c(e, "./subscription/deleted");
29
- let t = e.getDescendantsOfKind(p.SwitchStatement).find((e) => e.getExpression().getText().includes("event.type"));
30
- if (!t) return;
31
- let n = t.getCaseBlock().getClauses().filter((e) => {
32
- if (e.getKind() !== p.CaseClause) return !1;
33
- let t = e.asKindOrThrow(p.CaseClause).getExpression(), n = t.asKind(p.StringLiteral) ?? t.asKind(p.NoSubstitutionTemplateLiteral);
34
- return n ? m.has(n.getLiteralValue()) : !1;
35
- }).map((e) => e.asKindOrThrow(p.CaseClause));
36
- for (let e of n.reverse()) e.remove();
37
- s(e);
38
- }), r = n.replace(/(break;)\n(\s*default:)/, "$1\n\n$2");
39
- return r === t ? {
40
- status: "success",
41
- changed: !1
42
- } : (d.writeFileSync(e, r, "utf8"), {
43
- status: "success",
44
- changed: !0
45
- });
46
- }
47
- //#endregion
48
- //#region src/patterns/disable/subscriptions/modifies/modify-app-layout-svelte.ts
49
- function g(e) {
50
- if (!d.existsSync(e)) return {
51
- status: "success",
52
- changed: !1
53
- };
54
- let t = u.fromPath(e);
55
- return !t.hasElement("AppSidebar") || !t.hasAttribute("AppSidebar", "subscription") || !t.removeAttribute("AppSidebar", "subscription") ? {
56
- status: "success",
57
- changed: !1
58
- } : (t.writeTo(e), {
59
- status: "success",
60
- changed: t.hasChanged()
61
- });
62
- }
63
- //#endregion
64
- //#region src/patterns/disable/subscriptions/modifies/modify-app-sidebar.ts
65
- function _(e) {
66
- let { source: t } = o(e, (e) => {
67
- for (let t of e.getVariableDeclarations()) {
68
- let e = t.getInitializer();
69
- if (!e || e.getText() !== "$props()") continue;
70
- let n = t.getNameNode();
71
- if (n.getKind() !== p.ObjectBindingPattern) continue;
72
- let r = n.asKindOrThrow(p.ObjectBindingPattern), i = r.getElements(), a = i.some((e) => e.getName() === "subscription"), o = t.getTypeNode();
73
- if (o?.getKind() === p.IntersectionType) {
74
- let e = o.asKindOrThrow(p.IntersectionType);
75
- for (let t of e.getTypeNodes()) {
76
- if (t.getKind() !== p.TypeLiteral) continue;
77
- let e = t.asKindOrThrow(p.TypeLiteral), n = e.getProperties().map((e) => e.getText().replace(/[;,]\s*$/, "")).filter((e) => !/^\s*subscription\??\s*:/.test(e));
78
- e.replaceWithText(n.length ? `{ ${n.join("; ")}; }` : "{}");
79
- break;
80
- }
81
- }
82
- if (a) {
83
- let e = i.filter((e) => e.getName() !== "subscription").map((e) => e.getText());
84
- r.replaceWithText(`{ ${e.join(", ")} }`);
85
- }
86
- }
87
- s(e);
88
- });
89
- return t;
90
- }
91
- function v(e) {
92
- if (!d.existsSync(e)) return {
93
- status: "success",
94
- changed: !1
95
- };
96
- let t = d.readFileSync(e, "utf8"), n = /subscription\??\s*:\s*\{/.test(t), r = /\bsubscription\s*=\s*null\b/.test(t), i = new u(t), a = i.hasElement("NavUser") && i.hasAttribute("NavUser", "subscription");
97
- return !n && !r && !a ? {
98
- status: "success",
99
- changed: !1
100
- } : ((n || r) && i.modifyScript(_), a && i.removeAttribute("NavUser", "subscription"), i.writeTo(e), {
101
- status: "success",
102
- changed: i.hasChanged()
103
- });
104
- }
105
- //#endregion
106
- //#region src/patterns/disable/subscriptions/modifies/revert-by-template.ts
107
- function y(e, t, n) {
108
- if (!d.existsSync(e)) return {
109
- status: "success",
110
- changed: !1
111
- };
112
- let r = d.readFileSync(e, "utf8");
113
- if (!r.includes(n)) return {
114
- status: "success",
115
- changed: !1
116
- };
117
- let i = t.replace(/^[ \t]*\/\/[ \t]*\[!code highlight:\d+\][ \t]*\r?\n/gm, "").replace(/^[ \t]*<!--[ \t]*\[!code highlight:\d+\][ \t]*-->[ \t]*\r?\n/gm, "");
118
- return r === i ? {
119
- status: "success",
120
- changed: !1
121
- } : (d.writeFileSync(e, i, "utf8"), {
122
- status: "success",
123
- changed: !0
124
- });
125
- }
126
- //#endregion
127
- //#region src/patterns/disable/subscriptions/modifies/modify-app-layout-server.ts
128
- var b = e`
129
- export const load = ({ locals }) => {
130
- \tconst user = locals.pb.authStore.record!;
131
- \tconst breadcrumbs = [{ title: 'Home', url: '/dashboard' }];
132
-
133
- \treturn { user, breadcrumbs };
134
- };
135
- ` + "\n";
136
- function x(e) {
137
- return y(e, b, "loadActiveSubscription");
138
- }
139
- //#endregion
140
- //#region src/patterns/disable/subscriptions/modifies/modify-nav-user.ts
141
- function S(e, t) {
142
- return y(e, t, "planLabel");
143
- }
144
- //#endregion
145
- //#region src/patterns/disable/subscriptions/modifies/modify-billing-page-server.ts
146
- function C(e, t) {
147
- return y(e, t, "selectPlan");
148
- }
149
- //#endregion
150
- //#region src/patterns/disable/subscriptions/modifies/modify-billing-page-svelte.ts
151
- function w(e, t) {
152
- return y(e, t, "availablePlans");
153
- }
154
- //#endregion
155
- //#region src/patterns/disable/subscriptions/generate.runtime.ts
156
- async function T(e) {
157
- let o = t(e), s = [], c = (e) => {
158
- e && s.push(e);
159
- };
160
- o.info("Reverting webhooks/stripe/handlers/dispatch.ts");
161
- let u = f.join(e.root, "src", "routes", "webhooks", "stripe", "handlers", "dispatch.ts");
162
- c(l(u, h(u))), o.info("Reverting (app)/+layout.server.ts");
163
- let d = f.join(e.root, "src", "routes", "(app)", "+layout.server.ts");
164
- c(l(d, x(d))), o.info("Reverting (app)/+layout.svelte");
165
- let p = f.join(e.root, "src", "routes", "(app)", "+layout.svelte");
166
- c(l(p, g(p))), o.info("Reverting app-sidebar.svelte");
167
- let m = f.join(e.root, "src", "lib", "components", "app-sidebar.svelte");
168
- c(l(m, v(m))), o.info("Reverting nav-user.svelte");
169
- let _ = f.join(e.root, "src", "lib", "components", "nav-user.svelte");
170
- c(l(_, S(_, i))), o.info("Reverting billing/+page.server.ts");
171
- let y = f.join(e.root, "src", "routes", "(app)", "billing", "+page.server.ts");
172
- c(l(y, C(y, r))), o.info("Reverting billing/+page.svelte");
173
- let b = f.join(e.root, "src", "routes", "(app)", "billing", "+page.svelte");
174
- return c(l(b, w(b, n))), {
175
- creates: [],
176
- modifies: s,
177
- deletes: [],
178
- components: [],
179
- packages: [],
180
- collections: [],
181
- collectionPatches: [],
182
- collectionDrops: await a(["stripe_subscriptions"], e)
183
- };
184
- }
185
- //#endregion
186
- export { T as generate };
187
-
188
- //# sourceMappingURL=generate.runtime-BO778G0r.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-BO778G0r.js","names":["paymentsNavUserTemplate","paymentsBillingPageServerTemplate","paymentsBillingPageSvelteTemplate","dedent","getLogger","nav_user_default","planDropsForCollections","withInMemoryScript","formatLikeSource","removeImportByModuleSpecifier","SvelteFile","fs","path","SUBSCRIPTION_CASE_VALUES","unmodifyWebhookServer","filePath","original","sf","switchStmt","SyntaxKind","stmt","toRemove","clause","expr","literal","c","spaced","source","unmodifyAppLayoutSvelte","file","updateScript","out","decl","init","nameNode","pattern","elements","hasSub","typeNode","intersection","member","lit","propTexts","p","t","remaining","unmodifyAppSidebar","hasSubPropType","hasSubProp","hasNavUserSubAttr","revertByTemplate","current","enabledMarker","stripped","template","BASELINE","unmodifyAppLayoutServer","unmodifyNavUser","paymentsNavUserTemplate","unmodifyBillingPageServer","paymentsBillingPageServerTemplate","unmodifyBillingPageSvelte","paymentsBillingPageSvelteTemplate","generate","logger","options","modifies","pushResult","webhookServerPath","modifyOutcomeToFile","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","_page_server_default","billingPageSveltePath","_page_default"],"sources":["../../src/patterns/disable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/disable/subscriptions/modifies/revert-by-template.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-nav-user.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/disable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst SUBSCRIPTION_CASE_VALUES = new Set([\n \"customer.subscription.created\",\n \"customer.subscription.updated\",\n \"customer.subscription.deleted\",\n]);\n\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n removeImportByModuleSpecifier(sf, \"./subscription/created\");\n removeImportByModuleSpecifier(sf, \"./subscription/updated\");\n removeImportByModuleSpecifier(sf, \"./subscription/deleted\");\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n // Collect matching case clauses first — removing invalidates node refs.\n const toRemove = caseBlock\n .getClauses()\n .filter((clause) => {\n if (clause.getKind() !== SyntaxKind.CaseClause) return false;\n const caseClause = clause.asKindOrThrow(SyntaxKind.CaseClause);\n const expr = caseClause.getExpression();\n const literal =\n expr.asKind(SyntaxKind.StringLiteral) ??\n expr.asKind(SyntaxKind.NoSubstitutionTemplateLiteral);\n if (!literal) return false;\n return SUBSCRIPTION_CASE_VALUES.has(literal.getLiteralValue());\n })\n .map((c) => c.asKindOrThrow(SyntaxKind.CaseClause));\n\n for (const clause of toRemove.reverse()) {\n clause.remove();\n }\n\n formatLikeSource(sf);\n });\n\n // Removing the clauses takes the blank line before `default:` with them.\n const spaced = source.replace(/(break;)\\n(\\s*default:)/, \"$1\\n\\n$2\");\n\n if (spaced === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, spaced, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const removed = file.removeAttribute(\"AppSidebar\", \"subscription\");\n if (!removed) {\n return { status: \"success\", changed: false };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction updateScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n const hasSub = elements.some((e) => e.getName() === \"subscription\");\n\n // Strip subscription from the props type literal (the specific type\n // added by enable-subscriptions — leave unrelated `subscription` props\n // alone).\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"))\n .filter((t) => !/^\\s*subscription\\??\\s*:/.test(t));\n lit.replaceWithText(\n propTexts.length ? `{ ${propTexts.join(\"; \")}; }` : \"{}\",\n );\n break;\n }\n }\n\n if (hasSub) {\n const remaining = elements\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n pattern.replaceWithText(`{ ${remaining.join(\", \")} }`);\n }\n }\n formatLikeSource(sf);\n });\n return out;\n}\n\nexport function unmodifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(filePath, \"utf8\");\n const hasSubPropType = /subscription\\??\\s*:\\s*\\{/.test(source);\n const hasSubProp = /\\bsubscription\\s*=\\s*null\\b/.test(source);\n\n const file = new SvelteFile(source);\n const hasNavUserSubAttr =\n file.hasElement(\"NavUser\") && file.hasAttribute(\"NavUser\", \"subscription\");\n\n if (!hasSubPropType && !hasSubProp && !hasNavUserSubAttr) {\n return { status: \"success\", changed: false };\n }\n\n if (hasSubPropType || hasSubProp) {\n file.modifyScript(updateScript);\n }\n if (hasNavUserSubAttr) {\n file.removeAttribute(\"NavUser\", \"subscription\");\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Rewrites a file to the given `template` if the current content still shows\n * the `enabledMarker` (meaning enable-subscriptions is applied). If the marker\n * is absent (already reverted or never applied), it's a no-op.\n *\n * Strips leading `// [!code highlight:N]` / `<!-- [!code highlight:N] -->`\n * lines so templates can be pulled from `preview-modifies/` directories which\n * use those for documentation highlighting.\n */\nexport function revertByTemplate(\n filePath: string,\n template: string,\n enabledMarker: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (!current.includes(enabledMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import dedent from \"dedent\";\nimport { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n// Baseline velastack-auth (app)/+layout.server.ts — the state of the file\n// before enable-subscriptions wrapped it with loadActiveSubscription.\nconst BASELINE =\n dedent`\n export const load = ({ locals }) => {\n \\tconst user = locals.pb.authStore.record!;\n \\tconst breadcrumbs = [{ title: 'Home', url: '/dashboard' }];\n\n \\treturn { user, breadcrumbs };\n };\n` + \"\\n\";\n\nexport function unmodifyAppLayoutServer(filePath: string): ModifyOutcome {\n return revertByTemplate(filePath, BASELINE, \"loadActiveSubscription\");\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyNavUser(\n filePath: string,\n paymentsNavUserTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(filePath, paymentsNavUserTemplate, \"planLabel\");\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageServer(\n filePath: string,\n paymentsBillingPageServerTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageServerTemplate,\n \"selectPlan\",\n );\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageSvelte(\n filePath: string,\n paymentsBillingPageSvelteTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageSvelteTemplate,\n \"availablePlans\",\n );\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\nimport { unmodifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { unmodifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { unmodifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { unmodifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { unmodifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\n\n// Pull the \"post-payments\" state of files that enable-subscriptions fully\n// overwrote. For the billing pages, that's exactly what enable-payments\n// writes in creates-app-mode; for nav-user it's the payments preview-modifies\n// snapshot (with highlight annotations stripped by the revert helper).\nimport paymentsNavUserTemplate from \"../../enable/payments/preview-modifies/src/lib/components/nav-user.svelte?raw\";\nimport paymentsBillingPageServerTemplate from \"../../enable/payments/creates-app-mode/src/routes/(app)/billing/+page.server.ts?raw\";\nimport paymentsBillingPageSvelteTemplate from \"../../enable/payments/creates-app-mode/src/routes/(app)/billing/+page.svelte?raw\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n unmodifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n unmodifyAppLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n unmodifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Reverting app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, unmodifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n navUserPath,\n unmodifyNavUser(navUserPath, paymentsNavUserTemplate),\n ),\n );\n\n logger.info(\"Reverting billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n unmodifyBillingPageServer(\n billingPageServerPath,\n paymentsBillingPageServerTemplate,\n ),\n ),\n );\n\n logger.info(\"Reverting billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n unmodifyBillingPageSvelte(\n billingPageSveltePath,\n paymentsBillingPageSvelteTemplate,\n ),\n ),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"stripe_subscriptions\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;AASA,IAAMa,oBAA2B,IAAI,IAAI;CACvC;CACA;CACA;AACF,CAAC;AAED,SAAgBC,EAAsB,GAAiC;CACrE,IAAI,CAACH,EAAG,WAAWI,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAE7C,IAAMC,IAAWL,EAAG,aAAaI,GAAU,MAAM;CACjD,IAAI,CAACC,EAAS,SAAS,2BAA2B,GAChD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,EAAE,cAAWT,EAAmBS,IAAW,MAAO;EAGtD,AAFAP,EAA8BQ,GAAI,wBAAwB,GAC1DR,EAA8BQ,GAAI,wBAAwB,GAC1DR,EAA8BQ,GAAI,wBAAwB;EAE1D,IAAMC,IAAaD,EAChB,qBAAqBE,EAAW,eAAe,CAAC,CAChD,MAAM,MAASC,EAAK,cAAc,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,YAAY,CAAC;EACvE,IAAI,CAACF,GAAY;EAIjB,IAAMG,IAFYH,EAAW,aAEZ,CAAA,CACd,WAAW,CAAC,CACZ,QAAQ,MAAW;GAClB,IAAII,EAAO,QAAQ,MAAMH,EAAW,YAAY,OAAO;GAEvD,IAAMI,IADaD,EAAO,cAAcH,EAAW,UACtC,CAAA,CAAW,cAAc,GAChCK,IACJD,EAAK,OAAOJ,EAAW,aAAa,KACpCI,EAAK,OAAOJ,EAAW,6BAA6B;GAEtD,OADKK,IACEX,EAAyB,IAAIW,EAAQ,gBAAgB,CAAC,IADxC;EAEvB,CAAC,CAAC,CACD,KAAK,MAAMC,EAAE,cAAcN,EAAW,UAAU,CAAC;EAEpD,KAAK,IAAMG,KAAUD,EAAS,QAAQ,GACpC,EAAO,OAAO;EAGhB,EAAiBJ,CAAE;C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KAAK,gCAAgC;CAC5C,IAAMO,IAAsB3D,EAAK,KAC/BqD,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAQA,AAPAE,EACEE,EACEE,GACA3C,EAAwB2C,CAAmB,CAC7C,CACF,GAEAP,EAAO,KAAK,8BAA8B;CAC1C,IAAMQ,IAAiB5D,EAAK,KAC1BqD,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJAE,EACEE,EAAoBG,GAAgB1B,EAAmB0B,CAAc,CAAC,CACxE,GAEAR,EAAO,KAAK,2BAA2B;CACvC,IAAMS,IAAc7D,EAAK,KACvBqD,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAQA,AAPAE,EACEE,EACEI,GACAhB,EAAgBgB,GAAazE,CAAuB,CACtD,CACF,GAEAgE,EAAO,KAAK,mCAAmC;CAC/C,IAAMU,IAAwB9D,EAAK,KACjCqD,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVAE,EACEE,EACEK,GACAf,EACEe,GACAzE,CACF,CACF,CACF,GAEA+D,EAAO,KAAK,gCAAgC;CAC5C,IAAMY,IAAwBhE,EAAK,KACjCqD,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAgBA,OAfAE,EACEE,EACEO,GACAf,EACEe,GACA1E,CACF,CACF,CACF,GAOO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4BI,EAC5B,CAAC,sBAAsB,GACvB2D,CACF;CAWA;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-BgTz41Zg.js","names":["FAILURE_HINT","NOT_FOUND_HINT","languageFromPath","_taggedTemplateLiteral","getLogger","modifyEnv","formatLikeSource","addNavItemToScript","SvelteFile","withPocketbase","migrationDelay","getMigrationFile","STRIPE_ENV_VARS","fs","path","Stripe","BILLING_NAV_SNIPPET","FAILURE_HINT$1","NOT_FOUND_HINT$1","addItemToNavUser","file","navUserSnippet","wasAdded","tryAdd","run","result","source","title","url","icon","iconImportPath","fn","modifyNavUser","navUserPath","newNavUserSnippet","WORKFLOW_MODULE","RUN_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","modifyUserSignup","userSignupPath","originalSource","sourceFile","Project","QuoteKind","requestVerificationCall","SyntaxKind","expr","ce","statement","syncUsersToStripeCustomers","stripe","stripeSecretKey","users","pb","existing","linkedUserIds","c","user","logger","matching","customer","isExistingCustomer","error","paymentMethods","paymentMethod","defaultPaymentMethod","createTestProductAndPrice","products","product","prices","getProductAndPriceById","price","priceId","_templateObject","pushMigrationCreates","created","migrationFile","collectionName","action","options","creates","paymentPageSnippet","dedent","generate","isAppMode","modifies","pushResult","envEdits","stripePublishableKey","stripeWebhookSecret","envPath","modifyOutcomeToFile","envVars","modifyEnvVarsFiles","create","createCollectionIdempotent","spec","productsResult","pricesResult","customersResult","stripeCustomersCollection","paymentMethodsResult","stripePaymentMethodsCollection","transactionsResult","syncResult","stripePriceId"],"sources":["../../src/patterns/enable/payments/modifies/modify-nav-user.ts","../../src/patterns/enable/payments/modifies/modify-user-signup.ts","../../src/patterns/enable/payments/runtime/stripe.ts","../../src/patterns/enable/payments/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BILLING_NAV_SNIPPET = [\n \"import CreditCardIcon from '@lucide/svelte/icons/credit-card';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Billing', url: '/billing', icon: CreditCardIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Billing nav item to nav-user.svelte:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Billing entry:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Billing\",\n \"/billing\",\n \"CreditCardIcon\",\n \"@lucide/svelte/icons/credit-card\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst WORKFLOW_MODULE = \"#lib/workflows/link-stripe-customer.js\";\n\nconst RUN_SNIPPET = dedent`\n // Queued here, done in the background: the Stripe calls retry on their own,\n // and the key means a retry never makes a second customer for this user.\n await linkStripeCustomer.run(\n { userId: user.id, email: form.data.email },\n { idempotencyKey: user.id }\n );\n`;\n\nconst FAILURE_HINT = [\n \"Could not locate the requestVerification call in signup +page.server.ts.\",\n \"Start the workflow once the user exists:\",\n \"\",\n `import { linkStripeCustomer } from '${WORKFLOW_MODULE}';`,\n \"\",\n RUN_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments.\",\n].join(\"\\n\");\n\n/**\n * Starts the link-stripe-customer workflow right after the user is created.\n * The work itself lives in src/lib/workflows/link-stripe-customer.ts.\n */\nexport function modifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n if (originalSource.includes(\"linkStripeCustomer\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n const requestVerificationCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => {\n const expr = ce.getExpression();\n return (\n expr.getKind() === SyntaxKind.PropertyAccessExpression &&\n expr.getText().includes(\"requestVerification\")\n );\n });\n\n if (!requestVerificationCall) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const statement = requestVerificationCall.getFirstAncestorByKind(\n SyntaxKind.ExpressionStatement,\n );\n\n if (!statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n sourceFile.addImportDeclaration({\n namedImports: [\"linkStripeCustomer\"],\n moduleSpecifier: WORKFLOW_MODULE,\n });\n\n statement.replaceWithText(RUN_SNIPPET + \"\\n\\n\" + statement.getText());\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import Stripe from \"stripe\";\nimport type PocketBase from \"pocketbase\";\nimport type { Logger } from \"../../../../core/logger\";\n\nexport interface StripeTestFixture {\n product: Stripe.Product;\n price: Stripe.Price;\n existing: boolean;\n}\n\nexport interface SyncUsersResult {\n total: number;\n linked: number;\n created: number;\n reused: number;\n skipped: number;\n}\n\nexport async function syncUsersToStripeCustomers(\n pb: PocketBase,\n stripeSecretKey: string,\n logger: Logger,\n): Promise<SyncUsersResult> {\n const stripe = new Stripe(stripeSecretKey);\n const users = await pb\n .collection(\"users\")\n .getFullList<{ id: string; email: string }>();\n\n const existing = await pb\n .collection(\"stripe_customers\")\n .getFullList<{ id: string; user: string }>();\n const linkedUserIds = new Set(existing.map((c) => c.user));\n\n const result: SyncUsersResult = {\n total: users.length,\n linked: linkedUserIds.size,\n created: 0,\n reused: 0,\n skipped: 0,\n };\n\n for (const user of users) {\n if (linkedUserIds.has(user.id)) {\n result.skipped += 1;\n continue;\n }\n\n if (!user.email) {\n logger.info(`Skipping user ${user.id} with no email`);\n result.skipped += 1;\n continue;\n }\n\n const matching = await stripe.customers.list({\n email: user.email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n });\n\n let customer: Stripe.Customer;\n let isExistingCustomer = false;\n\n if (matching.data.length > 0) {\n customer = matching.data[0];\n isExistingCustomer = true;\n result.reused += 1;\n logger.info(`Reusing Stripe customer ${customer.id} for ${user.email}`);\n } else {\n customer = await stripe.customers.create({ email: user.email });\n result.created += 1;\n logger.info(`Created Stripe customer ${customer.id} for ${user.email}`);\n }\n\n try {\n await pb.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n } catch (error) {\n logger.info(\n `Failed to create stripe_customers row for ${user.email}: ${(error as Error).message}`,\n );\n continue;\n }\n\n if (!isExistingCustomer) {\n continue;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n { type: \"card\", allow_redisplay: \"always\" },\n );\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === \"unspecified\") continue;\n try {\n await pb.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n } catch {}\n }\n\n const defaultPaymentMethod =\n customer.invoice_settings?.default_payment_method;\n if (defaultPaymentMethod) {\n try {\n await pb.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method:\n typeof defaultPaymentMethod === \"string\"\n ? defaultPaymentMethod\n : defaultPaymentMethod.id,\n });\n } catch {}\n }\n }\n\n return result;\n}\n\nexport async function createTestProductAndPrice(\n stripeSecretKey: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n\n const products = await stripe.products.search({\n query: `name:\"Test Product\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n const product = products.data[0];\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n if (prices.data.length > 0) {\n return { product, price: prices.data[0], existing: true };\n }\n }\n\n const product = await stripe.products.create({\n name: \"Test Product\",\n metadata: { test: \"true\" },\n });\n\n const price = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n });\n\n return { product, price, existing: false };\n}\n\nexport async function getProductAndPriceById(\n stripeSecretKey: string,\n priceId: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n const price = await stripe.prices.retrieve(priceId, { expand: [\"product\"] });\n const product =\n typeof price.product === \"string\"\n ? await stripe.products.retrieve(price.product)\n : (price.product as Stripe.Product);\n price.product = product.id;\n return { product, price, existing: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { createCollectionIdempotent } from \"../../../runtime/collections\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { STRIPE_ENV_VARS } from \"./runtime/env-vars\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { modifyEnv, type EnvEdit } from \"./modifies/modify-env\";\nimport {\n createTestProductAndPrice,\n getProductAndPriceById,\n syncUsersToStripeCustomers,\n} from \"./runtime/stripe\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n action: \"created\" | \"updated\",\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, action, options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nfunction paymentPageSnippet(priceId: string): string {\n return dedent`\n <script lang=\"ts\">\n import PaymentButton from '#lib/components/payments/payment-button.svelte';\n </script>\n\n <section data-role=\"content\">\n <PaymentButton priceId=\"${priceId}\" />\n </section>\n `;\n}\n\nexport async function generate(options: Options) {\n const {\n stripeSecretKey,\n stripePublishableKey,\n stripeWebhookSecret,\n stripePriceId,\n } = options.input as {\n stripeSecretKey: string;\n stripePublishableKey: string;\n stripeWebhookSecret: string;\n stripePriceId?: string;\n };\n\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Writing Stripe credentials to .env\");\n const envEdits: EnvEdit[] = [\n { type: \"comment\", key: \"Stripe credentials\" },\n { type: \"var\", key: \"STRIPE_SECRET_KEY\", value: stripeSecretKey },\n {\n type: \"var\",\n key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\",\n value: stripePublishableKey,\n },\n { type: \"var\", key: \"STRIPE_WEBHOOK_SECRET\", value: stripeWebhookSecret },\n ];\n\n const envPath = path.join(options.root, \".env\");\n pushResult(modifyOutcomeToFile(envPath, modifyEnv(envPath, envEdits)));\n\n logger.info(\"Declaring Stripe variables in src/env.ts\");\n const envVars = modifyEnvVarsFiles(options.root, STRIPE_ENV_VARS);\n if (envVars.create) creates.push(envVars.create);\n pushResult(envVars.modify);\n\n await withPocketbase(options.root, async (pb) => {\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating stripe_products collection\");\n const productsResult = await create({\n name: \"stripe_products\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"name\", required: false, type: \"text\" },\n { name: \"active\", required: false, type: \"text\" },\n { name: \"default_price\", required: false, type: \"text\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_products\",\n \"created\",\n options,\n productsResult.created,\n );\n\n logger.info(\"Creating stripe_prices collection\");\n const pricesResult = await create({\n name: \"stripe_prices\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"billing_scheme\", required: false, type: \"text\" },\n { name: \"currency\", required: false, type: \"text\" },\n { name: \"product\", required: false, type: \"text\" },\n { name: \"recurring\", required: false, type: \"json\" },\n { name: \"type\", required: false, type: \"text\" },\n { name: \"unit_amount\", required: false, type: \"number\" },\n { name: \"active\", required: false, type: \"bool\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_prices\",\n \"created\",\n options,\n pricesResult.created,\n );\n\n if (isAppMode) {\n logger.info(\"Creating stripe_customers collection\");\n const customersResult = await create({\n name: \"stripe_customers\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripeCustomersCollection = customersResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"created\",\n options,\n customersResult.created,\n );\n\n logger.info(\"Creating stripe_payment_methods collection\");\n const paymentMethodsResult = await create({\n name: \"stripe_payment_methods\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"exp_month\", required: true, type: \"number\" },\n { name: \"exp_year\", required: true, type: \"number\" },\n {\n collectionId: stripeCustomersCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"customer\",\n required: true,\n type: \"relation\",\n cascadeDelete: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripePaymentMethodsCollection = paymentMethodsResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_payment_methods\",\n \"created\",\n options,\n paymentMethodsResult.created,\n );\n\n logger.info(\"Linking default_payment_method on stripe_customers\");\n await pb.collections.update(\"stripe_customers\", {\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n collectionId: stripePaymentMethodsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"default_payment_method\",\n required: false,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"updated\",\n options,\n );\n\n logger.info(\"Creating transactions collection\");\n const transactionsResult = await create({\n name: \"transactions\",\n type: \"base\",\n fields: [\n {\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"stripe_payment_intent\", required: true, type: \"text\" },\n { name: \"amount\", required: true, type: \"number\" },\n { name: \"currency\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"created\", required: true, type: \"date\" },\n { name: \"stripe_charge\", required: true, type: \"text\" },\n { name: \"stripe_customer\", required: true, type: \"text\" },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n { name: \"receipt_url\", required: true, type: \"url\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"transactions\",\n \"created\",\n options,\n transactionsResult.created,\n );\n\n logger.info(\"Syncing existing PocketBase users to Stripe customers\");\n const syncResult = await syncUsersToStripeCustomers(\n pb,\n stripeSecretKey,\n logger,\n );\n logger.info(\n `Synced ${syncResult.total} users (created ${syncResult.created}, reused ${syncResult.reused}, skipped ${syncResult.skipped})`,\n );\n }\n });\n\n if (stripePriceId) {\n logger.info(`Fetching Stripe product/price ${stripePriceId}`);\n } else {\n logger.info(\"Creating test Stripe product and price\");\n }\n const { product, price, existing } = stripePriceId\n ? await getProductAndPriceById(stripeSecretKey, stripePriceId)\n : await createTestProductAndPrice(stripeSecretKey);\n\n if (existing) {\n logger.info(\"Stripe product/price already exists, skipping creation\");\n }\n\n logger.info(\"Seeding Stripe product/price records\");\n await withPocketbase(options.root, async (pb) => {\n try {\n await pb.collection(\"stripe_products\").getOne(product.id);\n } catch (error) {\n await pb.collection(\"stripe_products\").create({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price: product.default_price,\n });\n }\n\n try {\n await pb.collection(\"stripe_prices\").getOne(price.id);\n } catch (error) {\n await pb.collection(\"stripe_prices\").create({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: price.product,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active,\n });\n }\n });\n\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: paymentPageSnippet(price.id),\n status: \"success\",\n });\n\n if (isAppMode) {\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, modifyUserSignup(userSignupPath)),\n );\n }\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAKA,IAAMgB,IAAsB;CAC1B;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAELhB,IAAe;CACnB;CACA;CACAgB;AACF,CAAC,CAAC,KAAK,IAAI,GAELf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