@velastack/patterns 0.8.0 → 0.10.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/_page-B6yd6_Vl.js +6 -0
- package/dist/chunks/_page-B6yd6_Vl.js.map +1 -0
- 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-BrOPb9tW.js +175 -0
- package/dist/chunks/generate-BrOPb9tW.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-DuDcKDUl.js +162 -0
- package/dist/chunks/generate.runtime-DuDcKDUl.js.map +1 -0
- package/dist/chunks/{generate.runtime-Dt3Edp8-.js → generate.runtime-J2lLMjDn.js} +97 -126
- package/dist/chunks/generate.runtime-J2lLMjDn.js.map +1 -0
- package/dist/chunks/generate.runtime-nyJ6v56q.js +64 -0
- package/dist/chunks/generate.runtime-nyJ6v56q.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/modify-nav-user-iUpv2lm-.js +53 -0
- package/dist/chunks/modify-nav-user-iUpv2lm-.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.d.ts +156 -2
- package/dist/index.js +1972 -1807
- 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
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"collections-BrEA7a62.js","names":["dedent","_templateObject","buyPageSnippet","_taggedTemplateLiteral","variantId","users","stripeCustomers","stripePaymentMethods","STRIPE_PRODUCTS","STRIPE_PRICES","stripeCustomersCollection","stripePaymentMethodsCollection","transactions","PAYMENTS_BASE_COLLECTIONS","PAYMENTS_APP_MODE_COLLECTIONS"],"sources":["../../src/patterns/enable/payments/shopify-page.ts","../../src/patterns/enable/payments/runtime/collections.ts"],"sourcesContent":["import dedent from \"dedent\";\n\n/** The demo page: one Buy button for the variant named on the command line. */\nexport function buyPageSnippet(variantId: string): string {\n return dedent`\n <script lang=\"ts\">\n import BuyButton from '#lib/components/payments/buy-button.svelte';\n </script>\n\n <section data-role=\"content\">\n <BuyButton variantId=\"${variantId}\" />\n </section>\n `;\n}\n","import type { CollectionSpec } from \"../../../../core/types\";\n\nconst users = \"users\";\nconst stripeCustomers = \"stripe_customers\";\nconst stripePaymentMethods = \"stripe_payment_methods\";\n\n/**\n * The Stripe catalog as `sync-stripe-catalog.ts` copies it: the fields the\n * payment and billing pages read, plus what a store page shows (description,\n * images, metadata, the product URL, a price's nickname and lookup key).\n * `setupStripe` creates these and adds any field an older project's\n * collection lacks.\n */\nexport const STRIPE_PRODUCTS: CollectionSpec = {\n name: \"stripe_products\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"name\", required: false, type: \"text\" },\n { name: \"active\", required: false, type: \"text\" },\n { name: \"default_price\", required: false, type: \"text\" },\n { name: \"description\", required: false, type: \"text\" },\n // Stripe's list of image URLs, and its free-form key/value metadata.\n { name: \"images\", required: false, type: \"json\" },\n { name: \"metadata\", required: false, type: \"json\" },\n { name: \"url\", required: false, type: \"text\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n};\n\nexport const STRIPE_PRICES: CollectionSpec = {\n name: \"stripe_prices\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"billing_scheme\", required: false, type: \"text\" },\n { name: \"currency\", required: false, type: \"text\" },\n { name: \"product\", required: false, type: \"text\" },\n { name: \"recurring\", required: false, type: \"json\" },\n { name: \"type\", required: false, type: \"text\" },\n { name: \"unit_amount\", required: false, type: \"number\" },\n { name: \"active\", required: false, type: \"bool\" },\n { name: \"nickname\", required: false, type: \"text\" },\n { name: \"lookup_key\", required: false, type: \"text\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n};\n\nconst stripeCustomersCollection: CollectionSpec = {\n name: stripeCustomers,\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n type: \"text\",\n },\n {\n collectionId: users,\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n collectionId: stripePaymentMethods,\n maxSelect: 1,\n minSelect: 0,\n name: \"default_payment_method\",\n required: false,\n type: \"relation\",\n },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n};\n\nconst stripePaymentMethodsCollection: CollectionSpec = {\n name: stripePaymentMethods,\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: 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: stripeCustomers,\n maxSelect: 1,\n minSelect: 0,\n name: \"customer\",\n required: true,\n type: \"relation\",\n cascadeDelete: true,\n },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n};\n\nconst transactions: CollectionSpec = {\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 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: users,\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\nexport const PAYMENTS_BASE_COLLECTIONS: CollectionSpec[] = [\n STRIPE_PRODUCTS,\n STRIPE_PRICES,\n];\n\nexport const PAYMENTS_APP_MODE_COLL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;AACF,GAEMM,IAA+B;CACnC,MAAM;CACN,MAAM;CACN,QAAQ;EACN;GACE,qBAAqB;GACrB,KAAK;GACL,KAAK;GACL,MAAM;GACN,SAAS;GACT,YAAY;GACZ,UAAU;GACV,MAAM;EACR;EACA;GAAE,MAAM;GAAyB,UAAU;GAAM,MAAM;EAAO;EAC9D;GAAE,MAAM;GAAU,UAAU;GAAM,MAAM;EAAS;EACjD;GAAE,MAAM;GAAY,UAAU;GAAM,MAAM;EAAO;EACjD;GAAE,MAAM;GAAS,UAAU;GAAM,MAAM;EAAO;EAC9C;GAAE,MAAM;GAAS,UAAU;GAAM,MAAM;EAAO;EAC9C;GAAE,MAAM;GAAW,UAAU;GAAM,MAAM;EAAO;EAChD;GAAE,MAAM;GAAiB,UAAU;GAAM,MAAM;EAAO;EACtD;GAAE,MAAM;GAAmB,UAAU;GAAM,MAAM;EAAO;EACxD;GACE,cAAcP;GACd,WAAW;GACX,WAAW;GACX,MAAM;GACN,UAAU;GACV,MAAM;EACR;EACA;GAAE,MAAM;GAAe,UAAU;GAAM,MAAM;EAAM;CACrD;AACF,GAEaQ,IAA8C,CACzDL,GACAC,CACF,GAEaK,IAAkD;CAC7DJ;CACAC;CACAC;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate-6JS05dWK.js","names":["__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_","__import_glob__0_7_","__import_glob__0_8_","__import_glob__0_9_","__import_glob__0_10_","__import_glob__0_11_","__import_glob__0_12_","__import_glob__0_13_","__import_glob__0_14_","__import_glob__0_15_","__import_glob__0_16_","__import_glob__0_17_","__import_glob__0_18_","__import_glob__0_19_","__import_glob__0_20_","__import_glob__0_21_","__import_glob__0_22_","__import_glob__0_23_","__import_glob__0_24_","__import_glob__0_25_","__import_glob__0_26_","__import_glob__0_27_","__import_glob__0_28_","__import_glob__0_29_","__import_glob__0_30_","__import_glob__0_31_","__import_glob__0_32_","__import_glob__0_33_","__import_glob__0_34_","__import_glob__0_35_","__import_glob__0_36_","__import_glob__0_37_","__import_glob__0_38_","__import_glob__0_39_","__import_glob__0_40_","__import_glob__1_0_","__import_glob__1_1_","languageFromPath","filesFromGlob","allProviderPaths","_server_default","confirm_dialog_default","customer_fields_default","dispatch_default","server_test_default$1","use_payment_intent_svelte_default","buy_button_default","stripe_payment_form_default","stripe_constants_default","stripe_event_default","stripe_default","_server_default$1","use_stripe_svelte_default","payment_dialog_default","order_button_default","succeeded_default","currency_svelte_default","shopify_default","currency_select_default","link_stripe_customer_default","server_test_default$6","order_default","server_test_default$5","_server_default$3","server_test_default$3","sync_stripe_customers_default","_layout_server_default","sync_stripe_catalog_default","server_test_default","dispatch_default$1","README_default","PROVIDERS","attached_default","_server_default$2","succeeded_default$1","server_test_default$4","setup_dialog_default","server_test_default$2","order_test_default","setup_button_default","payment_button_default","stripe_customer_default","_page_server_default","_page_default","providersRaw","createsRaw","DEMO_PAGE","providersToRemove","detected","options","match","provider","generate","paths","path"],"sources":["../../src/patterns/disable/payments/generate.ts"],"sourcesContent":["import type { File, Options, Provider, Result } from \"../../../core/types\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { filesFromGlob, languageFromPath } from \"../../../core/util\";\nimport { PROVIDERS } from \"../../enable/payments/generate\";\n\nconst providersRaw = import.meta.glob<string>(\n [\n \"../../enable/payments/providers/**\",\n \"../../enable/payments/providers-app-mode/**\",\n ],\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\n// Shared by every provider: the currency store and its select.\nconst createsRaw = import.meta.glob<string>(\n \"../../enable/payments/creates/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\n// The demo page enable-payments writes at runtime (it carries the price or\n// variant id), so it is in no template tree: without the payment components it\n// would no longer build.\nconst DEMO_PAGE = \"src/routes/(public)/payment/+page.svelte\";\n\n/**\n * The provider whose files to remove: the one detected, else every one.\n * Removing every provider's files is safe, since a missing path is skipped.\n */\nexport function providersToRemove(\n options: Pick<Options, \"providers\">,\n): Provider[] {\n const detected = options.providers?.payments;\n const match = PROVIDERS.filter((provider) => provider.id === detected);\n return match.length > 0 ? match : PROVIDERS;\n}\n\nexport async function generate(options: Options) {\n // Both the plain and the app-mode files go, whatever auth is now: auth may\n // have been turned on or off since payments was enabled.\n const paths = new Set([\n DEMO_PAGE,\n ...Object.keys(filesFromGlob(createsRaw, \"../../enable/payments/creates/\")),\n ]);\n for (const provider of providersToRemove(options)) {\n for (const path of allProviderPaths(providersRaw, provider.id)) {\n paths.add(path);\n }\n }\n\n const deletes: File[] = [...paths].sort().map((path) => ({\n path,\n language: languageFromPath(path),\n content: \"\",\n status: \"success\",\n }));\n\n return {\n creates: [],\n modifies: [],\n deletes,\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;AAKA,IAAM0F,IAAe,uBAAA,OAAA;CAAA,yFAAA1F;CAAA,8DAAAC;CAAA,4FAAAC;CAAA,4FAAAC;CAAA,4FAAAC;CAAA,0FAAAC;CAAA,iGAAAC;CAAA,mGAAAC;CAAA,2FAAAC;CAAA,4DAAAC;CAAA,4EAAAC;CAAA,mFAAAC;CAAA,0FAAAC;CAAA,8FAAAC;CAAA,gFAAAC;CAAA,0FAAAC;CAAA,4GAAAC;CAAA,0GAAAC;CAAA,oFAAAC;CAAA,+FAAAC;CAAA,4FAAAC;CAAA,kEAAAC;CAAA,6DAAAC;CAAA,mGAAAC;CAAA,mGAAAC;CAAA,qFAAAC;CAAA,6FAAAC;CAAA,8FAAAC;CAAA,8FAAAC;CAAA,4FAAAC;CAAA,yFAAAC;CAAA,sFAAAC;CAAA,mGAAAC;CAAA,uGAAAC;CAAA,iGAAAC;CAAA,qGAAAC;CAAA,mGAAAC;CAAA,qHAAAC;CAAA,mHAAAC;CAAA,kHAAAC;CAAA,qHAAAC;AAMrB,CAAA,GAGMmD,IAAa,uBAAA,OAAA;CAAA,2EAAAlD;CAAA,4DAAAC;AAGnB,CAAA,GAKMkD,IAAY;AAMlB,SAAgBC,EACd,GACY;CACZ,IAAMC,IAAWC,EAAQ,WAAW,UAC9BC,IAAQnB,EAAU,QAAQ,MAAaoB,EAAS,OAAOH,CAAQ;CACrE,OAAOE,EAAM,SAAS,IAAIA,IAAQnB;AACpC;AAEA,eAAsBqB,EAAS,GAAkB;CAG/C,IAAMC,oBAAQ,IAAI,IAAI,CACpBP,GACA,GAAG,OAAO,KAAKhD,EAAc+C,GAAY,gCAAgC,CAAC,CAC5E,CAAC;CACD,KAAK,IAAMM,KAAYJ,EAAkBE,CAAO,GAC9C,KAAK,IAAMK,KAAQvD,EAAiB6C,GAAcO,EAAS,EAAE,GAC3D,EAAM,IAAIG,CAAI;CAWlB,OAAO;EACL,SAAS,CAAC;EACV,UAAU,CAAC;EACX,SAVsB,CAAC,GAAGD,CAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,OAAU;GACvD;GACA,UAAUxD,EAAiByD,CAAI;GAC/B,SAAS;GACT,QAAQ;EACV,EAKE;EACA,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-BOl3LpPB.js","names":["FAILURE_HINT","NOT_FOUND_HINT","FAILURE_HINT","FAILURE_HINT","dedent","getLogger","withInMemoryScript","formatLikeSource","ensureImports","modifyOutcomeToFile","SvelteFile","probeFirstExisting","VITE_CONFIG_CANDIDATES","fs","path","FAILURE_HINT$3","NOT_FOUND_HINT$1","elementName","text","modifyViteConfig","call","pluginArgs","viteConfigPath","sourceFile","Project","QuoteKind","changed","failed","d","configArg","SyntaxKind","ce","configObj","pluginsProp","pluginsInit","arr","elements","el","sveltekitIndex","newProject","ensureNamedImports","existing","moduleSpecifier","names","name","ni","ensureImportSpec","spec","unwrapFunction","Node","node","arg","fn","findLoadFunction","declaration","variable","initializer","isFunctionNode","findFinalReturn","statements","body","last","r","returnedObject","expression","statement","hasProperty","object","property","hasSpreadOf","expressionText","inspectEventParameter","params","param","nameNode","DEFAULT_LOCALE","WUCHALE_LOCALE","eventName","cmsSnippet","locale","importLine","parts","createdLayoutServer","imports","snippet","FAILURE_HINT$2","modifyLayoutServer","layoutServerPath","event","returned","spreadIndex","returnIndex","destructuring","typeText","FAILURE_HINT$1","modifyLayoutUniversal","layoutPath","dataExpression","element","IMPORT_SNIPPET","MARKUP_SNIPPET","NOT_FOUND_HINT","FAILURE_HINT","modifyLayoutSvelte","file","out","source","sf","readWuchaleLocales","configPath","root","match","locales","m","vitePluginArgs","mode","list","generate","logger","options","modifies","resolveMode","i18n","pushResult","layoutUniversalPath","layoutSveltePath"],"sources":["../../src/patterns/enable/cms/modifies/vite-config.ts","../../src/patterns/enable/cms/modifies/load-function.ts","../../src/patterns/enable/cms/modifies/layout.server.ts","../../src/patterns/enable/cms/modifies/layout.ts","../../src/patterns/enable/cms/modifies/layout.svelte.ts","../../src/patterns/enable/cms/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n type PropertyAssignment,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = [\n \"Add the CMS plugin to your Vite config, ahead of sveltekit():\",\n \"\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the CMS plugin ahead of sveltekit():\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit()],\",\n \"});\",\n].join(\"\\n\");\n\nfunction elementName(text: string): string {\n return text.replace(/\\s/g, \"\");\n}\n\n/**\n * Registers `cms(...)` from `@velastack/cms/vite` in the Vite plugin list, just\n * ahead of `sveltekit()`. Only the plugin array is touched, so the inline\n * `sveltekit({ ... })` shape the templates use is left alone.\n */\nexport function modifyViteConfig(\n viteConfigPath: string,\n pluginArgs = \"\",\n): ModifyOutcome {\n const call = `cms(${pluginArgs})`;\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"@velastack/cms/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"cms\"],\n moduleSpecifier: \"@velastack/cms/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: `[${call}]`,\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (pluginsProp as PropertyAssignment).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as PropertyAssignment).setInitializer(`[${call}]`);\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as ArrayLiteralExpression;\n const elements = arr.getElements();\n const hasCms = elements.some((el) =>\n elementName(el.getText()).startsWith(\"cms(\"),\n );\n\n if (!hasCms) {\n const sveltekitIndex = elements.findIndex((el) =>\n elementName(el.getText()).startsWith(\"sveltekit(\"),\n );\n arr.insertElement(sveltekitIndex === -1 ? 0 : sveltekitIndex, call);\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","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 \"../../../../runtime/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","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n ensureImportSpec,\n ensureNamedImports,\n findFinalReturn,\n findLoadFunction,\n hasProperty,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport interface LayoutServerLocale {\n /**\n * Expression passed as `locale` to `loadCms`, given the name of the load's\n * event parameter: `() => \"'en'\"` or `(event) => \\`getLocale(${event}.url)\\``.\n */\n expression: (eventName: string) => string;\n /** Imports the expression depends on. */\n imports?: ImportSpec[];\n}\n\n/** A single-locale site: the literal default locale. */\nexport const DEFAULT_LOCALE: LayoutServerLocale = {\n expression: () => \"'en'\",\n};\n\n/** A wuchale site: the locale enable-i18n's reroute already resolved from the URL. */\nexport const WUCHALE_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `getLocale(${eventName}.url)`,\n imports: [\n { namedImports: [\"getLocale\"], moduleSpecifier: \"#locales/main.url.js\" },\n ],\n};\n\nfunction cmsSnippet(eventName: string, locale: string): string {\n return dedent`\n const { cms, notFound, gone, redirectTo } = await loadCms(${eventName}, { locale: ${locale} });\n if (redirectTo) redirect(308, redirectTo);\n if (gone) error(410, 'Gone');\n if (notFound) error(404, 'Not found');\n `;\n}\n\nfunction importLine(spec: ImportSpec): string {\n const parts: string[] = [];\n if (spec.defaultImport) parts.push(spec.defaultImport);\n if (spec.namespaceImport) parts.push(`* as ${spec.namespaceImport}`);\n if (spec.namedImports?.length)\n parts.push(`{ ${spec.namedImports.join(\", \")} }`);\n return `import ${parts.join(\", \")} from '${spec.moduleSpecifier}';`;\n}\n\n/**\n * A root `+layout.server.ts` written from scratch, for a project that has\n * none — the static template keeps its layout load universal.\n */\nexport function createdLayoutServer(locale: LayoutServerLocale): string {\n const imports = [\n \"import { error, redirect } from '@sveltejs/kit';\",\n \"import { loadCms } from '#lib/cms.js';\",\n ...(locale.imports ?? []).map(importLine),\n \"import type { LayoutServerLoad } from './$types';\",\n ].join(\"\\n\");\n const snippet = cmsSnippet(\"event\", locale.expression(\"event\"))\n .split(\"\\n\")\n .join(\"\\n\\t\");\n\n return dedent`\n ${imports}\n\n export const load: LayoutServerLoad = async (event) => {\n \t${snippet}\n\n \treturn { cms };\n };\n `.concat(\"\\n\");\n}\n\nconst FAILURE_HINT = [\n \"Call loadCms from the root +layout.server.ts load and return `cms`:\",\n \"\",\n createdLayoutServer(DEFAULT_LOCALE).trimEnd(),\n \"\",\n \"loadCms needs the whole event, so a destructured parameter has to become\",\n \"`event` with the destructuring moved into the body.\",\n].join(\"\\n\");\n\n/**\n * Wires `loadCms` into the root `+layout.server.ts`, creating the file when\n * the project has none:\n *\n * - `loadCms` needs the whole request event, so a destructured parameter is\n * renamed to `event` and the destructuring becomes the first statement.\n * - The tombstone triple (`redirectTo`, `gone`, `notFound`) is handled just\n * before the return.\n * - `cms` is added to the returned object, ahead of any spread so nothing\n * later can shadow it.\n *\n * Anything else — no exported `load`, an expression-bodied arrow, several\n * returns, a non-literal return — is reported as `failed` with the snippet to\n * paste, and the file is left exactly as it was.\n */\nexport function modifyLayoutServer(\n layoutServerPath: string,\n locale: LayoutServerLocale = DEFAULT_LOCALE,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n fs.mkdirSync(path.dirname(layoutServerPath), { recursive: true });\n fs.writeFileSync(layoutServerPath, createdLayoutServer(locale));\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (original.includes(\"loadCms(\")) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutServerPath);\n\n // --- Inspect everything before touching anything. ---\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"failed\", message: FAILURE_HINT };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\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 const eventName = event.kind === \"identifier\" ? event.name : \"event\";\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n if (!hasProperty(object, \"cms\")) {\n const spreadIndex = object\n .getProperties()\n .findIndex((property) => Node.isSpreadAssignment(property));\n if (spreadIndex === -1) {\n object.addShorthandPropertyAssignment({ name: \"cms\" });\n } else {\n object.insertShorthandPropertyAssignment(spreadIndex, { name: \"cms\" });\n }\n }\n\n // insertStatements counts comment lines, which getStatements() skips.\n const returnIndex = body.getStatementsWithComments().indexOf(returned);\n body.insertStatements(\n returnIndex,\n `\\n${cmsSnippet(eventName, locale.expression(eventName))}\\n`,\n );\n\n if (event.kind === \"binding\") {\n const destructuring = event.pattern.getText();\n body.insertStatements(0, `const ${destructuring} = ${eventName};`);\n const typeText = event.param.getTypeNode()?.getText();\n event.param.replaceWithText(\n typeText ? `${eventName}: ${typeText}` : eventName,\n );\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: eventName });\n }\n\n if (!fn.isAsync()) fn.setIsAsync(true);\n\n ensureNamedImports(sourceFile, \"@sveltejs/kit\", [\"error\", \"redirect\"]);\n ensureNamedImports(sourceFile, \"#lib/cms.js\", [\"loadCms\"]);\n for (const spec of locale.imports ?? []) {\n ensureImportSpec(sourceFile, spec);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\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 hasSpreadOf,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Forward the server load's data through the root +layout.ts, so \\`cms\\` reaches\n the page:\n\n export const load = async ({ url, data }) => {\n // ...existing code...\n return { ...data, /* existing keys */ };\n };\n`;\n\n/**\n * Make a universal root \\`+layout.ts\\` forward its server load's data.\n *\n * SvelteKit hands a universal load the server load's result as \\`data\\`, and\n * only what the universal load returns reaches the page. A layout that\n * returns its own object without spreading \\`data\\` — the static template\n * does — would drop \\`cms\\` on the floor once \\`+layout.server.ts\\` exists.\n *\n * No file, or a file without a \\`load\\`, needs nothing: server data flows\n * through on its own.\n */\nexport function modifyLayoutUniversal(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutPath);\n\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"success\", changed: false };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n if (!returned) return { status: \"failed\", message: FAILURE_HINT };\n\n const dataExpression =\n event.kind === \"identifier\" ? `${event.name}.data` : \"data\";\n\n // `return data;` already forwards everything.\n const expression = returned.getExpression();\n if (expression && expression.getText() === dataExpression) {\n return { status: \"success\", changed: false };\n }\n\n const object = returnedObject(returned);\n if (!object) return { status: \"failed\", message: FAILURE_HINT };\n if (hasSpreadOf(object, dataExpression)) {\n return { status: \"success\", changed: false };\n }\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n // First, so the layout's own keys still win over anything the server sent.\n object.insertSpreadAssignment(0, { expression: dataExpression });\n\n if (event.kind === \"binding\") {\n const hasData = event.pattern\n .getElements()\n .some((element) => element.getName() === \"data\");\n if (!hasData) {\n const text = event.pattern.getText();\n event.pattern.replaceWithText(text.replace(/^\\{\\s*/, \"{ data, \"));\n }\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: \"{ data }\" });\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","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 IMPORT_SNIPPET = dedent`\n import { AdminBar } from '@velastack/cms';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<AdminBar />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <AdminBar /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <AdminBar /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/**\n * Mounts `<AdminBar />` at the top level of the root layout, ahead of\n * `{@render children()}` so the bar is in the DOM before the page content.\n * Falls back to appending when the layout has no render tag or slot.\n */\nexport function modifyLayoutSvelte(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(\"AdminBar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { namedImports: [\"AdminBar\"], moduleSpecifier: \"@velastack/cms\" },\n ]);\n });\n return out;\n });\n\n if (!file.insertBeforeChildren(MARKUP_SNIPPET)) {\n file.appendMarkup(MARKUP_SNIPPET);\n }\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\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 { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { resolveMode, type CmsMode } from \"./generate\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport {\n DEFAULT_LOCALE,\n WUCHALE_LOCALE,\n modifyLayoutServer,\n} from \"./modifies/layout.server\";\nimport { modifyLayoutUniversal } from \"./modifies/layout\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\n/** The locale list from `wuchale.config.js`, or null when it cannot be read. */\nexport function readWuchaleLocales(root: string): string[] | null {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return null;\n const match = fs\n .readFileSync(configPath, \"utf8\")\n .match(/locales:\\s*\\[([^\\]]*)\\]/);\n if (!match) return null;\n const locales = [...match[1].matchAll(/['\"]([^'\"]+)['\"]/g)].map((m) => m[1]);\n return locales.length > 0 ? locales : null;\n}\n\n/**\n * Arguments for the `cms()` Vite plugin.\n *\n * A hosted CMS needs the endpoint and locales at build time so media can be\n * downloaded into the prerendered site. An app hosting the backend itself\n * needs nothing: the media steps are no-ops without an endpoint.\n */\nexport function vitePluginArgs(mode: CmsMode, locales: string[]): string {\n if (mode.local) return \"\";\n const list = locales.map((locale) => `'${locale}'`).join(\", \");\n return `{ endpoint: '${mode.endpoint}', locales: [${list}] }`;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const mode = resolveMode(options);\n const i18n = options.features.i18n;\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n const locales = (i18n && readWuchaleLocales(options.root)) || [\"en\"];\n pushResult(\n modifyOutcomeToFile(\n viteConfigPath,\n modifyViteConfig(viteConfigPath, vitePluginArgs(mode, locales)),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const locale = i18n ? WUCHALE_LOCALE : DEFAULT_LOCALE;\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n modifyLayoutServer(layoutServerPath, locale),\n ),\n );\n\n // A universal root layout has to pass the server load's data along, or\n // `cms` never reaches the page. The static template has one.\n logger.info(\"Modifying src/routes/+layout.ts\");\n const layoutUniversalPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutUniversalPath,\n modifyLayoutUniversal(layoutUniversalPath),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutSveltePath, modifyLayoutSvelte(layoutSveltePath)),\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":";;;;;;;;;;;AAYA,IAAMA,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAELC,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAASgB,EAAY,GAAsB;CACzC,OAAOC,EAAK,QAAQ,OAAO,EAAE;AAC/B;AAOA,SAAgBC,EACd,GACA,IAAa,IACE;CACf,IAAMC,IAAO,OAAOC,EAAW;CAC/B,IAAI,CAACR,EAAG,WAAWS,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAa,SAASrB;CAAe;CAOxD,IAAMsB,IAAa,IA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,IAAO9C,IAAiBD,CAIQ,CAC7C,CACF,GAIA2C,EAAO,KAAK,iCAAiC;CAC7C,IAAMM,IAAsB9G,EAAK,KAC/ByG,EAAQ,MACR,OACA,UACA,YACF;CAQA,AAPAI,EACElH,EACEmH,GACA7B,EAAsB6B,CAAmB,CAC3C,CACF,GAEAN,EAAO,KAAK,qCAAqC;CACjD,IAAMO,IAAmB/G,EAAK,KAC5ByG,EAAQ,MACR,OACA,UACA,gBACF;CAKA,OAJAI,EACElH,EAAoBoH,GAAkBtB,EAAmBsB,CAAgB,CAAC,CAC5E,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-Dt3Edp8-.js","names":["InvalidArgumentError","languageFromPath","mergeResults","providerEnvVars","resolveProvider","suppliedProviderEnv","dedent","_taggedTemplateLiteral","getLogger","envEditsFor","META","buyPageSnippet","STRIPE_PRODUCTS","STRIPE_PRICES","withPocketbase","migrationDelay","getMigrationFile","normalizeCurrency","normalizeCurrencies","normalizeCountry","sitePath","ensureSiteBusiness","modifyEnv","addNavItemToScript","modifyOutcomeToFile","SvelteFile","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","hasVitest","pkg","root","generate","provider","envPath","envVars","modifyEnvVarsFiles","siteExisted","siteFile","currency","country","currencies","layoutPath","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 { 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 { 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\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 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":";;;;;;;;;;;;;;;;;;;;;;;AAQA,eAAsBmC,EAAa,GAAkB;CACnD,IAAMC,IAAS5B,EAAU6B,CAAO,GAC1BC,IACJ,OAAOD,EAAQ,MAAM,UAAW,WAAWA,EAAQ,MAAM,OAAO,KAAK,IAAI,IAErEE,IAAU,CAAC;CAWjB,OAVID,MACFF,EAAO,KAAK,+BAA+B,GAC3CG,EAAQ,KAAK;EACX,MAAM;EACN,UAAU;EACV,SAAS5B,EAAe2B,CAAS;EACjC,QAAQ;CACV,CAAC,IAGI;EACL;EACA,UAAU,CAAC;EACX,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF;;;AC7BA,IAAME,IAAsB;CAC1B;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAELC,IAAe;CACnB;CACA;CACAD;AACF,CAAC,CAAC,KAAK,IAAI,GAELE,IAAiB;CACrB;CACA;CACAF;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,S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ACEb,EAAoBkG,GAAYhG,EAA+BgG,CAAU,CAAC,CAC5E;CAEA,IAAMC,IAAc;EAClB;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB,GAEMC,IACJX,EAAS,OAAO,WACZ,MAAMvB,EAAYrD,CAAO,IACzB4E,EAAS,OAAO,YACd,MAAM9E,EAAaE,CAAO,IAC1B,MAAMmE,EAAcnE,GAASoE,CAAQ;CAE7C,OAAOvG,EAAa,CAACyH,GAAKC,CAAK,CAAC;AAClC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-KrQk7mqG.js","names":["isLibSpecifier","getLogger","envEditsFor","planDropsForCollections","providersToRemove","modifyEnvRemove","removeNavItemFromScript","removeStatementWithComments","ensureBlankLineAfterImports","formatLikeSource","modifyOutcomeToFile","SvelteFile","unmodifyRootLayoutCurrencySelect","modifyWuchaleJsFiles","TRANSLATED_LIB_FILES","fs","path","unmodifyNavUser","navUserPath","source","file","wasRemoved","tryRemove","run","result","src","fn","CALL_EXPRESSIONS","unmodifyUserSignup","userSignupPath","originalSource","sourceFile","Project","QuoteKind","module","decl","d","linkFn","s","callStatements","SyntaxKind","ce","call","stmt","STRIPE_COLLECTIONS","generate","isAppMode","options","logger","providers","isStripe","provider","modifies","deletes","pushResult","envPath","layoutPath","envVars","unmodifyEnvVarsFiles","variable","wuchaleConfig"],"sources":["../../src/patterns/disable/payments/modifies/modify-nav-user.ts","../../src/patterns/disable/payments/modifies/modify-user-signup.ts","../../src/patterns/disable/payments/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { removeNavItemFromScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(source);\n let wasRemoved = false;\n\n const tryRemove = (run: (fn: (s: string) => string) => boolean) => {\n if (wasRemoved) return;\n run((src) => {\n const result = removeNavItemFromScript(\n src,\n \"Billing\",\n \"@lucide/svelte/icons/credit-card\",\n );\n if (result.wasRemoved) wasRemoved = true;\n return result.source;\n });\n };\n\n tryRemove((fn) => file.modifyModuleScript(fn));\n if (!wasRemoved) tryRemove((fn) => file.modifyScript(fn));\n\n if (!wasRemoved) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(navUserPath, file.toString(), \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureBlankLineAfterImports,\n formatLikeSource,\n removeStatementWithComments,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { isLibSpecifier } from \"../../../../runtime/lib-specifier\";\n\nconst CALL_EXPRESSIONS = new Set([\n \"linkStripeCustomer.run\",\n // Projects from before the workflow: an inline helper called directly.\n \"linkStripeCustomer\",\n]);\n\nexport function unmodifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n if (!originalSource.includes(\"linkStripeCustomer\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n for (const module of [\"workflows/link-stripe-customer\", \"stripe\"]) {\n const decl = sourceFile\n .getImportDeclarations()\n .find((d) => isLibSpecifier(d.getModuleSpecifierValue(), module));\n if (decl) decl.remove();\n }\n\n const linkFn = sourceFile.getVariableStatement((s) =>\n s.getDeclarations().some((d) => d.getName() === \"linkStripeCustomer\"),\n );\n if (linkFn) linkFn.remove();\n\n const callStatements = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((ce) => CALL_EXPRESSIONS.has(ce.getExpression().getText()));\n for (const call of callStatements) {\n const stmt = call.getFirstAncestorByKind(SyntaxKind.ExpressionStatement);\n // With the two comment lines enable-payments put above it: left behind,\n // they keep the file from matching the stock signup, and enable-whatsapp\n // then refuses to swap it.\n if (stmt) removeStatementWithComments(sourceFile, stmt);\n }\n\n formatLikeSource(sourceFile);\n ensureBlankLineAfterImports(sourceFile);\n sourceFile.saveSync();\n\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 { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnvRemove } from \"../../../runtime/env\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { envEditsFor } from \"../../enable/payments/generate\";\nimport { providersToRemove } from \"./generate\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyRootLayoutCurrencySelect } from \"../../enable/payments/modifies/root-layout.svelte\";\nimport { unmodifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\nimport fs from \"node:fs\";\nimport {\n modifyWuchaleJsFiles,\n TRANSLATED_LIB_FILES,\n} from \"../../../runtime/wuchale-config\";\n\n/** Everything enable-payments creates in PocketBase for Stripe. */\nconst STRIPE_COLLECTIONS = [\n \"transactions\",\n \"stripe_customers\",\n \"stripe_payment_methods\",\n \"stripe_prices\",\n \"stripe_products\",\n];\n\nexport async function generate(options: Options) {\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const providers = providersToRemove(options);\n const isStripe = providers.some((provider) => provider.id === \"stripe\");\n const modifies: File[] = [];\n const deletes: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n const envPath = path.join(options.root, \".env\");\n for (const provider of providers) {\n logger.info(`Stripping ${provider.label} credentials from .env`);\n pushResult(\n modifyOutcomeToFile(\n envPath,\n modifyEnvRemove(envPath, envEditsFor(provider)),\n ),\n );\n }\n\n logger.info(\"Removing the currency select from 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(\n layoutPath,\n unmodifyRootLayoutCurrencySelect(layoutPath),\n ),\n );\n\n logger.info(\"Removing payment variables from src/env.ts\");\n const envVars = unmodifyEnvVarsFiles(\n options.root,\n providers.flatMap((provider) =>\n (provider.env ?? []).map((variable) => variable.key),\n ),\n );\n pushResult(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n // WhatsApp's order message was listed for wuchale; the module goes, so the\n // entry does too.\n const wuchaleConfig = path.join(options.root, \"wuchale.config.js\");\n if (\n providers.some((provider) => provider.id === \"whatsapp\") &&\n fs.existsSync(wuchaleConfig)\n ) {\n logger.info(\"Removing src/lib/order.ts from wuchale's js adapter\");\n pushResult(\n modifyOutcomeToFile(\n wuchaleConfig,\n modifyWuchaleJsFiles(wuchaleConfig, TRANSLATED_LIB_FILES, \"remove\"),\n ),\n );\n }\n\n // The nav item and the signup link exist only in auth's files, which\n // enable-payments edits for Stripe alone.\n if (isStripe && isAppMode) {\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 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, unmodifyUserSignup(userSignupPath)),\n );\n }\n\n // Every Stripe collection is planned, whatever auth is now; one that was\n // never created is planned as missing and left alone. Without a backend\n // (no provider detected, on a Shopify project) there is nothing to drop.\n const collectionDrops =\n isStripe && options.features.backend\n ? await planDropsForCollections(STRIPE_COLLECTIONS, options)\n : [];\n\n return {\n creates: [],\n modifies,\n deletes,\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAKA,SAAgBiB,EAAgB,GAAoC;CAClE,IAAI,CAACF,EAAG,WAAWG,CAAW,GAC5B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAASJ,EAAG,aAAaG,GAAa,MAAM;CAClD,IAAI,CAACC,EAAO,SAAS,UAAU,GAC7B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAO,IAAIT,EAAWQ,CAAM,GAC9BE,IAAa,IAEXC,KAAa,MAAgD;EACjE,AAAID,KACJE,GAAK,MAAQ;GACX,IAAMC,IAASlB,EACbmB,GACA,WACA,kCACF;GAEA,OADID,EAAO,eAAY,IAAa,KAC7BA,EAAO;EAChB,CAAC;CACH;CAUA,OARAF,GAAW,MAAOF,EAAK,mBAAmBM,CAAE,CAAC,GACxCL,KAAYC,GAAW,MAAOF,EAAK,aAAaM,CAAE,CAAC,GAEnDL,KAILN,EAAG,cAAcG,GAAaE,EAAK,SAAS,GAAG,MAAM,GAC9C;EAAE,QAAQ;EAAW,SAAS;CAAK,KAJjC;EAAE,QAAQ;EAAW,SAAS;CAAM;AAK/C;;;AC9BA,IAAMO,oBAAmB,IAAI,IAAI,CAC/B,0BAEA,oBACF,CAAC;AAED,SAAgBC,EAAmB,GAAuC;CACxE,IAAI,CAACb,EAAG,WAAWc,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAiBf,EAAG,aAAac,GAAgB,MAAM;C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,EAAmBC,CAAc,CAAC,CACxE;CACF;CAUA,OAAO;EACL,SAAS,CAAC;EACV;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAZAqB,KAAYH,EAAQ,SAAS,UACzB,MAAM5C,EAAwByC,GAAoBG,CAAO,IACzD,CAAC;CAWP;AACF"}
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
import { r as e } from "./lib-specifier-Cngo1zF_.js";
|
|
2
|
-
import { t } from "./dedent-Gq6Krl4n.js";
|
|
3
|
-
import { _ as n, n as r, r as i, u as a } from "./ts-morph-helpers-CHI9wAil.js";
|
|
4
|
-
import { t as o } from "./svelte-file-Dv5-bl79.js";
|
|
5
|
-
import s from "node:fs";
|
|
6
|
-
//#region src/patterns/enable/payments/modifies/root-layout.svelte.ts
|
|
7
|
-
function c(e) {
|
|
8
|
-
return `<Navbar.Item>\n${e}\t<CurrencySelect />\n${e}</Navbar.Item>\n${e}`;
|
|
9
|
-
}
|
|
10
|
-
var l = c(" "), u = t`
|
|
11
|
-
import CurrencySelect from '#lib/components/currency-select.svelte';
|
|
12
|
-
`, d = [
|
|
13
|
-
"Add the currency select inside your <Navbar.List> in the root layout.",
|
|
14
|
-
"",
|
|
15
|
-
"Import to add to the <script> tag:",
|
|
16
|
-
"",
|
|
17
|
-
u,
|
|
18
|
-
"",
|
|
19
|
-
"Markup to add at the end of <Navbar.List>, after the language select if there is one:",
|
|
20
|
-
l
|
|
21
|
-
].join("\n"), f = [
|
|
22
|
-
"Create a root layout that includes a currency select inside <Navbar.List>.",
|
|
23
|
-
"",
|
|
24
|
-
"Import for the <script> tag:",
|
|
25
|
-
"",
|
|
26
|
-
u,
|
|
27
|
-
"",
|
|
28
|
-
"Markup at the end of <Navbar.List>:",
|
|
29
|
-
l
|
|
30
|
-
].join("\n");
|
|
31
|
-
function p(e) {
|
|
32
|
-
if (!s.existsSync(e)) return {
|
|
33
|
-
status: "not-found",
|
|
34
|
-
message: f
|
|
35
|
-
};
|
|
36
|
-
let t = o.fromPath(e);
|
|
37
|
-
if (t.hasElement("CurrencySelect")) return {
|
|
38
|
-
status: "success",
|
|
39
|
-
changed: !1
|
|
40
|
-
};
|
|
41
|
-
if (!t.hasElement("Navbar.List")) return {
|
|
42
|
-
status: "failed",
|
|
43
|
-
message: d
|
|
44
|
-
};
|
|
45
|
-
let r = t.findElementContaining("Navbar.Item", "LanguageSelect");
|
|
46
|
-
if (r) t.insertAfterElement(r, "<Navbar.Item>\n <CurrencySelect />\n</Navbar.Item>");
|
|
47
|
-
else {
|
|
48
|
-
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}`;
|
|
49
|
-
if (!t.insertBeforeClosingTag("Navbar.List", n)) return {
|
|
50
|
-
status: "failed",
|
|
51
|
-
message: d
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
return t.modifyScript((e) => {
|
|
55
|
-
let { source: t } = n(e, (e) => {
|
|
56
|
-
i(e, [{
|
|
57
|
-
defaultImport: "CurrencySelect",
|
|
58
|
-
moduleSpecifier: "#lib/components/currency-select.svelte"
|
|
59
|
-
}]);
|
|
60
|
-
});
|
|
61
|
-
return t;
|
|
62
|
-
}), t.writeTo(e), {
|
|
63
|
-
status: "success",
|
|
64
|
-
changed: t.hasChanged()
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
function m(t) {
|
|
68
|
-
if (!s.existsSync(t)) return {
|
|
69
|
-
status: "success",
|
|
70
|
-
changed: !1
|
|
71
|
-
};
|
|
72
|
-
let i = s.readFileSync(t, "utf8");
|
|
73
|
-
if (!i.includes("CurrencySelect")) return {
|
|
74
|
-
status: "success",
|
|
75
|
-
changed: !1
|
|
76
|
-
};
|
|
77
|
-
let c = o.fromPath(t);
|
|
78
|
-
c.modifyScript((t) => {
|
|
79
|
-
let { source: i } = n(t, (t) => {
|
|
80
|
-
a(t, e("components/currency-select.svelte")), r(t);
|
|
81
|
-
});
|
|
82
|
-
return i;
|
|
83
|
-
});
|
|
84
|
-
let l = c.toString();
|
|
85
|
-
return l = l.replace(/[ \t]*<Navbar\.Item>\s*<CurrencySelect\s*\/>\s*<\/Navbar\.Item>[ \t]*\r?\n?/g, ""), l = l.replace(/[ \t]*<CurrencySelect\s*\/>[ \t]*\r?\n?/g, ""), s.writeFileSync(t, l, "utf8"), {
|
|
86
|
-
status: "success",
|
|
87
|
-
changed: l !== i
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
//#endregion
|
|
91
|
-
export { m as n, p as t };
|
|
92
|
-
|
|
93
|
-
//# sourceMappingURL=root-layout.svelte-CsJ2QJYi.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"root-layout.svelte-CsJ2QJYi.js","names":["libModule","withInMemoryScript","ensureBlankLineAfterImports","ensureImports","removeImportByModuleSpecifier","SvelteFile","fs","snippet","indent","SNIPPET","IMPORT","FAILURE_HINT","NOT_FOUND_HINT","modifyRootLayoutCurrencySelect","layoutPath","file","language","item","out","source","sf","unmodifyRootLayoutCurrencySelect","original","updated"],"sources":["../../src/patterns/enable/payments/modifies/root-layout.svelte.ts"],"sourcesContent":["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":";;;;;;AAaA,SAASO,EAAQ,GAAwB;CACvC,OAAO,kBAAkBC,EAAO,wBAAwBA,EAAO,kBAAkBA;AACnF;AAEA,IAAMC,IAAUF,EAAQ,KAAQ,GAE1BG,IAAS,CAAM;;GAIfC,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,IAAI;AAOX,SAAgBI,EACd,GACe;CACf,IAAI,CAACP,EAAG,WAAWQ,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAASF;CAAe;CAExD,IAAMG,IAAOV,EAAW,SAASS,CAAU;CAC3C,IA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