@velastack/patterns 0.0.61 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/chunks/_server-BSm1eAiY.js +6 -0
  2. package/dist/chunks/_server-BSm1eAiY.js.map +1 -0
  3. package/dist/chunks/{collections-DZOoJLVj.js → collections-DgZjDXef.js} +2 -2
  4. package/dist/chunks/{collections-DZOoJLVj.js.map → collections-DgZjDXef.js.map} +1 -1
  5. package/dist/chunks/{config-target-Co-ij8p3.js → config-target-DOi8kI_f.js} +9 -9
  6. package/dist/chunks/{config-target-Co-ij8p3.js.map → config-target-DOi8kI_f.js.map} +1 -1
  7. package/dist/chunks/{generate.runtime-6qpoLA04.js → generate.runtime--0bYEUP_.js} +19 -19
  8. package/dist/chunks/{generate.runtime-6qpoLA04.js.map → generate.runtime--0bYEUP_.js.map} +1 -1
  9. package/dist/chunks/{generate.runtime-DBG6kEKb.js → generate.runtime-677mL0-8.js} +17 -17
  10. package/dist/chunks/{generate.runtime-DBG6kEKb.js.map → generate.runtime-677mL0-8.js.map} +1 -1
  11. package/dist/chunks/{generate.runtime-CtzHFod-.js → generate.runtime-BOLZHcGN.js} +24 -24
  12. package/dist/chunks/{generate.runtime-CtzHFod-.js.map → generate.runtime-BOLZHcGN.js.map} +1 -1
  13. package/dist/chunks/{generate.runtime-DfqzMG8Z.js → generate.runtime-BgW9zLGZ.js} +2 -2
  14. package/dist/chunks/{generate.runtime-DfqzMG8Z.js.map → generate.runtime-BgW9zLGZ.js.map} +1 -1
  15. package/dist/chunks/{generate.runtime-CYmjlSQp.js → generate.runtime-C52G7ZnV.js} +15 -15
  16. package/dist/chunks/{generate.runtime-CYmjlSQp.js.map → generate.runtime-C52G7ZnV.js.map} +1 -1
  17. package/dist/chunks/{generate.runtime-a5PXS1Kd.js → generate.runtime-CDSkTWtx.js} +10 -10
  18. package/dist/chunks/{generate.runtime-a5PXS1Kd.js.map → generate.runtime-CDSkTWtx.js.map} +1 -1
  19. package/dist/chunks/{generate.runtime-AmiNbSR3.js → generate.runtime-CFKrhkAA.js} +12 -12
  20. package/dist/chunks/{generate.runtime-AmiNbSR3.js.map → generate.runtime-CFKrhkAA.js.map} +1 -1
  21. package/dist/chunks/{generate.runtime-BnnsaLsg.js → generate.runtime-CFwzS666.js} +12 -12
  22. package/dist/chunks/{generate.runtime-BnnsaLsg.js.map → generate.runtime-CFwzS666.js.map} +1 -1
  23. package/dist/chunks/{generate.runtime-CRS9C9xX.js → generate.runtime-CG0gMypH.js} +14 -14
  24. package/dist/chunks/{generate.runtime-CRS9C9xX.js.map → generate.runtime-CG0gMypH.js.map} +1 -1
  25. package/dist/chunks/{generate.runtime-rfNiROHo.js → generate.runtime-CNwy0UB2.js} +30 -30
  26. package/dist/chunks/{generate.runtime-rfNiROHo.js.map → generate.runtime-CNwy0UB2.js.map} +1 -1
  27. package/dist/chunks/{generate.runtime-D9t6eaQd.js → generate.runtime-Cc1SG-nN.js} +20 -20
  28. package/dist/chunks/{generate.runtime-D9t6eaQd.js.map → generate.runtime-Cc1SG-nN.js.map} +1 -1
  29. package/dist/chunks/{generate.runtime-Di0p-J8l.js → generate.runtime-CfclK4xT.js} +12 -12
  30. package/dist/chunks/{generate.runtime-Di0p-J8l.js.map → generate.runtime-CfclK4xT.js.map} +1 -1
  31. package/dist/chunks/{generate.runtime-CtS6qa_1.js → generate.runtime-Coi_Y6nm.js} +22 -22
  32. package/dist/chunks/generate.runtime-Coi_Y6nm.js.map +1 -0
  33. package/dist/chunks/{generate.runtime-EokncTLy.js → generate.runtime-Dad9oAKS.js} +27 -27
  34. package/dist/chunks/{generate.runtime-EokncTLy.js.map → generate.runtime-Dad9oAKS.js.map} +1 -1
  35. package/dist/chunks/{generate.runtime-CNxgU9v1.js → generate.runtime-Dbhctzy1.js} +17 -17
  36. package/dist/chunks/{generate.runtime-CNxgU9v1.js.map → generate.runtime-Dbhctzy1.js.map} +1 -1
  37. package/dist/chunks/{generate.runtime-P8IVwJLB.js → generate.runtime-DpV_oOT7.js} +23 -23
  38. package/dist/chunks/{generate.runtime-P8IVwJLB.js.map → generate.runtime-DpV_oOT7.js.map} +1 -1
  39. package/dist/chunks/{generate.runtime-6TJoTPg9.js → generate.runtime-DrDZe6gu.js} +25 -20
  40. package/dist/chunks/generate.runtime-DrDZe6gu.js.map +1 -0
  41. package/dist/chunks/{generate.runtime-CINxHRnJ.js → generate.runtime-PtDQdWNY.js} +11 -11
  42. package/dist/chunks/{generate.runtime-CINxHRnJ.js.map → generate.runtime-PtDQdWNY.js.map} +1 -1
  43. package/dist/chunks/{generate.runtime-qZhYdFI1.js → generate.runtime-WaqVbEPP.js} +19 -19
  44. package/dist/chunks/{generate.runtime-qZhYdFI1.js.map → generate.runtime-WaqVbEPP.js.map} +1 -1
  45. package/dist/chunks/{generate.runtime-DsLlDfIo.js → generate.runtime-lvraqNgB.js} +25 -25
  46. package/dist/chunks/{generate.runtime-DsLlDfIo.js.map → generate.runtime-lvraqNgB.js.map} +1 -1
  47. package/dist/chunks/{generate.runtime-CGtKTfYU.js → generate.runtime-qsPylve5.js} +2 -2
  48. package/dist/chunks/{generate.runtime-CGtKTfYU.js.map → generate.runtime-qsPylve5.js.map} +1 -1
  49. package/dist/chunks/{modify-svelte-config-remote-CDKs_Qi0.js → modify-svelte-config-remote-D3eBzcZc.js} +2 -2
  50. package/dist/chunks/{modify-svelte-config-remote-CDKs_Qi0.js.map → modify-svelte-config-remote-D3eBzcZc.js.map} +1 -1
  51. package/dist/chunks/{pocketbase-BbFvZ4HI.js → pocketbase-BPwW3TWr.js} +15 -15
  52. package/dist/chunks/{pocketbase-BbFvZ4HI.js.map → pocketbase-BPwW3TWr.js.map} +1 -1
  53. package/dist/chunks/{shared-C4-NNykV.js → shared-BGvy1V-z.js} +2 -2
  54. package/dist/chunks/{shared-C4-NNykV.js.map → shared-BGvy1V-z.js.map} +1 -1
  55. package/dist/chunks/{test-setup-CcD8wSRD.js → test-setup-BGhcb0Qm.js} +3 -3
  56. package/dist/chunks/{test-setup-CcD8wSRD.js.map → test-setup-BGhcb0Qm.js.map} +1 -1
  57. package/dist/chunks/{write-result-DtTqt0Cs.js → write-result-BhULcFGo.js} +45 -45
  58. package/dist/chunks/{write-result-DtTqt0Cs.js.map → write-result-BhULcFGo.js.map} +1 -1
  59. package/dist/index.d.ts +22 -0
  60. package/dist/index.js +80 -70
  61. package/dist/index.js.map +1 -1
  62. package/package.json +13 -3
  63. package/dist/chunks/_server-Cie287JZ.js +0 -6
  64. package/dist/chunks/_server-Cie287JZ.js.map +0 -1
  65. package/dist/chunks/env.runtime-BVage9Kk.js +0 -31
  66. package/dist/chunks/env.runtime-BVage9Kk.js.map +0 -1
  67. package/dist/chunks/generate.runtime-6TJoTPg9.js.map +0 -1
  68. package/dist/chunks/generate.runtime-CtS6qa_1.js.map +0 -1
