@velastack/patterns 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{collections-BrEA7a62.js → collections-DZOuRpvS.js} +6 -1
- package/dist/chunks/collections-DZOuRpvS.js.map +1 -0
- package/dist/chunks/{generate-BZ741GPx.js → currency.server-Bb2Ndutg.js} +6 -3
- package/dist/chunks/{generate-BZ741GPx.js.map → currency.server-Bb2Ndutg.js.map} +1 -1
- package/dist/chunks/{generate-6JS05dWK.js → generate-B-cqjI-U.js} +62 -55
- package/dist/chunks/generate-B-cqjI-U.js.map +1 -0
- package/dist/chunks/{generate.runtime-BOl3LpPB.js → generate.runtime-BnqS_Zq8.js} +84 -158
- package/dist/chunks/generate.runtime-BnqS_Zq8.js.map +1 -0
- package/dist/chunks/{generate.runtime-KrQk7mqG.js → generate.runtime-DG9Lp3vR.js} +39 -37
- package/dist/chunks/generate.runtime-DG9Lp3vR.js.map +1 -0
- package/dist/chunks/{generate.runtime-Dt3Edp8-.js → generate.runtime-X-uAteso.js} +123 -104
- package/dist/chunks/generate.runtime-X-uAteso.js.map +1 -0
- package/dist/chunks/load-function-Dmkhg1pQ.js +79 -0
- package/dist/chunks/load-function-Dmkhg1pQ.js.map +1 -0
- package/dist/chunks/root-layout.svelte-CUVbnlX-.js +302 -0
- package/dist/chunks/root-layout.svelte-CUVbnlX-.js.map +1 -0
- package/dist/index.js +15 -15
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/collections-BrEA7a62.js.map +0 -1
- package/dist/chunks/generate-6JS05dWK.js.map +0 -1
- package/dist/chunks/generate.runtime-BOl3LpPB.js.map +0 -1
- package/dist/chunks/generate.runtime-Dt3Edp8-.js.map +0 -1
- package/dist/chunks/generate.runtime-KrQk7mqG.js.map +0 -1
- package/dist/chunks/root-layout.svelte-CsJ2QJYi.js +0 -93
- package/dist/chunks/root-layout.svelte-CsJ2QJYi.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate.runtime-X-uAteso.js","names":["__import_glob__0_0_","__import_glob__0_1_","InvalidArgumentError","languageFromPath","mergeResults","providerEnvVars","resolveProvider","suppliedProviderEnv","dedent","_taggedTemplateLiteral","getLogger","envEditsFor","currency_server_test_default","META","currency_server_default","buyPageSnippet","STRIPE_PRODUCTS","STRIPE_PRICES","withPocketbase","migrationDelay","getMigrationFile","normalizeCurrency","normalizeCurrencies","normalizeCountry","sitePath","ensureSiteBusiness","modifyEnv","addNavItemToScript","modifyOutcomeToFile","SvelteFile","modifyLayoutServerCurrency","modifyLayoutSvelteCurrency","modifyHooksServerCurrency","modifyRootLayoutCurrencySelect","modifyWuchaleJsFiles","TRANSLATED_LIB_FILES","modifyUserSignup","ensureCollectionFields","createCollectionIdempotent","fs","path","Stripe","setupShopify","logger","options","variantId","creates","BILLING_NAV_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","addItemToNavUser","file","navUserSnippet","wasAdded","tryAdd","run","result","source","title","url","icon","iconImportPath","fn","modifyNavUser","navUserPath","newNavUserSnippet","syncUsersToStripeCustomers","stripe","stripeSecretKey","users","pb","existing","linkedUserIds","c","user","matching","label","customer","isExistingCustomer","error","paymentMethods","paymentMethod","defaultPaymentMethod","createTestProductAndPrice","products","product","prices","getProductAndPriceById","price","priceId","_templateObject","pushMigrationCreates","created","migrationFile","collectionName","action","paymentPageSnippet","setupStripe","stripePriceId","isAppMode","modifies","pushResult","create","spec","customersResult","stripeCustomersCollection","paymentMethodsResult","stripePaymentMethodsCollection","transactionsResult","syncResult","userSignupPath","setupWhatsApp","business","given","wuchaleConfig","edit","createsServerRaw","serverCreates","filesFromGlob","unitTests","a","b","hasVitest","pkg","root","generate","provider","envPath","envVars","modifyEnvVarsFiles","siteExisted","siteFile","currency","country","currencies","layoutPath","layoutServerPath","layoutServer","hooksServerPath","rootLayoutPath","env","setup"],"sources":["../../src/patterns/enable/payments/runtime/setup-shopify.ts","../../src/patterns/enable/payments/modifies/modify-nav-user.ts","../../src/patterns/enable/payments/runtime/stripe.ts","../../src/patterns/enable/payments/runtime/setup-stripe.ts","../../src/patterns/enable/payments/runtime/setup-whatsapp.ts","../../src/patterns/enable/payments/generate.runtime.ts"],"sourcesContent":["import type { Options, Result } from \"../../../../core/types\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { buyPageSnippet } from \"../shopify-page\";\n\n/**\n * Shopify keeps products, customers and checkout on its side, so past the env\n * there is only the demo page, and only when a variant to sell was given.\n */\nexport async function setupShopify(options: Options) {\n const logger = getLogger(options);\n const variantId =\n typeof options.input.demoId === \"string\" ? options.input.demoId.trim() : \"\";\n\n const creates = [];\n if (variantId) {\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: buyPageSnippet(variantId),\n status: \"success\" as const,\n });\n }\n\n return {\n creates,\n modifies: [],\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BILLING_NAV_SNIPPET = [\n \"import CreditCardIcon from '@lucide/svelte/icons/credit-card';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Billing', url: '/billing', icon: CreditCardIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Billing nav item to nav-user.svelte:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Billing entry:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Billing\",\n \"/billing\",\n \"CreditCardIcon\",\n \"@lucide/svelte/icons/credit-card\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import Stripe from \"stripe\";\nimport type PocketBase from \"pocketbase\";\nimport type { Logger } from \"../../../../core/logger\";\n\nexport interface StripeTestFixture {\n product: Stripe.Product;\n price: Stripe.Price;\n existing: boolean;\n}\n\nexport interface SyncUsersResult {\n total: number;\n linked: number;\n created: number;\n reused: number;\n skipped: number;\n}\n\nexport async function syncUsersToStripeCustomers(\n pb: PocketBase,\n stripeSecretKey: string,\n logger: Logger,\n): Promise<SyncUsersResult> {\n const stripe = new Stripe(stripeSecretKey);\n const users = await pb.collection(\"users\").getFullList<{\n id: string;\n email?: string;\n name?: string;\n phone?: string;\n }>();\n\n const existing = await pb\n .collection(\"stripe_customers\")\n .getFullList<{ id: string; user: string }>();\n const linkedUserIds = new Set(existing.map((c) => c.user));\n\n const result: SyncUsersResult = {\n total: users.length,\n linked: linkedUserIds.size,\n created: 0,\n reused: 0,\n skipped: 0,\n };\n\n for (const user of users) {\n if (linkedUserIds.has(user.id)) {\n result.skipped += 1;\n continue;\n }\n\n // A user made with a phone number may have no email to match on.\n const matching = user.email\n ? await stripe.customers.list({\n email: user.email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n })\n : { data: [] };\n const label = user.email || user.id;\n\n let customer: Stripe.Customer;\n let isExistingCustomer = false;\n\n if (matching.data.length > 0) {\n customer = matching.data[0];\n isExistingCustomer = true;\n result.reused += 1;\n logger.info(`Reusing Stripe customer ${customer.id} for ${label}`);\n } else {\n customer = await stripe.customers.create(\n user.email\n ? { email: user.email }\n : { name: user.name || undefined, phone: user.phone || undefined },\n );\n result.created += 1;\n logger.info(`Created Stripe customer ${customer.id} for ${label}`);\n }\n\n try {\n await pb.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n } catch (error) {\n logger.info(\n `Failed to create stripe_customers row for ${label}: ${(error as Error).message}`,\n );\n continue;\n }\n\n if (!isExistingCustomer) {\n continue;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n { type: \"card\", allow_redisplay: \"always\" },\n );\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === \"unspecified\") continue;\n try {\n await pb.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n } catch {}\n }\n\n const defaultPaymentMethod =\n customer.invoice_settings?.default_payment_method;\n if (defaultPaymentMethod) {\n try {\n await pb.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method:\n typeof defaultPaymentMethod === \"string\"\n ? defaultPaymentMethod\n : defaultPaymentMethod.id,\n });\n } catch {}\n }\n }\n\n return result;\n}\n\nexport async function createTestProductAndPrice(\n stripeSecretKey: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n\n const products = await stripe.products.search({\n query: `name:\"Test Product\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n const product = products.data[0];\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n if (prices.data.length > 0) {\n return { product, price: prices.data[0], existing: true };\n }\n }\n\n const product = await stripe.products.create({\n name: \"Test Product\",\n metadata: { test: \"true\" },\n });\n\n const price = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n });\n\n return { product, price, existing: false };\n}\n\nexport async function getProductAndPriceById(\n stripeSecretKey: string,\n priceId: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n const price = await stripe.prices.retrieve(priceId, { expand: [\"product\"] });\n const product =\n typeof price.product === \"string\"\n ? await stripe.products.retrieve(price.product)\n : (price.product as Stripe.Product);\n price.product = product.id;\n return { product, price, existing: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport type { File, Options, Result } from \"../../../../core/types\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { suppliedProviderEnv } from \"../../../../core/providers\";\nimport { languageFromPath } from \"../../../../core/util\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../../runtime/pocketbase\";\nimport {\n createCollectionIdempotent,\n ensureCollectionFields,\n} from \"../../../../runtime/collections\";\nimport { STRIPE_PRICES, STRIPE_PRODUCTS } from \"./collections\";\nimport { modifyOutcomeToFile } from \"../../../../runtime/modify-file\";\nimport { modifyNavUser } from \"../modifies/modify-nav-user\";\nimport { modifyUserSignup } from \"../modifies/modify-user-signup\";\nimport {\n createTestProductAndPrice,\n getProductAndPriceById,\n syncUsersToStripeCustomers,\n} from \"./stripe\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n action: \"created\" | \"updated\",\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, action, options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nfunction paymentPageSnippet(priceId: string): string {\n return dedent`\n <script lang=\"ts\">\n import PaymentButton from '#lib/components/payments/payment-button.svelte';\n </script>\n\n <section data-role=\"content\">\n <PaymentButton priceId=\"${priceId}\" />\n </section>\n `;\n}\n\n/**\n * Everything Stripe needs past its env: the catalog and customer collections,\n * the existing users as Stripe customers, a product/price for the demo page,\n * and, with auth, the billing nav item and the signup link to Stripe.\n */\nexport async function setupStripe(options: Options) {\n const stripeSecretKey = suppliedProviderEnv(options).STRIPE_SECRET_KEY ?? \"\";\n const stripePriceId =\n typeof options.input.demoId === \"string\" && options.input.demoId !== \"\"\n ? options.input.demoId\n : undefined;\n\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n await withPocketbase(options.root, async (pb) => {\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n // The catalog: created, or, when a project enabled payments before a\n // field existed, brought up to the spec (the next sync fills the field).\n for (const spec of [STRIPE_PRODUCTS, STRIPE_PRICES]) {\n logger.info(`Creating ${spec.name} collection`);\n const result = await create(spec);\n await pushMigrationCreates(\n creates,\n spec.name,\n \"created\",\n options,\n result.created,\n );\n if (!result.created) {\n creates.push(\n ...(await ensureCollectionFields(pb, spec, options, logger)),\n );\n }\n }\n\n if (isAppMode) {\n logger.info(\"Creating stripe_customers collection\");\n const customersResult = await create({\n name: \"stripe_customers\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripeCustomersCollection = customersResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"created\",\n options,\n customersResult.created,\n );\n\n logger.info(\"Creating stripe_payment_methods collection\");\n const paymentMethodsResult = await create({\n name: \"stripe_payment_methods\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"exp_month\", required: true, type: \"number\" },\n { name: \"exp_year\", required: true, type: \"number\" },\n {\n collectionId: stripeCustomersCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"customer\",\n required: true,\n type: \"relation\",\n cascadeDelete: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripePaymentMethodsCollection = paymentMethodsResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_payment_methods\",\n \"created\",\n options,\n paymentMethodsResult.created,\n );\n\n logger.info(\"Linking default_payment_method on stripe_customers\");\n await pb.collections.update(\"stripe_customers\", {\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n collectionId: stripePaymentMethodsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"default_payment_method\",\n required: false,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"updated\",\n options,\n );\n\n logger.info(\"Creating transactions collection\");\n const transactionsResult = await create({\n name: \"transactions\",\n type: \"base\",\n fields: [\n {\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"stripe_payment_intent\", required: true, type: \"text\" },\n { name: \"amount\", required: true, type: \"number\" },\n { name: \"currency\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"created\", required: true, type: \"date\" },\n { name: \"stripe_charge\", required: true, type: \"text\" },\n { name: \"stripe_customer\", required: true, type: \"text\" },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n { name: \"receipt_url\", required: true, type: \"url\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"transactions\",\n \"created\",\n options,\n transactionsResult.created,\n );\n\n logger.info(\"Syncing existing PocketBase users to Stripe customers\");\n const syncResult = await syncUsersToStripeCustomers(\n pb,\n stripeSecretKey,\n logger,\n );\n logger.info(\n `Synced ${syncResult.total} users (created ${syncResult.created}, reused ${syncResult.reused}, skipped ${syncResult.skipped})`,\n );\n }\n });\n\n if (stripePriceId) {\n logger.info(`Fetching Stripe product/price ${stripePriceId}`);\n } else {\n logger.info(\"Creating test Stripe product and price\");\n }\n const { product, price, existing } = stripePriceId\n ? await getProductAndPriceById(stripeSecretKey, stripePriceId)\n : await createTestProductAndPrice(stripeSecretKey);\n\n if (existing) {\n logger.info(\"Stripe product/price already exists, skipping creation\");\n }\n\n logger.info(\"Seeding Stripe product/price records\");\n await withPocketbase(options.root, async (pb) => {\n try {\n await pb.collection(\"stripe_products\").getOne(product.id);\n } catch (error) {\n await pb.collection(\"stripe_products\").create({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price: product.default_price,\n });\n }\n\n try {\n await pb.collection(\"stripe_prices\").getOne(price.id);\n } catch (error) {\n await pb.collection(\"stripe_prices\").create({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: price.product,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active,\n });\n }\n });\n\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: paymentPageSnippet(price.id),\n status: \"success\",\n });\n\n if (isAppMode) {\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, modifyUserSignup(userSignupPath)),\n );\n }\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../../core/types\";\nimport { InvalidArgumentError } from \"../../../../core/errors\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../../runtime/modify-file\";\nimport type { SiteBusiness } from \"../../../../runtime/site\";\nimport {\n modifyWuchaleJsFiles,\n TRANSLATED_LIB_FILES,\n} from \"../../../../runtime/wuchale-config\";\n\n/**\n * WhatsApp keeps nothing past the env: orders go to the business's chat, and\n * the hosted form they are recorded to is created by the CLI. Every price is\n * in `site.currency`, so a project without one can't take orders: `business`\n * is what `src/lib/site.ts` declares after the shared step wrote it.\n */\nexport async function setupWhatsApp(options: Options, business: SiteBusiness) {\n if (!business.currency) {\n const given = options.input.currency;\n throw new InvalidArgumentError(\n given === undefined || given === \"\"\n ? \"Payments on WhatsApp need the business's currency, the one it prices in (an ISO 4217 code such as MXN or EUR). Pass --currency, or set `currency` in src/lib/site.ts.\"\n : `${String(given)} is not an ISO 4217 currency code, such as MXN or EUR.`,\n );\n }\n const modifies: File[] = [];\n\n // The order message is text a visitor sends, so with wuchale on it is\n // translated like the pages: the js adapter has to be told about the module.\n const wuchaleConfig = path.join(options.root, \"wuchale.config.js\");\n if (fs.existsSync(wuchaleConfig)) {\n getLogger(options).info(\"Adding src/lib/order.ts to wuchale's js adapter\");\n const edit = modifyOutcomeToFile(\n wuchaleConfig,\n modifyWuchaleJsFiles(wuchaleConfig, TRANSLATED_LIB_FILES),\n );\n if (edit) modifies.push(edit);\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","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n providerEnvVars,\n resolveProvider,\n suppliedProviderEnv,\n} from \"../../../core/providers\";\nimport { filesFromGlob, mergeResults } from \"../../../core/util\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnv } from \"../../../runtime/env\";\nimport {\n ensureSiteBusiness,\n normalizeCountry,\n normalizeCurrencies,\n normalizeCurrency,\n sitePath,\n} from \"../../../runtime/site\";\nimport { envEditsFor, META } from \"./generate\";\nimport { modifyHooksServerCurrency } from \"./modifies/hooks.server\";\nimport { modifyLayoutServerCurrency } from \"./modifies/layout.server\";\nimport { modifyLayoutSvelteCurrency } from \"./modifies/layout.svelte\";\nimport { modifyRootLayoutCurrencySelect } from \"./modifies/root-layout.svelte\";\nimport { setupShopify } from \"./runtime/setup-shopify\";\nimport { setupStripe } from \"./runtime/setup-stripe\";\nimport { setupWhatsApp } from \"./runtime/setup-whatsapp\";\n\nconst createsServerRaw = import.meta.glob<string>(\"./creates-server/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\n/** The server half of the currency store, for a project with a server load. */\nexport function serverCreates(unitTests: boolean): File[] {\n return Object.values(filesFromGlob(createsServerRaw, \"./creates-server/\"))\n .filter((file) => unitTests || !file.path.endsWith(\".test.ts\"))\n .sort((a, b) => a.path.localeCompare(b.path));\n}\n\n/** Whether the project can run a unit test (`vitest` in package.json). */\nexport function hasVitest(root: string): boolean {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(root, \"package.json\"), \"utf8\"),\n ) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return Boolean(pkg.devDependencies?.vitest || pkg.dependencies?.vitest);\n } catch {\n return false;\n }\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const provider = resolveProvider(META, options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(`Writing ${provider.label} credentials to .env`);\n const envPath = path.join(options.root, \".env\");\n pushResult(\n modifyOutcomeToFile(\n envPath,\n modifyEnv(envPath, envEditsFor(provider, suppliedProviderEnv(options))),\n ),\n );\n\n // SvelteKit 3 exposes only declared variables, and only `public: true`\n // ones through `$app/env/public`.\n logger.info(`Declaring ${provider.label} variables in src/env.ts`);\n const envVars = modifyEnvVarsFiles(options.root, providerEnvVars(provider));\n if (envVars.create) creates.push(envVars.create);\n pushResult(envVars.modify);\n\n // What the business declares in src/lib/site.ts: the currency it prices\n // in, the country it is in, and the other currencies it shows prices in.\n // Asked for by the CLI; a value already there is kept.\n const { currency, country, currencies } = options.input;\n const siteExisted = fs.existsSync(sitePath(options.root));\n const { file: siteFile, business } = await ensureSiteBusiness(options, {\n currency: normalizeCurrency(currency) ?? undefined,\n country: normalizeCountry(country) ?? undefined,\n currencies:\n normalizeCurrencies(\n currencies,\n normalizeCurrency(currency) ?? undefined,\n ) ?? undefined,\n });\n if (siteFile) (siteExisted ? modifies : creates).push(siteFile);\n\n logger.info(\"Adding the currency select to the navbar\");\n const layoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"root-layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutPath, modifyRootLayoutCurrencySelect(layoutPath)),\n );\n\n // With a server, the visitor's currency is decided per request and the\n // first render already shows it. A static site (a universal root load) keeps\n // the store's browser-side start.\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n if (fs.existsSync(layoutServerPath)) {\n logger.info(\"Resolving the visitor's currency on the server\");\n const layoutServer = modifyLayoutServerCurrency(layoutServerPath);\n pushResult(modifyOutcomeToFile(layoutServerPath, layoutServer));\n if (layoutServer.status === \"success\") {\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerCurrency(hooksServerPath),\n ),\n );\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyLayoutSvelteCurrency(rootLayoutPath),\n ),\n );\n for (const file of serverCreates(hasVitest(options.root)))\n creates.push(file);\n }\n }\n\n const env: Result = {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n };\n\n const setup =\n provider.id === \"stripe\"\n ? await setupStripe(options)\n : provider.id === \"shopify\"\n ? await setupShopify(options)\n : await setupWhatsApp(options, business);\n\n return mergeResults([env, setup]) satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;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Aa,WAAW,WAAW;GACrC,IAAMC,IAAkBlG,EAAK,KAAKI,EAAQ,MAAM,OAAO,iBAAiB;GACxE,EACEhB,EACE8G,GACA1G,EAA0B0G,CAAe,CAC3C,CACF;GACA,IAAMC,IAAiBnG,EAAK,KAC1BI,EAAQ,MACR,OACA,UACA,gBACF;GACA,EACEhB,EACE+G,GACA5G,EAA2B4G,CAAc,CAC3C,CACF;GACA,KAAK,IAAMxF,KAAQkE,GAAcK,EAAU9E,EAAQ,IAAI,CAAC,GACtD,EAAQ,KAAKO,CAAI;EACrB;CACF;CAEA,IAAMyF,IAAc;EAClB;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB,GAEMC,IACJf,EAAS,OAAO,WACZ,MAAM7B,GAAYrD,CAAO,IACzBkF,EAAS,OAAO,YACd,MAAMpF,EAAaE,CAAO,IAC1B,MAAMmE,GAAcnE,GAASoE,CAAQ;CAE7C,OAAO5G,EAAa,CAACwI,GAAKC,CAAK,CAAC;AAClC"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { Node as e, Project as t, QuoteKind as n, SyntaxKind as r } from "ts-morph";
|
|
2
|
+
//#region src/runtime/load-function.ts
|
|
3
|
+
function i() {
|
|
4
|
+
return new t({
|
|
5
|
+
compilerOptions: { allowJs: !0 },
|
|
6
|
+
manipulationSettings: { quoteKind: n.Single }
|
|
7
|
+
});
|
|
8
|
+
}
|
|
9
|
+
function a(e, t, n) {
|
|
10
|
+
let r = e.getImportDeclarations().find((e) => e.getModuleSpecifierValue() === t);
|
|
11
|
+
if (!r) e.addImportDeclaration({
|
|
12
|
+
namedImports: n,
|
|
13
|
+
moduleSpecifier: t
|
|
14
|
+
});
|
|
15
|
+
else for (let e of n) r.getNamedImports().some((t) => t.getName() === e) || r.addNamedImport(e);
|
|
16
|
+
}
|
|
17
|
+
function o(e, t) {
|
|
18
|
+
t.namedImports?.length && a(e, t.moduleSpecifier, t.namedImports), !e.getImportDeclarations().find((e) => e.getModuleSpecifierValue() === t.moduleSpecifier) && e.addImportDeclaration({
|
|
19
|
+
moduleSpecifier: t.moduleSpecifier,
|
|
20
|
+
defaultImport: t.defaultImport,
|
|
21
|
+
namespaceImport: t.namespaceImport
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
function s(t) {
|
|
25
|
+
if (e.isArrowFunction(t) || e.isFunctionExpression(t)) return t;
|
|
26
|
+
if (e.isParenthesizedExpression(t) || e.isAsExpression(t) || e.isSatisfiesExpression(t)) return s(t.getExpression());
|
|
27
|
+
if (e.isCallExpression(t)) for (let e of t.getArguments()) {
|
|
28
|
+
let t = s(e);
|
|
29
|
+
if (t) return t;
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
function c(e) {
|
|
34
|
+
let t = e.getFunction("load");
|
|
35
|
+
if (t) return t.isExported() ? t : null;
|
|
36
|
+
let n = e.getVariableDeclaration("load");
|
|
37
|
+
if (!n || !n.getVariableStatement()?.isExported()) return null;
|
|
38
|
+
let r = n.getInitializer();
|
|
39
|
+
return r ? s(r) : null;
|
|
40
|
+
}
|
|
41
|
+
function l(t) {
|
|
42
|
+
return e.isArrowFunction(t) || e.isFunctionExpression(t) || e.isFunctionDeclaration(t) || e.isMethodDeclaration(t);
|
|
43
|
+
}
|
|
44
|
+
function u(t, n) {
|
|
45
|
+
let i = n.getStatements(), a = i[i.length - 1];
|
|
46
|
+
return !a || !e.isReturnStatement(a) || n.getDescendantsOfKind(r.ReturnStatement).filter((e) => e.getFirstAncestor(l) === t).length !== 1 ? null : a;
|
|
47
|
+
}
|
|
48
|
+
function d(t) {
|
|
49
|
+
let n = t.getExpression();
|
|
50
|
+
for (; n && e.isParenthesizedExpression(n);) n = n.getExpression();
|
|
51
|
+
return !n || !e.isObjectLiteralExpression(n) ? null : n;
|
|
52
|
+
}
|
|
53
|
+
function f(t, n) {
|
|
54
|
+
return t.getProperties().some((t) => e.isPropertyAssignment(t) || e.isShorthandPropertyAssignment(t) ? t.getName() === n : !1);
|
|
55
|
+
}
|
|
56
|
+
function p(t, n) {
|
|
57
|
+
return t.getProperties().some((t) => e.isSpreadAssignment(t) && t.getExpression().getText() === n);
|
|
58
|
+
}
|
|
59
|
+
function m(t) {
|
|
60
|
+
let n = t.getParameters();
|
|
61
|
+
if (n.length === 0) return { kind: "none" };
|
|
62
|
+
if (n.length > 1) return { kind: "unsupported" };
|
|
63
|
+
let r = n[0];
|
|
64
|
+
if (r.getInitializer() || r.isRestParameter()) return { kind: "unsupported" };
|
|
65
|
+
let i = r.getNameNode();
|
|
66
|
+
return e.isIdentifier(i) ? {
|
|
67
|
+
kind: "identifier",
|
|
68
|
+
name: i.getText(),
|
|
69
|
+
param: r
|
|
70
|
+
} : e.isObjectBindingPattern(i) ? {
|
|
71
|
+
kind: "binding",
|
|
72
|
+
pattern: i,
|
|
73
|
+
param: r
|
|
74
|
+
} : { kind: "unsupported" };
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
77
|
+
export { f as a, i as c, c as i, d as l, a as n, p as o, u as r, m as s, o as t };
|
|
78
|
+
|
|
79
|
+
//# sourceMappingURL=load-function-Dmkhg1pQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-function-Dmkhg1pQ.js","names":["newProject","Project","QuoteKind","ensureNamedImports","existing","sourceFile","d","moduleSpecifier","names","name","ni","ensureImportSpec","spec","unwrapFunction","Node","node","arg","fn","findLoadFunction","declaration","variable","initializer","isFunctionNode","findFinalReturn","statements","body","last","SyntaxKind","r","returnedObject","expression","statement","hasProperty","object","property","hasSpreadOf","expressionText","inspectEventParameter","params","param","nameNode"],"sources":["../../src/runtime/load-function.ts"],"sourcesContent":["import {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrowFunction,\n type Block,\n type FunctionDeclaration,\n type FunctionExpression,\n type ObjectLiteralExpression,\n type ParameterDeclaration,\n type ReturnStatement,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ImportSpec } from \"./ts-morph-helpers\";\n\n/**\n * What the two layout modifiers have in common: finding a SvelteKit `load`,\n * working out how it receives its event, and locating the object it returns.\n */\n\nexport type LoadFunction =\n ArrowFunction | FunctionExpression | FunctionDeclaration;\n\nexport function newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\nexport function ensureNamedImports(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n names: string[],\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({ namedImports: names, moduleSpecifier });\n return;\n }\n for (const name of names) {\n const has = existing.getNamedImports().some((ni) => ni.getName() === name);\n if (!has) existing.addNamedImport(name);\n }\n}\n\nexport function ensureImportSpec(sourceFile: SourceFile, spec: ImportSpec) {\n if (spec.namedImports?.length) {\n ensureNamedImports(sourceFile, spec.moduleSpecifier, spec.namedImports);\n }\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({\n moduleSpecifier: spec.moduleSpecifier,\n defaultImport: spec.defaultImport,\n namespaceImport: spec.namespaceImport,\n });\n}\n\n/** Peel wrappers (`loadFlash(fn)`, `(fn)`, `fn satisfies X`) down to the function. */\nfunction unwrapFunction(node: Node): ArrowFunction | FunctionExpression | null {\n if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) {\n return node;\n }\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isSatisfiesExpression(node)\n ) {\n return unwrapFunction(node.getExpression());\n }\n if (Node.isCallExpression(node)) {\n for (const arg of node.getArguments()) {\n const fn = unwrapFunction(arg);\n if (fn) return fn;\n }\n }\n return null;\n}\n\n/** The exported `load`, whether declared as a function or wrapped in a const. */\nexport function findLoadFunction(sourceFile: SourceFile): LoadFunction | null {\n const declaration = sourceFile.getFunction(\"load\");\n if (declaration) {\n return declaration.isExported() ? declaration : null;\n }\n\n const variable = sourceFile.getVariableDeclaration(\"load\");\n if (!variable) return null;\n if (!variable.getVariableStatement()?.isExported()) return null;\n\n const initializer = variable.getInitializer();\n return initializer ? unwrapFunction(initializer) : null;\n}\n\nfunction isFunctionNode(node: Node): boolean {\n return (\n Node.isArrowFunction(node) ||\n Node.isFunctionExpression(node) ||\n Node.isFunctionDeclaration(node) ||\n Node.isMethodDeclaration(node)\n );\n}\n\n/**\n * The single, final `return <expression>` of the load body, or null when the\n * body has early returns — those would need any insertion hoisted above them,\n * and guessing where is worse than refusing.\n */\nexport function findFinalReturn(\n fn: LoadFunction,\n body: Block,\n): ReturnStatement | null {\n const statements = body.getStatements();\n const last = statements[statements.length - 1];\n if (!last || !Node.isReturnStatement(last)) return null;\n\n const returns = body\n .getDescendantsOfKind(SyntaxKind.ReturnStatement)\n .filter((r) => r.getFirstAncestor(isFunctionNode) === fn);\n if (returns.length !== 1) return null;\n\n return last;\n}\n\n/** The object literal a return statement yields, unwrapping parentheses. */\nexport function returnedObject(\n statement: ReturnStatement,\n): ObjectLiteralExpression | null {\n let expression = statement.getExpression();\n while (expression && Node.isParenthesizedExpression(expression)) {\n expression = expression.getExpression();\n }\n if (!expression || !Node.isObjectLiteralExpression(expression)) return null;\n return expression;\n}\n\nexport function hasProperty(\n object: ObjectLiteralExpression,\n name: string,\n): boolean {\n return object.getProperties().some((property) => {\n if (\n Node.isPropertyAssignment(property) ||\n Node.isShorthandPropertyAssignment(property)\n ) {\n return property.getName() === name;\n }\n return false;\n });\n}\n\nexport function hasSpreadOf(\n object: ObjectLiteralExpression,\n expressionText: string,\n): boolean {\n return object\n .getProperties()\n .some(\n (property) =>\n Node.isSpreadAssignment(property) &&\n property.getExpression().getText() === expressionText,\n );\n}\n\n/** How a load receives its event: not at all, by name, or destructured. */\nexport type EventParameter =\n | { kind: \"none\" }\n | { kind: \"identifier\"; name: string; param: ParameterDeclaration }\n | {\n kind: \"binding\";\n pattern: import(\"ts-morph\").ObjectBindingPattern;\n param: ParameterDeclaration;\n }\n | { kind: \"unsupported\" };\n\nexport function inspectEventParameter(fn: LoadFunction): EventParameter {\n const params = fn.getParameters();\n if (params.length === 0) return { kind: \"none\" };\n if (params.length > 1) return { kind: \"unsupported\" };\n\n const param = params[0];\n if (param.getInitializer() || param.isRestParameter()) {\n return { kind: \"unsupported\" };\n }\n const nameNode = param.getNameNode();\n if (Node.isIdentifier(nameNode)) {\n return { kind: \"identifier\", name: nameNode.getText(), param };\n }\n if (Node.isObjectBindingPattern(nameNode)) {\n return { kind: \"binding\", pattern: nameNode, param };\n }\n return { kind: \"unsupported\" };\n}\n"],"mappings":";;AAwBA,SAAgBA,IAAsB;CACpC,OAAO,IAAIC,EAAQ;EACjB,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAWC,EAAU,OAAO;CACtD,CAAC;AACH;AAEA,SAAgBC,EACd,GACA,GACA,GACA;CACA,IAAMC,IAAWC,EACd,sBAAsB,CAAC,CACvB,MAAM,MAAMC,EAAE,wBAAwB,MAAMC,CAAe;CAC9D,IAAI,CAACH,GACH,EAAW,qBAAqB;EAAE,cAAcI;EAAO;CAAgB,CAAC;MAG1E,KAAK,IAAMC,KAAQD,GAEjB,AADYJ,EAAS,gBAAgB,CAAC,CAAC,MAAM,MAAOM,EAAG,QAAQ,MAAMD,CAChE,KAAKL,EAAS,eAAeK,CAAI;AAE1C;AAEA,SAAgBE,EAAiB,GAAwB,GAAkB;CAOzE,AANIC,EAAK,cAAc,UACrBT,EAAmBE,GAAYO,EAAK,iBAAiBA,EAAK,YAAY,GAEvD,GACd,sBAAsB,CAAC,CACvB,MAAM,MAAMN,EAAE,wBAAwB,MAAMM,EAAK,eAChD,KACJP,EAAW,qBAAqB;EAC9B,iBAAiBO,EAAK;EACtB,eAAeA,EAAK;EACpB,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,EAAU,cAAc;CACzC,OAAOD,KAAchB,EAAK,0BAA0BgB,CAAU,IAC5D,IAAaA,EAAW,cAAc;CAGxC,OADI,CAACA,KAAc,CAAChB,EAAK,0BAA0BgB,CAAU,IAAU,OAChEA;AACT;AAEA,SAAgBE,EACd,GACA,GACS;CACT,OAAOC,EAAO,cAAc,CAAC,CAAC,MAAM,MAEhCnB,EAAK,qBAAqBoB,CAAQ,KAClCpB,EAAK,8BAA8BoB,CAAQ,IAEpCA,EAAS,QAAQ,MAAMzB,IAEzB,EACR;AACH;AAEA,SAAgB0B,EACd,GACA,GACS;CACT,OAAOF,EACJ,cAAc,CAAC,CACf,MACE,MACCnB,EAAK,mBAAmBoB,CAAQ,KAChCA,EAAS,cAAc,CAAC,CAAC,QAAQ,MAAME,CAC3C;AACJ;AAaA,SAAgBC,EAAsB,GAAkC;CACtE,IAAMC,IAASrB,EAAG,cAAc;CAChC,IAAIqB,EAAO,WAAW,GAAG,OAAO,EAAE,MAAM,OAAO;CAC/C,IAAIA,EAAO,SAAS,GAAG,OAAO,EAAE,MAAM,cAAc;CAEpD,IAAMC,IAAQD,EAAO;CACrB,IAAIC,EAAM,eAAe,KAAKA,EAAM,gBAAgB,GAClD,OAAO,EAAE,MAAM,cAAc;CAE/B,IAAMC,IAAWD,EAAM,YAAY;CAOnC,OANIzB,EAAK,aAAa0B,CAAQ,IACrB;EAAE,MAAM;EAAc,MAAMA,EAAS,QAAQ;EAAG;CAAM,IAE3D1B,EAAK,uBAAuB0B,CAAQ,IAC/B;EAAE,MAAM;EAAW,SAASA;EAAU;CAAM,IAE9C,EAAE,MAAM,cAAc;AAC/B"}
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
import { r as e } from "./lib-specifier-Cngo1zF_.js";
|
|
2
|
+
import { t } from "./dedent-Gq6Krl4n.js";
|
|
3
|
+
import { t as n } from "./taggedTemplateLiteral-KSUnuvOk.js";
|
|
4
|
+
import { _ as r, a as i, d as a, g as o, i as s, n as c, o as l, p as u, r as d, u as f } from "./ts-morph-helpers-CHI9wAil.js";
|
|
5
|
+
import { t as p } from "./svelte-file-Dv5-bl79.js";
|
|
6
|
+
import { n as m, t as h } from "./compose-handle-BBlamPfx.js";
|
|
7
|
+
import { a as g, c as _, i as v, l as y, r as b, s as x } from "./load-function-Dmkhg1pQ.js";
|
|
8
|
+
import S from "node:fs";
|
|
9
|
+
import C from "node:path";
|
|
10
|
+
import { Node as w, Project as T, QuoteKind as E } from "ts-morph";
|
|
11
|
+
//#region src/patterns/enable/payments/modifies/hooks.server.ts
|
|
12
|
+
var D = "handleCurrency", O = "#lib/currency.server.js", k = t`
|
|
13
|
+
Compose the currency handle into your exported handle:
|
|
14
|
+
|
|
15
|
+
import { sequence } from '@sveltejs/kit/hooks';
|
|
16
|
+
import { handleCurrency } from '#lib/currency.server.js';
|
|
17
|
+
|
|
18
|
+
export const handle = sequence(handleCurrency, /* your existing handle */);
|
|
19
|
+
`, A = t`
|
|
20
|
+
import { handleCurrency } from '#lib/currency.server.js';
|
|
21
|
+
|
|
22
|
+
export const handle = handleCurrency;
|
|
23
|
+
`;
|
|
24
|
+
function j() {
|
|
25
|
+
return new T({
|
|
26
|
+
compilerOptions: { allowJs: !0 },
|
|
27
|
+
manipulationSettings: { quoteKind: E.Single }
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
function M(e) {
|
|
31
|
+
if (!S.existsSync(e)) return S.existsSync(e.replace(/\.ts$/, ".js")) ? {
|
|
32
|
+
status: "failed",
|
|
33
|
+
message: k
|
|
34
|
+
} : (S.mkdirSync(C.dirname(e), { recursive: !0 }), S.writeFileSync(e, A + "\n"), {
|
|
35
|
+
status: "success",
|
|
36
|
+
changed: !0
|
|
37
|
+
});
|
|
38
|
+
let t = S.readFileSync(e, "utf8");
|
|
39
|
+
if (t.includes(D)) return {
|
|
40
|
+
status: "success",
|
|
41
|
+
changed: !1
|
|
42
|
+
};
|
|
43
|
+
let n = j().addSourceFileAtPath(e);
|
|
44
|
+
if (h(n, { expression: D }).status === "unsupported") return {
|
|
45
|
+
status: "failed",
|
|
46
|
+
message: k
|
|
47
|
+
};
|
|
48
|
+
s(n, O, D), l(n);
|
|
49
|
+
let r = n.getFullText();
|
|
50
|
+
return S.writeFileSync(e, r, "utf8"), {
|
|
51
|
+
status: "success",
|
|
52
|
+
changed: r !== t
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function N(t) {
|
|
56
|
+
if (!S.existsSync(t)) return {
|
|
57
|
+
status: "success",
|
|
58
|
+
changed: !1
|
|
59
|
+
};
|
|
60
|
+
let n = S.readFileSync(t, "utf8");
|
|
61
|
+
if (!n.includes(D)) return {
|
|
62
|
+
status: "success",
|
|
63
|
+
changed: !1
|
|
64
|
+
};
|
|
65
|
+
let r = j().addSourceFileAtPath(t);
|
|
66
|
+
if (m(r, D).status === "unsupported") return {
|
|
67
|
+
status: "failed",
|
|
68
|
+
message: `Remove ${D} from the handle chain in src/hooks.server.ts and its import from '${O}'.`
|
|
69
|
+
};
|
|
70
|
+
a(r, e("currency.server.js"), D), c(r), l(r);
|
|
71
|
+
let i = r.getFullText();
|
|
72
|
+
return S.writeFileSync(t, i, "utf8"), {
|
|
73
|
+
status: "success",
|
|
74
|
+
changed: i !== n
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/patterns/enable/payments/modifies/layout.server.ts
|
|
79
|
+
var P = "#lib/currency.server.js", F = ["currency", "rates"], I = t`
|
|
80
|
+
Return the visitor's currency and the day's rates from the root +layout.server.ts load:
|
|
81
|
+
|
|
82
|
+
import { displayRates } from '#lib/currency.server.js';
|
|
83
|
+
|
|
84
|
+
export const load = async ({ locals }) => {
|
|
85
|
+
return {
|
|
86
|
+
currency: locals.currency,
|
|
87
|
+
rates: await displayRates(locals.currency)
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
The load has to be async with a single, final return of an object literal.
|
|
92
|
+
`;
|
|
93
|
+
function L(e) {
|
|
94
|
+
if (!S.existsSync(e)) return {
|
|
95
|
+
status: "not-found",
|
|
96
|
+
message: I
|
|
97
|
+
};
|
|
98
|
+
let t = S.readFileSync(e, "utf8");
|
|
99
|
+
if (t.includes("displayRates(")) return {
|
|
100
|
+
status: "success",
|
|
101
|
+
changed: !1
|
|
102
|
+
};
|
|
103
|
+
let n = _().addSourceFileAtPath(e), r = v(n);
|
|
104
|
+
if (!r) return {
|
|
105
|
+
status: "failed",
|
|
106
|
+
message: I
|
|
107
|
+
};
|
|
108
|
+
let i = r.getBody();
|
|
109
|
+
if (!i || !w.isBlock(i) || !r.isAsync()) return {
|
|
110
|
+
status: "failed",
|
|
111
|
+
message: I
|
|
112
|
+
};
|
|
113
|
+
let a = x(r);
|
|
114
|
+
if (a.kind === "unsupported") return {
|
|
115
|
+
status: "failed",
|
|
116
|
+
message: I
|
|
117
|
+
};
|
|
118
|
+
let o = b(r, i), c = o && y(o);
|
|
119
|
+
if (!o || !c) return {
|
|
120
|
+
status: "failed",
|
|
121
|
+
message: I
|
|
122
|
+
};
|
|
123
|
+
let u = "locals";
|
|
124
|
+
if (a.kind === "identifier") u = `${a.name}.locals`;
|
|
125
|
+
else if (a.kind === "binding") {
|
|
126
|
+
if (!a.pattern.getElements().map((e) => e.getName()).includes("locals")) {
|
|
127
|
+
let e = a.pattern.getElements().map((e) => e.getText());
|
|
128
|
+
a.pattern.replaceWithText(`{ ${[...e, "locals"].join(", ")} }`);
|
|
129
|
+
}
|
|
130
|
+
} else r.addParameter({ name: "{ locals }" });
|
|
131
|
+
g(c, "currency") || c.addPropertyAssignment({
|
|
132
|
+
name: "currency",
|
|
133
|
+
initializer: `${u}.currency`
|
|
134
|
+
}), g(c, "rates") || c.addPropertyAssignment({
|
|
135
|
+
name: "rates",
|
|
136
|
+
initializer: `await displayRates(${u}.currency)`
|
|
137
|
+
}), s(n, P, "displayRates"), l(n);
|
|
138
|
+
let d = n.getFullText();
|
|
139
|
+
return S.writeFileSync(e, d, "utf8"), {
|
|
140
|
+
status: "success",
|
|
141
|
+
changed: d !== t
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
function R(t) {
|
|
145
|
+
if (!S.existsSync(t)) return {
|
|
146
|
+
status: "success",
|
|
147
|
+
changed: !1
|
|
148
|
+
};
|
|
149
|
+
let n = S.readFileSync(t, "utf8");
|
|
150
|
+
if (!n.includes("displayRates(")) return {
|
|
151
|
+
status: "success",
|
|
152
|
+
changed: !1
|
|
153
|
+
};
|
|
154
|
+
let r = _().addSourceFileAtPath(t), i = v(r), s = i?.getBody(), u = i && s && w.isBlock(s) ? b(i, s) : null, d = u && y(u);
|
|
155
|
+
if (!d) return {
|
|
156
|
+
status: "failed",
|
|
157
|
+
message: `Remove currency and rates from the root +layout.server.ts load and the import from '${P}'.`
|
|
158
|
+
};
|
|
159
|
+
for (let e of F) d.getProperty(e)?.remove();
|
|
160
|
+
a(r, e("currency.server.js"), "displayRates"), o(r, "locals"), c(r), l(r);
|
|
161
|
+
let f = r.getFullText();
|
|
162
|
+
return S.writeFileSync(t, f, "utf8"), {
|
|
163
|
+
status: "success",
|
|
164
|
+
changed: f !== n
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region src/patterns/enable/payments/modifies/layout.svelte.ts
|
|
169
|
+
var z, B = "currency.hydrate(data.currency, data.rates);", V = t(z ||= n(["\n Start the currency store from the layout's data in src/routes/+layout.svelte:\n\n <script lang=\"ts\">\n import { currency } from '#lib/currency.svelte.js';\n\n let { data, children } = $props();\n currency.hydrate(data.currency, data.rates);\n <\/script>\n"]));
|
|
170
|
+
function H(e) {
|
|
171
|
+
if (!S.existsSync(e)) return {
|
|
172
|
+
status: "not-found",
|
|
173
|
+
message: V
|
|
174
|
+
};
|
|
175
|
+
let t = p.fromPath(e);
|
|
176
|
+
return t.toString().includes("currency.hydrate(") ? {
|
|
177
|
+
status: "success",
|
|
178
|
+
changed: !1
|
|
179
|
+
} : t.getScript() ? (t.modifyScript((e) => {
|
|
180
|
+
let { source: t } = r(e, (e) => {
|
|
181
|
+
d(e, [{
|
|
182
|
+
namedImports: ["currency"],
|
|
183
|
+
moduleSpecifier: "#lib/currency.svelte.js"
|
|
184
|
+
}]), i(e, "data");
|
|
185
|
+
let t = e.getVariableStatements().find((e) => e.getText().includes("$props()"));
|
|
186
|
+
t ? e.insertStatements(t.getChildIndex() + 1, B) : e.addStatements(B);
|
|
187
|
+
});
|
|
188
|
+
return t;
|
|
189
|
+
}), t.writeTo(e), {
|
|
190
|
+
status: "success",
|
|
191
|
+
changed: t.hasChanged()
|
|
192
|
+
}) : {
|
|
193
|
+
status: "failed",
|
|
194
|
+
message: V
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
function U(t) {
|
|
198
|
+
if (!S.existsSync(t) || !S.readFileSync(t, "utf8").includes("currency.hydrate(")) return {
|
|
199
|
+
status: "success",
|
|
200
|
+
changed: !1
|
|
201
|
+
};
|
|
202
|
+
let n = p.fromPath(t), i = n.toString().replace(/<script[\s\S]*?<\/script>/g, "");
|
|
203
|
+
return n.modifyScript((t) => {
|
|
204
|
+
let { source: n } = r(t, (t) => {
|
|
205
|
+
for (let e of t.getStatements()) e.getText().includes("currency.hydrate(") && e.remove();
|
|
206
|
+
f(t, e("currency.svelte.js")), u(t, "data", i), c(t);
|
|
207
|
+
});
|
|
208
|
+
return n;
|
|
209
|
+
}), n.writeTo(t), {
|
|
210
|
+
status: "success",
|
|
211
|
+
changed: n.hasChanged()
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
//#endregion
|
|
215
|
+
//#region src/patterns/enable/payments/modifies/root-layout.svelte.ts
|
|
216
|
+
function W(e) {
|
|
217
|
+
return `<Navbar.Item>\n${e}\t<CurrencySelect />\n${e}</Navbar.Item>\n${e}`;
|
|
218
|
+
}
|
|
219
|
+
var G = W(" "), K = t`
|
|
220
|
+
import CurrencySelect from '#lib/components/currency-select.svelte';
|
|
221
|
+
`, q = [
|
|
222
|
+
"Add the currency select inside your <Navbar.List> in the root layout.",
|
|
223
|
+
"",
|
|
224
|
+
"Import to add to the <script> tag:",
|
|
225
|
+
"",
|
|
226
|
+
K,
|
|
227
|
+
"",
|
|
228
|
+
"Markup to add at the end of <Navbar.List>, after the language select if there is one:",
|
|
229
|
+
G
|
|
230
|
+
].join("\n"), J = [
|
|
231
|
+
"Create a root layout that includes a currency select inside <Navbar.List>.",
|
|
232
|
+
"",
|
|
233
|
+
"Import for the <script> tag:",
|
|
234
|
+
"",
|
|
235
|
+
K,
|
|
236
|
+
"",
|
|
237
|
+
"Markup at the end of <Navbar.List>:",
|
|
238
|
+
G
|
|
239
|
+
].join("\n");
|
|
240
|
+
function Y(e) {
|
|
241
|
+
if (!S.existsSync(e)) return {
|
|
242
|
+
status: "not-found",
|
|
243
|
+
message: J
|
|
244
|
+
};
|
|
245
|
+
let t = p.fromPath(e);
|
|
246
|
+
if (t.hasElement("CurrencySelect")) return {
|
|
247
|
+
status: "success",
|
|
248
|
+
changed: !1
|
|
249
|
+
};
|
|
250
|
+
if (!t.hasElement("Navbar.List")) return {
|
|
251
|
+
status: "failed",
|
|
252
|
+
message: q
|
|
253
|
+
};
|
|
254
|
+
let n = t.findElementContaining("Navbar.Item", "LanguageSelect");
|
|
255
|
+
if (n) t.insertAfterElement(n, "<Navbar.Item>\n <CurrencySelect />\n</Navbar.Item>");
|
|
256
|
+
else {
|
|
257
|
+
let e = /^([ \t]*)<\/Navbar\.List>/m.exec(t.toString())?.[1] ?? " ", n = `\t<Navbar.Item>\n${e}\t\t<CurrencySelect />\n${e}\t</Navbar.Item>\n${e}`;
|
|
258
|
+
if (!t.insertBeforeClosingTag("Navbar.List", n)) return {
|
|
259
|
+
status: "failed",
|
|
260
|
+
message: q
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
return t.modifyScript((e) => {
|
|
264
|
+
let { source: t } = r(e, (e) => {
|
|
265
|
+
d(e, [{
|
|
266
|
+
defaultImport: "CurrencySelect",
|
|
267
|
+
moduleSpecifier: "#lib/components/currency-select.svelte"
|
|
268
|
+
}]);
|
|
269
|
+
});
|
|
270
|
+
return t;
|
|
271
|
+
}), t.writeTo(e), {
|
|
272
|
+
status: "success",
|
|
273
|
+
changed: t.hasChanged()
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
function X(t) {
|
|
277
|
+
if (!S.existsSync(t)) return {
|
|
278
|
+
status: "success",
|
|
279
|
+
changed: !1
|
|
280
|
+
};
|
|
281
|
+
let n = S.readFileSync(t, "utf8");
|
|
282
|
+
if (!n.includes("CurrencySelect")) return {
|
|
283
|
+
status: "success",
|
|
284
|
+
changed: !1
|
|
285
|
+
};
|
|
286
|
+
let i = p.fromPath(t);
|
|
287
|
+
i.modifyScript((t) => {
|
|
288
|
+
let { source: n } = r(t, (t) => {
|
|
289
|
+
f(t, e("components/currency-select.svelte")), c(t);
|
|
290
|
+
});
|
|
291
|
+
return n;
|
|
292
|
+
});
|
|
293
|
+
let a = i.toString();
|
|
294
|
+
return a = a.replace(/[ \t]*<Navbar\.Item>\s*<CurrencySelect\s*\/>\s*<\/Navbar\.Item>[ \t]*\r?\n?/g, ""), a = a.replace(/[ \t]*<CurrencySelect\s*\/>[ \t]*\r?\n?/g, ""), S.writeFileSync(t, a, "utf8"), {
|
|
295
|
+
status: "success",
|
|
296
|
+
changed: a !== n
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
//#endregion
|
|
300
|
+
export { L as a, N as c, U as i, X as n, R as o, H as r, M as s, Y as t };
|
|
301
|
+
|
|
302
|
+
//# sourceMappingURL=root-layout.svelte-CUVbnlX-.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"root-layout.svelte-CUVbnlX-.js","names":["MODULE","FAILURE_HINT","FAILURE_HINT","FAILURE_HINT","libModule","_taggedTemplateLiteral","withInMemoryScript","ensurePropsBinding","removeNamedImportIfUnused","removeUnusedBindingElement","ensureNamedImport","ensureBlankLineAfterImports","formatLikeSource","removePropsBindingIfUnused","ensureImports","removeImportByModuleSpecifier","SvelteFile","removeHandle","addHandle","hasProperty","newProject","findLoadFunction","returnedObject","findFinalReturn","inspectEventParameter","fs","path","HANDLE","MODULE$1","FAILURE_HINT$3","HOOKS_SERVER_SNIPPET","project","Project","QuoteKind","modifyHooksServerCurrency","hooksServerPath","original","sourceFile","updated","unmodifyHooksServerCurrency","MODULE","PROPERTIES","FAILURE_HINT$2","modifyLayoutServerCurrency","layoutServerPath","fn","body","Node","event","returned","object","locals","texts","unmodifyLayoutServerCurrency","name","_templateObject","STATEMENT","FAILURE_HINT$1","dedent","modifyLayoutSvelteCurrency","layoutPath","file","out","source","sf","props","statement","unmodifyLayoutSvelteCurrency","markup","snippet","indent","SNIPPET","IMPORT","FAILURE_HINT","NOT_FOUND_HINT","modifyRootLayoutCurrencySelect","language","item","unmodifyRootLayoutCurrencySelect"],"sources":["../../src/patterns/enable/payments/modifies/hooks.server.ts","../../src/patterns/enable/payments/modifies/layout.server.ts","../../src/patterns/enable/payments/modifies/layout.svelte.ts","../../src/patterns/enable/payments/modifies/root-layout.svelte.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { addHandle, removeHandle } from \"../../../../runtime/compose-handle\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\nimport {\n ensureBlankLineAfterImports,\n ensureNamedImport,\n formatLikeSource,\n removeNamedImportIfUnused,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst HANDLE = \"handleCurrency\";\nconst MODULE = \"#lib/currency.server.js\";\n\nconst FAILURE_HINT = dedent`\n Compose the currency handle into your exported handle:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import { handleCurrency } from '#lib/currency.server.js';\n\n export const handle = sequence(handleCurrency, /* your existing handle */);\n`;\n\nconst HOOKS_SERVER_SNIPPET = dedent`\n import { handleCurrency } from '#lib/currency.server.js';\n\n export const handle = handleCurrency;\n`;\n\nfunction project(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/**\n * `handleCurrency` joins the server handle chain so every request knows the\n * currency its visitor reads prices in. Creates `hooks.server.ts` when the\n * project has none.\n */\nexport function modifyHooksServerCurrency(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n // SvelteKit loads the first `hooks.server.*` it finds, and `.js` sorts\n // first, so a new `.ts` beside it would never run.\n if (fs.existsSync(hooksServerPath.replace(/\\.ts$/, \".js\"))) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n fs.mkdirSync(path.dirname(hooksServerPath), { recursive: true });\n fs.writeFileSync(hooksServerPath, HOOKS_SERVER_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(HANDLE)) return { status: \"success\", changed: false };\n\n const sourceFile = project().addSourceFileAtPath(hooksServerPath);\n // Composed first: an unsupported handle leaves the file untouched.\n const composed = addHandle(sourceFile, { expression: HANDLE });\n if (composed.status === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n ensureNamedImport(sourceFile, MODULE, HANDLE);\n formatLikeSource(sourceFile);\n const updated = sourceFile.getFullText();\n fs.writeFileSync(hooksServerPath, updated, \"utf8\");\n return { status: \"success\", changed: updated !== original };\n}\n\n/** Take `handleCurrency` back out of the chain, and its import with it. */\nexport function unmodifyHooksServerCurrency(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (!original.includes(HANDLE)) return { status: \"success\", changed: false };\n\n const sourceFile = project().addSourceFileAtPath(hooksServerPath);\n const removed = removeHandle(sourceFile, HANDLE);\n if (removed.status === \"unsupported\") {\n return {\n status: \"failed\",\n message: `Remove ${HANDLE} from the handle chain in src/hooks.server.ts and its import from '${MODULE}'.`,\n };\n }\n removeNamedImportIfUnused(\n sourceFile,\n libModule(\"currency.server.js\"),\n HANDLE,\n );\n ensureBlankLineAfterImports(sourceFile);\n formatLikeSource(sourceFile);\n const updated = sourceFile.getFullText();\n fs.writeFileSync(hooksServerPath, updated, \"utf8\");\n return { status: \"success\", changed: updated !== original };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n findFinalReturn,\n findLoadFunction,\n hasProperty,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"../../../../runtime/load-function\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\nimport {\n ensureBlankLineAfterImports,\n ensureNamedImport,\n formatLikeSource,\n removeNamedImportIfUnused,\n removeUnusedBindingElement,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst MODULE = \"#lib/currency.server.js\";\nconst PROPERTIES = [\"currency\", \"rates\"] as const;\n\nconst FAILURE_HINT = dedent`\n Return the visitor's currency and the day's rates from the root +layout.server.ts load:\n\n import { displayRates } from '#lib/currency.server.js';\n\n export const load = async ({ locals }) => {\n \treturn {\n \t\tcurrency: locals.currency,\n \t\trates: await displayRates(locals.currency)\n \t};\n };\n\n The load has to be async with a single, final return of an object literal.\n`;\n\n/**\n * The root `+layout.server.ts` returns `currency` (what `handleCurrency`\n * resolved) and `rates` (the day's, when it isn't the business's own), so the\n * root layout can start the store before anything renders.\n *\n * A load that isn't async, has no final object-literal return, or receives\n * its event in a way the helpers can't extend is reported as `failed` with\n * the snippet to paste, and the file is left exactly as it was.\n */\nexport function modifyLayoutServerCurrency(\n layoutServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n return { status: \"not-found\", message: FAILURE_HINT };\n }\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (original.includes(\"displayRates(\")) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutServerPath);\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"failed\", message: FAILURE_HINT };\n const body = fn.getBody();\n if (!body || !Node.isBlock(body) || !fn.isAsync()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n const returned = findFinalReturn(fn, body);\n const object = returned && returnedObject(returned);\n if (!returned || !object) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n // Where `locals` comes from: the destructured parameter, the event's\n // property, or a parameter added for it.\n let locals = \"locals\";\n if (event.kind === \"identifier\") {\n locals = `${event.name}.locals`;\n } else if (event.kind === \"binding\") {\n const names = event.pattern.getElements().map((e) => e.getName());\n if (!names.includes(\"locals\")) {\n const texts = event.pattern.getElements().map((e) => e.getText());\n event.pattern.replaceWithText(`{ ${[...texts, \"locals\"].join(\", \")} }`);\n }\n } else {\n fn.addParameter({ name: \"{ locals }\" });\n }\n\n // After any spread, so nothing in it can shadow these.\n if (!hasProperty(object, \"currency\")) {\n object.addPropertyAssignment({\n name: \"currency\",\n initializer: `${locals}.currency`,\n });\n }\n if (!hasProperty(object, \"rates\")) {\n object.addPropertyAssignment({\n name: \"rates\",\n initializer: `await displayRates(${locals}.currency)`,\n });\n }\n ensureNamedImport(sourceFile, MODULE, \"displayRates\");\n formatLikeSource(sourceFile);\n const updated = sourceFile.getFullText();\n fs.writeFileSync(layoutServerPath, updated, \"utf8\");\n return { status: \"success\", changed: updated !== original };\n}\n\n/** Take `currency` and `rates` back out of the root layout's data. */\nexport function unmodifyLayoutServerCurrency(\n layoutServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (!original.includes(\"displayRates(\")) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutServerPath);\n const fn = findLoadFunction(sourceFile);\n const body = fn?.getBody();\n const returned =\n fn && body && Node.isBlock(body) ? findFinalReturn(fn, body) : null;\n const object = returned && returnedObject(returned);\n if (!object) {\n return {\n status: \"failed\",\n message: `Remove currency and rates from the root +layout.server.ts load and the import from '${MODULE}'.`,\n };\n }\n for (const name of PROPERTIES) {\n object.getProperty(name)?.remove();\n }\n removeNamedImportIfUnused(\n sourceFile,\n libModule(\"currency.server.js\"),\n \"displayRates\",\n );\n removeUnusedBindingElement(sourceFile, \"locals\");\n ensureBlankLineAfterImports(sourceFile);\n formatLikeSource(sourceFile);\n const updated = sourceFile.getFullText();\n fs.writeFileSync(layoutServerPath, updated, \"utf8\");\n return { status: \"success\", changed: updated !== original };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\nimport {\n ensureBlankLineAfterImports,\n ensureImports,\n ensurePropsBinding,\n removeImportByModuleSpecifier,\n removePropsBindingIfUnused,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst STATEMENT = \"currency.hydrate(data.currency, data.rates);\";\n\nconst FAILURE_HINT = dedent`\n Start the currency store from the layout's data in src/routes/+layout.svelte:\n\n <script lang=\"ts\">\n \timport { currency } from '#lib/currency.svelte.js';\n\n \tlet { data, children } = $props();\n \tcurrency.hydrate(data.currency, data.rates);\n </script>\n`;\n\n/**\n * The root `+layout.svelte` hands the store what the server resolved, before\n * any child renders: the first render already shows the visitor's currency,\n * on the server and in the browser alike.\n */\nexport function modifyLayoutSvelteCurrency(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: FAILURE_HINT };\n }\n const file = SvelteFile.fromPath(layoutPath);\n if (file.toString().includes(\"currency.hydrate(\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) return { status: \"failed\", message: FAILURE_HINT };\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"currency\"],\n moduleSpecifier: \"#lib/currency.svelte.js\",\n },\n ]);\n ensurePropsBinding(sf, \"data\");\n // Right after the props, which it reads.\n const props = sf\n .getVariableStatements()\n .find((statement) => statement.getText().includes(\"$props()\"));\n if (props) {\n sf.insertStatements(props.getChildIndex() + 1, STATEMENT);\n } else {\n sf.addStatements(STATEMENT);\n }\n });\n return out;\n });\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n\n/** Take the hydration back out, and the import and `data` prop if nothing else reads them. */\nexport function unmodifyLayoutSvelteCurrency(\n layoutPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(layoutPath, \"utf8\");\n if (!original.includes(\"currency.hydrate(\")) {\n return { status: \"success\", changed: false };\n }\n const file = SvelteFile.fromPath(layoutPath);\n const markup = file.toString().replace(/<script[\\s\\S]*?<\\/script>/g, \"\");\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const statement of sf.getStatements()) {\n if (statement.getText().includes(\"currency.hydrate(\"))\n statement.remove();\n }\n removeImportByModuleSpecifier(sf, libModule(\"currency.svelte.js\"));\n removePropsBindingIfUnused(sf, \"data\", markup);\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\nimport {\n ensureBlankLineAfterImports,\n ensureImports,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\n\n/** The item, indented like the list it joins; `indent` is the list's closing tag's. */\nfunction snippet(indent: string): string {\n return `<Navbar.Item>\\n${indent}\\t<CurrencySelect />\\n${indent}</Navbar.Item>\\n${indent}`;\n}\n\nconst SNIPPET = snippet(\"\\t\\t\\t\");\n\nconst IMPORT = dedent`\n import CurrencySelect from '#lib/components/currency-select.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the currency select inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Import to add to the <script> tag:\",\n \"\",\n IMPORT,\n \"\",\n \"Markup to add at the end of <Navbar.List>, after the language select if there is one:\",\n SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes a currency select inside <Navbar.List>.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT,\n \"\",\n \"Markup at the end of <Navbar.List>:\",\n SNIPPET,\n].join(\"\\n\");\n\n/**\n * The currency select goes in the navbar beside the language select, when\n * there is one, else as the last item. It renders nothing until the business\n * offers a second currency, so the layout gains it with payments.\n */\nexport function modifyRootLayoutCurrencySelect(\n layoutPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"CurrencySelect\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n const language = file.findElementContaining(\"Navbar.Item\", \"LanguageSelect\");\n if (language) {\n // On the line after the language select's item; the helper indents it.\n file.insertAfterElement(\n language,\n \"<Navbar.Item>\\n\\t<CurrencySelect />\\n</Navbar.Item>\",\n );\n } else {\n // The closing tag's own indentation already precedes the insertion point,\n // so the item starts one level in and hands that indentation back.\n const indent =\n /^([ \\t]*)<\\/Navbar\\.List>/m.exec(file.toString())?.[1] ?? \"\\t\\t\";\n const item = `\\t<Navbar.Item>\\n${indent}\\t\\t<CurrencySelect />\\n${indent}\\t</Navbar.Item>\\n${indent}`;\n if (!file.insertBeforeClosingTag(\"Navbar.List\", item))\n return { status: \"failed\", message: FAILURE_HINT };\n }\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"CurrencySelect\",\n moduleSpecifier: \"#lib/components/currency-select.svelte\",\n },\n ]);\n });\n return out;\n });\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n\n/** Take the currency select (and the nav item around it) back out. */\nexport function unmodifyRootLayoutCurrencySelect(\n layoutPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(layoutPath, \"utf8\");\n if (!original.includes(\"CurrencySelect\")) {\n return { status: \"success\", changed: false };\n }\n const file = SvelteFile.fromPath(layoutPath);\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(\n sf,\n libModule(\"components/currency-select.svelte\"),\n );\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n let updated = file.toString();\n updated = updated.replace(\n /[ \\t]*<Navbar\\.Item>\\s*<CurrencySelect\\s*\\/>\\s*<\\/Navbar\\.Item>[ \\t]*\\r?\\n?/g,\n \"\",\n );\n updated = updated.replace(/[ \\t]*<CurrencySelect\\s*\\/>[ \\t]*\\r?\\n?/g, \"\");\n fs.writeFileSync(layoutPath, updated, \"utf8\");\n return { status: \"success\", changed: updated !== original };\n}\n"],"mappings":";;;;;;;;;;;AAcA,IAAM2B,IAAS,kBACT3B,IAAS,2BAETC,IAAe,CAAM;;;;;;;GASrB6B,IAAuB,CAAM;;;;;AAMnC,SAASC,IAAmB;CAC1B,OAAO,IAAIC,EAAQ;EACjB,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAWC,EAAU,OAAO;CACtD,CAAC;AACH;AAOA,SAAgBC,EACd,GACe;CACf,IAAI,CAACT,EAAG,WAAWU,CAAe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