@velastack/patterns 0.15.2 → 0.15.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/_page-CFeYIl2d.js +5 -0
- package/dist/chunks/_page-CFeYIl2d.js.map +1 -0
- package/dist/chunks/_page-DkCd_o3E.js +5 -0
- package/dist/chunks/{_page-BFUn0CG1.js.map → _page-DkCd_o3E.js.map} +1 -1
- package/dist/chunks/{auth-pages-D8n8gfCL.js → auth-pages-mZeR1WIj.js} +2 -2
- package/dist/chunks/{auth-pages-D8n8gfCL.js.map → auth-pages-mZeR1WIj.js.map} +1 -1
- package/dist/chunks/{currency.server-BkzwY17R.js → currency.server-CHzEhyTx.js} +74 -74
- package/dist/chunks/currency.server-CHzEhyTx.js.map +1 -0
- package/dist/chunks/dispatch-DSkRrJFe.js +5 -0
- package/dist/chunks/{dispatch-BxlKS_5v.js.map → dispatch-DSkRrJFe.js.map} +1 -1
- package/dist/chunks/{generate-DI58vuk1.js → generate-DZ2S8KDR.js} +3 -3
- package/dist/chunks/{generate-DI58vuk1.js.map → generate-DZ2S8KDR.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C3IswX7B.js → generate.runtime-373mTxeo.js} +112 -103
- package/dist/chunks/generate.runtime-373mTxeo.js.map +1 -0
- package/dist/chunks/{generate.runtime-BH6hHygm.js → generate.runtime-BjTZ2Ls-.js} +74 -74
- package/dist/chunks/generate.runtime-BjTZ2Ls-.js.map +1 -0
- package/dist/chunks/{generate.runtime-B1Y2JrGW.js → generate.runtime-Bn17HK_S.js} +96 -94
- package/dist/chunks/generate.runtime-Bn17HK_S.js.map +1 -0
- package/dist/chunks/{generate.runtime-JftBoKYS.js → generate.runtime-DIIeK2w9.js} +2 -2
- package/dist/chunks/{generate.runtime-JftBoKYS.js.map → generate.runtime-DIIeK2w9.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CdZ3GzPS.js → generate.runtime-DVZUNxtv.js} +3 -3
- package/dist/chunks/{generate.runtime-CdZ3GzPS.js.map → generate.runtime-DVZUNxtv.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DdY44Ulv.js → generate.runtime-DXqBku2y.js} +2 -2
- package/dist/chunks/{generate.runtime-DdY44Ulv.js.map → generate.runtime-DXqBku2y.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D7KYlnvb.js → generate.runtime-DgKiFemb.js} +2 -2
- package/dist/chunks/{generate.runtime-D7KYlnvb.js.map → generate.runtime-DgKiFemb.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bs77Oc8P.js → generate.runtime-DmbDEjMA.js} +2 -2
- package/dist/chunks/{generate.runtime-Bs77Oc8P.js.map → generate.runtime-DmbDEjMA.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DlAJQ5Js.js → generate.runtime-VZIxJWlr.js} +69 -61
- package/dist/chunks/generate.runtime-VZIxJWlr.js.map +1 -0
- package/dist/chunks/{generate.runtime-DjEj-n6m.js → generate.runtime-sey-wxXB.js} +2 -2
- package/dist/chunks/{generate.runtime-DjEj-n6m.js.map → generate.runtime-sey-wxXB.js.map} +1 -1
- package/dist/chunks/{unmodify-load-CdWXJ_Ac.js → unmodify-load-DWixBz7y.js} +17 -4
- package/dist/chunks/unmodify-load-DWixBz7y.js.map +1 -0
- package/dist/index.js +1852 -1842
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/_page-BFUn0CG1.js +0 -5
- package/dist/chunks/_page-Bt37d4uo.js +0 -5
- package/dist/chunks/_page-Bt37d4uo.js.map +0 -1
- package/dist/chunks/currency.server-BkzwY17R.js.map +0 -1
- package/dist/chunks/dispatch-BxlKS_5v.js +0 -5
- package/dist/chunks/generate.runtime-B1Y2JrGW.js.map +0 -1
- package/dist/chunks/generate.runtime-BH6hHygm.js.map +0 -1
- package/dist/chunks/generate.runtime-C3IswX7B.js.map +0 -1
- package/dist/chunks/generate.runtime-DlAJQ5Js.js.map +0 -1
- package/dist/chunks/unmodify-load-CdWXJ_Ac.js.map +0 -1
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// src/patterns/enable/payments/providers-app-mode/stripe/src/routes/(app)/billing/+page.server.ts?raw
|
|
2
|
-
var e = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"#lib/stripe.js\";\nimport { getStripeCustomerId } from \"#lib/server/stripe-customer.js\";\n\nexport const load = async ({ locals, depends, parent }) => {\n const { user } = await parent();\n depends(\"app:billing\");\n\n let customer;\n try {\n const customerId = await getStripeCustomerId(locals.admin, user);\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(customerId);\n } catch {\n // The link-stripe-customer run has not finished yet.\n return { paymentMethods: [], user, billingReady: false };\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 return {\n billingReady: true,\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card!.brand,\n last4: pm.card!.last4,\n expMonth: pm.card!.exp_month,\n expYear: pm.card!.exp_year,\n isDefault: pm.id === customer.default_payment_method,\n })),\n user,\n };\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};\n", t = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import * as Card from '#lib/components/ui/card/index.js';\n import { Badge } from '#lib/components/ui/badge/index.js';\n import * as AlertDialog from '#lib/components/ui/alert-dialog/index.js';\n import SetupButton from '#lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate } from '$app/navigation';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $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<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if !data.billingReady}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">Setting up billing</p>\n <p class=\"text-sm\">This takes a moment after signing up. Refresh to check again.</p>\n </div>\n {:else if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n {#if data.billingReady}\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n {/if}\n </Card.Root>\n </div>\n </div>\n</div>\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";
|
|
3
|
-
export { e as n, t };
|
|
4
|
-
|
|
5
|
-
//# sourceMappingURL=_page-Bt37d4uo.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"_page-Bt37d4uo.js","names":["_page_server_default","_page_default"],"sources":[],"mappings":""}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"currency.server-BkzwY17R.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__1_0_","__import_glob__1_1_","__import_glob__1_2_","__import_glob__1_3_","__import_glob__1_4_","__import_glob__1_5_","__import_glob__1_6_","__import_glob__1_7_","__import_glob__1_8_","__import_glob__1_9_","__import_glob__1_10_","__import_glob__1_11_","__import_glob__1_12_","__import_glob__1_13_","__import_glob__1_14_","__import_glob__1_15_","__import_glob__1_16_","__import_glob__1_17_","__import_glob__1_18_","__import_glob__1_19_","__import_glob__1_20_","__import_glob__1_21_","__import_glob__1_22_","__import_glob__2_0_","__import_glob__2_1_","__import_glob__2_2_","__import_glob__2_3_","__import_glob__2_4_","__import_glob__2_5_","__import_glob__2_6_","__import_glob__2_7_","__import_glob__2_8_","__import_glob__2_9_","__import_glob__2_10_","__import_glob__2_11_","__import_glob__2_12_","__import_glob__2_13_","__import_glob__2_14_","__import_glob__2_15_","__import_glob__2_16_","__import_glob__2_17_","InvalidArgumentError","VELASTACK_WHATSAPP","filesFromGlob","resolveProvider","providerCreates","stripe_customer_default","_page_server_default","_page_default","currency_select_default","currency_svelte_default","buy_button_default","shopify_default","confirm_dialog_default","payment_button_default","payment_dialog_default","stripe_constants_default","stripe_payment_form_default","use_payment_intent_svelte_default","use_stripe_svelte_default","stripe_default","stripe_event_default","sync_stripe_catalog_default","_server_default$3","server_test_default$6","_server_default$2","dispatch_default$1","server_test_default$5","succeeded_default$1","server_test_default$4","customer_fields_default","order_button_default","order_test_default","order_default","setup_button_default","setup_dialog_default","link_stripe_customer_default","sync_stripe_customers_default","_layout_server_default","README_default","_server_default$1","server_test_default$3","_server_default","server_test_default$2","dispatch_default","server_test_default$1","succeeded_default","attached_default","server_test_default","PROVIDERS","META","envEditsFor","providerEnvEdits","provider","supplied","COMPONENTS","PACKAGES","createsRaw","providersRaw","providersAppModeRaw","isUnitTest","path","generate","options","current","label","candidate","isAppMode","creates","unitTests","file","components","a","b","currency_server_test_default","currency_server_default"],"sources":["../../src/patterns/enable/payments/generate.ts"],"sourcesContent":["import type {\n Component,\n Options,\n Package,\n Provider,\n Result,\n} from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport {\n providerCreates,\n providerEnvEdits,\n resolveProvider,\n} from \"../../../core/providers\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\nimport { VELASTACK_WHATSAPP } from \"../../../core/constants\";\nimport { filesFromGlob } from \"../../../core/util\";\n\n/**\n * The providers in prompt order. Each one's `env` keys are what the CLI asks\n * for, what `generate.runtime.ts` writes to `.env` (in this order, under a\n * `# <Label> credentials` heading) and declares in `src/env.ts`.\n */\nexport const PROVIDERS: Provider[] = [\n {\n id: \"stripe\",\n label: \"Stripe\",\n env: [\n {\n key: \"STRIPE_SECRET_KEY\",\n label: \"Stripe secret key\",\n placeholder: \"sk_...\",\n secret: true,\n required: true,\n description:\n \"Stripe secret key (`sk_...`) the server calls the Stripe API with.\",\n },\n {\n key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\",\n label: \"Stripe publishable key\",\n placeholder: \"pk_...\",\n public: true,\n required: true,\n description:\n \"Stripe publishable key (`pk_...`) that Stripe.js loads in the browser.\",\n },\n {\n key: \"STRIPE_WEBHOOK_SECRET\",\n label: \"Stripe webhook signing secret\",\n placeholder: \"whsec_...\",\n secret: true,\n required: true,\n description:\n \"Signing secret (`whsec_...`) that `/webhooks/stripe` verifies events with.\",\n },\n ],\n // The webhook route predates the `src/env.ts` declarations, so a project\n // that enabled payments before them is still recognised.\n markers: [\n { env: \"STRIPE_SECRET_KEY\" },\n { path: \"src/routes/webhooks/stripe\" },\n ],\n // Products, prices and customers are synced into PocketBase by workflows.\n requires: { backend: true, workflows: true },\n },\n {\n id: \"shopify\",\n label: \"Shopify\",\n env: [\n {\n key: \"PUBLIC_SHOPIFY_STORE_DOMAIN\",\n label: \"Shopify store domain\",\n placeholder: \"your-store.myshopify.com\",\n public: true,\n required: true,\n description:\n \"The store's `*.myshopify.com` domain the Storefront API is called on.\",\n },\n {\n key: \"PUBLIC_SHOPIFY_STOREFRONT_TOKEN\",\n label: \"Shopify Storefront API public access token\",\n public: true,\n required: true,\n description:\n \"Public Storefront API access token, from the store's Headless channel.\",\n },\n ],\n },\n {\n id: \"whatsapp\",\n label: \"WhatsApp\",\n env: [\n {\n key: \"PUBLIC_WHATSAPP_NUMBER\",\n label: \"WhatsApp number orders are sent to\",\n placeholder: \"+353 1 555 0100\",\n public: true,\n required: true,\n description:\n \"The business's WhatsApp number, with country code, that orders open a chat with.\",\n },\n {\n key: \"PUBLIC_WHATSAPP_ORDER_FORM\",\n label: \"Hosted VelaStack form orders are recorded to\",\n placeholder: \"https://velastack.dev/v1/projects/<project>/forms/order\",\n public: true,\n description:\n \"The hosted VelaStack form each order is recorded to, so it is kept even if the chat is never sent. Empty records nothing.\",\n },\n ],\n },\n];\n\n/** What `resolveProvider` needs; `index.ts` spreads the rest of the metadata. */\nexport const META = { slug: \"enable-payments\", providers: PROVIDERS };\n\n/** The `.env` lines for a provider, under a `# <Label> credentials` heading. */\nexport function envEditsFor(\n provider: Provider,\n supplied: Record<string, string> = {},\n): EnvEdit[] {\n return providerEnvEdits(provider, `${provider.label} credentials`, supplied);\n}\n\n// `select` is the currency select every provider gets.\nconst COMPONENTS: Record<string, Component[]> = {\n stripe: [\"dialog\", \"input\", \"label\", \"select\"],\n shopify: [\"button\", \"select\"],\n whatsapp: [\"button\", \"dialog\", \"input\", \"label\", \"textarea\", \"select\"],\n};\n\nconst PACKAGES: Record<string, Package[]> = {\n stripe: [\"stripe\", \"@stripe/stripe-js\"],\n shopify: [\"@shopify/storefront-api-client\"],\n whatsapp: [VELASTACK_WHATSAPP],\n};\n\n// Shared by every provider: the currency prices show in, and its select.\nconst createsRaw = import.meta.glob<string>(\"./creates/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst providersRaw = import.meta.glob<string>(\"./providers/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst providersAppModeRaw = import.meta.glob<string>(\n \"./providers-app-mode/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\nexport interface GenerateContext {\n /**\n * The project can run unit tests (vitest is installed), so a provider's\n * `*.test.ts` beside its code is written too. Server tests (`server.test.ts`)\n * always are: they run under `vela test:server`, which brings its own runner.\n */\n unitTests?: boolean;\n}\n\nconst isUnitTest = (path: string) =>\n path.endsWith(\".test.ts\") && !path.endsWith(\"server.test.ts\");\n\nexport async function generate(\n options: Options,\n { unitTests = false }: GenerateContext = {},\n) {\n const provider = resolveProvider(META, options);\n\n // A second provider would leave the project with both, and the patterns\n // built on payments could no longer tell which one it uses.\n const current = options.providers?.payments;\n if (current !== undefined && current !== provider.id) {\n const label =\n PROVIDERS.find((candidate) => candidate.id === current)?.label ?? current;\n throw new InvalidArgumentError(\n `This project already uses ${label} payments. To switch to ${provider.label}, ` +\n \"run `vela disable payments` first, then enable payments again.\",\n );\n }\n // Stripe keeps cards and customers for signed-in users; Shopify's checkout\n // owns its customers and WhatsApp has none, so neither has app-mode files.\n const isAppMode = options.features.auth;\n\n const creates = new Map(\n [\n ...Object.values(filesFromGlob(createsRaw, \"./creates/\")),\n ...providerCreates(providersRaw, provider.id),\n ]\n .filter((file) => unitTests || !isUnitTest(file.path))\n .map((file) => [file.path, file]),\n );\n if (isAppMode) {\n for (const file of providerCreates(\n providersAppModeRaw,\n provider.id,\n \"./providers-app-mode/\",\n )) {\n creates.set(file.path, file);\n }\n }\n\n const components = [...(COMPONENTS[provider.id] ?? [])];\n if (isAppMode && provider.id === \"stripe\") components.push(\"alert-dialog\");\n\n return {\n creates: [...creates.values()].sort((a, b) => a.path.localeCompare(b.path)),\n modifies: [],\n deletes: [],\n components,\n packages: PACKAGES[provider.id] ?? [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;A,ww2GAsBa2F,IAAwB;CACnC;EACE,IAAI;EACJ,OAAO;EACP,KAAK;GACH;IACE,KAAK;IACL,OAAO;IACP,aAAa;IACb,QAAQ;IACR,UAAU;IACV,aACE;GACJ;GACA;IACE,KAAK;IACL,OAAO;IACP,aAAa;IACb,QAAQ;IACR,UAAU;IACV,aACE;GACJ;GACA;IACE,KAAK;IACL,OAAO;IACP,aAAa;IACb,QAAQ;IACR,UAAU;IACV,aACE;GACJ;EACF;EAGA,SAAS,CACP,EAAE,KAAK,oBAAoB,GAC3B,EAAE,MAAM,6BAA6B,CACvC;EAEA,UAAU;GAAE,SAAS;GAAM,WAAW;EAAK;CAC7C;CACA;EACE,IAAI;EACJ,OAAO;EACP,KAAK,CACH;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,QAAQ;GACR,UAAU;GACV,aACE;EACJ,GACA;GACE,KAAK;GACL,OAAO;GACP,QAAQ;GACR,UAAU;GACV,aACE;EACJ,CACF;CACF;CACA;EACE,IAAI;EACJ,OAAO;EACP,KAAK,CACH;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,QAAQ;GACR,UAAU;GACV,aACE;EACJ,GACA;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,QAAQ;GACR,aACE;EACJ,CACF;CACF;AACF,GAGaC,IAAO;CAAE,MAAM;CAAmB,WAAWD;AAAU;AAGpE,SAAgBE,EACd,GACA,IAAmC,CAAC,GACzB;CACX,OAAOC,EAAiBC,GAAU,GAAGA,EAAS,MAAM,eAAeC,CAAQ;AAC7E;AAGA,IAAMC,IAA0C;CAC9C,QAAQ;EAAC;EAAU;EAAS;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MY,IACJhB,EAAU,MAAM,MAAciB,EAAU,OAAOF,CAAO,CAAC,EAAE,SAASA;EACpE,MAAM,IAAI/D,EACR,6BAA6BgE,EAAM,0BAA0BZ,EAAS,MAAM,mEAE9E;CACF;CAGA,IAAMc,IAAYJ,EAAQ,SAAS,MAE7BK,IAAU,IAAI,IAClB,CACE,GAAG,OAAO,OAAOjE,EAAcsD,IAAY,YAAY,CAAC,GACxD,GAAGpD,EAAgBqD,IAAcL,EAAS,EAAE,CAC9C,CAAC,CACE,QAAQ,MAASgB,KAAa,CAACT,GAAWU,EAAK,IAAI,CAAC,CAAC,CACrD,KAAK,MAAS,CAACA,EAAK,MAAMA,CAAI,CAAC,CACpC;CACA,IAAIH,GACF,KAAK,IAAMG,KAAQjE,EACjBsD,IACAN,EAAS,IACT,uBACF,GACE,EAAQ,IAAIiB,EAAK,MAAMA,CAAI;CAI/B,IAAMC,IAAa,CAAC,GAAIhB,EAAWF,EAAS,OAAO,CAAC,CAAE;CAGtD,OAFIc,KAAad,EAAS,OAAO,YAAUkB,EAAW,KAAK,cAAc,GAElE;EACL,SAAS,CAAC,GAAGH,EAAQ,OAAO,CAAC,CAAC,CAAC,MAAM,GAAG,MAAMI,EAAE,KAAK,cAAcC,EAAE,IAAI,CAAC;EAC1E,UAAU,CAAC;EACX,SAAS,CAAC;EACV;EACA,UAAUjB,EAASH,EAAS,OAAO,CAAC;EACpC,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// src/patterns/enable/subscriptions/preview-modifies/src/lib/components/app-sidebar.svelte?raw
|
|
2
|
-
var e = "<script lang=\"ts\" module>\n import HomeIcon from '@lucide/svelte/icons/home';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n<\/script>\n\n<script lang=\"ts\">\n import favicon from '#lib/assets/favicon.svg';\n import { site } from '#lib/site.js';\n\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n import * as Sidebar from '#lib/components/ui/sidebar/index.js';\n import type { ComponentProps } from 'svelte';\n\n let {\n user,\n // [!code highlight:1]\n subscription = null,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & {\n user: any;\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <Sidebar.MenuItem>\n <Sidebar.MenuButton size=\"lg\">\n {#snippet child({ props })}\n <a href=\"/dashboard\" {...props}>\n <div\n class=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n >\n <img src={favicon} alt=\"logo\" class=\"size-6\" />\n </div>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{site.name}</span>\n </div>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} {subscription} />\n </Sidebar.Footer>\n</Sidebar.Root>\n", t = "<script lang=\"ts\">\n import { toggleMode, mode } from 'mode-watcher';\n import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\n import Settings2Icon from '@lucide/svelte/icons/settings-2';\n import CreditCardIcon from '@lucide/svelte/icons/credit-card';\n import LogOutIcon from '@lucide/svelte/icons/log-out';\n import MoonIcon from '@lucide/svelte/icons/moon';\n import SunIcon from '@lucide/svelte/icons/sun';\n import UserAvatar from '#lib/components/user-avatar.svelte';\n import { displayName, type UserIdentity } from '#lib/user.js';\n import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';\n import * as Sidebar from '#lib/components/ui/sidebar/index.js';\n\n let data = {\n navUser: [\n {\n title: 'Settings',\n url: '/settings',\n icon: Settings2Icon\n },\n {\n title: 'Billing',\n url: '/billing',\n icon: CreditCardIcon\n }\n ]\n };\n\n let {\n user,\n // [!code highlight:1]\n subscription = null\n }: {\n user: UserIdentity & {\n id: 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 <UserAvatar {user} class=\"size-8 rounded-lg\" fallbackClass=\"rounded-lg\" />\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{displayName(user)}</span>\n <!-- [!code highlight:1] -->\n <span class=\"truncate text-xs text-muted-foreground\">{planLabel}</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 <UserAvatar {user} class=\"size-8 rounded-lg\" fallbackClass=\"rounded-lg\" />\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{displayName(user)}</span>\n <!-- [!code highlight:1] -->\n <span class=\"truncate text-xs\">{planLabel}</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 href={item.url} class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\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 type=\"submit\" class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\">\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", n = "// [!code highlight:33]\nasync function loadActiveSubscription(locals: App.Locals, userId: string) {\n const subscriptions = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\n 'user = {:user} && (status = \"active\" || status = \"trialing\")',\n { user: userId },\n ),\n expand: \"price\",\n sort: \"-created\",\n })\n .catch(() => []);\n\n const sub = subscriptions[0];\n if (!sub) return null;\n\n const price = sub.expand?.price;\n let productName: string | null = null;\n if (price?.product) {\n const product = await locals.admin\n .collection(\"stripe_products\")\n .getOne(price.product)\n .catch(() => null);\n productName = product?.name ?? null;\n }\n\n return {\n id: sub.id,\n status: sub.status as string,\n productName,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n };\n}\n\nexport const load = async ({ locals }) => {\n const user = locals.pb.authStore.record!;\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n // [!code highlight:1]\n const subscription = await loadActiveSubscription(locals, user.id);\n\n // [!code highlight:1]\n return { user, breadcrumbs, subscription };\n};\n", r = "<script lang=\"ts\">\n import * as Sidebar from \"#lib/components/ui/sidebar/index.js\";\n import { Separator } from \"#lib/components/ui/separator/index.js\";\n import AppSidebar from \"#lib/components/app-sidebar.svelte\";\n import * as Breadcrumb from \"#lib/components/ui/breadcrumb/index.js\";\n import { page } from \"$app/state\";\n\n let breadcrumbs = $derived(page.data.breadcrumbs || []) as {\n title: string;\n url: string;\n }[];\n let { data, children } = $props();\n<\/script>\n\n<div class=\"min-h-dvh dashboard\">\n <Sidebar.Provider>\n <!-- [!code highlight:5] -->\n <AppSidebar\n user={data.user}\n \n subscription={data.subscription}\n />\n <Sidebar.Inset>\n <header class=\"flex h-16 shrink-0 items-center gap-2\">\n <div class=\"flex items-center gap-2 px-4\">\n <Sidebar.Trigger class=\"-ml-1\" />\n <Separator\n orientation=\"vertical\"\n class=\"mr-2 data-[orientation=vertical]:h-4\"\n />\n {#if breadcrumbs.length > 0}\n <Breadcrumb.Root>\n <Breadcrumb.List>\n {#if breadcrumbs.length > 1}\n {#each breadcrumbs.slice(0, -1) as breadcrumb}\n <Breadcrumb.Item>\n <Breadcrumb.Link href={breadcrumb.url}\n >{breadcrumb.title}</Breadcrumb.Link\n >\n </Breadcrumb.Item>\n <Breadcrumb.Separator />\n {/each}\n {/if}\n <Breadcrumb.Page>\n {breadcrumbs[breadcrumbs.length - 1].title}\n </Breadcrumb.Page>\n </Breadcrumb.List>\n </Breadcrumb.Root>\n {/if}\n </div>\n </header>\n <div class=\"flex flex-1 flex-col p-4 pt-0\">\n {@render children?.()}\n </div>\n </Sidebar.Inset>\n </Sidebar.Provider>\n</div>\n\n<style>\n :global(body:has(div.dashboard)) {\n background-color: var(--color-sidebar);\n }\n</style>\n", i = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"#lib/stripe.js\";\nimport { getStripeCustomerId } from \"#lib/server/stripe-customer.js\";\n\ntype RecurringInfo = {\n interval: string;\n interval_count: number;\n trial_period_days?: number | null;\n};\n\nfunction parseRecurring(value: unknown): RecurringInfo | null {\n if (!value) return null;\n if (typeof value === \"object\") return value as RecurringInfo;\n try {\n return JSON.parse(value as string) as RecurringInfo;\n } catch {\n return null;\n }\n}\n\nconst ACTIVE_SUBSCRIPTION_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n];\n\nexport const load = async ({ locals, depends, parent }) => {\n const { user } = await parent();\n depends(\"app:billing\");\n\n let customer;\n try {\n const customerId = await getStripeCustomerId(locals.admin, user);\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(customerId);\n } catch {\n // The link-stripe-customer run has not finished yet.\n return {\n paymentMethods: [],\n user,\n billingReady: false,\n hasDefaultPaymentMethod: false,\n activeSubscription: null,\n availablePlans: [],\n };\n }\n\n const stripeCustomer = await stripe.customers.retrieve(customer.id);\n if (stripeCustomer.deleted) {\n return error(400, \"Customer not found\");\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n const subscriptionRecords = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\"user = {:user}\", { user: user.id }),\n expand: \"price\",\n sort: \"-created\",\n });\n\n const recurringPrices = await locals.admin\n .collection(\"stripe_prices\")\n .getFullList({\n filter: locals.admin.filter(\"type = {:type} && active = true\", {\n type: \"recurring\",\n }),\n });\n\n const productIds: string[] = Array.from(\n new Set(\n recurringPrices\n .map((p) => p.product)\n .filter((id): id is string => Boolean(id)),\n ),\n );\n const productMap = new Map<string, string>();\n if (productIds.length > 0) {\n const products = await locals.admin\n .collection(\"stripe_products\")\n .getFullList({\n filter: productIds.map((id) => `id = \"${id}\"`).join(\" || \"),\n });\n for (const product of products) {\n productMap.set(product.id, product.name ?? product.id);\n }\n }\n\n const availablePlans = recurringPrices.map((price) => ({\n id: price.id,\n productName:\n (price.product && productMap.get(price.product)) ?? price.product ?? \"\",\n unitAmount: (price.unit_amount ?? 0) as number,\n currency: (price.currency ?? \"\") as string,\n recurring: parseRecurring(price.recurring),\n }));\n\n const subscriptions = subscriptionRecords.map((sub) => {\n const expanded = sub.expand?.price;\n return {\n id: sub.id,\n status: sub.status as string,\n currentPeriodStart: (sub.current_period_start as string | null) ?? null,\n currentPeriodEnd: (sub.current_period_end as string | null) ?? null,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n canceledAt: (sub.canceled_at as string | null) || null,\n priceId: sub.price as string,\n productName: expanded\n ? ((expanded.product && productMap.get(expanded.product)) ??\n expanded.product ??\n null)\n : null,\n unitAmount: expanded ? ((expanded.unit_amount ?? null) as number | null) : null,\n currency: expanded ? ((expanded.currency ?? null) as string | null) : null,\n recurring: expanded ? parseRecurring(expanded.recurring) : null,\n };\n });\n\n const activeSubscription =\n subscriptions.find((s) => ACTIVE_SUBSCRIPTION_STATUSES.includes(s.status)) ||\n null;\n\n // If the active plan isn't in the list (e.g., price was deactivated), include\n // it so it can still be shown as the current plan.\n if (\n activeSubscription &&\n !availablePlans.some((p) => p.id === activeSubscription.priceId)\n ) {\n availablePlans.push({\n id: activeSubscription.priceId,\n productName: activeSubscription.productName ?? \"\",\n unitAmount: activeSubscription.unitAmount ?? 0,\n currency: activeSubscription.currency ?? \"\",\n recurring: activeSubscription.recurring,\n });\n }\n\n availablePlans.sort((a, b) => a.unitAmount - b.unitAmount);\n\n return {\n billingReady: true,\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card!.brand,\n last4: pm.card!.last4,\n expMonth: pm.card!.exp_month,\n expYear: pm.card!.exp_year,\n isDefault: pm.id === customer.default_payment_method,\n })),\n user,\n hasDefaultPaymentMethod: Boolean(customer.default_payment_method),\n activeSubscription,\n availablePlans,\n };\n};\n\nasync function getUserCustomer(locals: App.Locals) {\n const user = locals.pb.authStore.record;\n if (!user) {\n return error(401, \"Unauthorized\");\n }\n let customerId: string;\n try {\n customerId = await getStripeCustomerId(locals.admin, user);\n } catch {\n return error(503, \"Billing is still being set up. Try again shortly.\");\n }\n return locals.admin.collection(\"stripe_customers\").getOne(customerId);\n}\n\n// A subscription can be updated in-place unless it has fully terminated.\nconst UPDATABLE_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n \"paused\",\n];\n\nasync function findUpdatableSubscription(\n locals: App.Locals,\n userId: string,\n) {\n const filterClause = UPDATABLE_STATUSES.map(\n (s) => `status = \"${s}\"`,\n ).join(\" || \");\n const subs = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(`user = {:user} && (${filterClause})`, {\n user: userId,\n }),\n sort: \"-created\",\n });\n return subs[0] ?? null;\n}\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n selectPlan: async ({ locals, request }) => {\n const formData = await request.formData();\n const priceId = formData.get(\"priceId\") as string;\n if (!priceId) return error(400, \"Price ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // If an updatable subscription already exists, change its price in place\n // rather than creating a duplicate. Covers switch, resume-to-different-plan,\n // and races where the webhook hasn't delivered the existing sub yet.\n const existing = await findUpdatableSubscription(locals, userId);\n if (existing) {\n const stripeSub = await stripe.subscriptions.retrieve(existing.id);\n const item = stripeSub.items.data[0];\n if (!item) return error(500, \"Subscription has no items\");\n\n await stripe.subscriptions.update(existing.id, {\n items: [{ id: item.id, price: priceId }],\n proration_behavior: \"create_prorations\",\n cancel_at_period_end: false,\n });\n return;\n }\n\n const customer = await getUserCustomer(locals);\n if (!customer.default_payment_method) {\n return error(400, \"Add a default payment method before subscribing\");\n }\n\n await stripe.subscriptions.create({\n customer: customer.id,\n items: [{ price: priceId }],\n default_payment_method: customer.default_payment_method,\n payment_behavior: \"error_if_incomplete\",\n off_session: true,\n });\n },\n cancelSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // Verify the subscription belongs to this user before touching Stripe.\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: true,\n });\n },\n resumeSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n },\n};\n", a = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import * as Card from '#lib/components/ui/card/index.js';\n import { Badge } from '#lib/components/ui/badge/index.js';\n import * as AlertDialog from '#lib/components/ui/alert-dialog/index.js';\n import SetupButton from '#lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check, Package } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate, refreshAll } from '$app/navigation';\n import { untrack } from 'svelte';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let availablePlans = $derived(data.availablePlans);\n let hasDefaultPaymentMethod = $derived(data.hasDefaultPaymentMethod);\n\n // Local, mutable mirror of the server-side subscription. We optimistically\n // update it on user actions so the UI reflects the change immediately; the\n // $effect re-syncs from the server after the webhook has had a chance to\n // fire (refreshAll runs on a short delay below).\n let activeSubscription = $state(untrack(() => data.activeSubscription));\n $effect(() => {\n activeSubscription = data.activeSubscription;\n });\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n let showCancelDialog = $state(false);\n let isSubscribing = $state<string | null>(null);\n let isCanceling = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n\n function formatAmount(amount: number | null, currency: string | null) {\n if (amount === null || !currency) return '—';\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: currency.toUpperCase()\n }).format(amount / 100);\n }\n\n function formatInterval(recurring: { interval: string; interval_count: number } | null) {\n if (!recurring) return '';\n if (recurring.interval_count === 1) return `/ ${recurring.interval}`;\n return `every ${recurring.interval_count} ${recurring.interval}s`;\n }\n\n function formatDate(iso: string | null) {\n if (!iso) return '—';\n return new Date(iso).toLocaleDateString(undefined, {\n year: 'numeric',\n month: 'short',\n day: 'numeric'\n });\n }\n\n async function selectPlan(priceId: string, successMessage: string) {\n if (!hasDefaultPaymentMethod) {\n toast.error('Add a default payment method first');\n return;\n }\n const previous = activeSubscription;\n const plan = availablePlans.find((p) => p.id === priceId);\n if (plan) {\n activeSubscription = previous\n ? {\n ...previous,\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false\n }\n : {\n id: 'pending',\n status: 'active',\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false,\n currentPeriodStart: null,\n currentPeriodEnd: null,\n canceledAt: null\n };\n }\n\n isSubscribing = priceId;\n try {\n const formData = new FormData();\n formData.append('priceId', priceId);\n\n const res = await fetch('?/selectPlan', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`selectPlan failed: ${res.status}`);\n }\n\n toast.success(successMessage);\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error selecting plan:', err);\n toast.error('Failed to update plan');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function subscribe(priceId: string) {\n await selectPlan(priceId, 'Subscription started');\n }\n\n async function switchPlan(priceId: string) {\n await selectPlan(priceId, 'Subscription updated');\n }\n\n async function resumeSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isSubscribing = activeSubscription.priceId;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: false };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/resumeSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Resume failed: ${res.status}`);\n }\n\n toast.success('Subscription resumed');\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error resuming subscription:', err);\n toast.error('Failed to resume subscription');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function handleCancelSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isCanceling = true;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: true };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/cancelSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Cancel failed: ${res.status}`);\n }\n\n toast.success('Subscription will cancel at period end');\n showCancelDialog = false;\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error canceling subscription:', err);\n toast.error('Failed to cancel subscription');\n activeSubscription = previous;\n } finally {\n isCanceling = false;\n }\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if !data.billingReady}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">Setting up billing</p>\n <p class=\"text-sm\">This takes a moment after signing up. Refresh to check again.</p>\n </div>\n {:else if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n {#if data.billingReady}\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n {/if}\n </Card.Root>\n </div>\n </div>\n\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Plan</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">Manage your subscription.</p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if availablePlans.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <Package class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No plans available</p>\n <p class=\"text-sm\">Check back soon.</p>\n </div>\n {:else}\n {#if !hasDefaultPaymentMethod}\n <p class=\"text-muted-foreground mb-4 rounded-md border border-dashed p-3 text-sm\">\n Add a default payment method above to subscribe.\n </p>\n {/if}\n <div class=\"space-y-4\">\n {#each availablePlans as plan (plan.id)}\n {@const isCurrent = activeSubscription?.priceId === plan.id}\n <div\n class=\"flex items-center justify-between rounded-lg border p-4 transition-colors {isCurrent\n ? 'border-primary ring-primary ring-1'\n : 'border-border hover:bg-accent/50'}\"\n >\n <div class=\"flex items-center gap-4\">\n <div class=\"bg-muted flex size-12 items-center justify-center rounded-lg\">\n <Package class=\"size-5\" />\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">{plan.productName}</p>\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Badge variant=\"outline\">Pending cancellation</Badge>\n {:else if activeSubscription.status === 'trialing'}\n <Badge variant=\"secondary\">Trial</Badge>\n {:else if activeSubscription.status === 'past_due'}\n <Badge variant=\"destructive\">Past due</Badge>\n {:else}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Current\n </Badge>\n {/if}\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(plan.unitAmount, plan.currency)}\n {formatInterval(plan.recurring)}\n {#if isCurrent && activeSubscription?.currentPeriodEnd}\n <span>\n •\n {activeSubscription.cancelAtPeriodEnd ? 'Cancels on' : 'Renews on'}\n {formatDate(activeSubscription.currentPeriodEnd)}\n </span>\n {/if}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={isSubscribing === plan.id}\n onclick={resumeSubscription}\n >\n {isSubscribing === plan.id ? 'Resuming...' : 'Resume'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => (showCancelDialog = true)}\n >\n Cancel subscription\n </Button>\n {/if}\n {:else if activeSubscription}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => switchPlan(plan.id)}\n >\n {isSubscribing === plan.id ? 'Switching...' : 'Switch'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => subscribe(plan.id)}\n >\n {isSubscribing === plan.id ? 'Subscribing...' : 'Subscribe'}\n </Button>\n {/if}\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Cancel Subscription Dialog -->\n<AlertDialog.Root bind:open={showCancelDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Cancel Subscription</AlertDialog.Title>\n <AlertDialog.Description>\n Your subscription will remain active until the end of the current billing period, then\n cancel automatically.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={() => (showCancelDialog = false)}>\n Keep Subscription\n </AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleCancelSubscription} disabled={isCanceling}>\n {isCanceling ? 'Canceling...' : 'Cancel at Period End'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", o = "import type Stripe from 'stripe';\nimport { handlePaymentIntentSucceeded } from './payment-intent/succeeded';\nimport { handlePaymentMethodAttached } from './payment-method/attached';\nimport { handleSubscriptionCreated } from './subscription/created';\nimport { handleSubscriptionUpdated } from './subscription/updated';\nimport { handleSubscriptionDeleted } from './subscription/deleted';\n\n/**\n * Routes a verified Stripe event to its handler. Runs inside the stripe-event\n * workflow, so a handler that throws is retried with backoff rather than lost.\n */\nexport async function dispatchStripeEvent(event: Stripe.Event, locals: App.Locals) {\n switch (event.type) {\n case 'payment_intent.succeeded':\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n case 'payment_method.attached':\n await handlePaymentMethodAttached(event.data.object, locals);\n break;\n\n case 'customer.subscription.created':\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case 'customer.subscription.updated':\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case 'customer.subscription.deleted':\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n}\n";
|
|
3
|
-
export { n as a, r as i, a as n, t as o, i as r, e as s, o as t };
|
|
4
|
-
|
|
5
|
-
//# sourceMappingURL=dispatch-BxlKS_5v.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-B1Y2JrGW.js","names":["FAILURE_HINT","NOT_FOUND_HINT","FAILURE_HINT","NOT_FOUND_HINT","getLogger","readMigration","createCollectionIdempotent","applyCollectionRulePatches","migrationDelay","getMigrationFile","modifyOutcomeToFile","ensureSiteFile","SvelteFile","withInMemoryScript","formatLikeSource","ensureImports","addNavItemToScript","dedent","TEAM_RULE_PATCHES","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$2","modifyAppLayoutSvelte","layoutPath","file","NEW_HEADER","IMPORT_SNIPPET","LEGACY_NAME","FAILURE_HINT$1","NOT_FOUND_HINT$1","updateAppSidebarScript","out","source","legacyName","sf","decl","init","nameNode","SyntaxKind","pattern","elements","typeNode","intersection","member","lit","propTexts","p","t","elementTexts","insertIdx","modifyAppSidebar","appSidebarPath","modifyLayoutServer","layoutServerPath","snippet","originalSource","sourceFile","Project","addProperty","obj","name","initializer","loadArrow","loadFn","varDecl","directArrow","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","obp","hasDepends","el","hasLocals","parts","tail","currentName","body","blockBody","statements","hasTeam","stmt","id","hasTeams","hasDependsTeam","ce","args","argText","expr","ret","inner","bodyExpr","fnBody","TEAMS_NAV_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","addItemToNavUser","navUserSnippet","wasAdded","tryAdd","run","result","title","url","icon","iconImportPath","fn","modifyNavUser","navUserPath","newNavUserSnippet","pushMigrationCreates","created","migrationFile","collectionName","options","creates","generate","logger","withPocketbase","userCollection","pb","create","spec","teamsResult","teamsCollection","teamMembershipsResult","teamMembershipsCollection","teamUsersResult","teamInvitesResult","teamInviteLinksResult","ruleMigrations","modifies","pushResult","appLayoutPath","siteFile"],"sources":["../../src/patterns/enable/teams/modifies/modify-app-layout.ts","../../src/patterns/enable/teams/modifies/modify-app-sidebar.ts","../../src/patterns/enable/teams/modifies/+layout.server.ts","../../src/patterns/enable/teams/modifies/modify-nav-user.ts","../../src/patterns/enable/teams/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass team props to <AppSidebar> in your app layout:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app layout that renders <AppSidebar> with team props:\",\n \"\",\n \"<AppSidebar team={data.team} teams={data.teams ?? []} />\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"teams\")) {\n return { status: \"success\", changed: false };\n }\n\n file.appendToAttributes(\n \"AppSidebar\",\n \" team={data.team} teams={data.teams ?? []}\",\n );\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NEW_HEADER = `<Sidebar.Header>\n\t\t<Sidebar.Menu>\n\t\t\t<TeamSwitcher {teams}>\n\t\t\t\t{#snippet children()}\n\t\t\t\t\t{@const activeTeam = teams.find((t) => t.id === team)}\n\t\t\t\t\t{#if activeTeam}\n\t\t\t\t\t\t<Avatar.Root class=\"size-8 rounded-lg\">\n\t\t\t\t\t\t\t<Avatar.Fallback class=\"rounded-lg bg-primary text-primary-foreground font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">\n\t\t\t\t\t\t\t\t{activeTeam.name}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{:else}\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclass=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<img src={favicon} alt=\"logo\" class=\"size-6\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class=\"grid flex-1 text-left text-sm leading-tight\">\n\t\t\t\t\t\t\t<span class=\"truncate font-medium\">{site.name}</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t{/if}\n\t\t\t\t\t<ChevronsUpDownIcon class=\"ml-auto\" />\n\t\t\t\t{/snippet}\n\t\t\t</TeamSwitcher>\n\t\t</Sidebar.Menu>\n\t</Sidebar.Header>`;\n\nconst IMPORT_SNIPPET = [\n \"import favicon from '#lib/assets/favicon.svg';\",\n \"import TeamSwitcher from '#lib/components/team-switcher.svelte';\",\n \"import ChevronsUpDownIcon from '@lucide/svelte/icons/chevrons-up-down';\",\n \"import * as Avatar from '#lib/components/ui/avatar/index.js';\",\n \"import { site } from '#lib/site.js';\",\n].join(\"\\n\");\n\n/**\n * A sidebar from before `#lib/site.js` names the app with a `meta` prop. Keep\n * whichever the header already uses, so an older project stays consistent.\n */\nconst LEGACY_NAME = \"{meta.appName}\";\n\nconst FAILURE_HINT = [\n \"Replace the <Sidebar.Header> in your app sidebar with the team switcher.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Props to destructure in $props(): team, teams = []\",\n \"\",\n \"Markup to use as the header:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create an app sidebar with a <Sidebar.Header> containing the team switcher.\",\n \"\",\n \"Imports:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Header markup:\",\n NEW_HEADER,\n].join(\"\\n\");\n\nfunction updateAppSidebarScript(source: string, legacyName: boolean): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n if (!legacyName) {\n ensureImports(sf, [\n { namedImports: [\"site\"], moduleSpecifier: \"#lib/site.js\" },\n ]);\n }\n ensureImports(sf, [\n {\n defaultImport: \"favicon\",\n moduleSpecifier: \"#lib/assets/favicon.svg\",\n },\n {\n defaultImport: \"TeamSwitcher\",\n moduleSpecifier: \"#lib/components/team-switcher.svelte\",\n },\n {\n defaultImport: \"ChevronsUpDownIcon\",\n moduleSpecifier: \"@lucide/svelte/icons/chevrons-up-down\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"#lib/components/ui/avatar/index.js\",\n },\n ]);\n\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n\n if (elements.some((e) => e.getName() === \"team\")) continue;\n\n // Type changes first — name change can shift positions and invalidate type node refs.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^team\\b/.test(t))) break;\n propTexts.push(\n \"team?: string | undefined\",\n \"teams?: { id: string; name: string }[]\",\n );\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Rebuild binding pattern: insert team, teams = [] before first rest/initializer element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elements.length;\n elementTexts.splice(insertIdx, 0, \"team\", \"teams = []\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n }\n formatLikeSource(sf);\n });\n return out;\n}\n\nexport function modifyAppSidebar(appSidebarPath: string): ModifyOutcome {\n if (!fs.existsSync(appSidebarPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(appSidebarPath);\n if (file.hasElement(\"TeamSwitcher\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasElement(\"Sidebar.Header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const legacyName = file.toString().includes(LEGACY_NAME);\n file.modifyScript((source) => updateAppSidebarScript(source, legacyName));\n file.replaceElement(\n \"Sidebar.Header\",\n legacyName ? NEW_HEADER.replace(\"{site.name}\", LEGACY_NAME) : NEW_HEADER,\n );\n file.writeTo(appSidebarPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n const user = locals.pb.authStore.record!;\n const team = locals.team;\n const teams = await locals.pb.collection(\"teams\").getFullList();\n depends(\"app:team\");\n\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n return { user, team, teams, breadcrumbs };\n };\n `;\n\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n const hasProperty = !!obj.getProperty(name);\n if (!hasProperty) {\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n }\n };\n\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n \"const user = locals.pb.authStore.record!;\",\n \"const team = locals.team;\",\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n 'depends(\"app:team\");',\n \"\",\n 'const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];',\n \"return { user, team, teams, breadcrumbs };\",\n ],\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasDepends = obp\n .getElements()\n .some((el) => el.getName() === \"depends\");\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n\n if (!hasDepends) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n\n if (hasLocals) {\n first.set({\n name: `{ depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) {\n loadArrow.setIsAsync(true);\n } else if (loadFn && !loadFn.isAsync()) {\n loadFn.setIsAsync(true);\n }\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const hasTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id: import(\"ts-morph\").Identifier) => id.getText() === \"team\"),\n );\n\n const hasTeams = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.VariableStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id: import(\"ts-morph\").Identifier) => id.getText() === \"teams\",\n ),\n );\n\n const hasDependsTeam = statements.some(\n (stmt: import(\"ts-morph\").Statement) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .some((ce: import(\"ts-morph\").CallExpression) => {\n const expr = ce.getExpression();\n if (expr.getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:team'\" || argText === '\"app:team\"')\n );\n }),\n );\n\n if (!hasTeam) {\n blockBody.insertStatements(1, \"const team = locals.team;\");\n }\n\n if (!hasTeams) {\n blockBody.insertStatements(\n 2,\n 'const teams = await locals.pb.collection(\"teams\").getFullList();',\n );\n }\n\n if (!hasDependsTeam) {\n blockBody.insertStatements(3, 'depends(\"app:team\");');\n }\n }\n\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n } else {\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = bodyExpr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) {\n const returns = fnBody.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = expr as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const obj = inner as import(\"ts-morph\").ObjectLiteralExpression;\n addProperty(obj, \"team\", \"team\");\n addProperty(obj, \"teams\", \"teams\");\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst TEAMS_NAV_SNIPPET = [\n \"import UsersIcon from '@lucide/svelte/icons/users';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Teams', url: '/teams', icon: UsersIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Teams nav item to nav-user.svelte:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Teams entry:\",\n \"\",\n TEAMS_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/teams\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Teams\",\n \"/teams\",\n \"UsersIcon\",\n \"@lucide/svelte/icons/users\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n readMigration,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { TEAM_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n // Wait so the next schema op lands in a different PocketBase timestamp second.\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) {\n return;\n }\n creates.push(await readMigration(migrationFile, options));\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating teams collection\");\n const teamsResult = await create({\n name: \"teams\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"name\",\n type: \"text\",\n required: true,\n },\n {\n name: \"owner\",\n type: \"relation\",\n cascadeDelete: false,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n });\n const teamsCollection = teamsResult.collection;\n await pushMigrationCreates(creates, \"teams\", options, teamsResult.created);\n\n logger.info(\"Creating team_memberships collection\");\n const teamMembershipsResult = await create({\n name: \"team_memberships\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"user\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const teamMembershipsCollection = teamMembershipsResult.collection;\n await pushMigrationCreates(\n creates,\n \"team_memberships\",\n options,\n teamMembershipsResult.created,\n );\n\n logger.info(\"Creating team_users view\");\n const teamUsersResult = await create({\n name: \"team_users\",\n type: \"view\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"email\",\n exceptDomains: null,\n onlyDomains: null,\n // Accounts made with a phone number may have no email.\n required: false,\n type: \"email\",\n },\n {\n name: \"name\",\n max: 255,\n required: false,\n type: \"text\",\n },\n {\n name: \"membership_id\",\n cascadeDelete: false,\n collectionId: teamMembershipsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: false,\n type: \"relation\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"role\",\n maxSelect: 1,\n required: true,\n type: \"select\",\n values: [\"owner\", \"admin\", \"member\"],\n },\n ],\n viewQuery:\n \"select users.id, users.email, users.name, team_memberships.id as membership_id, team_memberships.team, team_memberships.role from users join team_memberships on team_memberships.user = users.id;\",\n });\n await pushMigrationCreates(\n creates,\n \"team_users\",\n options,\n teamUsersResult.created,\n );\n\n logger.info(\"Creating team_invites collection\");\n const teamInvitesResult = await create({\n name: \"team_invites\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"team\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"email\",\n type: \"email\",\n required: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invites\",\n options,\n teamInvitesResult.created,\n );\n\n logger.info(\"Creating team_invite_links collection\");\n const teamInviteLinksResult = await create({\n name: \"team_invite_links\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n name: \"team\",\n cascadeDelete: true,\n collectionId: teamsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n indexes: [\n \"CREATE UNIQUE INDEX `idx_9y3Oz1KVzz` ON `team_invite_links` (`team`)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"team_invite_links\",\n options,\n teamInviteLinksResult.created,\n );\n\n logger.info(\"Applying team rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n TEAM_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerPath, modifyLayoutServer(layoutServerPath)),\n );\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayoutSvelte(appLayoutPath)),\n );\n\n logger.info(\"Modifying app-sidebar\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n // The invite and join pages and the sidebar header show `site.name`.\n const siteFile = await ensureSiteFile(options);\n if (siteFile) creates.push(siteFile);\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,IAAMA,IAAe,mHAMfC,IAAiB;AAMvB,SAAgBsB,EAAsB,GAAmC;CACvE,IAAI,CAACJ,EAAG,WAAWK,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAASvB;CAAe;CAGxD,IAAMwB,IAAOb,EAAW,SAASY,CAAU;CAa3C,OAZKC,EAAK,WAAW,YAAY,IAG7BA,EAAK,aAAa,cAAc,OAAO,IAClC;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7CA,EAAK,mBACH,cACA,4CACF,GACAA,EAAK,QAAQD,CAAU,GAChB;EAAE,QAAQ;EAAW,SAASC,EAAK,WAAW;CAAE,KAX9C;EAAE,QAAQ;EAAU,SAASzB;CAAa;AAYrD;;ACzBA,IAAM0B,IAAa,ulCAgCbC,IAAiB,kSAYjBC,IAAc,kBAEd1B,IAAe;CACnB;CACA;CACA;CACA;CACAyB;CACA;CACA;CACA;CACA;CACAD;AACF,CAAC,CAAC,KAAK,IAAI,GAELvB,IAAiB;CACrB;CACA;CACA;CACA;CACAwB;CACA;CACA;CACAD;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAASK,EAAuB,GAAgB,GAA6B;CAC3E,IAAM,EAAE,QAAQC,MAAQnB,EAAmBoB,IAAS,MAAO;EAMzD,AALKC,KACHnB,EAAcoB,GAAI,CAChB;GAAE,cAAc,CAAC,MAAM;GAAG,iBAAiB;EAAe,CAC5D,CAAC,GAEHpB,EAAcoB,GAAI;GAChB;IACE,eAAe;IACf,iBAAiB;GACnB;GACA;IACE,eAAe;IACf,iBAAiB;GACnB;GACA;IACE,eAAe;IACf,iBAAiB;GACnB;GACA;IACE,iBAAiB;IACjB,iBAAiB;GACnB;EACF,CAAC;EAED,KAAK,IAAMC,KA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AE5B;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-BH6hHygm.js","names":["paymentsBillingPageServerTemplate","paymentsBillingPageSvelteTemplate","getLogger","modifyOutcomeToFile","planDropsForCollections","withInMemoryScript","removeTopLevelStatementByIdentifier","formatLikeSource","removeImportByModuleSpecifier","SvelteFile","removeFromLoad","propsStatement","bindingText","_page_server_default","_page_default","fs","path","SUBSCRIPTION_CASE_VALUES","unmodifyWebhookServer","filePath","original","sf","switchStmt","SyntaxKind","stmt","toRemove","clause","expr","literal","c","spaced","source","unmodifyAppLayoutSvelte","file","updateScript","out","decl","init","nameNode","pattern","elements","hasSub","typeNode","intersection","member","lit","propTexts","p","t","remaining","unmodifyAppSidebar","hasSubPropType","hasSubProp","hasNavUserSubAttr","unmodifyAppLayoutServer","fromLoad","Project","QuoteKind","unmodifyNavUser","content","binding","kept","revertByTemplate","current","enabledMarker","stripped","template","unmodifyBillingPageServer","paymentsBillingPageServerTemplate","unmodifyBillingPageSvelte","paymentsBillingPageSvelteTemplate","generate","logger","options","modifies","pushResult","webhookServerPath","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/disable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-nav-user.ts","../../src/patterns/disable/subscriptions/modifies/revert-by-template.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/disable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst SUBSCRIPTION_CASE_VALUES = new Set([\n \"customer.subscription.created\",\n \"customer.subscription.updated\",\n \"customer.subscription.deleted\",\n]);\n\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n removeImportByModuleSpecifier(sf, \"./subscription/created\");\n removeImportByModuleSpecifier(sf, \"./subscription/updated\");\n removeImportByModuleSpecifier(sf, \"./subscription/deleted\");\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n // Collect matching case clauses first — removing invalidates node refs.\n const toRemove = caseBlock\n .getClauses()\n .filter((clause) => {\n if (clause.getKind() !== SyntaxKind.CaseClause) return false;\n const caseClause = clause.asKindOrThrow(SyntaxKind.CaseClause);\n const expr = caseClause.getExpression();\n const literal =\n expr.asKind(SyntaxKind.StringLiteral) ??\n expr.asKind(SyntaxKind.NoSubstitutionTemplateLiteral);\n if (!literal) return false;\n return SUBSCRIPTION_CASE_VALUES.has(literal.getLiteralValue());\n })\n .map((c) => c.asKindOrThrow(SyntaxKind.CaseClause));\n\n for (const clause of toRemove.reverse()) {\n clause.remove();\n }\n\n formatLikeSource(sf);\n });\n\n // Removing the clauses takes the blank line before `default:` with them.\n const spaced = source.replace(/(break;)\\n(\\s*default:)/, \"$1\\n\\n$2\");\n\n if (spaced === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, spaced, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const removed = file.removeAttribute(\"AppSidebar\", \"subscription\");\n if (!removed) {\n return { status: \"success\", changed: false };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction updateScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n const hasSub = elements.some((e) => e.getName() === \"subscription\");\n\n // Strip subscription from the props type literal (the specific type\n // added by enable-subscriptions — leave unrelated `subscription` props\n // alone).\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"))\n .filter((t) => !/^\\s*subscription\\??\\s*:/.test(t));\n lit.replaceWithText(\n propTexts.length ? `{ ${propTexts.join(\"; \")}; }` : \"{}\",\n );\n break;\n }\n }\n\n if (hasSub) {\n const remaining = elements\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n pattern.replaceWithText(`{ ${remaining.join(\", \")} }`);\n }\n }\n formatLikeSource(sf);\n });\n return out;\n}\n\nexport function unmodifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(filePath, \"utf8\");\n const hasSubPropType = /subscription\\??\\s*:\\s*\\{/.test(source);\n const hasSubProp = /\\bsubscription\\s*=\\s*null\\b/.test(source);\n\n const file = new SvelteFile(source);\n const hasNavUserSubAttr =\n file.hasElement(\"NavUser\") && file.hasAttribute(\"NavUser\", \"subscription\");\n\n if (!hasSubPropType && !hasSubProp && !hasNavUserSubAttr) {\n return { status: \"success\", changed: false };\n }\n\n if (hasSubPropType || hasSubProp) {\n file.modifyScript(updateScript);\n }\n if (hasNavUserSubAttr) {\n file.removeAttribute(\"NavUser\", \"subscription\");\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeFromLoad } from \"../../../../runtime/unmodify-load\";\nimport {\n formatLikeSource,\n removeTopLevelStatementByIdentifier,\n} from \"../../../../runtime/ts-morph-helpers\";\n\n/**\n * Takes out what enable-subscriptions added to the (app) layout load: the\n * `subscription` it loads and returns, and the `loadActiveSubscription`\n * helper. The rest of the load (what other patterns added) stays.\n */\nexport function unmodifyAppLayoutServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"loadActiveSubscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const fromLoad = removeFromLoad(filePath, {\n variables: [\"subscription\"],\n dependsKeys: [],\n returnProps: [\"subscription\"],\n });\n if (fromLoad.status !== \"success\") return fromLoad;\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n removeTopLevelStatementByIdentifier(sf, \"loadActiveSubscription\");\n formatLikeSource(sf);\n sf.saveSync();\n\n return {\n status: \"success\",\n changed: fs.readFileSync(filePath, \"utf8\") !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { withInMemoryScript } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n bindingText,\n propsStatement,\n} from \"../../../enable/subscriptions/modifies/modify-nav-user\";\n\n/**\n * Takes the plan label out of nav-user: the lines showing it, `planLabel`\n * and the `subscription` prop. What other patterns added stays.\n */\nexport function unmodifyNavUser(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"planLabel\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n file.modifyScript(\n (content) =>\n withInMemoryScript(\n // With the blank line enable-subscriptions put before it.\n content.replace(\n /\\n[ \\t]*\\n[ \\t]*const planLabel = \\$derived\\([^\\n]*\\);/,\n \"\",\n ),\n (sf) => {\n const decl = propsStatement(sf)?.getDeclarations()[0];\n const binding = decl\n ?.getNameNode()\n .asKind(SyntaxKind.ObjectBindingPattern);\n const kept = binding\n ?.getElements()\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n if (binding && kept) {\n binding.replaceWithText(bindingText(binding.getText(), kept));\n }\n decl\n ?.getTypeNode()\n ?.asKind(SyntaxKind.TypeLiteral)\n ?.getProperty(\"subscription\")\n ?.remove();\n },\n ).source,\n );\n\n // The lines under the name, with the line break before them.\n const out = file\n .toString()\n .replace(/\\n[ \\t]*<span class=\"[^\"]*\">\\s*\\{planLabel\\}\\s*<\\/span>/g, \"\");\n\n fs.writeFileSync(filePath, out, \"utf8\");\n return { status: \"success\", changed: out !== original };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Rewrites a file to the given `template` if the current content still shows\n * the `enabledMarker` (meaning enable-subscriptions is applied). If the marker\n * is absent (already reverted or never applied), it's a no-op.\n *\n * Strips leading `// [!code highlight:N]` / `<!-- [!code highlight:N] -->`\n * lines so templates can be pulled from `preview-modifies/` directories which\n * use those for documentation highlighting.\n */\nexport function revertByTemplate(\n filePath: string,\n template: string,\n enabledMarker: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (!current.includes(enabledMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageServer(\n filePath: string,\n paymentsBillingPageServerTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageServerTemplate,\n \"selectPlan\",\n );\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageSvelte(\n filePath: string,\n paymentsBillingPageSvelteTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageSvelteTemplate,\n \"availablePlans\",\n );\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\nimport { unmodifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { unmodifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { unmodifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { unmodifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { unmodifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\n\n// Pull the \"post-payments\" state of files that enable-subscriptions fully\n// overwrote. For the billing pages, that's exactly what enable-payments\n// writes in creates-app-mode; for nav-user it's the payments preview-modifies\n// snapshot (with highlight annotations stripped by the revert helper).\nimport paymentsBillingPageServerTemplate from \"../../enable/payments/providers-app-mode/stripe/src/routes/(app)/billing/+page.server.ts?raw\";\nimport paymentsBillingPageSvelteTemplate from \"../../enable/payments/providers-app-mode/stripe/src/routes/(app)/billing/+page.svelte?raw\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n unmodifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n unmodifyAppLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n unmodifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Reverting app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, unmodifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n logger.info(\"Reverting billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n unmodifyBillingPageServer(\n billingPageServerPath,\n paymentsBillingPageServerTemplate,\n ),\n ),\n );\n\n logger.info(\"Reverting billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n unmodifyBillingPageSvelte(\n billingPageSveltePath,\n paymentsBillingPageSvelteTemplate,\n ),\n ),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"stripe_subscriptions\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n coll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IAAMK,IAAsB7D,EAAK,KAC/ByD,EAAQ,MACR,OACA,UACA,SACA,mBACF;CAQA,AAPAE,EACExE,EACE0E,GACAvB,EAAwBuB,CAAmB,CAC7C,CACF,GAEAL,EAAO,KAAK,gCAAgC;CAC5C,IAAMM,IAAsB9D,EAAK,KAC/ByD,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAQA,AAPAE,EACExE,EACE2E,GACA9C,EAAwB8C,CAAmB,CAC7C,CACF,GAEAN,EAAO,KAAK,8BAA8B;CAC1C,IAAMO,IAAiB/D,EAAK,KAC1ByD,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJAE,EACExE,EAAoB4E,GAAgB7B,EAAmB6B,CAAc,CAAC,CACxE,GAEAP,EAAO,KAAK,2BAA2B;CACvC,IAAMQ,IAAchE,EAAK,KACvByD,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,AAFAE,EAAWxE,EAAoB6E,GAAatB,EAAgBsB,CAAW,CAAC,CAAC,GAEzER,EAAO,KAAK,mCAAmC;CAC/C,IAAMS,IAAwBjE,EAAK,KACjCyD,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVAE,EACExE,EACE8E,GACAd,EACEc,GACAjF,CACF,CACF,CACF,GAEAwE,EAAO,KAAK,gCAAgC;CAC5C,IAAMU,IAAwBlE,EAAK,KACjCyD,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAgBA,OAfAE,EACExE,EACE+E,GACAb,EACEa,GACAjF,CACF,CACF,CACF,GAOO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4BG,EAC5B,CAAC,sBAAsB,GACvBqE,CACF;CAWA;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-C3IswX7B.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__0_4_","__import_glob__0_5_","__import_glob__0_6_","stripeCustomerHelper","_layout_server_default","_layout_default","nav_user_default","_page_server_default","app_sidebar_default","dispatch_default","InvalidArgumentError","getLogger","keepMissing","modifyOutcomeToFile","dedent","withInMemoryScript","formatLikeSource","ensureImports","SvelteFile","modifyNavUser","stripe_customer_default","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$5","SUBSCRIPTION_CASES_SNIPPET","modifyWebhookServer","filePath","original","addedCases","sf","switchStmt","SyntaxKind","stmt","clauses","defaultClause","c","prefix","last","source","LOAD_LINE","NOT_FOUND_HINT$4","failureHint","helper","helperFrom","clean","template","start","end","findLoad","varDecl","init","fn","modifyAppLayoutServer","Project","QuoteKind","load","body","block","binding","hasLocals","el","userIndex","s","d","statements","ret","returned","text","writer","FAILURE_HINT$1","NOT_FOUND_HINT$3","modifyAppLayoutSvelte","file","SUBSCRIPTION_TYPE","FAILURE_HINT","NOT_FOUND_HINT$2","updateScript","wasAdded","out","decl","nameNode","pattern","elements","typeNode","intersection","member","lit","propTexts","p","t","elementTexts","insertIdx","modifyAppSidebar","scriptChanged","src","templateChanged","modifyByTemplate","notFoundHint","current","idempotencyMarker","stripped","NOT_FOUND_HINT$1","modifyBillingPageServer","NOT_FOUND_HINT","modifyBillingPageSvelte","STRIPE_CUSTOMER_HELPER","BILLING_PAGE","assertPaymentsAppMode","root","previewRaw","_page_default","content","relativePath","generate","logger","options","modifies","pushResult","webhookServerPath","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/enable/subscriptions/modifies/modify-by-template.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/enable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Wire the subscription event handlers into src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n Add imports:\n import { handleSubscriptionCreated } from \"./subscription/created\";\n import { handleSubscriptionUpdated } from \"./subscription/updated\";\n import { handleSubscriptionDeleted } from \"./subscription/deleted\";\n\n Add switch cases inside the event.type switch:\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first — src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\nconst SUBSCRIPTION_CASES_SNIPPET = dedent`\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\nexport function modifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n let addedCases = false;\n const { source } = withInMemoryScript(original, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"handleSubscriptionCreated\"],\n moduleSpecifier: \"./subscription/created\",\n },\n {\n namedImports: [\"handleSubscriptionUpdated\"],\n moduleSpecifier: \"./subscription/updated\",\n },\n {\n namedImports: [\"handleSubscriptionDeleted\"],\n moduleSpecifier: \"./subscription/deleted\",\n },\n ]);\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n const clauses = caseBlock.getClauses();\n const defaultClause = clauses.find(\n (c) => c.getKind() === SyntaxKind.DefaultClause,\n );\n\n // Prepend subscription cases in front of the default clause, or append\n // before the closing brace of the case block if there's no default.\n const prefix = `${SUBSCRIPTION_CASES_SNIPPET}\\n\\n`;\n if (defaultClause) {\n defaultClause.replaceWithText(prefix + defaultClause.getText());\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(\n last.getText() + `\\n\\n${SUBSCRIPTION_CASES_SNIPPET}`,\n );\n } else {\n return;\n }\n\n formatLikeSource(sf);\n addedCases = true;\n });\n\n if (!addedCases) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst LOAD_LINE =\n \"const subscription = await loadActiveSubscription(locals, user.id);\";\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.server.ts before enabling subscriptions.\",\n \"Enable auth first — the (app) layout is provided by the velastack-auth baseline.\",\n].join(\"\\n\");\n\nconst failureHint = (helper: string) =>\n [\n \"Could not find the user and the returned object in the (app) layout load.\",\n \"Add the active subscription to it by hand:\",\n \"\",\n helper,\n \"\",\n \"// In load, once `user` is set:\",\n LOAD_LINE,\n \"// ...and return it with the rest:\",\n \"return { ..., subscription };\",\n ].join(\"\\n\");\n\n/**\n * The `loadActiveSubscription` helper, taken from the preview template so the\n * docs and what gets written stay the same.\n */\nfunction helperFrom(template: string): string {\n const clean = template.replace(\n /^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm,\n \"\",\n );\n const start = clean.indexOf(\"async function loadActiveSubscription\");\n const end = clean.indexOf(\"\\n}\\n\", start);\n if (start === -1 || end === -1) {\n throw new Error(\"No loadActiveSubscription in the layout template\");\n }\n return clean.slice(start, end + 2);\n}\n\nfunction findLoad(sf: SourceFile) {\n const varDecl = sf.getVariableDeclaration(\"load\");\n if (varDecl?.getVariableStatement()?.hasExportKeyword()) {\n const init = varDecl.getInitializer();\n const fn =\n varDecl.getInitializerIfKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.FunctionExpression);\n if (fn) return { fn, statement: varDecl.getVariableStatement()! };\n }\n const fn = sf.getFunction(\"load\");\n return fn?.isExported() ? { fn, statement: fn } : undefined;\n}\n\n/**\n * Adds the active subscription to the (app) layout's data: the\n * `loadActiveSubscription` helper, a call to it in `load`, and `subscription`\n * in what `load` returns. Edits the file rather than replacing it, so what\n * other patterns put in the load (teams' `team`/`teams`, say) stays.\n */\nexport function modifyAppLayoutServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"loadActiveSubscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const helper = helperFrom(template);\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n const load = findLoad(sf);\n const body = load?.fn.getBody();\n if (!load || !body || body.getKind() !== SyntaxKind.Block) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n const block = body.asKindOrThrow(SyntaxKind.Block);\n\n // The call needs `locals` and `user`, and goes before the return.\n const params = load.fn.getParameters();\n const binding = params[0]?.getNameNode();\n const hasLocals =\n binding?.getKind() === SyntaxKind.ObjectBindingPattern &&\n binding\n .asKindOrThrow(SyntaxKind.ObjectBindingPattern)\n .getElements()\n .some((el) => el.getName() === \"locals\");\n const userIndex = block.getStatements().findIndex(\n (s) =>\n s.getKind() === SyntaxKind.VariableStatement &&\n s\n .asKindOrThrow(SyntaxKind.VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === \"user\"),\n );\n const statements = block.getStatements();\n const ret = [...statements]\n .reverse()\n .find((s) => s.getKind() === SyntaxKind.ReturnStatement)\n ?.asKind(SyntaxKind.ReturnStatement);\n const returned = ret\n ?.getExpression()\n ?.asKind(SyntaxKind.ObjectLiteralExpression);\n if (!hasLocals || userIndex === -1 || !ret || !returned) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n\n block.insertStatements(statements.indexOf(ret), LOAD_LINE);\n if (!returned.getProperty(\"subscription\")) {\n const text = returned.getText();\n if (text.includes(\"\\n\")) {\n returned.addShorthandPropertyAssignment({ name: \"subscription\" });\n } else {\n // Kept on one line, as written.\n returned.replaceWithText(text.replace(/\\s*\\}$/, \", subscription }\"));\n }\n }\n if (!load.fn.isAsync()) load.fn.setIsAsync(true);\n sf.insertStatements(sf.getStatements().indexOf(load.statement), (writer) =>\n writer.write(helper).blankLine(),\n );\n\n formatLikeSource(sf);\n sf.saveSync();\n return { status: \"success\", changed: sf.getFullText() !== original };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass the subscription prop to <AppSidebar> in src/routes/(app)/+layout.svelte:\",\n \"\",\n \"<AppSidebar user={data.user} subscription={data.subscription} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with an <AppSidebar /> that receives the subscription prop.\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const appended = file.appendToAttributes(\n \"AppSidebar\",\n \" subscription={data.subscription}\",\n );\n if (!appended) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst SUBSCRIPTION_TYPE = \"{ id: string; productName: string | null } | null\";\n\nconst FAILURE_HINT = [\n \"Update src/lib/components/app-sidebar.svelte to forward a subscription prop:\",\n \"\",\n \"1. Add `subscription = null` to the destructured $props() call.\",\n `2. Add \\`subscription?: ${SUBSCRIPTION_TYPE}\\` to the props type.`,\n \"3. Pass `{subscription}` to <NavUser>.\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/lib/components/app-sidebar.svelte before enabling subscriptions.\",\n].join(\"\\n\");\n\nfunction updateScript(source: string): {\n source: string;\n wasAdded: boolean;\n} {\n let wasAdded = false;\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n if (elements.some((e) => e.getName() === \"subscription\")) {\n // Already has subscription prop — no-op.\n return;\n }\n\n // Insert subscription?: ... into the props type literal if present.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^\\s*subscription\\??\\s*:/.test(t))) {\n continue;\n }\n propTexts.push(`subscription?: ${SUBSCRIPTION_TYPE}`);\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Insert `subscription = null` before the first rest/default-only element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elementTexts.length;\n elementTexts.splice(insertIdx, 0, \"subscription = null\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n wasAdded = true;\n }\n formatLikeSource(sf);\n });\n return { source: out, wasAdded };\n}\n\nexport function modifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (\n original.includes(\"subscription?: {\") ||\n original.includes(\"subscription={subscription}\") ||\n original.includes(\"{subscription}\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n if (!file.hasElement(\"NavUser\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const scriptChanged = file.modifyScript((src) => updateScript(src).source);\n\n const templateChanged = !file.hasAttribute(\"NavUser\", \"subscription\")\n ? file.appendToAttributes(\"NavUser\", \" {subscription}\")\n : false;\n\n if (!scriptChanged && !templateChanged) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Overwrites a file with the given template content, guarded by an idempotency\n * marker: if the current file already contains the marker, the modify is a\n * no-op. Used for complex rewrites where surgical AST changes aren't worth it\n * (e.g. pages that are largely replaced).\n *\n * Strips leading `// [!code highlight:N]` and `<!-- [!code highlight:N] -->`\n * lines so the same content can be shared with preview-modifies, which uses\n * those comments for documentation highlighting.\n */\nexport function modifyByTemplate(\n filePath: string,\n template: string,\n idempotencyMarker: string,\n notFoundHint: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: notFoundHint };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (current.includes(idempotencyMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.server.ts is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"selectPlan\", NOT_FOUND_HINT);\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.svelte is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageSvelte(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"availablePlans\", NOT_FOUND_HINT);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { keepMissing, modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { modifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { modifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\nimport stripeCustomerHelper from \"../payments/providers-app-mode/stripe/src/lib/server/stripe-customer.ts?raw\";\n\n// The billing page imports this payments helper, which apps that enabled\n// payments before it existed do not have yet.\nconst STRIPE_CUSTOMER_HELPER = \"src/lib/server/stripe-customer.ts\";\n\n// enable-payments writes the billing page (and the stripe_customers collection\n// subscriptions relate to) only when auth is already on.\nconst BILLING_PAGE = \"src/routes/(app)/billing/+page.server.ts\";\n\n/**\n * Refuses a project whose payments were enabled before auth. Every `requires`\n * flag passes there (auth and payments are both on), yet the billing page and\n * `stripe_customers` don't exist, so this runs before any collection is made.\n */\nexport function assertPaymentsAppMode(root: string): void {\n if (fs.existsSync(path.join(root, BILLING_PAGE))) return;\n throw new InvalidArgumentError(\n [\n \"Subscriptions need payments set up with auth on: they add plans to the billing page\",\n `(${BILLING_PAGE}) and link to the stripe_customers collection, which enable-payments`,\n \"creates only when auth is already enabled. This project enabled payments before auth.\",\n \"\",\n \"Re-enable payments now that auth is on: `vela disable payments`, then `vela enable payments`.\",\n \"disable-payments drops the catalog collections, which the sync workflow refills from Stripe.\",\n ].join(\"\\n\"),\n );\n}\n\n// Share the final-state files between preview (rendered as-is) and runtime\n// (used as overwrite templates for modifies that amount to full rewrites).\nconst previewRaw = import.meta.glob<string>(\"./preview-modifies/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nfunction template(relativePath: string): string {\n const key = `./preview-modifies/${relativePath}`;\n const content = previewRaw[key];\n if (content === undefined) {\n throw new Error(\n `Missing template for ${relativePath} in subscriptions preview-modifies`,\n );\n }\n return content;\n}\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(\"Modifying webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n modifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyAppLayoutServer(\n appLayoutServerPath,\n template(\"src/routes/(app)/+layout.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n modifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Modifying app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n modifyBillingPageServer(\n billingPageServerPath,\n template(\"src/routes/(app)/billing/+page.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n modifyBillingPageSvelte(\n billingPageSveltePath,\n template(\"src/routes/(app)/billing/+page.svelte\"),\n ),\n ),\n );\n\n const creates = keepMissing(\n [\n {\n path: STRIPE_CUSTOMER_HELPER,\n language: \"ts\",\n content: stripeCustomerHelper,\n status: \"success\",\n },\n ],\n options.root,\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":";;;;;;;;;;;;;AAUA,IAAMA,IAAe,CAAM;;;;;;;;;;;;;;;;;;GAoBrBC,IACJ,0GAEImC,IAA6B,CAAM;;;;;;;;;;;;;AAczC,SAAgBC,EAAoB,GAAiC;CACnE,IAAI,CAACL,EAAG,WAAWM,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAa,SAASrC;CAAe;CAGxD,IAAMsC,IAAWP,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G,GAAgB7B,EAAiB6B,CAAc,CAAC,CACtE,GAEAP,EAAO,KAAK,2BAA2B;CACvC,IAAMQ,IAAcrG,EAAK,KACvB8F,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,AAFAE,EAAWzG,EAAoB8G,GAAaxG,EAAcwG,CAAW,CAAC,CAAC,GAEvER,EAAO,KAAK,mCAAmC;CAC/C,IAAMS,IAAwBtG,EAAK,KACjC8F,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVAE,EACEzG,EACE+G,GACArB,EACEqB,GACA9E,EAAS,0CAA0C,CACrD,CACF,CACF,GAEAqE,EAAO,KAAK,gCAAgC;CAC5C,IAAMU,IAAwBvG,EAAK,KACjC8F,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAuBA,OAtBAE,EACEzG,EACEgH,GACApB,EACEoB,GACA/E,EAAS,uCAAuC,CAClD,CACF,CACF,GAcO;EACL,SAbclC,EACd,CACE;GACE,MAAM8F;GACN,UAAU;GACV,SAASvG;GACT,QAAQ;EACV,CACF,GACAiH,EAAQ,IAIR;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-DlAJQ5Js.js","names":["getLogger","readMigration","createCollectionIdempotent","applyCollectionRulePatches","migrationDelay","getMigrationFile","modifyOutcomeToFile","modifyUtils","dedent","SvelteFile","withInMemoryScript","formatLikeSource","ensureImports","NOTIFICATION_RULE_PATCHES","fs","path","BELL_SNIPPET","IMPORT_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","modifyAppLayout","layoutPath","file","out","source","sf","FETCH_STATEMENT","NOTIFICATIONS_STATEMENT","DEPENDS_STATEMENT","modifyLayoutServer","layoutServerPath","snippet","originalSource","sourceFile","Project","addProperty","obj","name","initializer","loadArrow","loadFn","varDecl","SyntaxKind","directArrow","init","innerArrow","innerFnExpr","maybeFn","fnLike","params","first","original","nameNode","obp","elementNames","el","hasDepends","hasLocals","existingParts","parts","currentName","body","blockBody","statements","declaresVar","stmt","d","hasDependsCall","ce","args","argText","hasNotificationsList","hasNotifications","returnIdx","s","insertAt","augmentReturnObject","augmentReturns","expr","ret","inner","arrowBody","bodyExpr","fnBody","pushMigrationCreates","created","migrationFile","collectionName","options","creates","generate","logger","withPocketbase","userCollection","pb","create","spec","result","ruleMigrations","modifies","pushResult","appLayoutPath","appLayoutServerPath","utilsPath"],"sources":["../../src/patterns/enable/notifications/modifies/modify-app-layout.ts","../../src/patterns/enable/notifications/modifies/+layout.server.ts","../../src/patterns/enable/notifications/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BELL_SNIPPET = `\n\t\t<div class=\"ml-auto px-4\">\n\t\t\t<NotificationsBell />\n\t\t</div>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import NotificationsBell from '#lib/components/notifications-bell.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the notifications bell inside the (app) layout's <header>.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with a <header> that includes the bell.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <header>:\",\n BELL_SNIPPET,\n].join(\"\\n\");\n\nexport function modifyAppLayout(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"header\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"NotificationsBell\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"NotificationsBell\",\n moduleSpecifier: \"#lib/components/notifications-bell.svelte\",\n },\n ]);\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"header\", BELL_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FETCH_STATEMENT = dedent`\n const notificationsList = await locals.pb\n .collection(\"notifications\")\n .getList(1, 5, {\n filter: \\`user = \"\\${locals.pb.authStore.record!.id}\" && read = false\\`,\n sort: \"-created\",\n });\n`;\n\nconst NOTIFICATIONS_STATEMENT =\n \"const notifications = { count: notificationsList.totalItems, items: notificationsList.items };\";\n\nconst DEPENDS_STATEMENT = 'depends(\"app:notifications\");';\n\nexport function modifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n const snippet = dedent`\n export const load = async ({ locals, depends }) => {\n ${FETCH_STATEMENT}\n ${NOTIFICATIONS_STATEMENT}\n ${DEPENDS_STATEMENT}\n return { notifications };\n };\n `;\n fs.writeFileSync(layoutServerPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutServerPath);\n\n const addProperty = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n name: string,\n initializer: string,\n ) => {\n if (obj.getProperty(name)) return;\n if (name === initializer) {\n obj.addShorthandPropertyAssignment({ name });\n } else {\n obj.addPropertyAssignment({ name, initializer });\n }\n };\n\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n if (vs?.hasExportKeyword()) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n\n if (!loadArrow && !loadFn) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) loadFn = maybeFn;\n }\n\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals, depends }\" }],\n statements: [\n FETCH_STATEMENT,\n NOTIFICATIONS_STATEMENT,\n DEPENDS_STATEMENT,\n \"return { notifications };\",\n ],\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const fnLike = (loadArrow ?? loadFn!) as\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression;\n\n // Ensure first param destructures { locals, depends }\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals, depends }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const elementNames = obp.getElements().map((el) => el.getName());\n const hasDepends = elementNames.includes(\"depends\");\n const hasLocals = elementNames.includes(\"locals\");\n\n if (!hasDepends || !hasLocals) {\n const existingParts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const parts: string[] = hasLocals ? [] : [\"locals\"];\n parts.push(...existingParts);\n if (!hasDepends) parts.push(\"depends\");\n first.set({\n name: `{ ${parts.join(\", \")} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, depends, ...${currentName} }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n } else {\n first.set({\n name: `{ locals, depends }`,\n type: original.type,\n initializer: (original as { initializer?: string }).initializer,\n });\n }\n }\n }\n\n if (loadArrow && !loadArrow.isAsync()) loadArrow.setIsAsync(true);\n else if (loadFn && !loadFn.isAsync()) loadFn.setIsAsync(true);\n\n const body = fnLike.getBody();\n if (body && body.getKind() === SyntaxKind.Block) {\n const blockBody = body as import(\"ts-morph\").Block;\n const statements = blockBody.getStatements();\n\n const declaresVar = (name: string) =>\n statements.some((stmt) => {\n if (stmt.getKind() !== SyntaxKind.VariableStatement) return false;\n return (stmt as import(\"ts-morph\").VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === name);\n });\n\n const hasDependsCall = statements.some(\n (stmt) =>\n stmt.getKind() === SyntaxKind.ExpressionStatement &&\n stmt.getDescendantsOfKind(SyntaxKind.CallExpression).some((ce) => {\n if (ce.getExpression().getText() !== \"depends\") return false;\n const args = ce.getArguments();\n const argText = args[0]?.getText() ?? \"\";\n return (\n args.length === 1 &&\n (argText === \"'app:notifications'\" ||\n argText === '\"app:notifications\"')\n );\n }),\n );\n\n const hasNotificationsList = declaresVar(\"notificationsList\");\n const hasNotifications = declaresVar(\"notifications\");\n\n const returnIdx = statements.findIndex(\n (s) => s.getKind() === SyntaxKind.ReturnStatement,\n );\n let insertAt = returnIdx >= 0 ? returnIdx : statements.length;\n\n if (!hasNotificationsList) {\n blockBody.insertStatements(insertAt, FETCH_STATEMENT);\n insertAt++;\n }\n if (!hasNotifications) {\n blockBody.insertStatements(insertAt, NOTIFICATIONS_STATEMENT);\n insertAt++;\n }\n if (!hasDependsCall) {\n blockBody.insertStatements(insertAt, DEPENDS_STATEMENT);\n }\n }\n\n const augmentReturnObject = (\n obj: import(\"ts-morph\").ObjectLiteralExpression,\n ) => {\n addProperty(obj, \"notifications\", \"notifications\");\n };\n\n const augmentReturns = (target: import(\"ts-morph\").Node) => {\n const returns = target.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n });\n };\n\n if (loadArrow) {\n const arrowBody = loadArrow.getBody();\n if (arrowBody.getKind() === SyntaxKind.Block) {\n augmentReturns(arrowBody);\n } else {\n const bodyExpr = arrowBody as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n inner as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n augmentReturnObject(\n bodyExpr as import(\"ts-morph\").ObjectLiteralExpression,\n );\n }\n }\n } else if (loadFn) {\n const fnBody = loadFn.getBody();\n if (fnBody) augmentReturns(fnBody);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n applyCollectionRulePatches,\n createCollectionIdempotent,\n readMigration,\n} from \"../../../runtime/collections\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyUtils } from \"../../../runtime/modify-utils\";\nimport { modifyAppLayout } from \"./modifies/modify-app-layout\";\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { NOTIFICATION_RULE_PATCHES } from \"./runtime/pocketbase\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, \"created\", options);\n if (!migrationFile) return;\n creates.push(await readMigration(migrationFile, options));\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n const userCollection = await pb.collections.getOne(\"users\");\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating notifications collection\");\n const result = await create({\n name: \"notifications\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n type: \"text\",\n primaryKey: true,\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n pattern: \"^[a-z0-9]+$\",\n required: true,\n },\n {\n name: \"user\",\n type: \"relation\",\n cascadeDelete: true,\n collectionId: userCollection.id,\n maxSelect: 1,\n minSelect: 0,\n required: true,\n },\n {\n name: \"title\",\n type: \"text\",\n required: true,\n },\n {\n name: \"body\",\n type: \"text\",\n },\n {\n name: \"read\",\n type: \"bool\",\n },\n {\n name: \"created\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: false,\n },\n {\n name: \"updated\",\n type: \"autodate\",\n onCreate: true,\n onUpdate: true,\n },\n ],\n indexes: [\n \"CREATE INDEX `idx_notifications_user_read_created` ON `notifications` (`user`, `read`, `created` DESC)\",\n ],\n });\n await pushMigrationCreates(\n creates,\n \"notifications\",\n options,\n result.created,\n );\n\n logger.info(\"Applying notifications rule patches\");\n const ruleMigrations = await applyCollectionRulePatches(\n pb,\n NOTIFICATION_RULE_PATCHES,\n options,\n logger,\n );\n creates.push(...ruleMigrations);\n });\n\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, modifyAppLayout(appLayoutPath)),\n );\n\n logger.info(\"Modifying (app) +layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Modifying utils.ts\");\n const utilsPath = path.join(options.root, \"src\", \"lib\", \"utils.ts\");\n pushResult(modifyOutcomeToFile(utilsPath, modifyUtils(utilsPath)));\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;AASA,IAAMgB,IAAe,2EAMfC,IAAiB,CAAM;;GAIvBC,IAAe;CACnB;CACA;CACA;CACA;CACAD;CACA;CACA;CACAD;AACF,CAAC,CAAC,KAAK,IAAI,GAELG,IAAiB;CACrB;CACA;CACA;CACA;CACAF;CACA;CACA;CACAD;AACF,CAAC,CAAC,KAAK,IA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D,GACAS,EAAO,OACT,GAEAN,EAAO,KAAK,qCAAqC;EACjD,IAAMO,IAAiB,MAAM/F,EAC3B2F,GACAjF,GACA2E,GACAG,CACF;EACA,EAAQ,KAAK,GAAGO,CAAc;CAChC,CAAC;CAED,IAAMC,IAAmB,CAAC,GACpBC,KAAc,MAAsB;EACxC,AAAI9E,KAAM6E,EAAS,KAAK7E,CAAI;CAC9B;CAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM+E,IAAgBtF,EAAK,KACzByE,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAKA,AAJAY,EACE9F,EAAoB+F,GAAejF,EAAgBiF,CAAa,CAAC,CACnE,GAEAV,EAAO,KAAK,mCAAmC;CAC/C,IAAMW,IAAsBvF,EAAK,KAC/ByE,EAAQ,MACR,OACA,UACA,SACA,mBACF;CAQA,AAPAY,EACE9F,EACEgG,GACAzE,EAAmByE,CAAmB,CACxC,CACF,GAEAX,EAAO,KAAK,oBAAoB;CAChC,IAAMY,IAAYxF,EAAK,KAAKyE,EAAQ,MAAM,OAAO,OAAO,UAAU;CAGlE,OAFAY,EAAW9F,EAAoBiG,GAAWhG,EAAYgG,CAAS,CAAC,CAAC,GAE1D;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"unmodify-load-CdWXJ_Ac.js","names":["formatLikeSource","fs","findLoad","varDecl","sf","SyntaxKind","direct","init","inner","fn","asObjectLiteral","expr","node","returnedObjects","body","obj","ret","escapeRegExp","text","removeFromLoad","filePath","original","Project","QuoteKind","block","dependsRe","spec","stmt","s","d","name","stillDepends","first","nameNode","elements","kept","el","structure","finalBody","statements","prev"],"sources":["../../src/runtime/unmodify-load.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrowFunction,\n type FunctionDeclaration,\n type FunctionExpression,\n type Node,\n type ObjectLiteralExpression,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../core/types\";\nimport { formatLikeSource } from \"./ts-morph-helpers\";\n\nexport interface LoadRevertSpec {\n /** Declarations in the load body to drop, by name. */\n variables: string[];\n /** `depends(\"<key>\")` calls to drop. */\n dependsKeys: string[];\n /** Properties to drop from every object the load returns. */\n returnProps: string[];\n}\n\ntype LoadFn = ArrowFunction | FunctionDeclaration | FunctionExpression;\n\n/** The exported `load`, whether arrow, wrapped (`loadFlash(...)`) or a function. */\nfunction findLoad(sf: SourceFile): LoadFn | undefined {\n const varDecl = sf.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n if (vs?.hasExportKeyword()) {\n const direct = varDecl.getInitializerIfKind(SyntaxKind.ArrowFunction);\n if (direct) return direct;\n const init = varDecl.getInitializer();\n const inner =\n init?.getFirstDescendantByKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.FunctionExpression);\n if (inner) return inner;\n }\n }\n const fn = sf.getFunction(\"load\");\n return fn?.isExported() ? fn : undefined;\n}\n\nfunction asObjectLiteral(\n node: Node | undefined,\n): ObjectLiteralExpression | null {\n let expr = node;\n if (expr?.getKind() === SyntaxKind.ParenthesizedExpression) {\n expr = expr\n .asKindOrThrow(SyntaxKind.ParenthesizedExpression)\n .getExpression();\n }\n return expr?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? expr.asKindOrThrow(SyntaxKind.ObjectLiteralExpression)\n : null;\n}\n\nfunction returnedObjects(fn: LoadFn): ObjectLiteralExpression[] {\n const body = fn.getBody();\n if (!body) return [];\n if (body.getKind() !== SyntaxKind.Block) {\n const obj = asObjectLiteral(body);\n return obj ? [obj] : [];\n }\n return body\n .getDescendantsOfKind(SyntaxKind.ReturnStatement)\n .map((ret) => asObjectLiteral(ret.getExpression()))\n .filter((obj): obj is ObjectLiteralExpression => obj !== null);\n}\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * The inverse of the `modifyLayoutServer` family: drop the declarations,\n * `depends()` calls and returned properties an enable pattern added to the\n * exported `load`, then tidy what they leave behind (an unused `depends`\n * parameter, an `async` with nothing left to await).\n */\nexport function removeFromLoad(\n filePath: string,\n spec: LoadRevertSpec,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n const fn = findLoad(sf);\n if (!fn) {\n return { status: \"success\", changed: false };\n }\n\n const body = fn.getBody();\n if (body?.getKind() === SyntaxKind.Block) {\n const block = body.asKindOrThrow(SyntaxKind.Block);\n const dependsRe =\n spec.dependsKeys.length > 0\n ? new RegExp(\n `^depends\\\\(\\\\s*['\"](?:${spec.dependsKeys.map(escapeRegExp).join(\"|\")})['\"]\\\\s*\\\\)`,\n )\n : null;\n // One statement per pass: a removal invalidates its siblings.\n for (;;) {\n const stmt = block.getStatements().find((s) => {\n if (s.getKind() === SyntaxKind.VariableStatement) {\n return s\n .asKindOrThrow(SyntaxKind.VariableStatement)\n .getDeclarations()\n .some((d) => spec.variables.includes(d.getName()));\n }\n return (\n s.getKind() === SyntaxKind.ExpressionStatement &&\n dependsRe !== null &&\n dependsRe.test(s.getText())\n );\n });\n if (!stmt) break;\n stmt.remove();\n }\n }\n\n for (const obj of returnedObjects(fn)) {\n for (const name of spec.returnProps) {\n obj.getProperty(name)?.remove();\n }\n }\n\n const stillDepends = /\\bdepends\\s*\\(/.test(fn.getBody()?.getText() ?? \"\");\n const first = fn.getParameters()[0];\n if (first && !stillDepends) {\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n const kept = elements\n .filter((el) => el.getName() !== \"depends\")\n .map((el) => el.getText());\n if (kept.length !== elements.length) {\n const structure = first.getStructure();\n first.set({\n name: `{ ${kept.join(\", \")} }`,\n type: structure.type,\n initializer: structure.initializer,\n });\n }\n }\n }\n\n if (\n fn.isAsync() &&\n (fn.getBody()?.getDescendantsOfKind(SyntaxKind.AwaitExpression).length ??\n 0) === 0\n ) {\n fn.setIsAsync(false);\n }\n\n formatLikeSource(sf);\n\n // Removing the statements just above `return` takes the blank line that\n // separated them with it; put it back so the layout reads as it did.\n const finalBody = fn.getBody();\n if (finalBody?.getKind() === SyntaxKind.Block) {\n const statements = finalBody\n .asKindOrThrow(SyntaxKind.Block)\n .getStatements();\n const ret = statements[statements.length - 1];\n const prev = statements[statements.length - 2];\n if (ret?.getKind() === SyntaxKind.ReturnStatement && prev) {\n const between = sf.getFullText().slice(prev.getEnd(), ret.getStart());\n if ((between.match(/\\n/g) ?? []).length < 2) {\n sf.insertText(prev.getEnd(), \"\\n\");\n }\n }\n }\n\n sf.saveSync();\n return { status: \"success\", changed: sf.getFullText() !== original };\n}\n"],"mappings":";;;;AA2BA,SAASE,EAAS,GAAoC;CACpD,IAAMC,IAAUC,EAAG,uBAAuB,MAAM;CAChD,IAAID,KACSA,EAAQ,uBAAuBE,EAAW,iBACjD,CAAA,EAAI,iBAAiB,GAAG;EAC1B,IAAMC,IAASH,EAAQ,qBAAqBE,EAAW,aAAa;EACpE,IAAIC,GAAQ,OAAOA;EACnB,IAAMC,IAAOJ,EAAQ,eAAe,GAC9BK,IACJD,GAAM,yBAAyBF,EAAW,aAAa,KACvDE,GAAM,yBAAyBF,EAAW,kBAAkB;EAC9D,IAAIG,GAAO,OAAOA;CACpB;CAEF,IAAMC,IAAKL,EAAG,YAAY,MAAM;CAChC,OAAOK,GAAI,WAAW,IAAIA,IAAK,KAAA;AACjC;AAEA,S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