@@ -0,0 +1,6 @@
1
+ //#region src/patterns/enable/subscriptions/preview-modifies/data/hooks/stripe.pb.js?raw
2
+ var e = "/// <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", t = "<script lang=\"ts\" module>\n import HomeIcon from '@lucide/svelte/icons/home';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n<\/script>\n\n<script lang=\"ts\">\n import favicon from '$lib/assets/favicon.svg';\n\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n import * as Sidebar from '$lib/components/ui/sidebar';\n import type { ComponentProps } from 'svelte';\n\n let {\n user,\n meta,\n // [!code highlight:1]\n subscription = null,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & {\n user: any;\n meta: any;\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <Sidebar.MenuItem>\n <Sidebar.MenuButton size=\"lg\">\n {#snippet child({ props })}\n <a href=\"/dashboard\" {...props}>\n <div\n class=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n >\n <img src={favicon} alt=\"logo\" class=\"size-6\" />\n </div>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{meta.appName}</span>\n </div>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} {subscription} />\n </Sidebar.Footer>\n</Sidebar.Root>\n", n = "<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", r = "// [!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", i = "<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", a = "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", o = "<script lang=\"ts\">\n import { Button } from '$lib/components/ui/button';\n import * as Card from '$lib/components/ui/card';\n import { Badge } from '$lib/components/ui/badge';\n import * as AlertDialog from '$lib/components/ui/alert-dialog';\n import SetupButton from '$lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check, Package } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate, invalidateAll } from '$app/navigation';\n import { untrack } from 'svelte';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let availablePlans = $derived(data.availablePlans);\n let hasDefaultPaymentMethod = $derived(data.hasDefaultPaymentMethod);\n\n // Local, mutable mirror of the server-side subscription. We optimistically\n // update it on user actions so the UI reflects the change immediately; the\n // $effect re-syncs from the server after the webhook has had a chance to\n // fire (invalidateAll runs on a short delay below).\n let activeSubscription = $state(untrack(() => data.activeSubscription));\n $effect(() => {\n activeSubscription = data.activeSubscription;\n });\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n let showCancelDialog = $state(false);\n let isSubscribing = $state<string | null>(null);\n let isCanceling = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n\n function formatAmount(amount: number | null, currency: string | null) {\n if (amount === null || !currency) return '—';\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: currency.toUpperCase()\n }).format(amount / 100);\n }\n\n function formatInterval(recurring: { interval: string; interval_count: number } | null) {\n if (!recurring) return '';\n if (recurring.interval_count === 1) return `/ ${recurring.interval}`;\n return `every ${recurring.interval_count} ${recurring.interval}s`;\n }\n\n function formatDate(iso: string | null) {\n if (!iso) return '—';\n return new Date(iso).toLocaleDateString(undefined, {\n year: 'numeric',\n month: 'short',\n day: 'numeric'\n });\n }\n\n async function selectPlan(priceId: string, successMessage: string) {\n if (!hasDefaultPaymentMethod) {\n toast.error('Add a default payment method first');\n return;\n }\n const previous = activeSubscription;\n const plan = availablePlans.find((p) => p.id === priceId);\n if (plan) {\n activeSubscription = previous\n ? {\n ...previous,\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false\n }\n : {\n id: 'pending',\n status: 'active',\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false,\n currentPeriodStart: null,\n currentPeriodEnd: null,\n canceledAt: null\n };\n }\n\n isSubscribing = priceId;\n try {\n const formData = new FormData();\n formData.append('priceId', priceId);\n\n const res = await fetch('?/selectPlan', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`selectPlan failed: ${res.status}`);\n }\n\n toast.success(successMessage);\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error selecting plan:', err);\n toast.error('Failed to update plan');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function subscribe(priceId: string) {\n await selectPlan(priceId, 'Subscription started');\n }\n\n async function switchPlan(priceId: string) {\n await selectPlan(priceId, 'Subscription updated');\n }\n\n async function resumeSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isSubscribing = activeSubscription.priceId;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: false };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/resumeSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Resume failed: ${res.status}`);\n }\n\n toast.success('Subscription resumed');\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error resuming subscription:', err);\n toast.error('Failed to resume subscription');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function handleCancelSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isCanceling = true;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: true };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/cancelSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Cancel failed: ${res.status}`);\n }\n\n toast.success('Subscription will cancel at period end');\n showCancelDialog = false;\n setTimeout(() => {\n invalidateAll();\n }, 2000);\n } catch (err) {\n console.error('Error canceling subscription:', err);\n toast.error('Failed to cancel subscription');\n activeSubscription = previous;\n } finally {\n isCanceling = false;\n }\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n </Card.Root>\n </div>\n </div>\n\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Plan</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">Manage your subscription.</p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if availablePlans.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <Package class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No plans available</p>\n <p class=\"text-sm\">Check back soon.</p>\n </div>\n {:else}\n {#if !hasDefaultPaymentMethod}\n <p class=\"text-muted-foreground mb-4 rounded-md border border-dashed p-3 text-sm\">\n Add a default payment method above to subscribe.\n </p>\n {/if}\n <div class=\"space-y-4\">\n {#each availablePlans as plan (plan.id)}\n {@const isCurrent = activeSubscription?.priceId === plan.id}\n <div\n class=\"flex items-center justify-between rounded-lg border p-4 transition-colors {isCurrent\n ? 'border-primary ring-primary ring-1'\n : 'border-border hover:bg-accent/50'}\"\n >\n <div class=\"flex items-center gap-4\">\n <div class=\"bg-muted flex size-12 items-center justify-center rounded-lg\">\n <Package class=\"size-5\" />\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">{plan.productName}</p>\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Badge variant=\"outline\">Pending cancellation</Badge>\n {:else if activeSubscription.status === 'trialing'}\n <Badge variant=\"secondary\">Trial</Badge>\n {:else if activeSubscription.status === 'past_due'}\n <Badge variant=\"destructive\">Past due</Badge>\n {:else}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Current\n </Badge>\n {/if}\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(plan.unitAmount, plan.currency)}\n {formatInterval(plan.recurring)}\n {#if isCurrent && activeSubscription?.currentPeriodEnd}\n <span>\n &bull;\n {activeSubscription.cancelAtPeriodEnd ? 'Cancels on' : 'Renews on'}\n {formatDate(activeSubscription.currentPeriodEnd)}\n </span>\n {/if}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={isSubscribing === plan.id}\n onclick={resumeSubscription}\n >\n {isSubscribing === plan.id ? 'Resuming...' : 'Resume'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => (showCancelDialog = true)}\n >\n Cancel subscription\n </Button>\n {/if}\n {:else if activeSubscription}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => switchPlan(plan.id)}\n >\n {isSubscribing === plan.id ? 'Switching...' : 'Switch'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => subscribe(plan.id)}\n >\n {isSubscribing === plan.id ? 'Subscribing...' : 'Subscribe'}\n </Button>\n {/if}\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Cancel Subscription Dialog -->\n<AlertDialog.Root bind:open={showCancelDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Cancel Subscription</AlertDialog.Title>\n <AlertDialog.Description>\n Your subscription will remain active until the end of the current billing period, then\n cancel automatically.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={() => (showCancelDialog = false)}>\n Keep Subscription\n </AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleCancelSubscription} disabled={isCanceling}>\n {isCanceling ? 'Canceling...' : 'Cancel at Period End'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", s = "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";
3
+ //#endregion
4
+ export { r as a, e as c, i, o as n, n as o, a as r, t as s, s as t };
5
+
6
+ //# sourceMappingURL=_server-BSm1eAiY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_server-BSm1eAiY.js","names":[],"sources":[],"mappings":""}
@@ -1,7 +1,7 @@
1
1
  import { t as e } from "./errors-D3Zy3wCg.js";
2
2
  import { i as t } from "./util-Bk7aQQJR.js";
3
3
  import { n, t as r } from "./logger-CQONztPm.js";
