@velastack/patterns 0.0.41 → 0.0.43
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.
- package/LICENSE +21 -0
- package/dist/chunks/{_server-CsAmAg4q.js → _server-Cv3bTkG0.js} +1 -1
- package/dist/chunks/{_server-CsAmAg4q.js.map → _server-Cv3bTkG0.js.map} +1 -1
- package/dist/chunks/{collections-rD0M_Wxo.js → collections-VC2LOzBB.js} +2 -2
- package/dist/chunks/{collections-rD0M_Wxo.js.map → collections-VC2LOzBB.js.map} +1 -1
- package/dist/chunks/{env-CDsRI_A5.js → env-KcKcG4Mg.js} +1 -1
- package/dist/chunks/env-KcKcG4Mg.js.map +1 -0
- package/dist/chunks/{env.preview-Ds0NigL8.js → env.preview-u7rnWI2E.js} +1 -1
- package/dist/chunks/{env.preview-Ds0NigL8.js.map → env.preview-u7rnWI2E.js.map} +1 -1
- package/dist/chunks/{env.runtime-BGmr1gQZ.js → env.runtime-N65jqPxq.js} +1 -1
- package/dist/chunks/{env.runtime-BGmr1gQZ.js.map → env.runtime-N65jqPxq.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BbZ5w6b_.js → generate.runtime-33rNLYvg.js} +5 -5
- package/dist/chunks/generate.runtime-33rNLYvg.js.map +1 -0
- package/dist/chunks/{generate.runtime-Bcgms0O_.js → generate.runtime-AgF-_CuZ.js} +2 -2
- package/dist/chunks/{generate.runtime-Bcgms0O_.js.map → generate.runtime-AgF-_CuZ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-PFOJ6hwY.js → generate.runtime-B07nsq-H.js} +4 -4
- package/dist/chunks/{generate.runtime-PFOJ6hwY.js.map → generate.runtime-B07nsq-H.js.map} +1 -1
- package/dist/chunks/generate.runtime-B2xOWBKK.js +148 -0
- package/dist/chunks/generate.runtime-B2xOWBKK.js.map +1 -0
- package/dist/chunks/{generate.runtime-C7g-fJTr.js → generate.runtime-B9YSOuDJ.js} +4 -4
- package/dist/chunks/generate.runtime-B9YSOuDJ.js.map +1 -0
- package/dist/chunks/{generate.runtime-qlUWZTcR.js → generate.runtime-CZALdXt6.js} +2 -2
- package/dist/chunks/{generate.runtime-qlUWZTcR.js.map → generate.runtime-CZALdXt6.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C4_8WPai.js → generate.runtime-CczM1Zuw.js} +6 -6
- package/dist/chunks/{generate.runtime-C4_8WPai.js.map → generate.runtime-CczM1Zuw.js.map} +1 -1
- package/dist/chunks/{generate.runtime-zHO95VHU.js → generate.runtime-CznAdWvM.js} +6 -6
- package/dist/chunks/{generate.runtime-zHO95VHU.js.map → generate.runtime-CznAdWvM.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BSlNFRop.js → generate.runtime-D5pHSGv2.js} +4 -4
- package/dist/chunks/{generate.runtime-BSlNFRop.js.map → generate.runtime-D5pHSGv2.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D24qi85n.js → generate.runtime-DWi7AATX.js} +5 -5
- package/dist/chunks/{generate.runtime-D24qi85n.js.map → generate.runtime-DWi7AATX.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CPVMJTKB.js → generate.runtime-DZbx8giO.js} +2 -2
- package/dist/chunks/{generate.runtime-CPVMJTKB.js.map → generate.runtime-DZbx8giO.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C7ZDF3hy.js → generate.runtime-DrU9LGRv.js} +4 -4
- package/dist/chunks/{generate.runtime-C7ZDF3hy.js.map → generate.runtime-DrU9LGRv.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BVPDsGmt.js → generate.runtime-DuAbZVdC.js} +3 -3
- package/dist/chunks/generate.runtime-DuAbZVdC.js.map +1 -0
- package/dist/chunks/{generate.runtime-D_8Nz9Kl.js → generate.runtime-Dw6iUo_7.js} +3 -3
- package/dist/chunks/{generate.runtime-D_8Nz9Kl.js.map → generate.runtime-Dw6iUo_7.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BPsBAuGR.js → generate.runtime-KJTobj9H.js} +4 -4
- package/dist/chunks/{generate.runtime-BPsBAuGR.js.map → generate.runtime-KJTobj9H.js.map} +1 -1
- package/dist/chunks/{generate.runtime-4WWju7dJ.js → generate.runtime-LKYA2LrJ.js} +3 -3
- package/dist/chunks/{generate.runtime-4WWju7dJ.js.map → generate.runtime-LKYA2LrJ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DHVmSY2L.js → generate.runtime-PK7amfVR.js} +5 -5
- package/dist/chunks/{generate.runtime-DHVmSY2L.js.map → generate.runtime-PK7amfVR.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D6C-brcS.js → generate.runtime-VhD6Bmgq.js} +3 -3
- package/dist/chunks/generate.runtime-VhD6Bmgq.js.map +1 -0
- package/dist/chunks/{generate.runtime-CTXSSehF.js → generate.runtime-wy4PDbqn.js} +4 -4
- package/dist/chunks/{generate.runtime-CTXSSehF.js.map → generate.runtime-wy4PDbqn.js.map} +1 -1
- package/dist/chunks/{modify-file-Bgo3_PuG.js → modify-file-DE7tPADZ.js} +1 -1
- package/dist/chunks/{modify-file-Bgo3_PuG.js.map → modify-file-DE7tPADZ.js.map} +1 -1
- package/dist/chunks/{modify-svelte-config-remote-C-Wl2nk1.js → modify-svelte-config-remote-BUt0Wt_p.js} +1 -1
- package/dist/chunks/{modify-svelte-config-remote-C-Wl2nk1.js.map → modify-svelte-config-remote-BUt0Wt_p.js.map} +1 -1
- package/dist/chunks/{nav-user-Jp5yYtw5.js → nav-user-_VheJA6n.js} +1 -1
- package/dist/chunks/{nav-user-Jp5yYtw5.js.map → nav-user-_VheJA6n.js.map} +1 -1
- package/dist/chunks/{pocketbase-D5p0NSdu.js → pocketbase-Bj-cW2Zl.js} +1 -1
- package/dist/chunks/{pocketbase-D5p0NSdu.js.map → pocketbase-Bj-cW2Zl.js.map} +1 -1
- package/dist/chunks/{pocketbase-CEhGbssT.js → pocketbase-CjSrDiqR.js} +1 -1
- package/dist/chunks/{pocketbase-CEhGbssT.js.map → pocketbase-CjSrDiqR.js.map} +1 -1
- package/dist/chunks/pocketbase-Dm2SF3vM.js +13 -0
- package/dist/chunks/pocketbase-Dm2SF3vM.js.map +1 -0
- package/dist/chunks/{shared-4hq3AXC3.js → shared-C55q8tz4.js} +2 -2
- package/dist/chunks/shared-C55q8tz4.js.map +1 -0
- package/dist/chunks/{ts-morph-helpers-DjpZhZ7I.js → ts-morph-helpers-bR0-x04t.js} +1 -1
- package/dist/chunks/{ts-morph-helpers-DjpZhZ7I.js.map → ts-morph-helpers-bR0-x04t.js.map} +1 -1
- package/dist/chunks/{write-result-BPDot58Z.js → write-result-ByDzyVll.js} +2 -2
- package/dist/chunks/{write-result-BPDot58Z.js.map → write-result-ByDzyVll.js.map} +1 -1
- package/dist/index.d.ts +90 -30
- package/dist/index.js +1532 -1354
- package/dist/index.js.map +1 -1
- package/package.json +23 -1
- package/dist/chunks/env-CDsRI_A5.js.map +0 -1
- package/dist/chunks/generate.runtime-BVPDsGmt.js.map +0 -1
- package/dist/chunks/generate.runtime-BbZ5w6b_.js.map +0 -1
- package/dist/chunks/generate.runtime-C7g-fJTr.js.map +0 -1
- package/dist/chunks/generate.runtime-D6C-brcS.js.map +0 -1
- package/dist/chunks/shared-4hq3AXC3.js.map +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 VelaStack
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_server-CsAmAg4q.js","names":[],"sources":["../../src/patterns/enable/subscriptions/preview-modifies/data/hooks/stripe.pb.js?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/lib/components/app-sidebar.svelte?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/lib/components/nav-user.svelte?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/routes/(app)/+layout.server.ts?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/routes/(app)/+layout.svelte?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/routes/(app)/billing/+page.server.ts?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/routes/(app)/billing/+page.svelte?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/routes/webhooks/stripe/+server.ts?raw"],"sourcesContent":["export default \"/// <reference path=\\\"../types.d.ts\\\" />\\n\\ncronAdd(\\\"stripe-products\\\", \\\"*/2 * * * *\\\", () => {\\n const utils = require(`${__hooks}/utils.js`);\\n utils.triggerJob(\\\"/api/stripe/sync/products\\\");\\n});\\n\\ncronAdd(\\\"stripe-prices\\\", \\\"*/2 * * * *\\\", () => {\\n const utils = require(`${__hooks}/utils.js`);\\n utils.triggerJob(\\\"/api/stripe/sync/prices\\\");\\n});\\n\\ncronAdd(\\\"stripe-customers\\\", \\\"* * * * *\\\", () => {\\n const utils = require(`${__hooks}/utils.js`);\\n utils.triggerJob(\\\"/api/stripe/sync/customers\\\");\\n});\\n\\n// [!code highlight:4]\\ncronAdd(\\\"stripe-subscriptions\\\", \\\"*/2 * * * *\\\", () => {\\n const utils = require(`${__hooks}/utils.js`);\\n utils.triggerJob(\\\"/api/stripe/sync/subscriptions\\\");\\n});\\n\"","export default \"<script lang=\\\"ts\\\" module>\\n\\timport HomeIcon from '@lucide/svelte/icons/home';\\n\\n\\tlet data = {\\n\\t\\tnavMain: [\\n\\t\\t\\t{\\n\\t\\t\\t\\ttitle: 'Dashboard',\\n\\t\\t\\t\\turl: '/dashboard',\\n\\t\\t\\t\\ticon: HomeIcon\\n\\t\\t\\t}\\n\\t\\t]\\n\\t};\\n</script>\\n\\n<script lang=\\\"ts\\\">\\n\\timport NavMain from './nav-main.svelte';\\n\\timport NavUser from './nav-user.svelte';\\n\\timport * as Sidebar from '$lib/components/ui/sidebar';\\n\\timport type { ComponentProps } from 'svelte';\\n\\n\\tlet {\\n\\t\\tuser,\\n\\t\\tmeta,\\n\\t\\t// [!code highlight:1]\\n\\t\\tsubscription = null,\\n\\t\\tref = $bindable(null),\\n\\t\\t...restProps\\n\\t}: ComponentProps<typeof Sidebar.Root> & {\\n\\t\\tuser: any;\\n\\t\\tmeta: any;\\n\\t\\t// [!code highlight:1]\\n\\t\\tsubscription?: { id: string; productName: string | null } | null;\\n\\t} = $props();\\n</script>\\n\\n<Sidebar.Root bind:ref variant=\\\"inset\\\" {...restProps}>\\n\\t<Sidebar.Header>\\n\\t\\t<Sidebar.Menu>\\n\\t\\t\\t<Sidebar.MenuItem>\\n\\t\\t\\t\\t<Sidebar.MenuButton size=\\\"lg\\\">\\n\\t\\t\\t\\t\\t{#snippet child({ props })}\\n\\t\\t\\t\\t\\t\\t<a href=\\\"/dashboard\\\" {...props}>\\n\\t\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\t\\tclass=\\\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\\\"\\n\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t<img src=\\\"/favicon.svg\\\" alt=\\\"logo\\\" class=\\\"size-6\\\" />\\n\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t<div class=\\\"grid flex-1 text-left text-sm leading-tight\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t<span class=\\\"truncate font-medium\\\">{meta.appName}</span>\\n\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t</a>\\n\\t\\t\\t\\t\\t{/snippet}\\n\\t\\t\\t\\t</Sidebar.MenuButton>\\n\\t\\t\\t</Sidebar.MenuItem>\\n\\t\\t</Sidebar.Menu>\\n\\t</Sidebar.Header>\\n\\t<Sidebar.Content>\\n\\t\\t<NavMain items={data.navMain} />\\n\\t</Sidebar.Content>\\n\\t<Sidebar.Footer>\\n\\t\\t<NavUser {user} {subscription} />\\n\\t</Sidebar.Footer>\\n</Sidebar.Root>\\n\"","export default \"<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\\\";\\n import * as DropdownMenu from \\\"$lib/components/ui/dropdown-menu\\\";\\n import * as Sidebar from \\\"$lib/components/ui/sidebar\\\";\\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\"","export default \"// [!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\"","export default \"<script lang=\\\"ts\\\">\\n import * as Sidebar from \\\"$lib/components/ui/sidebar\\\";\\n import { Separator } from \\\"$lib/components/ui/separator\\\";\\n import AppSidebar from \\\"$lib/components/app-sidebar.svelte\\\";\\n import * as Breadcrumb from \\\"$lib/components/ui/breadcrumb\\\";\\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 meta={data.meta}\\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\"","export default \"import { error } from \\\"@sveltejs/kit\\\";\\nimport stripe from \\\"$lib/stripe\\\";\\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 const customer = await locals.admin\\n .collection(\\\"stripe_customers\\\")\\n .getFirstListItem(locals.admin.filter(\\\"user = {:user}\\\", { user: user.id }));\\n\\n if (!customer || !customer.id) {\\n return error(400, \\\"Customer not found\\\");\\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 depends(\\\"app:billing\\\");\\n\\n return {\\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\"","export default \"<script lang=\\\"ts\\\">\\n\\timport { Button } from '$lib/components/ui/button';\\n\\timport * as Card from '$lib/components/ui/card';\\n\\timport { Badge } from '$lib/components/ui/badge';\\n\\timport * as AlertDialog from '$lib/components/ui/alert-dialog';\\n\\timport SetupButton from '$lib/components/payments/setup-button.svelte';\\n\\timport { CreditCard, Trash2, Check, Package } from '@lucide/svelte';\\n\\timport { toast } from 'svelte-sonner';\\n\\timport { invalidate, invalidateAll } from '$app/navigation';\\n\\timport { untrack } from 'svelte';\\n\\n\\tlet { data } = $props();\\n\\tlet paymentMethods = $derived(data.paymentMethods);\\n\\tlet availablePlans = $derived(data.availablePlans);\\n\\tlet hasDefaultPaymentMethod = $derived(data.hasDefaultPaymentMethod);\\n\\n\\t// Local, mutable mirror of the server-side subscription. We optimistically\\n\\t// update it on user actions so the UI reflects the change immediately; the\\n\\t// $effect re-syncs from the server after the webhook has had a chance to\\n\\t// fire (invalidateAll runs on a short delay below).\\n\\tlet activeSubscription = $state(untrack(() => data.activeSubscription));\\n\\t$effect(() => {\\n\\t\\tactiveSubscription = data.activeSubscription;\\n\\t});\\n\\tlet showDeleteDialog = $state(false);\\n\\tlet selectedPaymentMethodId = $state<string | null>(null);\\n\\tlet isProcessing = $state(false);\\n\\tlet showCancelDialog = $state(false);\\n\\tlet isSubscribing = $state<string | null>(null);\\n\\tlet isCanceling = $state(false);\\n\\n\\tfunction openDeleteDialog(paymentMethodId: string) {\\n\\t\\tselectedPaymentMethodId = paymentMethodId;\\n\\t\\tshowDeleteDialog = true;\\n\\t}\\n\\n\\tfunction closeDeleteDialog() {\\n\\t\\tshowDeleteDialog = false;\\n\\t\\tselectedPaymentMethodId = null;\\n\\t}\\n\\n\\tasync function handleDeletePaymentMethod() {\\n\\t\\tif (!selectedPaymentMethodId) return;\\n\\t\\tisProcessing = true;\\n\\n\\t\\ttry {\\n\\t\\t\\tconst formData = new FormData();\\n\\t\\t\\tformData.append('paymentMethodId', selectedPaymentMethodId);\\n\\n\\t\\t\\tawait fetch('?/deletePaymentMethod', {\\n\\t\\t\\t\\tmethod: 'POST',\\n\\t\\t\\t\\tbody: formData\\n\\t\\t\\t});\\n\\n\\t\\t\\tawait invalidate('app:billing');\\n\\t\\t\\ttoast.success('Payment method removed successfully');\\n\\t\\t\\tcloseDeleteDialog();\\n\\t\\t} catch (err) {\\n\\t\\t\\tconsole.error('Error deleting payment method:', err);\\n\\t\\t\\ttoast.error('Failed to remove payment method');\\n\\t\\t} finally {\\n\\t\\t\\tisProcessing = false;\\n\\t\\t}\\n\\t}\\n\\n\\tasync function setDefaultPaymentMethod(paymentMethodId: string) {\\n\\t\\ttry {\\n\\t\\t\\tconst formData = new FormData();\\n\\t\\t\\tformData.append('paymentMethodId', paymentMethodId);\\n\\n\\t\\t\\tawait fetch('?/setDefaultPaymentMethod', {\\n\\t\\t\\t\\tmethod: 'POST',\\n\\t\\t\\t\\tbody: formData\\n\\t\\t\\t});\\n\\n\\t\\t\\tawait invalidate('app:billing');\\n\\t\\t\\ttoast.success('Default payment method updated');\\n\\t\\t} catch (err) {\\n\\t\\t\\tconsole.error('Error setting default payment method:', err);\\n\\t\\t\\ttoast.error('Failed to update default payment method');\\n\\t\\t}\\n\\t}\\n\\n\\tfunction getCardBrandIcon(brand: string) {\\n\\t\\t// You can customize these icons or use actual card brand icons\\n\\t\\tconst brands: Record<string, string> = {\\n\\t\\t\\tvisa: '💳',\\n\\t\\t\\tmastercard: '💳',\\n\\t\\t\\tamex: '💳',\\n\\t\\t\\tdiscover: '💳',\\n\\t\\t\\tunknown: '💳'\\n\\t\\t};\\n\\t\\treturn brands[brand.toLowerCase()] || brands.unknown;\\n\\t}\\n\\n\\tfunction formatCardBrand(brand: string) {\\n\\t\\treturn brand.charAt(0).toUpperCase() + brand.slice(1);\\n\\t}\\n\\n\\tfunction formatAmount(amount: number | null, currency: string | null) {\\n\\t\\tif (amount === null || !currency) return '—';\\n\\t\\treturn new Intl.NumberFormat('en-US', {\\n\\t\\t\\tstyle: 'currency',\\n\\t\\t\\tcurrency: currency.toUpperCase()\\n\\t\\t}).format(amount / 100);\\n\\t}\\n\\n\\tfunction formatInterval(recurring: { interval: string; interval_count: number } | null) {\\n\\t\\tif (!recurring) return '';\\n\\t\\tif (recurring.interval_count === 1) return `/ ${recurring.interval}`;\\n\\t\\treturn `every ${recurring.interval_count} ${recurring.interval}s`;\\n\\t}\\n\\n\\tfunction formatDate(iso: string | null) {\\n\\t\\tif (!iso) return '—';\\n\\t\\treturn new Date(iso).toLocaleDateString(undefined, {\\n\\t\\t\\tyear: 'numeric',\\n\\t\\t\\tmonth: 'short',\\n\\t\\t\\tday: 'numeric'\\n\\t\\t});\\n\\t}\\n\\n\\tasync function selectPlan(priceId: string, successMessage: string) {\\n\\t\\tif (!hasDefaultPaymentMethod) {\\n\\t\\t\\ttoast.error('Add a default payment method first');\\n\\t\\t\\treturn;\\n\\t\\t}\\n\\t\\tconst previous = activeSubscription;\\n\\t\\tconst plan = availablePlans.find((p) => p.id === priceId);\\n\\t\\tif (plan) {\\n\\t\\t\\tactiveSubscription = previous\\n\\t\\t\\t\\t? {\\n\\t\\t\\t\\t\\t\\t...previous,\\n\\t\\t\\t\\t\\t\\tpriceId,\\n\\t\\t\\t\\t\\t\\tproductName: plan.productName,\\n\\t\\t\\t\\t\\t\\tunitAmount: plan.unitAmount,\\n\\t\\t\\t\\t\\t\\tcurrency: plan.currency,\\n\\t\\t\\t\\t\\t\\trecurring: plan.recurring,\\n\\t\\t\\t\\t\\t\\tcancelAtPeriodEnd: false\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t: {\\n\\t\\t\\t\\t\\t\\tid: 'pending',\\n\\t\\t\\t\\t\\t\\tstatus: 'active',\\n\\t\\t\\t\\t\\t\\tpriceId,\\n\\t\\t\\t\\t\\t\\tproductName: plan.productName,\\n\\t\\t\\t\\t\\t\\tunitAmount: plan.unitAmount,\\n\\t\\t\\t\\t\\t\\tcurrency: plan.currency,\\n\\t\\t\\t\\t\\t\\trecurring: plan.recurring,\\n\\t\\t\\t\\t\\t\\tcancelAtPeriodEnd: false,\\n\\t\\t\\t\\t\\t\\tcurrentPeriodStart: null,\\n\\t\\t\\t\\t\\t\\tcurrentPeriodEnd: null,\\n\\t\\t\\t\\t\\t\\tcanceledAt: null\\n\\t\\t\\t\\t\\t};\\n\\t\\t}\\n\\n\\t\\tisSubscribing = priceId;\\n\\t\\ttry {\\n\\t\\t\\tconst formData = new FormData();\\n\\t\\t\\tformData.append('priceId', priceId);\\n\\n\\t\\t\\tconst res = await fetch('?/selectPlan', {\\n\\t\\t\\t\\tmethod: 'POST',\\n\\t\\t\\t\\tbody: formData\\n\\t\\t\\t});\\n\\n\\t\\t\\tif (!res.ok) {\\n\\t\\t\\t\\tthrow new Error(`selectPlan failed: ${res.status}`);\\n\\t\\t\\t}\\n\\n\\t\\t\\ttoast.success(successMessage);\\n\\t\\t\\tsetTimeout(() => {\\n\\t\\t\\t\\tinvalidateAll();\\n\\t\\t\\t}, 2000);\\n\\t\\t} catch (err) {\\n\\t\\t\\tconsole.error('Error selecting plan:', err);\\n\\t\\t\\ttoast.error('Failed to update plan');\\n\\t\\t\\tactiveSubscription = previous;\\n\\t\\t} finally {\\n\\t\\t\\tisSubscribing = null;\\n\\t\\t}\\n\\t}\\n\\n\\tasync function subscribe(priceId: string) {\\n\\t\\tawait selectPlan(priceId, 'Subscription started');\\n\\t}\\n\\n\\tasync function switchPlan(priceId: string) {\\n\\t\\tawait selectPlan(priceId, 'Subscription updated');\\n\\t}\\n\\n\\tasync function resumeSubscription() {\\n\\t\\tif (!activeSubscription) return;\\n\\t\\tconst previous = activeSubscription;\\n\\t\\tisSubscribing = activeSubscription.priceId;\\n\\t\\tactiveSubscription = { ...activeSubscription, cancelAtPeriodEnd: false };\\n\\t\\ttry {\\n\\t\\t\\tconst formData = new FormData();\\n\\t\\t\\tformData.append('subscriptionId', previous.id);\\n\\n\\t\\t\\tconst res = await fetch('?/resumeSubscription', {\\n\\t\\t\\t\\tmethod: 'POST',\\n\\t\\t\\t\\tbody: formData\\n\\t\\t\\t});\\n\\n\\t\\t\\tif (!res.ok) {\\n\\t\\t\\t\\tthrow new Error(`Resume failed: ${res.status}`);\\n\\t\\t\\t}\\n\\n\\t\\t\\ttoast.success('Subscription resumed');\\n\\t\\t\\tsetTimeout(() => {\\n\\t\\t\\t\\tinvalidateAll();\\n\\t\\t\\t}, 2000);\\n\\t\\t} catch (err) {\\n\\t\\t\\tconsole.error('Error resuming subscription:', err);\\n\\t\\t\\ttoast.error('Failed to resume subscription');\\n\\t\\t\\tactiveSubscription = previous;\\n\\t\\t} finally {\\n\\t\\t\\tisSubscribing = null;\\n\\t\\t}\\n\\t}\\n\\n\\tasync function handleCancelSubscription() {\\n\\t\\tif (!activeSubscription) return;\\n\\t\\tconst previous = activeSubscription;\\n\\t\\tisCanceling = true;\\n\\t\\tactiveSubscription = { ...activeSubscription, cancelAtPeriodEnd: true };\\n\\t\\ttry {\\n\\t\\t\\tconst formData = new FormData();\\n\\t\\t\\tformData.append('subscriptionId', previous.id);\\n\\n\\t\\t\\tconst res = await fetch('?/cancelSubscription', {\\n\\t\\t\\t\\tmethod: 'POST',\\n\\t\\t\\t\\tbody: formData\\n\\t\\t\\t});\\n\\n\\t\\t\\tif (!res.ok) {\\n\\t\\t\\t\\tthrow new Error(`Cancel failed: ${res.status}`);\\n\\t\\t\\t}\\n\\n\\t\\t\\ttoast.success('Subscription will cancel at period end');\\n\\t\\t\\tshowCancelDialog = false;\\n\\t\\t\\tsetTimeout(() => {\\n\\t\\t\\t\\tinvalidateAll();\\n\\t\\t\\t}, 2000);\\n\\t\\t} catch (err) {\\n\\t\\t\\tconsole.error('Error canceling subscription:', err);\\n\\t\\t\\ttoast.error('Failed to cancel subscription');\\n\\t\\t\\tactiveSubscription = previous;\\n\\t\\t} finally {\\n\\t\\t\\tisCanceling = false;\\n\\t\\t}\\n\\t}\\n</script>\\n\\n<div class=\\\"divide-y divide-gray-900/10 dark:divide-white/10\\\">\\n\\t<div class=\\\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\\\">\\n\\t\\t<div class=\\\"px-4 sm:px-0\\\">\\n\\t\\t\\t<h2 class=\\\"text-base/7 font-semibold text-gray-900 dark:text-white\\\">Payment Methods</h2>\\n\\t\\t\\t<p class=\\\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\\\">\\n\\t\\t\\t\\tManage your payment methods for subscriptions and purchases.\\n\\t\\t\\t</p>\\n\\t\\t</div>\\n\\n\\t\\t<div class=\\\"md:col-span-2\\\">\\n\\t\\t\\t<Card.Root>\\n\\t\\t\\t\\t<Card.Content>\\n\\t\\t\\t\\t\\t{#if paymentMethods.length === 0}\\n\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\tclass=\\\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\\\"\\n\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t<CreditCard class=\\\"mb-4 size-12 opacity-50\\\" />\\n\\t\\t\\t\\t\\t\\t\\t<p class=\\\"mb-2 text-lg font-medium\\\">No payment methods</p>\\n\\t\\t\\t\\t\\t\\t\\t<p class=\\\"text-sm\\\">Add a payment method to get started</p>\\n\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t{:else}\\n\\t\\t\\t\\t\\t\\t<div class=\\\"space-y-4\\\">\\n\\t\\t\\t\\t\\t\\t\\t{#each paymentMethods as method (method.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tclass=\\\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-4\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tclass=\\\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{getCardBrandIcon(method.brand)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-2\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<p class=\\\"font-medium\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{formatCardBrand(method.brand)} •••• {method.last4}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</p>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if method.isDefault}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Badge variant=\\\"secondary\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Check class=\\\"mr-1 size-3\\\" />\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tDefault\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Badge>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<p class=\\\"text-muted-foreground text-sm\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tExpires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</p>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-2\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if !method.isDefault}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={() => setDefaultPaymentMethod(method.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tSet as Default\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"icon-sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={() => openDeleteDialog(method.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tdisabled={method.isDefault && paymentMethods.length === 1}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Trash2 class=\\\"size-4\\\" />\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t{/each}\\n\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t</Card.Content>\\n\\t\\t\\t\\t<Card.Footer class=\\\"border-t justify-end\\\">\\n\\t\\t\\t\\t\\t<SetupButton\\n\\t\\t\\t\\t\\t\\tlabel=\\\"Add Payment Method\\\"\\n\\t\\t\\t\\t\\t\\tprocessingLabel=\\\"Adding...\\\"\\n\\t\\t\\t\\t\\t\\tonsuccess={() => invalidate('app:billing')}\\n\\t\\t\\t\\t\\t/>\\n\\t\\t\\t\\t</Card.Footer>\\n\\t\\t\\t</Card.Root>\\n\\t\\t</div>\\n\\t</div>\\n\\n\\t<div class=\\\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\\\">\\n\\t\\t<div class=\\\"px-4 sm:px-0\\\">\\n\\t\\t\\t<h2 class=\\\"text-base/7 font-semibold text-gray-900 dark:text-white\\\">Plan</h2>\\n\\t\\t\\t<p class=\\\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\\\">Manage your subscription.</p>\\n\\t\\t</div>\\n\\n\\t\\t<div class=\\\"md:col-span-2\\\">\\n\\t\\t\\t<Card.Root>\\n\\t\\t\\t\\t<Card.Content>\\n\\t\\t\\t\\t\\t{#if availablePlans.length === 0}\\n\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\tclass=\\\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\\\"\\n\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t<Package class=\\\"mb-4 size-12 opacity-50\\\" />\\n\\t\\t\\t\\t\\t\\t\\t<p class=\\\"mb-2 text-lg font-medium\\\">No plans available</p>\\n\\t\\t\\t\\t\\t\\t\\t<p class=\\\"text-sm\\\">Check back soon.</p>\\n\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t{:else}\\n\\t\\t\\t\\t\\t\\t{#if !hasDefaultPaymentMethod}\\n\\t\\t\\t\\t\\t\\t\\t<p class=\\\"text-muted-foreground mb-4 rounded-md border border-dashed p-3 text-sm\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\tAdd a default payment method above to subscribe.\\n\\t\\t\\t\\t\\t\\t\\t</p>\\n\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t<div class=\\\"space-y-4\\\">\\n\\t\\t\\t\\t\\t\\t\\t{#each availablePlans as plan (plan.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t{@const isCurrent = activeSubscription?.priceId === plan.id}\\n\\t\\t\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tclass=\\\"flex items-center justify-between rounded-lg border p-4 transition-colors {isCurrent\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t? 'border-primary ring-primary ring-1'\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t: 'border-border hover:bg-accent/50'}\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-4\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"bg-muted flex size-12 items-center justify-center rounded-lg\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Package class=\\\"size-5\\\" />\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-2\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<p class=\\\"font-medium\\\">{plan.productName}</p>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if isCurrent && activeSubscription}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if activeSubscription.cancelAtPeriodEnd}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Badge variant=\\\"outline\\\">Pending cancellation</Badge>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else if activeSubscription.status === 'trialing'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Badge variant=\\\"secondary\\\">Trial</Badge>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else if activeSubscription.status === 'past_due'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Badge variant=\\\"destructive\\\">Past due</Badge>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Badge variant=\\\"secondary\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Check class=\\\"mr-1 size-3\\\" />\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tCurrent\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Badge>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<p class=\\\"text-muted-foreground text-sm\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{formatAmount(plan.unitAmount, plan.currency)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{formatInterval(plan.recurring)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if isCurrent && activeSubscription?.currentPeriodEnd}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<span>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t•\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{activeSubscription.cancelAtPeriodEnd ? 'Cancels on' : 'Renews on'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{formatDate(activeSubscription.currentPeriodEnd)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</span>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</p>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-2\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if isCurrent && activeSubscription}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if activeSubscription.cancelAtPeriodEnd}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tdisabled={isSubscribing === plan.id}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={resumeSubscription}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{isSubscribing === plan.id ? 'Resuming...' : 'Resume'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={() => (showCancelDialog = true)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tCancel subscription\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else if activeSubscription}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tdisabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={() => switchPlan(plan.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{isSubscribing === plan.id ? 'Switching...' : 'Switch'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tdisabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={() => subscribe(plan.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{isSubscribing === plan.id ? 'Subscribing...' : 'Subscribe'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t{/each}\\n\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t</Card.Content>\\n\\t\\t\\t</Card.Root>\\n\\t\\t</div>\\n\\t</div>\\n</div>\\n\\n<!-- Cancel Subscription Dialog -->\\n<AlertDialog.Root bind:open={showCancelDialog}>\\n\\t<AlertDialog.Content>\\n\\t\\t<AlertDialog.Header>\\n\\t\\t\\t<AlertDialog.Title>Cancel Subscription</AlertDialog.Title>\\n\\t\\t\\t<AlertDialog.Description>\\n\\t\\t\\t\\tYour subscription will remain active until the end of the current billing period, then\\n\\t\\t\\t\\tcancel automatically.\\n\\t\\t\\t</AlertDialog.Description>\\n\\t\\t</AlertDialog.Header>\\n\\t\\t<AlertDialog.Footer>\\n\\t\\t\\t<AlertDialog.Cancel onclick={() => (showCancelDialog = false)}>\\n\\t\\t\\t\\tKeep Subscription\\n\\t\\t\\t</AlertDialog.Cancel>\\n\\t\\t\\t<AlertDialog.Action onclick={handleCancelSubscription} disabled={isCanceling}>\\n\\t\\t\\t\\t{isCanceling ? 'Canceling...' : 'Cancel at Period End'}\\n\\t\\t\\t</AlertDialog.Action>\\n\\t\\t</AlertDialog.Footer>\\n\\t</AlertDialog.Content>\\n</AlertDialog.Root>\\n\\n<!-- Delete Confirmation Dialog -->\\n<AlertDialog.Root bind:open={showDeleteDialog}>\\n\\t<AlertDialog.Content>\\n\\t\\t<AlertDialog.Header>\\n\\t\\t\\t<AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\\n\\t\\t\\t<AlertDialog.Description>\\n\\t\\t\\t\\tAre you sure you want to remove this payment method? This action cannot be undone.\\n\\t\\t\\t</AlertDialog.Description>\\n\\t\\t</AlertDialog.Header>\\n\\t\\t<AlertDialog.Footer>\\n\\t\\t\\t<AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\\n\\t\\t\\t<AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\\n\\t\\t\\t\\t{isProcessing ? 'Removing...' : 'Remove'}\\n\\t\\t\\t</AlertDialog.Action>\\n\\t\\t</AlertDialog.Footer>\\n\\t</AlertDialog.Content>\\n</AlertDialog.Root>\\n\"","export default \"import Stripe from \\\"stripe\\\";\\nimport { json } from \\\"@sveltejs/kit\\\";\\nimport { env } from \\\"$env/dynamic/private\\\";\\nimport stripe from \\\"$lib/stripe\\\";\\nimport { handlePaymentIntentSucceeded } from \\\"./handlers/payment-intent/succeeded\\\";\\nimport { handlePaymentMethodAttached } from \\\"./handlers/payment-method/attached\\\";\\nimport { handleSubscriptionCreated } from \\\"./handlers/subscription/created\\\";\\nimport { handleSubscriptionUpdated } from \\\"./handlers/subscription/updated\\\";\\nimport { handleSubscriptionDeleted } from \\\"./handlers/subscription/deleted\\\";\\n\\nconst processedEvents = new Set<string>();\\n\\nasync function verifyWebhookSignature(\\n request: Request,\\n webhookSecret: string,\\n): Promise<Stripe.Event> {\\n const body = await request.text();\\n const signature = request.headers.get(\\\"stripe-signature\\\");\\n\\n if (!signature) {\\n throw new Error(\\\"Missing stripe-signature header\\\");\\n }\\n\\n if (!webhookSecret) {\\n throw new Error(\\\"Missing webhook secret\\\");\\n }\\n\\n try {\\n return stripe.webhooks.constructEvent(body, signature, webhookSecret);\\n } catch (err) {\\n console.error(\\\"Webhook signature verification failed:\\\", err);\\n throw new Error(\\\"Invalid signature\\\");\\n }\\n}\\n\\nexport const POST = async ({ request, locals }) => {\\n try {\\n const event = await verifyWebhookSignature(\\n request,\\n env.STRIPE_WEBHOOK_SECRET,\\n );\\n\\n if (processedEvents.has(event.id)) {\\n console.log(`Event ${event.id} already processed, skipping`);\\n return json({ received: true, message: \\\"Event already processed\\\" });\\n }\\n\\n processedEvents.add(event.id);\\n\\n console.log(`Processing webhook event: ${event.type} (${event.id})`);\\n\\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 return json({\\n received: true,\\n eventId: event.id,\\n eventType: event.type,\\n });\\n } catch (error) {\\n console.error(\\\"Webhook processing error:\\\", error);\\n\\n return json(\\n {\\n error: \\\"Webhook processing failed\\\",\\n message: error instanceof Error ? error.message : \\\"Unknown error\\\",\\n },\\n { status: 400 },\\n );\\n }\\n};\\n\""],"mappings":";AAAA,IAAA,IAAe,wtBCAf,IAAe,goDCAf,IAAe,unKCAf,IAAe,owCCAf,IAAe,8gECAf,IAAe,s0VCAf,IAAe,wvfCAf,IAAe"}
|
|
1
|
+
{"version":3,"file":"_server-Cv3bTkG0.js","names":[],"sources":["../../src/patterns/enable/subscriptions/preview-modifies/data/hooks/stripe.pb.js?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/lib/components/app-sidebar.svelte?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/lib/components/nav-user.svelte?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/routes/(app)/+layout.server.ts?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/routes/(app)/+layout.svelte?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/routes/(app)/billing/+page.server.ts?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/routes/(app)/billing/+page.svelte?raw","../../src/patterns/enable/subscriptions/preview-modifies/src/routes/webhooks/stripe/+server.ts?raw"],"sourcesContent":["export default \"/// <reference path=\\\"../types.d.ts\\\" />\\n\\ncronAdd(\\\"stripe-products\\\", \\\"*/2 * * * *\\\", () => {\\n const utils = require(`${__hooks}/utils.js`);\\n utils.triggerJob(\\\"/api/stripe/sync/products\\\");\\n});\\n\\ncronAdd(\\\"stripe-prices\\\", \\\"*/2 * * * *\\\", () => {\\n const utils = require(`${__hooks}/utils.js`);\\n utils.triggerJob(\\\"/api/stripe/sync/prices\\\");\\n});\\n\\ncronAdd(\\\"stripe-customers\\\", \\\"* * * * *\\\", () => {\\n const utils = require(`${__hooks}/utils.js`);\\n utils.triggerJob(\\\"/api/stripe/sync/customers\\\");\\n});\\n\\n// [!code highlight:4]\\ncronAdd(\\\"stripe-subscriptions\\\", \\\"*/2 * * * *\\\", () => {\\n const utils = require(`${__hooks}/utils.js`);\\n utils.triggerJob(\\\"/api/stripe/sync/subscriptions\\\");\\n});\\n\"","export default \"<script lang=\\\"ts\\\" module>\\n\\timport HomeIcon from '@lucide/svelte/icons/home';\\n\\n\\tlet data = {\\n\\t\\tnavMain: [\\n\\t\\t\\t{\\n\\t\\t\\t\\ttitle: 'Dashboard',\\n\\t\\t\\t\\turl: '/dashboard',\\n\\t\\t\\t\\ticon: HomeIcon\\n\\t\\t\\t}\\n\\t\\t]\\n\\t};\\n</script>\\n\\n<script lang=\\\"ts\\\">\\n\\timport NavMain from './nav-main.svelte';\\n\\timport NavUser from './nav-user.svelte';\\n\\timport * as Sidebar from '$lib/components/ui/sidebar';\\n\\timport type { ComponentProps } from 'svelte';\\n\\n\\tlet {\\n\\t\\tuser,\\n\\t\\tmeta,\\n\\t\\t// [!code highlight:1]\\n\\t\\tsubscription = null,\\n\\t\\tref = $bindable(null),\\n\\t\\t...restProps\\n\\t}: ComponentProps<typeof Sidebar.Root> & {\\n\\t\\tuser: any;\\n\\t\\tmeta: any;\\n\\t\\t// [!code highlight:1]\\n\\t\\tsubscription?: { id: string; productName: string | null } | null;\\n\\t} = $props();\\n</script>\\n\\n<Sidebar.Root bind:ref variant=\\\"inset\\\" {...restProps}>\\n\\t<Sidebar.Header>\\n\\t\\t<Sidebar.Menu>\\n\\t\\t\\t<Sidebar.MenuItem>\\n\\t\\t\\t\\t<Sidebar.MenuButton size=\\\"lg\\\">\\n\\t\\t\\t\\t\\t{#snippet child({ props })}\\n\\t\\t\\t\\t\\t\\t<a href=\\\"/dashboard\\\" {...props}>\\n\\t\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\t\\tclass=\\\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\\\"\\n\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t<img src=\\\"/favicon.svg\\\" alt=\\\"logo\\\" class=\\\"size-6\\\" />\\n\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t<div class=\\\"grid flex-1 text-left text-sm leading-tight\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t<span class=\\\"truncate font-medium\\\">{meta.appName}</span>\\n\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t</a>\\n\\t\\t\\t\\t\\t{/snippet}\\n\\t\\t\\t\\t</Sidebar.MenuButton>\\n\\t\\t\\t</Sidebar.MenuItem>\\n\\t\\t</Sidebar.Menu>\\n\\t</Sidebar.Header>\\n\\t<Sidebar.Content>\\n\\t\\t<NavMain items={data.navMain} />\\n\\t</Sidebar.Content>\\n\\t<Sidebar.Footer>\\n\\t\\t<NavUser {user} {subscription} />\\n\\t</Sidebar.Footer>\\n</Sidebar.Root>\\n\"","export default \"<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\\\";\\n import * as DropdownMenu from \\\"$lib/components/ui/dropdown-menu\\\";\\n import * as Sidebar from \\\"$lib/components/ui/sidebar\\\";\\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\"","export default \"// [!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\"","export default \"<script lang=\\\"ts\\\">\\n import * as Sidebar from \\\"$lib/components/ui/sidebar\\\";\\n import { Separator } from \\\"$lib/components/ui/separator\\\";\\n import AppSidebar from \\\"$lib/components/app-sidebar.svelte\\\";\\n import * as Breadcrumb from \\\"$lib/components/ui/breadcrumb\\\";\\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 meta={data.meta}\\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\"","export default \"import { error } from \\\"@sveltejs/kit\\\";\\nimport stripe from \\\"$lib/stripe\\\";\\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 const customer = await locals.admin\\n .collection(\\\"stripe_customers\\\")\\n .getFirstListItem(locals.admin.filter(\\\"user = {:user}\\\", { user: user.id }));\\n\\n if (!customer || !customer.id) {\\n return error(400, \\\"Customer not found\\\");\\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 depends(\\\"app:billing\\\");\\n\\n return {\\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\"","export default \"<script lang=\\\"ts\\\">\\n\\timport { Button } from '$lib/components/ui/button';\\n\\timport * as Card from '$lib/components/ui/card';\\n\\timport { Badge } from '$lib/components/ui/badge';\\n\\timport * as AlertDialog from '$lib/components/ui/alert-dialog';\\n\\timport SetupButton from '$lib/components/payments/setup-button.svelte';\\n\\timport { CreditCard, Trash2, Check, Package } from '@lucide/svelte';\\n\\timport { toast } from 'svelte-sonner';\\n\\timport { invalidate, invalidateAll } from '$app/navigation';\\n\\timport { untrack } from 'svelte';\\n\\n\\tlet { data } = $props();\\n\\tlet paymentMethods = $derived(data.paymentMethods);\\n\\tlet availablePlans = $derived(data.availablePlans);\\n\\tlet hasDefaultPaymentMethod = $derived(data.hasDefaultPaymentMethod);\\n\\n\\t// Local, mutable mirror of the server-side subscription. We optimistically\\n\\t// update it on user actions so the UI reflects the change immediately; the\\n\\t// $effect re-syncs from the server after the webhook has had a chance to\\n\\t// fire (invalidateAll runs on a short delay below).\\n\\tlet activeSubscription = $state(untrack(() => data.activeSubscription));\\n\\t$effect(() => {\\n\\t\\tactiveSubscription = data.activeSubscription;\\n\\t});\\n\\tlet showDeleteDialog = $state(false);\\n\\tlet selectedPaymentMethodId = $state<string | null>(null);\\n\\tlet isProcessing = $state(false);\\n\\tlet showCancelDialog = $state(false);\\n\\tlet isSubscribing = $state<string | null>(null);\\n\\tlet isCanceling = $state(false);\\n\\n\\tfunction openDeleteDialog(paymentMethodId: string) {\\n\\t\\tselectedPaymentMethodId = paymentMethodId;\\n\\t\\tshowDeleteDialog = true;\\n\\t}\\n\\n\\tfunction closeDeleteDialog() {\\n\\t\\tshowDeleteDialog = false;\\n\\t\\tselectedPaymentMethodId = null;\\n\\t}\\n\\n\\tasync function handleDeletePaymentMethod() {\\n\\t\\tif (!selectedPaymentMethodId) return;\\n\\t\\tisProcessing = true;\\n\\n\\t\\ttry {\\n\\t\\t\\tconst formData = new FormData();\\n\\t\\t\\tformData.append('paymentMethodId', selectedPaymentMethodId);\\n\\n\\t\\t\\tawait fetch('?/deletePaymentMethod', {\\n\\t\\t\\t\\tmethod: 'POST',\\n\\t\\t\\t\\tbody: formData\\n\\t\\t\\t});\\n\\n\\t\\t\\tawait invalidate('app:billing');\\n\\t\\t\\ttoast.success('Payment method removed successfully');\\n\\t\\t\\tcloseDeleteDialog();\\n\\t\\t} catch (err) {\\n\\t\\t\\tconsole.error('Error deleting payment method:', err);\\n\\t\\t\\ttoast.error('Failed to remove payment method');\\n\\t\\t} finally {\\n\\t\\t\\tisProcessing = false;\\n\\t\\t}\\n\\t}\\n\\n\\tasync function setDefaultPaymentMethod(paymentMethodId: string) {\\n\\t\\ttry {\\n\\t\\t\\tconst formData = new FormData();\\n\\t\\t\\tformData.append('paymentMethodId', paymentMethodId);\\n\\n\\t\\t\\tawait fetch('?/setDefaultPaymentMethod', {\\n\\t\\t\\t\\tmethod: 'POST',\\n\\t\\t\\t\\tbody: formData\\n\\t\\t\\t});\\n\\n\\t\\t\\tawait invalidate('app:billing');\\n\\t\\t\\ttoast.success('Default payment method updated');\\n\\t\\t} catch (err) {\\n\\t\\t\\tconsole.error('Error setting default payment method:', err);\\n\\t\\t\\ttoast.error('Failed to update default payment method');\\n\\t\\t}\\n\\t}\\n\\n\\tfunction getCardBrandIcon(brand: string) {\\n\\t\\t// You can customize these icons or use actual card brand icons\\n\\t\\tconst brands: Record<string, string> = {\\n\\t\\t\\tvisa: '💳',\\n\\t\\t\\tmastercard: '💳',\\n\\t\\t\\tamex: '💳',\\n\\t\\t\\tdiscover: '💳',\\n\\t\\t\\tunknown: '💳'\\n\\t\\t};\\n\\t\\treturn brands[brand.toLowerCase()] || brands.unknown;\\n\\t}\\n\\n\\tfunction formatCardBrand(brand: string) {\\n\\t\\treturn brand.charAt(0).toUpperCase() + brand.slice(1);\\n\\t}\\n\\n\\tfunction formatAmount(amount: number | null, currency: string | null) {\\n\\t\\tif (amount === null || !currency) return '—';\\n\\t\\treturn new Intl.NumberFormat('en-US', {\\n\\t\\t\\tstyle: 'currency',\\n\\t\\t\\tcurrency: currency.toUpperCase()\\n\\t\\t}).format(amount / 100);\\n\\t}\\n\\n\\tfunction formatInterval(recurring: { interval: string; interval_count: number } | null) {\\n\\t\\tif (!recurring) return '';\\n\\t\\tif (recurring.interval_count === 1) return `/ ${recurring.interval}`;\\n\\t\\treturn `every ${recurring.interval_count} ${recurring.interval}s`;\\n\\t}\\n\\n\\tfunction formatDate(iso: string | null) {\\n\\t\\tif (!iso) return '—';\\n\\t\\treturn new Date(iso).toLocaleDateString(undefined, {\\n\\t\\t\\tyear: 'numeric',\\n\\t\\t\\tmonth: 'short',\\n\\t\\t\\tday: 'numeric'\\n\\t\\t});\\n\\t}\\n\\n\\tasync function selectPlan(priceId: string, successMessage: string) {\\n\\t\\tif (!hasDefaultPaymentMethod) {\\n\\t\\t\\ttoast.error('Add a default payment method first');\\n\\t\\t\\treturn;\\n\\t\\t}\\n\\t\\tconst previous = activeSubscription;\\n\\t\\tconst plan = availablePlans.find((p) => p.id === priceId);\\n\\t\\tif (plan) {\\n\\t\\t\\tactiveSubscription = previous\\n\\t\\t\\t\\t? {\\n\\t\\t\\t\\t\\t\\t...previous,\\n\\t\\t\\t\\t\\t\\tpriceId,\\n\\t\\t\\t\\t\\t\\tproductName: plan.productName,\\n\\t\\t\\t\\t\\t\\tunitAmount: plan.unitAmount,\\n\\t\\t\\t\\t\\t\\tcurrency: plan.currency,\\n\\t\\t\\t\\t\\t\\trecurring: plan.recurring,\\n\\t\\t\\t\\t\\t\\tcancelAtPeriodEnd: false\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t: {\\n\\t\\t\\t\\t\\t\\tid: 'pending',\\n\\t\\t\\t\\t\\t\\tstatus: 'active',\\n\\t\\t\\t\\t\\t\\tpriceId,\\n\\t\\t\\t\\t\\t\\tproductName: plan.productName,\\n\\t\\t\\t\\t\\t\\tunitAmount: plan.unitAmount,\\n\\t\\t\\t\\t\\t\\tcurrency: plan.currency,\\n\\t\\t\\t\\t\\t\\trecurring: plan.recurring,\\n\\t\\t\\t\\t\\t\\tcancelAtPeriodEnd: false,\\n\\t\\t\\t\\t\\t\\tcurrentPeriodStart: null,\\n\\t\\t\\t\\t\\t\\tcurrentPeriodEnd: null,\\n\\t\\t\\t\\t\\t\\tcanceledAt: null\\n\\t\\t\\t\\t\\t};\\n\\t\\t}\\n\\n\\t\\tisSubscribing = priceId;\\n\\t\\ttry {\\n\\t\\t\\tconst formData = new FormData();\\n\\t\\t\\tformData.append('priceId', priceId);\\n\\n\\t\\t\\tconst res = await fetch('?/selectPlan', {\\n\\t\\t\\t\\tmethod: 'POST',\\n\\t\\t\\t\\tbody: formData\\n\\t\\t\\t});\\n\\n\\t\\t\\tif (!res.ok) {\\n\\t\\t\\t\\tthrow new Error(`selectPlan failed: ${res.status}`);\\n\\t\\t\\t}\\n\\n\\t\\t\\ttoast.success(successMessage);\\n\\t\\t\\tsetTimeout(() => {\\n\\t\\t\\t\\tinvalidateAll();\\n\\t\\t\\t}, 2000);\\n\\t\\t} catch (err) {\\n\\t\\t\\tconsole.error('Error selecting plan:', err);\\n\\t\\t\\ttoast.error('Failed to update plan');\\n\\t\\t\\tactiveSubscription = previous;\\n\\t\\t} finally {\\n\\t\\t\\tisSubscribing = null;\\n\\t\\t}\\n\\t}\\n\\n\\tasync function subscribe(priceId: string) {\\n\\t\\tawait selectPlan(priceId, 'Subscription started');\\n\\t}\\n\\n\\tasync function switchPlan(priceId: string) {\\n\\t\\tawait selectPlan(priceId, 'Subscription updated');\\n\\t}\\n\\n\\tasync function resumeSubscription() {\\n\\t\\tif (!activeSubscription) return;\\n\\t\\tconst previous = activeSubscription;\\n\\t\\tisSubscribing = activeSubscription.priceId;\\n\\t\\tactiveSubscription = { ...activeSubscription, cancelAtPeriodEnd: false };\\n\\t\\ttry {\\n\\t\\t\\tconst formData = new FormData();\\n\\t\\t\\tformData.append('subscriptionId', previous.id);\\n\\n\\t\\t\\tconst res = await fetch('?/resumeSubscription', {\\n\\t\\t\\t\\tmethod: 'POST',\\n\\t\\t\\t\\tbody: formData\\n\\t\\t\\t});\\n\\n\\t\\t\\tif (!res.ok) {\\n\\t\\t\\t\\tthrow new Error(`Resume failed: ${res.status}`);\\n\\t\\t\\t}\\n\\n\\t\\t\\ttoast.success('Subscription resumed');\\n\\t\\t\\tsetTimeout(() => {\\n\\t\\t\\t\\tinvalidateAll();\\n\\t\\t\\t}, 2000);\\n\\t\\t} catch (err) {\\n\\t\\t\\tconsole.error('Error resuming subscription:', err);\\n\\t\\t\\ttoast.error('Failed to resume subscription');\\n\\t\\t\\tactiveSubscription = previous;\\n\\t\\t} finally {\\n\\t\\t\\tisSubscribing = null;\\n\\t\\t}\\n\\t}\\n\\n\\tasync function handleCancelSubscription() {\\n\\t\\tif (!activeSubscription) return;\\n\\t\\tconst previous = activeSubscription;\\n\\t\\tisCanceling = true;\\n\\t\\tactiveSubscription = { ...activeSubscription, cancelAtPeriodEnd: true };\\n\\t\\ttry {\\n\\t\\t\\tconst formData = new FormData();\\n\\t\\t\\tformData.append('subscriptionId', previous.id);\\n\\n\\t\\t\\tconst res = await fetch('?/cancelSubscription', {\\n\\t\\t\\t\\tmethod: 'POST',\\n\\t\\t\\t\\tbody: formData\\n\\t\\t\\t});\\n\\n\\t\\t\\tif (!res.ok) {\\n\\t\\t\\t\\tthrow new Error(`Cancel failed: ${res.status}`);\\n\\t\\t\\t}\\n\\n\\t\\t\\ttoast.success('Subscription will cancel at period end');\\n\\t\\t\\tshowCancelDialog = false;\\n\\t\\t\\tsetTimeout(() => {\\n\\t\\t\\t\\tinvalidateAll();\\n\\t\\t\\t}, 2000);\\n\\t\\t} catch (err) {\\n\\t\\t\\tconsole.error('Error canceling subscription:', err);\\n\\t\\t\\ttoast.error('Failed to cancel subscription');\\n\\t\\t\\tactiveSubscription = previous;\\n\\t\\t} finally {\\n\\t\\t\\tisCanceling = false;\\n\\t\\t}\\n\\t}\\n</script>\\n\\n<div class=\\\"divide-y divide-gray-900/10 dark:divide-white/10\\\">\\n\\t<div class=\\\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\\\">\\n\\t\\t<div class=\\\"px-4 sm:px-0\\\">\\n\\t\\t\\t<h2 class=\\\"text-base/7 font-semibold text-gray-900 dark:text-white\\\">Payment Methods</h2>\\n\\t\\t\\t<p class=\\\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\\\">\\n\\t\\t\\t\\tManage your payment methods for subscriptions and purchases.\\n\\t\\t\\t</p>\\n\\t\\t</div>\\n\\n\\t\\t<div class=\\\"md:col-span-2\\\">\\n\\t\\t\\t<Card.Root>\\n\\t\\t\\t\\t<Card.Content>\\n\\t\\t\\t\\t\\t{#if paymentMethods.length === 0}\\n\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\tclass=\\\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\\\"\\n\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t<CreditCard class=\\\"mb-4 size-12 opacity-50\\\" />\\n\\t\\t\\t\\t\\t\\t\\t<p class=\\\"mb-2 text-lg font-medium\\\">No payment methods</p>\\n\\t\\t\\t\\t\\t\\t\\t<p class=\\\"text-sm\\\">Add a payment method to get started</p>\\n\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t{:else}\\n\\t\\t\\t\\t\\t\\t<div class=\\\"space-y-4\\\">\\n\\t\\t\\t\\t\\t\\t\\t{#each paymentMethods as method (method.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tclass=\\\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-4\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tclass=\\\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{getCardBrandIcon(method.brand)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-2\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<p class=\\\"font-medium\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{formatCardBrand(method.brand)} •••• {method.last4}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</p>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if method.isDefault}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Badge variant=\\\"secondary\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Check class=\\\"mr-1 size-3\\\" />\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tDefault\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Badge>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<p class=\\\"text-muted-foreground text-sm\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tExpires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</p>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-2\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if !method.isDefault}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={() => setDefaultPaymentMethod(method.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tSet as Default\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"icon-sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={() => openDeleteDialog(method.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tdisabled={method.isDefault && paymentMethods.length === 1}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Trash2 class=\\\"size-4\\\" />\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t{/each}\\n\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t</Card.Content>\\n\\t\\t\\t\\t<Card.Footer class=\\\"border-t justify-end\\\">\\n\\t\\t\\t\\t\\t<SetupButton\\n\\t\\t\\t\\t\\t\\tlabel=\\\"Add Payment Method\\\"\\n\\t\\t\\t\\t\\t\\tprocessingLabel=\\\"Adding...\\\"\\n\\t\\t\\t\\t\\t\\tonsuccess={() => invalidate('app:billing')}\\n\\t\\t\\t\\t\\t/>\\n\\t\\t\\t\\t</Card.Footer>\\n\\t\\t\\t</Card.Root>\\n\\t\\t</div>\\n\\t</div>\\n\\n\\t<div class=\\\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\\\">\\n\\t\\t<div class=\\\"px-4 sm:px-0\\\">\\n\\t\\t\\t<h2 class=\\\"text-base/7 font-semibold text-gray-900 dark:text-white\\\">Plan</h2>\\n\\t\\t\\t<p class=\\\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\\\">Manage your subscription.</p>\\n\\t\\t</div>\\n\\n\\t\\t<div class=\\\"md:col-span-2\\\">\\n\\t\\t\\t<Card.Root>\\n\\t\\t\\t\\t<Card.Content>\\n\\t\\t\\t\\t\\t{#if availablePlans.length === 0}\\n\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\tclass=\\\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\\\"\\n\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t<Package class=\\\"mb-4 size-12 opacity-50\\\" />\\n\\t\\t\\t\\t\\t\\t\\t<p class=\\\"mb-2 text-lg font-medium\\\">No plans available</p>\\n\\t\\t\\t\\t\\t\\t\\t<p class=\\\"text-sm\\\">Check back soon.</p>\\n\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t{:else}\\n\\t\\t\\t\\t\\t\\t{#if !hasDefaultPaymentMethod}\\n\\t\\t\\t\\t\\t\\t\\t<p class=\\\"text-muted-foreground mb-4 rounded-md border border-dashed p-3 text-sm\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\tAdd a default payment method above to subscribe.\\n\\t\\t\\t\\t\\t\\t\\t</p>\\n\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t<div class=\\\"space-y-4\\\">\\n\\t\\t\\t\\t\\t\\t\\t{#each availablePlans as plan (plan.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t{@const isCurrent = activeSubscription?.priceId === plan.id}\\n\\t\\t\\t\\t\\t\\t\\t\\t<div\\n\\t\\t\\t\\t\\t\\t\\t\\t\\tclass=\\\"flex items-center justify-between rounded-lg border p-4 transition-colors {isCurrent\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t? 'border-primary ring-primary ring-1'\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t: 'border-border hover:bg-accent/50'}\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-4\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"bg-muted flex size-12 items-center justify-center rounded-lg\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Package class=\\\"size-5\\\" />\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-2\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<p class=\\\"font-medium\\\">{plan.productName}</p>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if isCurrent && activeSubscription}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if activeSubscription.cancelAtPeriodEnd}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Badge variant=\\\"outline\\\">Pending cancellation</Badge>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else if activeSubscription.status === 'trialing'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Badge variant=\\\"secondary\\\">Trial</Badge>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else if activeSubscription.status === 'past_due'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Badge variant=\\\"destructive\\\">Past due</Badge>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Badge variant=\\\"secondary\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Check class=\\\"mr-1 size-3\\\" />\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tCurrent\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Badge>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<p class=\\\"text-muted-foreground text-sm\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{formatAmount(plan.unitAmount, plan.currency)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{formatInterval(plan.recurring)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if isCurrent && activeSubscription?.currentPeriodEnd}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<span>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t•\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{activeSubscription.cancelAtPeriodEnd ? 'Cancels on' : 'Renews on'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{formatDate(activeSubscription.currentPeriodEnd)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</span>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</p>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t<div class=\\\"flex items-center gap-2\\\">\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if isCurrent && activeSubscription}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{#if activeSubscription.cancelAtPeriodEnd}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tdisabled={isSubscribing === plan.id}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={resumeSubscription}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{isSubscribing === plan.id ? 'Resuming...' : 'Resume'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={() => (showCancelDialog = true)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tCancel subscription\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else if activeSubscription}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tdisabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={() => switchPlan(plan.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{isSubscribing === plan.id ? 'Switching...' : 'Switch'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{:else}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t<Button\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tvariant=\\\"outline\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tsize=\\\"sm\\\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tdisabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tonclick={() => subscribe(plan.id)}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{isSubscribing === plan.id ? 'Subscribing...' : 'Subscribe'}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t</Button>\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t\\t\\t{/each}\\n\\t\\t\\t\\t\\t\\t</div>\\n\\t\\t\\t\\t\\t{/if}\\n\\t\\t\\t\\t</Card.Content>\\n\\t\\t\\t</Card.Root>\\n\\t\\t</div>\\n\\t</div>\\n</div>\\n\\n<!-- Cancel Subscription Dialog -->\\n<AlertDialog.Root bind:open={showCancelDialog}>\\n\\t<AlertDialog.Content>\\n\\t\\t<AlertDialog.Header>\\n\\t\\t\\t<AlertDialog.Title>Cancel Subscription</AlertDialog.Title>\\n\\t\\t\\t<AlertDialog.Description>\\n\\t\\t\\t\\tYour subscription will remain active until the end of the current billing period, then\\n\\t\\t\\t\\tcancel automatically.\\n\\t\\t\\t</AlertDialog.Description>\\n\\t\\t</AlertDialog.Header>\\n\\t\\t<AlertDialog.Footer>\\n\\t\\t\\t<AlertDialog.Cancel onclick={() => (showCancelDialog = false)}>\\n\\t\\t\\t\\tKeep Subscription\\n\\t\\t\\t</AlertDialog.Cancel>\\n\\t\\t\\t<AlertDialog.Action onclick={handleCancelSubscription} disabled={isCanceling}>\\n\\t\\t\\t\\t{isCanceling ? 'Canceling...' : 'Cancel at Period End'}\\n\\t\\t\\t</AlertDialog.Action>\\n\\t\\t</AlertDialog.Footer>\\n\\t</AlertDialog.Content>\\n</AlertDialog.Root>\\n\\n<!-- Delete Confirmation Dialog -->\\n<AlertDialog.Root bind:open={showDeleteDialog}>\\n\\t<AlertDialog.Content>\\n\\t\\t<AlertDialog.Header>\\n\\t\\t\\t<AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\\n\\t\\t\\t<AlertDialog.Description>\\n\\t\\t\\t\\tAre you sure you want to remove this payment method? This action cannot be undone.\\n\\t\\t\\t</AlertDialog.Description>\\n\\t\\t</AlertDialog.Header>\\n\\t\\t<AlertDialog.Footer>\\n\\t\\t\\t<AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\\n\\t\\t\\t<AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\\n\\t\\t\\t\\t{isProcessing ? 'Removing...' : 'Remove'}\\n\\t\\t\\t</AlertDialog.Action>\\n\\t\\t</AlertDialog.Footer>\\n\\t</AlertDialog.Content>\\n</AlertDialog.Root>\\n\"","export default \"import Stripe from \\\"stripe\\\";\\nimport { json } from \\\"@sveltejs/kit\\\";\\nimport { env } from \\\"$env/dynamic/private\\\";\\nimport stripe from \\\"$lib/stripe\\\";\\nimport { handlePaymentIntentSucceeded } from \\\"./handlers/payment-intent/succeeded\\\";\\nimport { handlePaymentMethodAttached } from \\\"./handlers/payment-method/attached\\\";\\nimport { handleSubscriptionCreated } from \\\"./handlers/subscription/created\\\";\\nimport { handleSubscriptionUpdated } from \\\"./handlers/subscription/updated\\\";\\nimport { handleSubscriptionDeleted } from \\\"./handlers/subscription/deleted\\\";\\n\\nconst processedEvents = new Set<string>();\\n\\nasync function verifyWebhookSignature(\\n request: Request,\\n webhookSecret: string,\\n): Promise<Stripe.Event> {\\n const body = await request.text();\\n const signature = request.headers.get(\\\"stripe-signature\\\");\\n\\n if (!signature) {\\n throw new Error(\\\"Missing stripe-signature header\\\");\\n }\\n\\n if (!webhookSecret) {\\n throw new Error(\\\"Missing webhook secret\\\");\\n }\\n\\n try {\\n return stripe.webhooks.constructEvent(body, signature, webhookSecret);\\n } catch (err) {\\n console.error(\\\"Webhook signature verification failed:\\\", err);\\n throw new Error(\\\"Invalid signature\\\");\\n }\\n}\\n\\nexport const POST = async ({ request, locals }) => {\\n try {\\n const event = await verifyWebhookSignature(\\n request,\\n env.STRIPE_WEBHOOK_SECRET,\\n );\\n\\n if (processedEvents.has(event.id)) {\\n console.log(`Event ${event.id} already processed, skipping`);\\n return json({ received: true, message: \\\"Event already processed\\\" });\\n }\\n\\n processedEvents.add(event.id);\\n\\n console.log(`Processing webhook event: ${event.type} (${event.id})`);\\n\\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 return json({\\n received: true,\\n eventId: event.id,\\n eventType: event.type,\\n });\\n } catch (error) {\\n console.error(\\\"Webhook processing error:\\\", error);\\n\\n return json(\\n {\\n error: \\\"Webhook processing failed\\\",\\n message: error instanceof Error ? error.message : \\\"Unknown error\\\",\\n },\\n { status: 400 },\\n );\\n }\\n};\\n\""],"mappings":";AAAA,IAAA,IAAe,wtBCAf,IAAe,goDCAf,IAAe,unKCAf,IAAe,owCCAf,IAAe,8gECAf,IAAe,s0VCAf,IAAe,wvfCAf,IAAe"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as e } from "./errors-Co77I4oK.js";
|
|
2
2
|
import { i as t } from "./util-BNtpm1tP.js";
|
|
3
3
|
import { n, t as r } from "./logger-BpgCb-ZG.js";
|
|
4
|
-
import { getMigrationFile as i, migrationDelay as a, withPocketbase as o } from "./pocketbase-
|
|
4
|
+
import { getMigrationFile as i, migrationDelay as a, withPocketbase as o } from "./pocketbase-CjSrDiqR.js";
|
|
5
5
|
import { readFileSync as s } from "node:fs";
|
|
6
6
|
//#region src/runtime/collections.ts
|
|
7
7
|
function c(e) {
|
|
@@ -173,4 +173,4 @@ async function v(e, r) {
|
|
|
173
173
|
//#endregion
|
|
174
174
|
export { p as applyCollectionFieldsPatches, d as applyCollectionRulePatches, l as createCollectionIdempotent, v as createCollections, _ as dropCollections, g as planCollectionDrops };
|
|
175
175
|
|
|
176
|
-
//# sourceMappingURL=collections-
|
|
176
|
+
//# sourceMappingURL=collections-VC2LOzBB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collections-rD0M_Wxo.js","names":[],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(spec);\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\nexport interface DropCollectionResult {\n dropped: boolean;\n existed: boolean;\n}\n\n/**\n * Idempotent collection drop. Returns `{ existed: false, dropped: false }` if\n * the collection is already gone, matching the idempotency contract of\n * `createCollectionIdempotent`.\n */\nexport async function dropCollectionIdempotent(\n pb: PocketBase,\n name: string,\n logger: Logger = NOOP_LOGGER,\n): Promise<DropCollectionResult> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n logger.info(`Collection \"${name}\" does not exist, skipping drop`);\n return { dropped: false, existed: false };\n }\n throw error;\n }\n await pb.collections.delete(name);\n return { dropped: true, existed: true };\n}\n\nexport interface CollectionStats {\n exists: boolean;\n rowCount: number;\n}\n\nexport async function getCollectionStats(\n pb: PocketBase,\n name: string,\n): Promise<CollectionStats> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n return { exists: false, rowCount: 0 };\n }\n throw error;\n }\n\n try {\n const result = await pb.collection(name).getList(1, 1, { skipTotal: false });\n return { exists: true, rowCount: result.totalItems };\n } catch {\n return { exists: true, rowCount: 0 };\n }\n}\n\n/**\n * Resolve the set of collections to drop, with current row counts. Missing\n * collections are included with `exists: false, rowCount: 0` so callers can\n * display the full reversal plan even when some collections were already gone.\n */\nexport async function planCollectionDrops(\n pb: PocketBase,\n names: string[],\n): Promise<CollectionDropSpec[]> {\n const plans: CollectionDropSpec[] = [];\n for (const name of names) {\n const stats = await getCollectionStats(pb, name);\n plans.push({ name, exists: stats.exists, rowCount: stats.rowCount });\n }\n return plans;\n}\n\n/**\n * Drop each of the given collections (skipping those that are already gone)\n * and collect the `_deleted_<name>.js` migration file PocketBase emits for\n * each successful drop. Symmetric to `createCollections`.\n */\nexport async function dropCollections(\n specs: CollectionDropSpec[],\n options: Options,\n): Promise<File[]> {\n if (specs.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const spec of specs) {\n logger.info(`Dropping collection \"${spec.name}\"`);\n const { dropped } = await dropCollectionIdempotent(pb, spec.name, logger);\n if (!dropped) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(spec.name, \"deleted\", options);\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n\nexport async function createCollections(\n collections: CollectionSpec[],\n options: Options,\n): Promise<File[]> {\n if (collections.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const collection of collections) {\n logger.info(`Creating collection \"${collection.name}\"`);\n const { created } = await createCollectionIdempotent(\n pb,\n collection,\n logger,\n );\n if (!created) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n collection.name,\n \"created\",\n options,\n );\n if (!migrationFile) {\n continue;\n }\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;AA4BA,SAAS,EACP,GACS;AACT,KACE,EAAM,UAAU,MAAM,MAAM,SAAS,oCAErC,QAAO;CAGT,IAAM,IAAU,EAAM,SAAS,aAAa,IAAI;AAChD,QACE,EAAQ,SAAS,iBAAiB,IAAI,EAAQ,SAAS,iBAAiB;;AAiB5E,eAAsB,EACpB,GACA,GACA,IAAiB,GACgB;CACjC,IAAM,IAAQ,EAA0B;AACxC,KAAI;AAEF,SAAO;GAAE,YADU,MAAM,EAAG,YAAY,OAAO,EAAK;GAC/B,SAAS;GAAM;UAC7B,GAAO;AACd,M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Q;AAChE,QAEL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,EAAc;IACzC,SAAS,EAAa,GAAe,OAAO;IAC5C,QAAQ;IACT,CAAC;;GAEJ,EAEK;;AAGT,eAAsB,EACpB,GACA,GACiB;AACjB,KAAI,EAAY,WAAW,EACzB,QAAO,EAAE;CAGX,IAAM,IAAqB,EAAE,EACvB,IAAS,EAAU,EAAQ;AA+BjC,QA7BA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;AAC/C,OAAK,IAAM,KAAc,GAAa;AACpC,KAAO,KAAK,wBAAwB,EAAW,KAAK,GAAG;GACvD,IAAM,EAAE,eAAY,MAAM,EACxB,GACA,GACA,EACD;AACD,OAAI,CAAC,EAAS;AACd,SAAM,GAAgB;GAEtB,IAAM,IAAgB,EACpB,EAAW,MACX,WACA,EACD;AACI,QAIL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,EAAc;IACzC,SAAS,EAAa,GAAe,OAAO;IAC5C,QAAQ;IACT,CAAC;;GAEJ,EAEK"}
|
|
1
|
+
{"version":3,"file":"collections-VC2LOzBB.js","names":[],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(spec);\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\nexport interface DropCollectionResult {\n dropped: boolean;\n existed: boolean;\n}\n\n/**\n * Idempotent collection drop. Returns `{ existed: false, dropped: false }` if\n * the collection is already gone, matching the idempotency contract of\n * `createCollectionIdempotent`.\n */\nexport async function dropCollectionIdempotent(\n pb: PocketBase,\n name: string,\n logger: Logger = NOOP_LOGGER,\n): Promise<DropCollectionResult> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n logger.info(`Collection \"${name}\" does not exist, skipping drop`);\n return { dropped: false, existed: false };\n }\n throw error;\n }\n await pb.collections.delete(name);\n return { dropped: true, existed: true };\n}\n\nexport interface CollectionStats {\n exists: boolean;\n rowCount: number;\n}\n\nexport async function getCollectionStats(\n pb: PocketBase,\n name: string,\n): Promise<CollectionStats> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n return { exists: false, rowCount: 0 };\n }\n throw error;\n }\n\n try {\n const result = await pb\n .collection(name)\n .getList(1, 1, { skipTotal: false });\n return { exists: true, rowCount: result.totalItems };\n } catch {\n return { exists: true, rowCount: 0 };\n }\n}\n\n/**\n * Resolve the set of collections to drop, with current row counts. Missing\n * collections are included with `exists: false, rowCount: 0` so callers can\n * display the full reversal plan even when some collections were already gone.\n */\nexport async function planCollectionDrops(\n pb: PocketBase,\n names: string[],\n): Promise<CollectionDropSpec[]> {\n const plans: CollectionDropSpec[] = [];\n for (const name of names) {\n const stats = await getCollectionStats(pb, name);\n plans.push({ name, exists: stats.exists, rowCount: stats.rowCount });\n }\n return plans;\n}\n\n/**\n * Drop each of the given collections (skipping those that are already gone)\n * and collect the `_deleted_<name>.js` migration file PocketBase emits for\n * each successful drop. Symmetric to `createCollections`.\n */\nexport async function dropCollections(\n specs: CollectionDropSpec[],\n options: Options,\n): Promise<File[]> {\n if (specs.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const spec of specs) {\n logger.info(`Dropping collection \"${spec.name}\"`);\n const { dropped } = await dropCollectionIdempotent(pb, spec.name, logger);\n if (!dropped) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(spec.name, \"deleted\", options);\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n\nexport async function createCollections(\n collections: CollectionSpec[],\n options: Options,\n): Promise<File[]> {\n if (collections.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const collection of collections) {\n logger.info(`Creating collection \"${collection.name}\"`);\n const { created } = await createCollectionIdempotent(\n pb,\n collection,\n logger,\n );\n if (!created) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n collection.name,\n \"created\",\n options,\n );\n if (!migrationFile) {\n continue;\n }\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;AA4BA,SAAS,EACP,GACS;AACT,KACE,EAAM,UAAU,MAAM,MAAM,SAAS,oCAErC,QAAO;CAGT,IAAM,IAAU,EAAM,SAAS,aAAa,IAAI;AAChD,QACE,EAAQ,SAAS,iBAAiB,IAAI,EAAQ,SAAS,iBAAiB;;AAiB5E,eA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AAK,GAAG;GACjD,IAAM,EAAE,eAAY,MAAM,EAAyB,GAAI,EAAK,MAAM,EAAO;AACzE,OAAI,CAAC,EAAS;AACd,SAAM,GAAgB;GAEtB,IAAM,IAAgB,EAAiB,EAAK,MAAM,WAAW,EAAQ;AAChE,QAEL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,EAAc;IACzC,SAAS,EAAa,GAAe,OAAO;IAC5C,QAAQ;IACT,CAAC;;GAEJ,EAEK;;AAGT,eAAsB,EACpB,GACA,GACiB;AACjB,KAAI,EAAY,WAAW,EACzB,QAAO,EAAE;CAGX,IAAM,IAAqB,EAAE,EACvB,IAAS,EAAU,EAAQ;AA+BjC,QA7BA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;AAC/C,OAAK,IAAM,KAAc,GAAa;AACpC,KAAO,KAAK,wBAAwB,EAAW,KAAK,GAAG;GACvD,IAAM,EAAE,eAAY,MAAM,EACxB,GACA,GACA,EACD;AACD,OAAI,CAAC,EAAS;AACd,SAAM,GAAgB;GAEtB,IAAM,IAAgB,EACpB,EAAW,MACX,WACA,EACD;AACI,QAIL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,EAAc;IACzC,SAAS,EAAa,GAAe,OAAO;IAC5C,QAAQ;IACT,CAAC;;GAEJ,EAEK"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"env-KcKcG4Mg.js","names":[],"sources":["../../src/runtime/env.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../core/types\";\n\nexport interface EnvEdit {\n type: \"comment\" | \"var\";\n /** For \"comment\": the text after `# `. For \"var\": the KEY. */\n key: string;\n /** Only for \"var\" entries. */\n value?: string;\n}\n\nfunction appendEnvContent(existing: string, content: string): string {\n const withNewLine =\n !existing.length || existing.endsWith(\"\\n\") ? existing : existing + \"\\n\";\n return withNewLine + content + \"\\n\";\n}\n\nexport function applyEnvEdits(source: string, edits: EnvEdit[]): string {\n let next = source;\n for (const edit of edits) {\n if (edit.type === \"comment\") {\n const commented = `# ${edit.key}`;\n if (!next.includes(commented)) {\n next = appendEnvContent(next, commented);\n }\n continue;\n }\n if (!next.includes(`${edit.key}=`)) {\n next = appendEnvContent(next, `${edit.key}=${edit.value ?? \"\"}`);\n }\n }\n return next;\n}\n\nexport function modifyEnv(envPath: string, edits: EnvEdit[]): ModifyOutcome {\n const existing = fs.existsSync(envPath)\n ? fs.readFileSync(envPath, \"utf8\")\n : \"\";\n const next = applyEnvEdits(existing, edits);\n if (next === existing) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(envPath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\n/**\n * Remove lines matching the given edits from env source. Var edits remove the\n * exact `KEY=...` line (anchored, so `FOO` does not match `FOO_BAR`). Comment\n * edits remove the `# key` line only when it has become orphaned — i.e. the\n * next non-blank line is another comment, another orphaned block, or EOF.\n */\nexport function removeEnvEdits(source: string, edits: EnvEdit[]): string {\n const lines = source.split(\"\\n\");\n const keep: boolean[] = lines.map(() => true);\n\n for (const edit of edits) {\n if (edit.type !== \"var\") continue;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i]) continue;\n const line = lines[i];\n if (\n line === `${edit.key}=${edit.value ?? \"\"}` ||\n line.startsWith(`${edit.key}=`)\n ) {\n keep[i] = false;\n }\n }\n }\n\n for (const edit of edits) {\n if (edit.type !== \"comment\") continue;\n const target = `# ${edit.key}`;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i] || lines[i] !== target) continue;\n let j = i + 1;\n while (j < lines.length && (!keep[j] || lines[j].trim() === \"\")) j++;\n const nextIsComment = j >= lines.length || lines[j].startsWith(\"#\");\n if (nextIsComment) {\n keep[i] = false;\n }\n }\n }\n\n const result: string[] = [];\n let lastWasBlank = false;\n for (let i = 0; i < lines.length; i++) {\n if (!keep[i]) continue;\n const isBlank = lines[i].trim() === \"\";\n if (isBlank && lastWasBlank) continue;\n result.push(lines[i]);\n lastWasBlank = isBlank;\n }\n\n while (result.length > 0 && result[result.length - 1].trim() === \"\") {\n result.pop();\n }\n\n return result.length === 0 ? \"\" : result.join(\"\\n\") + \"\\n\";\n}\n\nexport function modifyEnvRemove(\n envPath: string,\n edits: EnvEdit[],\n): ModifyOutcome {\n const existing = fs.existsSync(envPath)\n ? fs.readFileSync(envPath, \"utf8\")\n : \"\";\n const next = removeEnvEdits(existing, edits);\n if (next === existing) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(envPath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;AAWA,SAAS,EAAiB,GAAkB,GAAyB;AAGnE,SADE,CAAC,EAAS,UAAU,EAAS,SAAS,KAAK,GAAG,IAAW,IAAW,QACjD,IAAU;;AAGjC,SAAgB,EAAc,GAAgB,GAA0B;CACtE,IAAI,IAAO;AACX,MAAK,IAAM,KAAQ,GAAO;AACxB,MAAI,EAAK,SAAS,WAAW;GAC3B,IAAM,IAAY,KAAK,EAAK;AAC5B,GAAK,EAAK,SAAS,EAAU,KAC3B,IAAO,EAAiB,GAAM,EAAU;AAE1C;;AAEF,EAAK,EAAK,SAAS,GAAG,EAAK,IAAI,GAAG,KAChC,IAAO,EAAiB,GAAM,GAAG,EAAK,IAAI,GAAG,EAAK,SAAS,KAAK;;AAGpE,QAAO;;AAGT,SAAgB,EAAU,GAAiB,GAAiC;CAC1E,IAAM,IAAW,EAAG,WAAW,EAAQ,GACnC,EAAG,aAAa,GAAS,OAAO,GAChC,IACE,IAAO,EAAc,GAAU,EAAM;AAK3C,QAJI,MAAS,IACJ;EAAE,QAAQ;EAAW,SAAS;EAAO,IAE9C,EAAG,cAAc,GAAS,GAAM,OAAO,EAChC;EAAE,QAAQ;EAAW,SAAS;EAAM;;AAS7C,SAAgB,EAAe,GAAgB,GAA0B;CACvE,IAAM,IAAQ,EAAO,MAAM,KAAK,EAC1B,IAAkB,EAAM,UAAU,GAAK;AAE7C,MAAK,IAAM,KAAQ,EACb,OAAK,SAA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}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"env.preview-
|
|
1
|
+
{"version":3,"file":"env.preview-u7rnWI2E.js","names":[],"sources":["../../src/parse/env.preview.ts"],"sourcesContent":["import type { Options } from \"../core/types\";\nimport type { Collection } from \"./types\";\n\nexport function getPreviewCollections(\n options: Pick<Options, \"features\">,\n): Collection[] {\n if (options.features.auth) {\n return [\n {\n id: \"users_preview\",\n name: \"users\",\n type: \"auth\",\n fields: [\n { name: \"email\", type: \"email\" },\n { name: \"name\", type: \"text\" },\n ],\n },\n ];\n }\n return [];\n}\n"],"mappings":";AAGA,SAAgB,EACd,GACc;AAcd,QAbI,EAAQ,SAAS,OACZ,CACL;EACE,IAAI;EACJ,MAAM;EACN,MAAM;EACN,QAAQ,CACN;GAAE,MAAM;GAAS,MAAM;GAAS,EAChC;GAAE,MAAM;GAAQ,MAAM;GAAQ,CAC/B;EACF,CACF,GAEI,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"env.runtime-
|
|
1
|
+
{"version":3,"file":"env.runtime-N65jqPxq.js","names":[],"sources":["../../src/parse/env.runtime.ts"],"sourcesContent":["import { getCollections as getCollectionsFromPB } from \"@velastack/pocketbase/internal\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { DATA_DIR } from \"../core/constants\";\nimport type { Collection } from \"./types\";\n\nfunction hasProjectMarkers(dir: string): boolean {\n return (\n fs.existsSync(path.join(dir, \"package.json\")) &&\n fs.existsSync(path.join(dir, DATA_DIR))\n );\n}\n\nexport function resolveProjectRoot(startDir = process.cwd()): string {\n let current = path.resolve(startDir);\n\n while (true) {\n if (hasProjectMarkers(current)) {\n return current;\n }\n\n const parent = path.dirname(current);\n if (parent === current) {\n break;\n }\n current = parent;\n }\n\n throw new Error(\n `Could not resolve project root from \"${startDir}\". Expected package.json, and ${DATA_DIR}.`,\n );\n}\n\nexport async function getCollections(): Promise<Collection[]> {\n const root = resolveProjectRoot();\n\n return getCollectionsFromPB({\n pocketbaseUrl: \"\",\n superuserEmail: process.env.POCKETBASE_SUPERUSER_EMAIL!,\n superuserPassword: process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n root,\n }) as Promise<Collection[]>;\n}\n"],"mappings":";;;;;;AAOA,SAAS,EAAkB,GAAsB;AAC/C,QACE,EAAG,WAAW,EAAK,KAAK,GAAK,eAAe,CAAC,IAC7C,EAAG,WAAW,EAAK,KAAK,GAAA,OAAc,CAAC;;AAI3C,SAAgB,EAAmB,IAAW,EAAQ,KAAK,EAAU;CACnE,IAAI,IAAU,EAAK,QAAQ,EAAS;AAEpC,UAAa;AACX,MAAI,EAAkB,EAAQ,CAC5B,QAAO;EAGT,IAAM,IAAS,EAAK,QAAQ,EAAQ;AACpC,MAAI,MAAW,EACb;AAEF,MAAU;;AAGZ,OAAU,MACR,wCAAwC,EAAS,gCAAgC,EAAS,GAC3F;;AAGH,eAAsB,IAAwC;CAC5D,IAAM,IAAO,GAAoB;AAEjC,QAAO,EAAqB;EAC1B,eAAe;EACf,gBAAgB,EAAQ,IAAI;EAC5B,mBAAmB,EAAQ,IAAI;EAC/B;EACD,CAAC"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as e } from "./dedent-C4qKBQXh.js";
|
|
2
2
|
import { n as t } from "./logger-BpgCb-ZG.js";
|
|
3
|
-
import { n, r, t as i } from "./nav-user-
|
|
4
|
-
import { t as a } from "./shared-
|
|
5
|
-
import { modifyOutcomeToFile as o } from "./modify-file-
|
|
6
|
-
import { a as s, o as c, r as l } from "./ts-morph-helpers-
|
|
3
|
+
import { n, r, t as i } from "./nav-user-_VheJA6n.js";
|
|
4
|
+
import { t as a } from "./shared-C55q8tz4.js";
|
|
5
|
+
import { modifyOutcomeToFile as o } from "./modify-file-DE7tPADZ.js";
|
|
6
|
+
import { a as s, o as c, r as l } from "./ts-morph-helpers-bR0-x04t.js";
|
|
7
7
|
import u from "node:fs";
|
|
8
8
|
import d from "node:path";
|
|
9
9
|
import { SyntaxKind as f } from "ts-morph";
|
|
@@ -208,4 +208,4 @@ async function E(e) {
|
|
|
208
208
|
//#endregion
|
|
209
209
|
export { E as generate };
|
|
210
210
|
|
|
211
|
-
//# sourceMappingURL=generate.runtime-
|
|
211
|
+
//# sourceMappingURL=generate.runtime-33rNLYvg.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate.runtime-33rNLYvg.js","names":[],"sources":["../../src/patterns/disable/subscriptions/modifies/modify-stripe-hooks.ts","../../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 type { ModifyOutcome } from \"../../../../core/types\";\n\n// Matches the entire cronAdd(\"stripe-subscriptions\", ...) {...}); block with\n// optional surrounding blank lines. Tolerates single- or double-quoted name\n// and trailing semicolon variants.\nconst SUBSCRIPTION_CRON_RE =\n /\\n*cronAdd\\(\\s*[\"']stripe-subscriptions[\"'][\\s\\S]*?\\}\\s*\\)\\s*;?\\s*\\n?/m;\n\nexport function unmodifyStripeHooks(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(\"stripe-subscriptions\")) {\n return { status: \"success\", changed: false };\n }\n const next = original.replace(SUBSCRIPTION_CRON_RE, \"\\n\");\n if (next === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, next, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\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, \"./handlers/subscription/created\");\n removeImportByModuleSpecifier(sf, \"./handlers/subscription/updated\");\n removeImportByModuleSpecifier(sf, \"./handlers/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 exprText = caseClause.getExpression().getText();\n return SUBSCRIPTION_CASE_VALUES.has(exprText);\n })\n .map((c) => c.asKindOrThrow(SyntaxKind.CaseClause));\n\n for (const clause of toRemove.reverse()) {\n clause.remove();\n }\n\n sf.formatText();\n });\n\n if (source === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, source, \"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 { withInMemoryScript } 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 sf.formatText();\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 { unmodifyStripeHooks } from \"./modifies/modify-stripe-hooks\";\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 data/hooks/stripe.pb.js\");\n const stripeHooksPath = path.join(\n options.root,\n \"data\",\n \"hooks\",\n \"stripe.pb.js\",\n );\n pushResult(\n modifyOutcomeToFile(stripeHooksPath, unmodifyStripeHooks(stripeHooksPath)),\n );\n\n logger.info(\"Reverting webhooks/stripe/+server.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"+server.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: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AsB,EAAK,KAC/B,EAAQ,MACR,OACA,UACA,SACA,iBACD;AAQD,CAPA,EACE,EACE,GACA,EAAwB,EAAoB,CAC7C,CACF,EAED,EAAO,KAAK,+BAA+B;CAC3C,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,OACA,cACA,qBACD;AAKD,CAJA,EACE,EAAoB,GAAgB,EAAmB,EAAe,CAAC,CACxE,EAED,EAAO,KAAK,4BAA4B;CACxC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,kBACD;AAQD,CAPA,EACE,EACE,GACA,EAAgB,GAAa,EAAwB,CACtD,CACF,EAED,EAAO,KAAK,oCAAoC;CAChD,IAAM,IAAwB,EAAK,KACjC,EAAQ,MACR,OACA,UACA,SACA,WACA,kBACD;AAWD,CAVA,EACE,EACE,GACA,EACE,GACA,EACD,CACF,CACF,EAED,EAAO,KAAK,iCAAiC;CAC7C,IAAM,IAAwB,EAAK,KACjC,EAAQ,MACR,OACA,UACA,SACA,WACA,eACD;AAgBD,QAfA,EACE,EACE,GACA,EACE,GACA,EACD,CACF,CACF,EAOM;EACL,SAAS,EAAE;EACX;EACA,SAAS,EAAE;EACX,YAAY,EAAE;EACd,UAAU,EAAE;EACZ,aAAa,EAAE;EACf,mBAAmB,EAAE;EACrB,iBAbsB,MAAM,EAC5B,CAAC,uBAAuB,EACxB,EACD;EAWA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as e } from "./logger-BpgCb-ZG.js";
|
|
2
|
-
import { modifyOutcomeToFile as t } from "./modify-file-
|
|
2
|
+
import { modifyOutcomeToFile as t } from "./modify-file-DE7tPADZ.js";
|
|
3
3
|
import n from "node:fs";
|
|
4
4
|
import r from "node:path";
|
|
5
5
|
//#region src/patterns/disable/i18n/modifies/gitignore.ts
|
|
@@ -62,4 +62,4 @@ async function o(n) {
|
|
|
62
62
|
//#endregion
|
|
63
63
|
export { o as generate };
|
|
64
64
|
|
|
65
|
-
//# sourceMappingURL=generate.runtime-
|
|
65
|
+
//# sourceMappingURL=generate.runtime-AgF-_CuZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-AgF-_CuZ.js","names":[],"sources":["../../src/patterns/disable/i18n/modifies/gitignore.ts","../../src/patterns/disable/i18n/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n if (!original.includes(\"src/locales/.wuchale\")) {\n return { status: \"success\", changed: false };\n }\n\n const lines = original.split(\"\\n\");\n const out: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line === \"# Wuchale\") {\n let j = i + 1;\n let hasWuchale = false;\n while (j < lines.length && lines[j].trim() !== \"\") {\n if (lines[j] === \"src/locales/.wuchale\") {\n hasWuchale = true;\n }\n j++;\n }\n if (hasWuchale) {\n i = j;\n continue;\n }\n }\n if (line === \"src/locales/.wuchale\") continue;\n out.push(line);\n }\n\n let updated = out.join(\"\\n\");\n updated = updated.replace(/\\n{3,}/g, \"\\n\\n\");\n\n if (updated === original) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(gitignorePath, updated);\n return { status: \"success\", changed: true };\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 { unmodifyGitignore } from \"./modifies/gitignore\";\n\nconst MANUAL_REMEDIATION = [\n \"vite.config, svelte.config, hooks.server, app.html, and +layout.ts must be reverted manually.\",\n \"The i18n integration touches these files in ways that are not safely reversible by tooling.\",\n \"See the enable-i18n modifies for the blocks to remove.\",\n].join(\" \");\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 .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n pushResult(\n modifyOutcomeToFile(gitignorePath, unmodifyGitignore(gitignorePath)),\n );\n\n logger.info(MANUAL_REMEDIATION);\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":";;;;;AAGA,SAAgB,EAAkB,GAAsC;AACtE,KAAI,CAAC,EAAG,WAAW,EAAc,CAC/B,QAAO;EAAE,QAAQ;EAAW,SAAS;EAAO;CAG9C,IAAM,IAAW,EAAG,aAAa,GAAe,OAAO;AACvD,KAAI,CAAC,EAAS,SAAS,uBAAuB,CAC5C,QAAO;EAAE,QAAQ;EAAW,SAAS;EAAO;CAG9C,IAAM,IAAQ,EAAS,MAAM,KAAK,EAC5B,IAAgB,EAAE;AACxB,MAAK,IAAI,IAAI,GAAG,IAAI,EAAM,QAAQ,KAAK;EACrC,IAAM,IAAO,EAAM;AACnB,MAAI,MAAS,aAAa;GACxB,IAAI,IAAI,IAAI,GACR,IAAa;AACjB,UAAO,IAAI,EAAM,UAAU,EAAM,GAAG,MAAM,KAAK,IAI7C,CAHI,EAAM,OAAO,2BACf,IAAa,KAEf;AAEF,OAAI,GAAY;AACd,QAAI;AACJ;;;AAGA,QAAS,0BACb,EAAI,KAAK,EAAK;;CAGhB,IAAI,IAAU,EAAI,KAAK,KAAK;AAQ5B,QAPA,IAAU,EAAQ,QAAQ,WAAW,OAAO,EAExC,MAAY,IACP;EAAE,QAAQ;EAAW,SAAS;EAAO,IAG9C,EAAG,cAAc,GAAe,EAAQ,EACjC;EAAE,QAAQ;EAAW,SAAS;EAAM;;;;ACrC7C,IAAM,IAAqB;CACzB;CACA;CACA;CACD,CAAC,KAAK,IAAI;AAEX,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,EAAQ,EAC3B,IAAmB,EAAE,EACrB,KAAc,MAAsB;AACxC,EAAI,KAAM,EAAS,KAAK,EAAK;;AAG/B,GAAO,KAAK,uBAAuB;CACnC,IAAM,IAAgB,EAAK,KAAK,EAAQ,MAAM,aAAa;AAO3D,QANA,EACE,EAAoB,GAAe,EAAkB,EAAc,CAAC,CACrE,EAED,EAAO,KAAK,EAAmB,EAExB;EACL,SAAS,EAAE;EACX;EACA,SAAS,EAAE;EACX,YAAY,EAAE;EACd,UAAU,EAAE;EACZ,aAAa,EAAE;EACf,mBAAmB,EAAE;EACrB,iBAAiB,EAAE;EACpB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as e } from "./logger-BpgCb-ZG.js";
|
|
2
|
-
import { t } from "./shared-
|
|
3
|
-
import { modifyOutcomeToFile as n } from "./modify-file-
|
|
4
|
-
import { i as r, o as i } from "./ts-morph-helpers-
|
|
2
|
+
import { t } from "./shared-C55q8tz4.js";
|
|
3
|
+
import { modifyOutcomeToFile as n } from "./modify-file-DE7tPADZ.js";
|
|
4
|
+
import { i as r, o as i } from "./ts-morph-helpers-bR0-x04t.js";
|
|
5
5
|
import a from "node:fs";
|
|
6
6
|
import o from "node:path";
|
|
7
7
|
//#region src/patterns/disable/teams/modifies/modify-nav-user.ts
|
|
@@ -57,4 +57,4 @@ async function l(r) {
|
|
|
57
57
|
//#endregion
|
|
58
58
|
export { l as generate };
|
|
59
59
|
|
|
60
|
-
//# sourceMappingURL=generate.runtime-
|
|
60
|
+
//# sourceMappingURL=generate.runtime-B07nsq-H.js.map
|