4
- import { getMigrationFile as i, migrationDelay as a, withPocketbase as o } from "./pocketbase-BbFvZ4HI.js";
4
+ import { getMigrationFile as i, migrationDelay as a, withPocketbase as o } from "./pocketbase-BPwW3TWr.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-DZOoJLVj.js.map
176
+ //# sourceMappingURL=collections-DgZjDXef.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"collections-DZOoJLVj.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;CACT,IACE,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAGT,IAAM,IAAU,EAAM,SAAS,YAAY,KAAK;CAChD,OACE,EAAQ,SAAS,gBAAgB,KAAK,EAAQ,SAAS,gBAAgB;AAE3E;AAeA,eAAsB,EACpB,GACA,GACA,IAAiB,GACgB;CACjC,IAAM,IAAQ,EAA0B;CACxC,IAAI;EAEF,OAAO;GAAE,YAAA,MADgB,EAAG,YAAY,OAAO,CAAI;GAC9B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,MAAM,EAAyB,GAAI,EAAK,MAAM,CAAM;GACxE,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EAAiB,EAAK,MAAM,WAAW,CAAO;GAC/D,KAEL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT;AAEA,eAAsB,EACpB,GACA,GACiB;CACjB,IAAI,EAAY,WAAW,GACzB,OAAO,CAAC;CAGV,IAAM,IAAqB,CAAC,GACtB,IAAS,EAAU,CAAO;CA+BhC,OA7BA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAM,KAAc,GAAa;GACpC,EAAO,KAAK,wBAAwB,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAM,EACxB,GACA,GACA,CACF;GACA,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EACpB,EAAW,MACX,WACA,CACF;GACK,KAIL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT"}
1
+ {"version":3,"file":"collections-DgZjDXef.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;CACT,IACE,EAAM,UAAU,MAAM,M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AAOA,eAAsB,EACpB,GACA,GACiB;CACjB,IAAI,EAAM,WAAW,GACnB,OAAO,CAAC;CAGV,IAAM,IAAqB,CAAC,GACtB,IAAS,EAAU,CAAO;CAqBhC,OAnBA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAM,KAAQ,GAAO;GACxB,EAAO,KAAK,wBAAwB,EAAK,KAAK,EAAE;GAChD,IAAM,EAAE,eAAY,MAAM,EAAyB,GAAI,EAAK,MAAM,CAAM;GACxE,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EAAiB,EAAK,MAAM,WAAW,CAAO;GAC/D,KAEL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT;AAEA,eAAsB,EACpB,GACA,GACiB;CACjB,IAAI,EAAY,WAAW,GACzB,OAAO,CAAC;CAGV,IAAM,IAAqB,CAAC,GACtB,IAAS,EAAU,CAAO;CA+BhC,OA7BA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAM,KAAc,GAAa;GACpC,EAAO,KAAK,wBAAwB,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAM,EACxB,GACA,GACA,CACF;GACA,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EACpB,EAAW,MACX,WACA,CACF;GACK,KAIL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT"}
@@ -1,5 +1,5 @@
1
- import e from "node:fs";
2
- import t from "node:path";
1
+ import e from "node:path";
2
+ import t from "node:fs";
3
3
  import { Project as n, QuoteKind as r, SyntaxKind as i } from "ts-morph";
4
4
  //#region src/runtime/config-target.ts
5
5
  var a = [
@@ -15,8 +15,8 @@ var a = [
15
15
  ];
16
16
  function s(n, r) {
17
17
  for (let i of r) {
18
- let r = t.join(n, i);
19
- if (e.existsSync(r)) return r;
18
+ let r = e.join(n, i);
19
+ if (t.existsSync(r)) return r;
20
20
  }
21
21
  return null;
22
22
  }
@@ -87,8 +87,8 @@ function m(e, t, n, r) {
87
87
  kitContainer: () => u(n, "kit", "{}")
88
88
  };
89
89
  }
90
- function h(e, n) {
91
- let r = n?.notFound ?? "Could not find a Svelte or Vite config to modify.", u = n?.failed ?? "Could not modify the Svelte or Vite config.", d = s(e, a), h = null, g = "", _ = null, v = null, y = !1;
90
+ function h(t, n) {
91
+ let r = n?.notFound ?? "Could not find a Svelte or Vite config to modify.", u = n?.failed ?? "Could not modify the Svelte or Vite config.", d = s(t, a), h = null, g = "", _ = null, v = null, y = !1;
92
92
  if (d) {
93
93
  h = c().addSourceFileAtPath(d), g = h.getFullText(), _ = f(h);
94
94
  let e = _?.getArguments()[0];
@@ -98,7 +98,7 @@ function h(e, n) {
98
98
  status: "resolved",
99
99
  target: p(h, d, v, g)
100
100
  };
101
- let b = s(e, o), x = null, S = "", C = null;
101
+ let b = s(t, o), x = null, S = "", C = null;
102
102
  if (b && (x = c().addSourceFileAtPath(b), S = x.getFullText(), C = l(x)), x && b && C) return {
103
103
  status: "resolved",
104
104
  target: m(x, b, C, S)
@@ -126,7 +126,7 @@ function h(e, n) {
126
126
  } : {
127
127
  status: "not-found",
128
128
  message: r,
129
- filePath: d ?? b ?? t.join(e, a[0])
129
+ filePath: d ?? b ?? e.join(t, a[0])
130
130
  };
131
131
  }
132
132
  function g(e) {
@@ -160,4 +160,4 @@ function _(e, t, n) {
160
160
  //#endregion
161
161
  export { s as a, _ as i, d as n, h as o, u as r, g as s, a as t };
162
162
 
163
- //# sourceMappingURL=config-target-Co-ij8p3.js.map
163
+ //# sourceMappingURL=config-target-DOi8kI_f.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config-target-Co-ij8p3.js","names":[],"sources":["../../src/runtime/config-target.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type CallExpression,\n type ObjectLiteralExpression,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../core/types\";\n\nexport const VITE_CONFIG_CANDIDATES = [\n \"vite.config.ts\",\n \"vite.config.js\",\n \"vite.config.mjs\",\n \"vite.config.cjs\",\n];\n\nexport const SVELTE_CONFIG_CANDIDATES = [\n \"svelte.config.ts\",\n \"svelte.config.js\",\n \"svelte.config.mjs\",\n \"svelte.config.cjs\",\n];\n\nexport type ConfigKind = \"svelte-config\" | \"vite-inline\";\n\n/**\n * A resolved place to read/write SvelteKit configuration. Either the default\n * export object of a `svelte.config.*` file, or the inline argument object of\n * the `sveltekit()` call inside a `vite.config.*` file.\n *\n * The only structural difference between the two is where kit-namespaced\n * settings (adapter, alias, experimental) live: under `config.kit` in\n * svelte.config, but flattened onto the `sveltekit()` arg in vite-inline.\n * `kitContainer()` papers over that; everything else (`compilerOptions`,\n * `preprocess`, `extensions`) sits at the root of `configObject` in both.\n */\nexport interface ConfigTarget {\n kind: ConfigKind;\n /** The file to add imports to and save. */\n sourceFile: SourceFile;\n /** Absolute path of the resolved file. */\n filePath: string;\n /** svelte.config default-export object OR the `sveltekit()` arg object. */\n configObject: ObjectLiteralExpression;\n /** Full text captured before any mutation, for change detection. */\n originalText: string;\n /** Object that owns kit-namespaced settings (adapter, alias, experimental). */\n kitContainer(): ObjectLiteralExpression | null;\n}\n\nexport type ResolveResult =\n | { status: \"resolved\"; target: ConfigTarget }\n | { status: \"not-found\"; message: string; filePath: string }\n | { status: \"failed\"; message: string; filePath: string };\n\n/** Result shape returned by every config modifier so call sites can build a File. */\nexport interface ConfigModifyResult {\n filePath: string;\n outcome: ModifyOutcome;\n}\n\n/** First candidate that exists under `root`, or null. */\nexport function probeFirstExisting(\n root: string,\n candidates: string[],\n): string | null {\n for (const rel of candidates) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/**\n * Resolve the config object exported as default — handles both\n * `export default { ... }` and `const config = { ... }; export default config`.\n */\nexport function getDefaultExportObject(\n sourceFile: SourceFile,\n): ObjectLiteralExpression | null {\n const defaultExport = sourceFile.getExportAssignment(\n (ea) => !ea.isExportEquals(),\n );\n const exportedExpr = defaultExport?.getExpression();\n if (exportedExpr?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n return exportedExpr as ObjectLiteralExpression;\n }\n if (exportedExpr?.getKind() === SyntaxKind.Identifier) {\n const ident = exportedExpr.getText();\n const varDecl = sourceFile.getVariableDeclaration(ident);\n const init = varDecl?.getInitializer();\n if (init?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n return init as ObjectLiteralExpression;\n }\n }\n return null;\n}\n\n/**\n * Get the object-literal value of property `name` on `obj`, creating it as an\n * empty object if missing (or replacing a non-object initializer). Returns null\n * if the property can't be coerced to an object literal.\n */\nexport function getOrCreateObjectLiteralProperty(\n obj: ObjectLiteralExpression,\n name: string,\n initializer: string,\n): ObjectLiteralExpression | null {\n const prop = obj.getProperty(name);\n if (!prop) {\n obj.addPropertyAssignment({ name, initializer });\n const added = obj.getProperty(name);\n if (!added || added.getKind() !== SyntaxKind.PropertyAssignment)\n return null;\n const init = (\n added as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ObjectLiteralExpression)\n return null;\n return init as ObjectLiteralExpression;\n }\n\n if (prop.getKind() !== SyntaxKind.PropertyAssignment) return null;\n const init = (prop as import(\"ts-morph\").PropertyAssignment).getInitializer();\n if (!init) return null;\n if (init.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n (prop as import(\"ts-morph\").PropertyAssignment).setInitializer(initializer);\n const init2 = (\n prop as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n return init2 && init2.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (init2 as ObjectLiteralExpression)\n : null;\n }\n\n return init as ObjectLiteralExpression;\n}\n\n/** Ensure `obj[name] === true`. Returns whether a change was made. */\nexport function ensureBooleanTrue(\n obj: ObjectLiteralExpression,\n name: string,\n): boolean {\n const existing = obj.getProperty(name);\n if (!existing) {\n obj.addPropertyAssignment({ name, initializer: \"true\" });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (init?.getText() === \"true\") return false;\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\"true\");\n return true;\n}\n\nfunction findSveltekitCall(sourceFile: SourceFile): CallExpression | null {\n return (\n sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"sveltekit\") ?? null\n );\n}\n\nfunction makeViteTarget(\n sourceFile: SourceFile,\n filePath: string,\n configObject: ObjectLiteralExpression,\n originalText: string,\n): ConfigTarget {\n return {\n kind: \"vite-inline\",\n sourceFile,\n filePath,\n configObject,\n originalText,\n // kit-namespaced settings are flattened onto the sveltekit() arg.\n kitContainer: () => configObject,\n };\n}\n\nfunction makeSvelteTarget(\n sourceFile: SourceFile,\n filePath: string,\n configObject: ObjectLiteralExpression,\n originalText: string,\n): ConfigTarget {\n return {\n kind: \"svelte-config\",\n sourceFile,\n filePath,\n configObject,\n originalText,\n kitContainer: () =>\n getOrCreateObjectLiteralProperty(configObject, \"kit\", \"{}\"),\n };\n}\n\n/**\n * Resolve where SvelteKit config should be read/written, mirroring SvelteKit's\n * own resolution order:\n * 1. `vite.config.*` has a `sveltekit(<object>)` call with an inline arg → use it\n * (svelte.config is ignored by Kit when this exists).\n * 2. else a `svelte.config.*` with a parseable default-export object → use it.\n * 3. else a bare `sveltekit()` in vite.config → create `{}` and use it (the new default).\n */\nexport function resolveConfigTarget(\n root: string,\n hints?: { notFound?: string; failed?: string },\n): ResolveResult {\n const notFound =\n hints?.notFound ?? \"Could not find a Svelte or Vite config to modify.\";\n const failed = hints?.failed ?? \"Could not modify the Svelte or Vite config.\";\n\n // --- Inspect vite.config.* ---\n const vitePath = probeFirstExisting(root, VITE_CONFIG_CANDIDATES);\n let viteSourceFile: SourceFile | null = null;\n let viteOriginal = \"\";\n let sveltekitCall: CallExpression | null = null;\n let viteInlineArg: ObjectLiteralExpression | null = null;\n let viteNonObjectArg = false;\n\n if (vitePath) {\n viteSourceFile = newProject().addSourceFileAtPath(vitePath);\n viteOriginal = viteSourceFile.getFullText();\n sveltekitCall = findSveltekitCall(viteSourceFile);\n const arg = sveltekitCall?.getArguments()[0];\n if (arg) {\n if (arg.getKind() === SyntaxKind.ObjectLiteralExpression) {\n viteInlineArg = arg as ObjectLiteralExpression;\n } else {\n viteNonObjectArg = true;\n }\n }\n }\n\n // Rule 1: vite.config carries an inline object arg → target it.\n if (viteSourceFile && vitePath && viteInlineArg) {\n return {\n status: \"resolved\",\n target: makeViteTarget(\n viteSourceFile,\n vitePath,\n viteInlineArg,\n viteOriginal,\n ),\n };\n }\n\n // --- Inspect svelte.config.* ---\n const sveltePath = probeFirstExisting(root, SVELTE_CONFIG_CANDIDATES);\n let svelteSourceFile: SourceFile | null = null;\n let svelteOriginal = \"\";\n let svelteConfigObj: ObjectLiteralExpression | null = null;\n if (sveltePath) {\n svelteSourceFile = newProject().addSourceFileAtPath(sveltePath);\n svelteOriginal = svelteSourceFile.getFullText();\n svelteConfigObj = getDefaultExportObject(svelteSourceFile);\n }\n\n // Rule 2: svelte.config with a parseable config object → target it.\n if (svelteSourceFile && sveltePath && svelteConfigObj) {\n return {\n status: \"resolved\",\n target: makeSvelteTarget(\n svelteSourceFile,\n sveltePath,\n svelteConfigObj,\n svelteOriginal,\n ),\n };\n }\n\n // Rule 3: bare `sveltekit()` in vite.config → create `{}` arg and target it.\n if (viteSourceFile && vitePath && sveltekitCall) {\n if (viteNonObjectArg) {\n return { status: \"failed\", message: failed, filePath: vitePath };\n }\n const created = sveltekitCall\n .addArgument(\"{}\")\n .asKind(SyntaxKind.ObjectLiteralExpression);\n if (!created) {\n return { status: \"failed\", message: failed, filePath: vitePath };\n }\n return {\n status: \"resolved\",\n target: makeViteTarget(viteSourceFile, vitePath, created, viteOriginal),\n };\n }\n\n // svelte.config exists but its shape is unparseable.\n if (sveltePath && !svelteConfigObj) {\n return { status: \"failed\", message: failed, filePath: sveltePath };\n }\n\n const reportPath =\n vitePath ?? sveltePath ?? path.join(root, VITE_CONFIG_CANDIDATES[0]);\n return { status: \"not-found\", message: notFound, filePath: reportPath };\n}\n\n/** Format, compare against the captured original, and save only if changed. */\nexport function saveTarget(target: ConfigTarget): ModifyOutcome {\n target.sourceFile.formatText();\n const newText = target.sourceFile.getFullText();\n if (newText === target.originalText) {\n return { status: \"success\", changed: false };\n }\n target.sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n\n/**\n * Resolve a config target and run `mutate` against it. Handles the\n * not-found/failed branches and change detection uniformly. `mutate` returns\n * `false` when the config shape can't be safely edited (→ failed).\n */\nexport function modifyConfig(\n root: string,\n hints: { notFound: string; failed: string },\n mutate: (target: ConfigTarget) => boolean,\n): ConfigModifyResult {\n const res = resolveConfigTarget(root, hints);\n if (res.status !== \"resolved\") {\n return {\n filePath: res.filePath,\n outcome: { status: res.status, message: res.message },\n };\n }\n const ok = mutate(res.target);\n if (!ok) {\n return {\n filePath: res.target.filePath,\n outcome: { status: \"failed\", message: hints.failed },\n };\n }\n return { filePath: res.target.filePath, outcome: saveTarget(res.target) };\n}\n"],"mappings":";;;;AAYA,IAAa,IAAyB;CACpC;CACA;CACA;CACA;AACF,GAEa,IAA2B;CACtC;CACA;CACA;CACA;AACF;AAyCA,SAAgB,EACd,GACA,GACe;CACf,KAAK,IAAM,KAAO,GAAY;EAC5B,IAAM,IAAM,EAAK,KAAK,GAAM,CAAG;EAC/B,IAA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ourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type CallExpression,\n type ObjectLiteralExpression,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../core/types\";\n\nexport const VITE_CONFIG_CANDIDATES = [\n \"vite.config.ts\",\n \"vite.config.js\",\n \"vite.config.mjs\",\n \"vite.config.cjs\",\n];\n\nexport const SVELTE_CONFIG_CANDIDATES = [\n \"svelte.config.ts\",\n \"svelte.config.js\",\n \"svelte.config.mjs\",\n \"svelte.config.cjs\",\n];\n\nexport type ConfigKind = \"svelte-config\" | \"vite-inline\";\n\n/**\n * A resolved place to read/write SvelteKit configuration. Either the default\n * export object of a `svelte.config.*` file, or the inline argument object of\n * the `sveltekit()` call inside a `vite.config.*` file.\n *\n * The only structural difference between the two is where kit-namespaced\n * settings (adapter, alias, experimental) live: under `config.kit` in\n * svelte.config, but flattened onto the `sveltekit()` arg in vite-inline.\n * `kitContainer()` papers over that; everything else (`compilerOptions`,\n * `preprocess`, `extensions`) sits at the root of `configObject` in both.\n */\nexport interface ConfigTarget {\n kind: ConfigKind;\n /** The file to add imports to and save. */\n sourceFile: SourceFile;\n /** Absolute path of the resolved file. */\n filePath: string;\n /** svelte.config default-export object OR the `sveltekit()` arg object. */\n configObject: ObjectLiteralExpression;\n /** Full text captured before any mutation, for change detection. */\n originalText: string;\n /** Object that owns kit-namespaced settings (adapter, alias, experimental). */\n kitContainer(): ObjectLiteralExpression | null;\n}\n\nexport type ResolveResult =\n | { status: \"resolved\"; target: ConfigTarget }\n | { status: \"not-found\"; message: string; filePath: string }\n | { status: \"failed\"; message: string; filePath: string };\n\n/** Result shape returned by every config modifier so call sites can build a File. */\nexport interface ConfigModifyResult {\n filePath: string;\n outcome: ModifyOutcome;\n}\n\n/** First candidate that exists under `root`, or null. */\nexport function probeFirstExisting(\n root: string,\n candidates: string[],\n): string | null {\n for (const rel of candidates) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/**\n * Resolve the config object exported as default — handles both\n * `export default { ... }` and `const config = { ... }; export default config`.\n */\nexport function getDefaultExportObject(\n sourceFile: SourceFile,\n): ObjectLiteralExpression | null {\n const defaultExport = sourceFile.getExportAssignment(\n (ea) => !ea.isExportEquals(),\n );\n const exportedExpr = defaultExport?.getExpression();\n if (exportedExpr?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n return exportedExpr as ObjectLiteralExpression;\n }\n if (exportedExpr?.getKind() === SyntaxKind.Identifier) {\n const ident = exportedExpr.getText();\n const varDecl = sourceFile.getVariableDeclaration(ident);\n const init = varDecl?.getInitializer();\n if (init?.getKind() === SyntaxKind.ObjectLiteralExpression) {\n return init as ObjectLiteralExpression;\n }\n }\n return null;\n}\n\n/**\n * Get the object-literal value of property `name` on `obj`, creating it as an\n * empty object if missing (or replacing a non-object initializer). Returns null\n * if the property can't be coerced to an object literal.\n */\nexport function getOrCreateObjectLiteralProperty(\n obj: ObjectLiteralExpression,\n name: string,\n initializer: string,\n): ObjectLiteralExpression | null {\n const prop = obj.getProperty(name);\n if (!prop) {\n obj.addPropertyAssignment({ name, initializer });\n const added = obj.getProperty(name);\n if (!added || added.getKind() !== SyntaxKind.PropertyAssignment)\n return null;\n const init = (\n added as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ObjectLiteralExpression)\n return null;\n return init as ObjectLiteralExpression;\n }\n\n if (prop.getKind() !== SyntaxKind.PropertyAssignment) return null;\n const init = (prop as import(\"ts-morph\").PropertyAssignment).getInitializer();\n if (!init) return null;\n if (init.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n (prop as import(\"ts-morph\").PropertyAssignment).setInitializer(initializer);\n const init2 = (\n prop as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n return init2 && init2.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (init2 as ObjectLiteralExpression)\n : null;\n }\n\n return init as ObjectLiteralExpression;\n}\n\n/** Ensure `obj[name] === true`. Returns whether a change was made. */\nexport function ensureBooleanTrue(\n obj: ObjectLiteralExpression,\n name: string,\n): boolean {\n const existing = obj.getProperty(name);\n if (!existing) {\n obj.addPropertyAssignment({ name, initializer: \"true\" });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (init?.getText() === \"true\") return false;\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\"true\");\n return true;\n}\n\nfunction findSveltekitCall(sourceFile: SourceFile): CallExpression | null {\n return (\n sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"sveltekit\") ?? null\n );\n}\n\nfunction makeViteTarget(\n sourceFile: SourceFile,\n filePath: string,\n configObject: ObjectLiteralExpression,\n originalText: string,\n): ConfigTarget {\n return {\n kind: \"vite-inline\",\n sourceFile,\n filePath,\n configObject,\n originalText,\n // kit-namespaced settings are flattened onto the sveltekit() arg.\n kitContainer: () => configObject,\n };\n}\n\nfunction makeSvelteTarget(\n sourceFile: SourceFile,\n filePath: string,\n configObject: ObjectLiteralExpression,\n originalText: string,\n): ConfigTarget {\n return {\n kind: \"svelte-config\",\n sourceFile,\n filePath,\n configObject,\n originalText,\n kitContainer: () =>\n getOrCreateObjectLiteralProperty(configObject, \"kit\", \"{}\"),\n };\n}\n\n/**\n * Resolve where SvelteKit config should be read/written, mirroring SvelteKit's\n * own resolution order:\n * 1. `vite.config.*` has a `sveltekit(<object>)` call with an inline arg → use it\n * (svelte.config is ignored by Kit when this exists).\n * 2. else a `svelte.config.*` with a parseable default-export object → use it.\n * 3. else a bare `sveltekit()` in vite.config → create `{}` and use it (the new default).\n */\nexport function resolveConfigTarget(\n root: string,\n hints?: { notFound?: string; failed?: string },\n): ResolveResult {\n const notFound =\n hints?.notFound ?? \"Could not find a Svelte or Vite config to modify.\";\n const failed = hints?.failed ?? \"Could not modify the Svelte or Vite config.\";\n\n // --- Inspect vite.config.* ---\n const vitePath = probeFirstExisting(root, VITE_CONFIG_CANDIDATES);\n let viteSourceFile: SourceFile | null = null;\n let viteOriginal = \"\";\n let sveltekitCall: CallExpression | null = null;\n let viteInlineArg: ObjectLiteralExpression | null = null;\n let viteNonObjectArg = false;\n\n if (vitePath) {\n viteSourceFile = newProject().addSourceFileAtPath(vitePath);\n viteOriginal = viteSourceFile.getFullText();\n sveltekitCall = findSveltekitCall(viteSourceFile);\n const arg = sveltekitCall?.getArguments()[0];\n if (arg) {\n if (arg.getKind() === SyntaxKind.ObjectLiteralExpression) {\n viteInlineArg = arg as ObjectLiteralExpression;\n } else {\n viteNonObjectArg = true;\n }\n }\n }\n\n // Rule 1: vite.config carries an inline object arg → target it.\n if (viteSourceFile && vitePath && viteInlineArg) {\n return {\n status: \"resolved\",\n target: makeViteTarget(\n viteSourceFile,\n vitePath,\n viteInlineArg,\n viteOriginal,\n ),\n };\n }\n\n // --- Inspect svelte.config.* ---\n const sveltePath = probeFirstExisting(root, SVELTE_CONFIG_CANDIDATES);\n let svelteSourceFile: SourceFile | null = null;\n let svelteOriginal = \"\";\n let svelteConfigObj: ObjectLiteralExpression | null = null;\n if (sveltePath) {\n svelteSourceFile = newProject().addSourceFileAtPath(sveltePath);\n svelteOriginal = svelteSourceFile.getFullText();\n svelteConfigObj = getDefaultExportObject(svelteSourceFile);\n }\n\n // Rule 2: svelte.config with a parseable config object → target it.\n if (svelteSourceFile && sveltePath && svelteConfigObj) {\n return {\n status: \"resolved\",\n target: makeSvelteTarget(\n svelteSourceFile,\n sveltePath,\n svelteConfigObj,\n svelteOriginal,\n ),\n };\n }\n\n // Rule 3: bare `sveltekit()` in vite.config → create `{}` arg and target it.\n if (viteSourceFile && vitePath && sveltekitCall) {\n if (viteNonObjectArg) {\n return { status: \"failed\", message: failed, filePath: vitePath };\n }\n const created = sveltekitCall\n .addArgument(\"{}\")\n .asKind(SyntaxKind.ObjectLiteralExpression);\n if (!created) {\n return { status: \"failed\", message: failed, filePath: vitePath };\n }\n return {\n status: \"resolved\",\n target: makeViteTarget(viteSourceFile, vitePath, created, viteOriginal),\n };\n }\n\n // svelte.config exists but its shape is unparseable.\n if (sveltePath && !svelteConfigObj) {\n return { status: \"failed\", message: failed, filePath: sveltePath };\n }\n\n const reportPath =\n vitePath ?? sveltePath ?? path.join(root, VITE_CONFIG_CANDIDATES[0]);\n return { status: \"not-found\", message: notFound, filePath: reportPath };\n}\n\n/** Format, compare against the captured original, and save only if changed. */\nexport function saveTarget(target: ConfigTarget): ModifyOutcome {\n target.sourceFile.formatText();\n const newText = target.sourceFile.getFullText();\n if (newText === target.originalText) {\n return { status: \"success\", changed: false };\n }\n target.sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n\n/**\n * Resolve a config target and run `mutate` against it. Handles the\n * not-found/failed branches and change detection uniformly. `mutate` returns\n * `false` when the config shape can't be safely edited (→ failed).\n */\nexport function modifyConfig(\n root: string,\n hints: { notFound: string; failed: string },\n mutate: (target: ConfigTarget) => boolean,\n): ConfigModifyResult {\n const res = resolveConfigTarget(root, hints);\n if (res.status !== \"resolved\") {\n return {\n filePath: res.filePath,\n outcome: { status: res.status, message: res.message },\n };\n }\n const ok = mutate(res.target);\n if (!ok) {\n return {\n filePath: res.target.filePath,\n outcome: { status: \"failed\", message: hints.failed },\n };\n }\n return { filePath: res.target.filePath, outcome: saveTarget(res.target) };\n}\n"],"mappings":";;;;AAYA,IAAa,IAAyB;CACpC;CACA;CACA;CACA;AACF,GAEa,IAA2B;CACtC;CACA;CACA;CACA;AACF;AAyCA,SAAgB,EACd,GACA,GACe;CACf,KAAK,IAAM,KAAO,GAAY;EAC5B,IAAM,IAAM,EAAK,KAAK,GAAM,CAAG;EAC/B,IAAI,EAAG,WAAW,CAAG,GAAG,OAAO;CACjC;C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import { a as n, o as r, r as i } from "./ts-morph-helpers-Bk82Z2n7.js";
4
- import a from "node:fs";
5
- import o from "node:path";
4
+ import a from "node:path";
5
+ import o from "node:fs";
6
6
  import { Project as s, QuoteKind as c, SyntaxKind as l } from "ts-morph";
7
7
  //#region src/patterns/disable/content-negotiation/modifies/hooks.server.ts
8
8
  function u(e) {
@@ -22,11 +22,11 @@ function d(e) {
22
22
  n && (t.getNamedImports().length === 1 && !t.getDefaultImport() ? t.remove() : n.remove());
23
23
  }
24
24
  function f(e) {
25
- if (!a.existsSync(e)) return {
25
+ if (!o.existsSync(e)) return {
26
26
  status: "success",
27
27
  changed: !1
28
28
  };
29
- let t = a.readFileSync(e, "utf8");
29
+ let t = o.readFileSync(e, "utf8");
30
30
  if (!t.includes("handleNegotiate")) return {
31
31
  status: "success",
32
32
  changed: !1
@@ -69,11 +69,11 @@ function m(e) {
69
69
  return e.getStatements().every((e) => e.getKind() === l.EmptyStatement);
70
70
  }
71
71
  function h(e) {
72
- if (!a.existsSync(e)) return {
72
+ if (!o.existsSync(e)) return {
73
73
  status: "success",
74
74
  changed: !1
75
75
  };
76
- let t = a.readFileSync(e, "utf8");
76
+ let t = o.readFileSync(e, "utf8");
77
77
  if (!t.includes("negotiateReroute")) return {
78
78
  status: "success",
79
79
  changed: !1
@@ -81,8 +81,8 @@ function h(e) {
81
81
  let n = new s({
82
82
  compilerOptions: { allowJs: !0 },
83
83
  manipulationSettings: { quoteKind: c.Single }
84
- }).addSourceFileAtPath(e), r = n.getVariableDeclaration("reroute"), i = (r?.getInitializer())?.getText() ?? "", o = n.getVariableDeclarations().some((e) => e.getName() === "rerouteDeLocalize");
85
- return r && o && i.includes("rerouteDeLocalize") && i.includes("negotiateReroute") ? r.setInitializer("({ url }) => rerouteDeLocalize(url.pathname)") : r && i.includes("negotiateReroute") && r.getFirstAncestorByKind(l.VariableStatement)?.remove(), p(n), m(n) ? (a.rmSync(e, { force: !0 }), {
84
+ }).addSourceFileAtPath(e), r = n.getVariableDeclaration("reroute"), i = (r?.getInitializer())?.getText() ?? "", a = n.getVariableDeclarations().some((e) => e.getName() === "rerouteDeLocalize");
85
+ return r && a && i.includes("rerouteDeLocalize") && i.includes("negotiateReroute") ? r.setInitializer("({ url }) => rerouteDeLocalize(url.pathname)") : r && i.includes("negotiateReroute") && r.getFirstAncestorByKind(l.VariableStatement)?.remove(), p(n), m(n) ? (o.rmSync(e, { force: !0 }), {
86
86
  status: "success",
87
87
  changed: !0
88
88
  }) : (n.formatText(), n.saveSync(), {
@@ -93,17 +93,17 @@ function h(e) {
93
93
  //#endregion
94
94
  //#region src/patterns/disable/content-negotiation/modifies/root-layout.svelte.ts
95
95
  function g(e) {
96
- if (!a.existsSync(e)) return {
96
+ if (!o.existsSync(e)) return {
97
97
  status: "success",
98
98
  changed: !1
99
99
  };
100
- let t = r.fromPath(e), o = t.hasElement("Negotiate");
100
+ let t = r.fromPath(e), a = t.hasElement("Negotiate");
101
101
  return t.modifyScript((e) => {
102
102
  let { source: t } = n(e, (e) => {
103
103
  i(e, "$lib/negotiate");
104
104
  });
105
105
  return t;
106
- }), o && t.removeElement("Negotiate"), t.writeTo(e), {
106
+ }), a && t.removeElement("Negotiate"), t.writeTo(e), {
107
107
  status: "success",
108
108
  changed: t.hasChanged()
109
109
  };
@@ -111,16 +111,16 @@ function g(e) {
111
111
  //#endregion
112
112
  //#region src/patterns/disable/content-negotiation/generate.runtime.ts
113
113
  async function _(n) {
114
- let r = e(n), i = [], a = (e) => {
114
+ let r = e(n), i = [], o = (e) => {
115
115
  e && i.push(e);
116
116
  };
117
117
  r.info("Reverting hooks.server.ts");
118
- let s = o.join(n.root, "src", "hooks.server.ts");
119
- a(t(s, f(s))), r.info("Reverting hooks.ts");
120
- let c = o.join(n.root, "src", "hooks.ts");
121
- a(t(c, h(c))), r.info("Reverting src/routes/+layout.svelte");
122
- let l = o.join(n.root, "src", "routes", "+layout.svelte");
123
- return a(t(l, g(l))), {
118
+ let s = a.join(n.root, "src", "hooks.server.ts");
119
+ o(t(s, f(s))), r.info("Reverting hooks.ts");
120
+ let c = a.join(n.root, "src", "hooks.ts");
121
+ o(t(c, h(c))), r.info("Reverting src/routes/+layout.svelte");
122
+ let l = a.join(n.root, "src", "routes", "+layout.svelte");
123
+ return o(t(l, g(l))), {
124
124
  creates: [],
125
125
  modifies: i,
126
126
  deletes: [],
@@ -134,4 +134,4 @@ async function _(n) {
134
134
  //#endregion
135
135
  export { _ as generate };
136
136
 
137
- //# sourceMappingURL=generate.runtime-6qpoLA04.js.map
137
+ //# sourceMappingURL=generate.runtime--0bYEUP_.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-6qpoLA04.js","names":[],"sources":["../../src/patterns/disable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/disable/content-negotiation/modifies/hooks.ts","../../src/patterns/disable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/disable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction removeSequenceImportIfUnused(sourceFile: SourceFile): void {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"@sveltejs/kit/hooks\");\n if (!decl) return;\n\n const stillReferenced = sourceFile\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => {\n if (id.getText() !== \"sequence\") return false;\n const parent = id.getParent();\n const kind = parent?.getKind();\n return (\n kind !== SyntaxKind.ImportSpecifier && kind !== SyntaxKind.ImportClause\n );\n });\n\n if (stillReferenced) return;\n\n const named = decl\n .getNamedImports()\n .find((ni) => ni.getName() === \"sequence\");\n if (!named) return;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n}\n\nexport function unmodifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (!original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const handleDecl = sourceFile.getVariableDeclaration(\"handle\");\n if (!handleDecl) {\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n }\n\n const init = handleDecl.getInitializer();\n if (init?.getKind() === SyntaxKind.CallExpression) {\n const call = init.asKindOrThrow(SyntaxKind.CallExpression);\n if (call.getExpression().getText() === \"sequence\") {\n const args = call.getArguments();\n const idx = args.findIndex((arg) => arg.getText() === \"handleNegotiate\");\n if (idx >= 0) {\n if (args.length === 2) {\n const keepText = args[idx === 0 ? 1 : 0].getText();\n handleDecl.setInitializer(keepText);\n } else {\n call.removeArgument(idx);\n }\n }\n }\n }\n\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction isMeaningfullyEmpty(sourceFile: SourceFile): boolean {\n return sourceFile\n .getStatements()\n .every((s) => s.getKind() === SyntaxKind.EmptyStatement);\n}\n\nexport function unmodifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (!original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n const init = rerouteDecl?.getInitializer();\n const initText = init?.getText() ?? \"\";\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n\n if (\n rerouteDecl &&\n hasI18nHelper &&\n initText.includes(\"rerouteDeLocalize\") &&\n initText.includes(\"negotiateReroute\")\n ) {\n rerouteDecl.setInitializer(\"({ url }) => rerouteDeLocalize(url.pathname)\");\n } else if (rerouteDecl && initText.includes(\"negotiateReroute\")) {\n const stmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n stmt?.remove();\n }\n\n removeNegotiateImport(sourceFile);\n\n if (isMeaningfullyEmpty(sourceFile)) {\n fs.rmSync(hooksPath, { force: true });\n return { status: \"success\", changed: true };\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyRootLayoutNegotiate(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n const hasElement = file.hasElement(\"Negotiate\");\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(sf, \"$lib/negotiate\");\n });\n return out;\n });\n\n if (hasElement) {\n file.removeElement(\"Negotiate\");\n }\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\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 { unmodifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { unmodifyHooksNegotiate } from \"./modifies/hooks\";\nimport { unmodifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\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 hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Reverting hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, unmodifyHooksNegotiate(hooksPath)));\n\n logger.info(\"Reverting src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n unmodifyRootLayoutNegotiate(rootLayoutPath),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;AAIA,SAAS,EAAsB,GAAiC;CAC9D,IAAM,IAAO,EACV,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,gBAAgB;CAC/D,IAAI,CAAC,GAAM,OAAO;CAElB,IAAM,IAAQ,EAAK,gBAAgB,CAAC,CAAC,MAAM,MAEvC,EAAG,QAAQ,MAAM,YACjB,EAAG,aAAa,CAAC,EAAE,QAAQ,MAAM,iBAEpC;CASD,OAPK,KAED,EAAK,gBAAgB,CAAC,CAAC,WAAW,KAAK,CAAC,EAAK,iBAAiB,IAChE,EAAK,OAAO,IAEZ,EAAM,OAAO,GAER,MAPY;AAQrB;AAEA,SAAS,EAA6B,GAA8B;CAClE,IAAM,IAAO,EACV,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,qBAAqB;CAcpE,IAbI,CAAC,KAEmB,EACrB,qBAAqB,EAAW,UAAU,CAAC,CAC3C,MAAM,MAAO;EACZ,IAAI,EAAG,QAAQ,MAAM,YAAY,OAAO;EAExC,IAAM,IADS,EAAG,UACL,CAAA,EAAQ,QAAQ;EAC7B,OACE,MAAS,EAAW,mBAAmB,MAAS,EAAW;CAE/D,CAEE,GAAiB;CAErB,IAAM,IAAQ,EACX,gBAAgB,CAAC,CACjB,MAAM,MAAO,EAAG,QAAQ,MAAM,UAAU;CACtC,MAED,EAAK,gBAAgB,CAAC,CAAC,WAAW,KAAK,CAAC,EAAK,iBAAiB,IAChE,EAAK,OAAO,IAEZ,EAAM,OAAO;AAEjB;AAEA,SAAgB,EACd,GACe;CACf,IAAI,CAAC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pB;AACF"}
1
+ {"version":3,"file":"generate.runtime--0bYEUP_.js","names":[],"sources":["../../src/patterns/disable/content-negotiation/modifies/hooks.server.ts","../../src/patterns/disable/content-negotiation/modifies/hooks.ts","../../src/patterns/disable/content-negotiation/modifies/root-layout.svelte.ts","../../src/patterns/disable/content-negotiation/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"handle\" &&\n ni.getAliasNode()?.getText() === \"handleNegotiate\"\n );\n });\n\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction removeSequenceImportIfUnused(sourceFile: SourceFile): void {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"@sveltejs/kit/hooks\");\n if (!decl) return;\n\n const stillReferenced = sourceFile\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => {\n if (id.getText() !== \"sequence\") return false;\n const parent = id.getParent();\n const kind = parent?.getKind();\n return (\n kind !== SyntaxKind.ImportSpecifier && kind !== SyntaxKind.ImportClause\n );\n });\n\n if (stillReferenced) return;\n\n const named = decl\n .getNamedImports()\n .find((ni) => ni.getName() === \"sequence\");\n if (!named) return;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n}\n\nexport function unmodifyHooksServerNegotiate(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (!original.includes(\"handleNegotiate\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const handleDecl = sourceFile.getVariableDeclaration(\"handle\");\n if (!handleDecl) {\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n }\n\n const init = handleDecl.getInitializer();\n if (init?.getKind() === SyntaxKind.CallExpression) {\n const call = init.asKindOrThrow(SyntaxKind.CallExpression);\n if (call.getExpression().getText() === \"sequence\") {\n const args = call.getArguments();\n const idx = args.findIndex((arg) => arg.getText() === \"handleNegotiate\");\n if (idx >= 0) {\n if (args.length === 2) {\n const keepText = args[idx === 0 ? 1 : 0].getText();\n handleDecl.setInitializer(keepText);\n } else {\n call.removeArgument(idx);\n }\n }\n }\n }\n\n removeNegotiateImport(sourceFile);\n removeSequenceImportIfUnused(sourceFile);\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction removeNegotiateImport(sourceFile: SourceFile): boolean {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === \"$lib/negotiate\");\n if (!decl) return false;\n\n const named = decl.getNamedImports().find((ni) => {\n return (\n ni.getName() === \"reroute\" &&\n ni.getAliasNode()?.getText() === \"negotiateReroute\"\n );\n });\n if (!named) return false;\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n }\n return true;\n}\n\nfunction isMeaningfullyEmpty(sourceFile: SourceFile): boolean {\n return sourceFile\n .getStatements()\n .every((s) => s.getKind() === SyntaxKind.EmptyStatement);\n}\n\nexport function unmodifyHooksNegotiate(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (!original.includes(\"negotiateReroute\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n const init = rerouteDecl?.getInitializer();\n const initText = init?.getText() ?? \"\";\n\n const hasI18nHelper = sourceFile\n .getVariableDeclarations()\n .some((d) => d.getName() === \"rerouteDeLocalize\");\n\n if (\n rerouteDecl &&\n hasI18nHelper &&\n initText.includes(\"rerouteDeLocalize\") &&\n initText.includes(\"negotiateReroute\")\n ) {\n rerouteDecl.setInitializer(\"({ url }) => rerouteDeLocalize(url.pathname)\");\n } else if (rerouteDecl && initText.includes(\"negotiateReroute\")) {\n const stmt = rerouteDecl.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n stmt?.remove();\n }\n\n removeNegotiateImport(sourceFile);\n\n if (isMeaningfullyEmpty(sourceFile)) {\n fs.rmSync(hooksPath, { force: true });\n return { status: \"success\", changed: true };\n }\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyRootLayoutNegotiate(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n const hasElement = file.hasElement(\"Negotiate\");\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(sf, \"$lib/negotiate\");\n });\n return out;\n });\n\n if (hasElement) {\n file.removeElement(\"Negotiate\");\n }\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\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 { unmodifyHooksServerNegotiate } from \"./modifies/hooks.server\";\nimport { unmodifyHooksNegotiate } from \"./modifies/hooks\";\nimport { unmodifyRootLayoutNegotiate } from \"./modifies/root-layout.svelte\";\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 hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerNegotiate(hooksServerPath),\n ),\n );\n\n logger.info(\"Reverting hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n pushResult(modifyOutcomeToFile(hooksPath, unmodifyHooksNegotiate(hooksPath)));\n\n logger.info(\"Reverting src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n unmodifyRootLayoutNegotiate(rootLayoutPath),\n ),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;AAIA,SAAS,EAAsB,GAAiC;CAC9D,IAAM,IAAO,EACV,sBAAsB,CAAC,CACvB,MAAM,MAAM,EAAE,wBAAwB,MAAM,gBAAgB;CAC/D,IAAI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,GAAI,gBAAgB;EACpD,CAAC;EACD,OAAO;CACT,CAAC,GAEG,KACF,EAAK,cAAc,WAAW,GAGhC,EAAK,QAAQ,CAAU,GAChB;EAAE,QAAQ;EAAW,SAAS,EAAK,WAAW;CAAE;AACzD;;;ACrBA,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,CAAO,GAC1B,IAAmB,CAAC,GACpB,KAAc,MAAsB;EACxC,AAAI,KAAM,EAAS,KAAK,CAAI;CAC9B;CAEA,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,iBAAiB;CAQxE,AAPA,EACE,EACE,GACA,EAA6B,CAAe,CAC9C,CACF,GAEA,EAAO,KAAK,oBAAoB;CAChC,IAAM,IAAY,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU;CAG3D,AAFA,EAAW,EAAoB,GAAW,EAAuB,CAAS,CAAC,CAAC,GAE5E,EAAO,KAAK,qCAAqC;CACjD,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,gBACF;CAQA,OAPA,EACE,EACE,GACA,EAA4B,CAAc,CAC5C,CACF,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,29 +1,29 @@
1
1
  import { n as e } from "./logger-CQONztPm.js";
2
- import { t } from "./shared-C4-NNykV.js";
2
+ import { t } from "./shared-BGvy1V-z.js";
3
3
  import { modifyOutcomeToFile as n } from "./modify-file-PVKmDJHk.js";
4
4
  import { i as r, o as i } from "./ts-morph-helpers-Bk82Z2n7.js";
5
5
  import { n as a } from "./env-BPfk1VAw.js";
6
- import o from "node:fs";
7
- import s from "node:path";
6
+ import o from "node:path";
7
+ import s from "node:fs";
8
8
  import { Project as c, QuoteKind as l, SyntaxKind as u } from "ts-morph";
9
9
  //#region src/patterns/disable/payments/modifies/modify-nav-user.ts
10
10
  function d(e) {
11
- if (!o.existsSync(e)) return {
11
+ if (!s.existsSync(e)) return {
12
12
  status: "success",
13
13
  changed: !1
14
14
  };
15
- let t = o.readFileSync(e, "utf8");
15
+ let t = s.readFileSync(e, "utf8");
16
16
  if (!t.includes("/billing")) return {
17
17
  status: "success",
18
18
  changed: !1
19
19
  };
20
- let n = new i(t), a = !1, s = (e) => {
20
+ let n = new i(t), a = !1, o = (e) => {
21
21
  a || e((e) => {
22
22
  let t = r(e, "Billing", "@lucide/svelte/icons/credit-card");
23
23
  return t.wasRemoved && (a = !0), t.source;
24
24
  });
25
25
  };
26
- return s((e) => n.modifyModuleScript(e)), a || s((e) => n.modifyScript(e)), a ? (o.writeFileSync(e, n.toString(), "utf8"), {
26
+ return o((e) => n.modifyModuleScript(e)), a || o((e) => n.modifyScript(e)), a ? (s.writeFileSync(e, n.toString(), "utf8"), {
27
27
  status: "success",
28
28
  changed: !0
29
29
  }) : {
@@ -34,11 +34,11 @@ function d(e) {
34
34
  //#endregion
35
35
  //#region src/patterns/disable/payments/modifies/modify-user-signup.ts
36
36
  function f(e) {
37
- if (!o.existsSync(e)) return {
37
+ if (!s.existsSync(e)) return {
38
38
  status: "success",
39
39
  changed: !1
40
40
  };
41
- let t = o.readFileSync(e, "utf8");
41
+ let t = s.readFileSync(e, "utf8");
42
42
  if (!t.includes("linkStripeCustomer")) return {
43
43
  status: "success",
44
44
  changed: !1
@@ -60,10 +60,10 @@ function f(e) {
60
60
  //#endregion
61
61
  //#region src/patterns/disable/payments/generate.runtime.ts
62
62
  async function p(r) {
63
- let i = r.features.auth, o = e(r), c = [], l = (e) => {
63
+ let i = r.features.auth, s = e(r), c = [], l = (e) => {
64
64
  e && c.push(e);
65
65
  };
66
- o.info("Stripping Stripe credentials from .env");
66
+ s.info("Stripping Stripe credentials from .env");
67
67
  let u = [
68
68
  {
69
69
  type: "comment",
@@ -85,12 +85,12 @@ async function p(r) {
85
85
  type: "var",
86
86
  key: "INTERNAL_JOB_SECRET"
87
87
  }
88
- ], p = s.join(r.root, ".env");
88
+ ], p = o.join(r.root, ".env");
89
89
  if (l(n(p, a(p, u))), i) {
90
- o.info("Reverting nav-user.svelte");
91
- let e = s.join(r.root, "src", "lib", "components", "nav-user.svelte");
92
- l(n(e, d(e))), o.info("Reverting signup +page.server.ts");
93
- let t = s.join(r.root, "src", "routes", "(public)", "(auth)", "signup", "+page.server.ts");
90
+ s.info("Reverting nav-user.svelte");
91
+ let e = o.join(r.root, "src", "lib", "components", "nav-user.svelte");
92
+ l(n(e, d(e))), s.info("Reverting signup +page.server.ts");
93
+ let t = o.join(r.root, "src", "routes", "(public)", "(auth)", "signup", "+page.server.ts");
94
94
  l(n(t, f(t)));
95
95
  }
96
96
  return {
@@ -113,4 +113,4 @@ async function p(r) {
113
113
  //#endregion
114
114
  export { p as generate };
115
115
 
116
- //# sourceMappingURL=generate.runtime-DBG6kEKb.js.map
116
+ //# sourceMappingURL=generate.runtime-677mL0-8.js.map