@velastack/patterns 0.14.0 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/dist/chunks/{collections-D-xbHi4M.js → collections-B_-NTtLW.js} +2 -2
  2. package/dist/chunks/{collections-D-xbHi4M.js.map → collections-B_-NTtLW.js.map} +1 -1
  3. package/dist/chunks/{constants-DpK-r_m5.js → constants-CTp-0HKk.js} +21 -31
  4. package/dist/chunks/{constants-DpK-r_m5.js.map → constants-CTp-0HKk.js.map} +1 -1
  5. package/dist/chunks/{currency.server-BwuXG0a9.js → currency.server-DOX4Rzyb.js} +2 -2
  6. package/dist/chunks/{currency.server-BwuXG0a9.js.map → currency.server-DOX4Rzyb.js.map} +1 -1
  7. package/dist/chunks/{env-vars-CVn2076k.js → env-vars-BbS_mWyP.js} +3 -3
  8. package/dist/chunks/{env-vars-CVn2076k.js.map → env-vars-BbS_mWyP.js.map} +1 -1
  9. package/dist/chunks/{generate-CuOm66dn.js → generate-4iujJNAW.js} +3 -3
  10. package/dist/chunks/{generate-CuOm66dn.js.map → generate-4iujJNAW.js.map} +1 -1
  11. package/dist/chunks/{generate-BCYvhyF9.js → generate-B4uDCW5D.js} +2 -2
  12. package/dist/chunks/{generate-BCYvhyF9.js.map → generate-B4uDCW5D.js.map} +1 -1
  13. package/dist/chunks/{generate-oZ1QeqPr.js → generate-BJY8AtAp.js} +2 -2
  14. package/dist/chunks/{generate-oZ1QeqPr.js.map → generate-BJY8AtAp.js.map} +1 -1
  15. package/dist/chunks/{generate-F4FDWvFo.js → generate-Bwkx_usZ.js} +2 -2
  16. package/dist/chunks/{generate-F4FDWvFo.js.map → generate-Bwkx_usZ.js.map} +1 -1
  17. package/dist/chunks/{generate-CY_Ii_bz.js → generate-JkvSNTy-.js} +2 -2
  18. package/dist/chunks/{generate-CY_Ii_bz.js.map → generate-JkvSNTy-.js.map} +1 -1
  19. package/dist/chunks/{generate.runtime-mE0knt2T.js → generate.runtime-27KTIg_o.js} +3 -3
  20. package/dist/chunks/{generate.runtime-mE0knt2T.js.map → generate.runtime-27KTIg_o.js.map} +1 -1
  21. package/dist/chunks/{generate.runtime-erWI6j7m.js → generate.runtime-B7XOa9_A.js} +3 -3
  22. package/dist/chunks/{generate.runtime-erWI6j7m.js.map → generate.runtime-B7XOa9_A.js.map} +1 -1
  23. package/dist/chunks/{generate.runtime-Dtae524O.js → generate.runtime-B8-ORwxT.js} +6 -6
  24. package/dist/chunks/{generate.runtime-Dtae524O.js.map → generate.runtime-B8-ORwxT.js.map} +1 -1
  25. package/dist/chunks/{generate.runtime-CqCXFeWH.js → generate.runtime-BFX_8erf.js} +6 -6
  26. package/dist/chunks/{generate.runtime-CqCXFeWH.js.map → generate.runtime-BFX_8erf.js.map} +1 -1
  27. package/dist/chunks/{generate.runtime-cYh0CQ5d.js → generate.runtime-BROXlbeJ.js} +3 -3
  28. package/dist/chunks/{generate.runtime-cYh0CQ5d.js.map → generate.runtime-BROXlbeJ.js.map} +1 -1
  29. package/dist/chunks/{generate.runtime-Bv_16lWi.js → generate.runtime-BU-4sjyu.js} +4 -4
  30. package/dist/chunks/{generate.runtime-Bv_16lWi.js.map → generate.runtime-BU-4sjyu.js.map} +1 -1
  31. package/dist/chunks/{generate.runtime-DZUPtJVF.js → generate.runtime-BXNBWGYr.js} +2 -2
  32. package/dist/chunks/{generate.runtime-DZUPtJVF.js.map → generate.runtime-BXNBWGYr.js.map} +1 -1
  33. package/dist/chunks/{generate.runtime-DICcLOts.js → generate.runtime-BlEy2fFF.js} +3 -3
  34. package/dist/chunks/{generate.runtime-DICcLOts.js.map → generate.runtime-BlEy2fFF.js.map} +1 -1
  35. package/dist/chunks/{generate.runtime-CMuxVUIY.js → generate.runtime-CBVcsole.js} +2 -2
  36. package/dist/chunks/{generate.runtime-CMuxVUIY.js.map → generate.runtime-CBVcsole.js.map} +1 -1
  37. package/dist/chunks/{generate.runtime-CjqX4tDg.js → generate.runtime-CCaCaXNu.js} +2 -2
  38. package/dist/chunks/{generate.runtime-CjqX4tDg.js.map → generate.runtime-CCaCaXNu.js.map} +1 -1
  39. package/dist/chunks/{generate.runtime-CM3bj0nP.js → generate.runtime-Cm75waRD.js} +2 -2
  40. package/dist/chunks/{generate.runtime-CM3bj0nP.js.map → generate.runtime-Cm75waRD.js.map} +1 -1
  41. package/dist/chunks/{generate.runtime-Cg-dfN9B.js → generate.runtime-CuvdtjKc.js} +2 -2
  42. package/dist/chunks/{generate.runtime-Cg-dfN9B.js.map → generate.runtime-CuvdtjKc.js.map} +1 -1
  43. package/dist/chunks/{generate.runtime-TCVlsBbJ.js → generate.runtime-D0lI3Gt8.js} +4 -4
  44. package/dist/chunks/{generate.runtime-TCVlsBbJ.js.map → generate.runtime-D0lI3Gt8.js.map} +1 -1
  45. package/dist/chunks/{generate.runtime-22jW8aVT.js → generate.runtime-D6l6uLiY.js} +2 -2
  46. package/dist/chunks/{generate.runtime-22jW8aVT.js.map → generate.runtime-D6l6uLiY.js.map} +1 -1
  47. package/dist/chunks/{generate.runtime-CsP4c8GY.js → generate.runtime-D77ueFKY.js} +5 -5
  48. package/dist/chunks/{generate.runtime-CsP4c8GY.js.map → generate.runtime-D77ueFKY.js.map} +1 -1
  49. package/dist/chunks/{generate.runtime-CZKIKP3B.js → generate.runtime-D9OC1RXu.js} +2 -2
  50. package/dist/chunks/{generate.runtime-CZKIKP3B.js.map → generate.runtime-D9OC1RXu.js.map} +1 -1
  51. package/dist/chunks/{generate.runtime-pbIrEsa7.js → generate.runtime-DLoYscQO.js} +3 -3
  52. package/dist/chunks/{generate.runtime-pbIrEsa7.js.map → generate.runtime-DLoYscQO.js.map} +1 -1
  53. package/dist/chunks/{generate.runtime-EB8vpc7D.js → generate.runtime-DhSH1o8H.js} +3 -3
  54. package/dist/chunks/{generate.runtime-EB8vpc7D.js.map → generate.runtime-DhSH1o8H.js.map} +1 -1
  55. package/dist/chunks/{generate.runtime-Bz9z0VPR.js → generate.runtime-DiEiFoxR.js} +3 -3
  56. package/dist/chunks/{generate.runtime-Bz9z0VPR.js.map → generate.runtime-DiEiFoxR.js.map} +1 -1
  57. package/dist/chunks/{generate.runtime-C37djibw.js → generate.runtime-Dm7IEo2h.js} +3 -3
  58. package/dist/chunks/{generate.runtime-C37djibw.js.map → generate.runtime-Dm7IEo2h.js.map} +1 -1
  59. package/dist/chunks/{generate.runtime-Db7JwGTb.js → generate.runtime-Dn0_y2iV.js} +4 -4
  60. package/dist/chunks/{generate.runtime-Db7JwGTb.js.map → generate.runtime-Dn0_y2iV.js.map} +1 -1
  61. package/dist/chunks/{generate.runtime-DfHFd8xs.js → generate.runtime-DuAYqKxl.js} +2 -2
  62. package/dist/chunks/{generate.runtime-DfHFd8xs.js.map → generate.runtime-DuAYqKxl.js.map} +1 -1
  63. package/dist/chunks/{generate.runtime-hq8xt0m_.js → generate.runtime-Duw_JI_b.js} +2 -2
  64. package/dist/chunks/{generate.runtime-hq8xt0m_.js.map → generate.runtime-Duw_JI_b.js.map} +1 -1
  65. package/dist/chunks/{generate.runtime-Ct7cG8va.js → generate.runtime-DxyQqNpu.js} +4 -4
  66. package/dist/chunks/{generate.runtime-Ct7cG8va.js.map → generate.runtime-DxyQqNpu.js.map} +1 -1
  67. package/dist/chunks/{generate.runtime-Cry-DBNl.js → generate.runtime-PDnSxiek.js} +6 -6
  68. package/dist/chunks/{generate.runtime-Cry-DBNl.js.map → generate.runtime-PDnSxiek.js.map} +1 -1
  69. package/dist/chunks/{generate.runtime-YFyuyFhh.js → generate.runtime-RTGpwxcS.js} +5 -5
  70. package/dist/chunks/{generate.runtime-YFyuyFhh.js.map → generate.runtime-RTGpwxcS.js.map} +1 -1
  71. package/dist/chunks/{generate.runtime-DkS7CBmK.js → generate.runtime-TQmspB4Z.js} +4 -4
  72. package/dist/chunks/{generate.runtime-DkS7CBmK.js.map → generate.runtime-TQmspB4Z.js.map} +1 -1
  73. package/dist/chunks/{generate.runtime-j_5K3Uue.js → generate.runtime-UtkANHk1.js} +3 -3
  74. package/dist/chunks/{generate.runtime-j_5K3Uue.js.map → generate.runtime-UtkANHk1.js.map} +1 -1
  75. package/dist/chunks/{generate.runtime-B06rPt_j.js → generate.runtime-VMTLHWLk.js} +7 -7
  76. package/dist/chunks/{generate.runtime-B06rPt_j.js.map → generate.runtime-VMTLHWLk.js.map} +1 -1
  77. package/dist/chunks/{generate.runtime-DhNspd-h.js → generate.runtime-XT_JQlTk.js} +2 -2
  78. package/dist/chunks/{generate.runtime-DhNspd-h.js.map → generate.runtime-XT_JQlTk.js.map} +1 -1
  79. package/dist/chunks/{generate.runtime-CVqPHddZ.js → generate.runtime-XpYi9SlM.js} +2 -2
  80. package/dist/chunks/{generate.runtime-CVqPHddZ.js.map → generate.runtime-XpYi9SlM.js.map} +1 -1
  81. package/dist/chunks/{generate.runtime-CyWuhV6m.js → generate.runtime-ZgLxGWuy.js} +3 -3
  82. package/dist/chunks/{generate.runtime-CyWuhV6m.js.map → generate.runtime-ZgLxGWuy.js.map} +1 -1
  83. package/dist/chunks/{generate.runtime-BgGeOqYG.js → generate.runtime-bsuqrKOm.js} +2 -2
  84. package/dist/chunks/{generate.runtime-BgGeOqYG.js.map → generate.runtime-bsuqrKOm.js.map} +1 -1
  85. package/dist/chunks/{generate.runtime-Cco2mFW2.js → generate.runtime-nXjFqHyb.js} +4 -4
  86. package/dist/chunks/{generate.runtime-Cco2mFW2.js.map → generate.runtime-nXjFqHyb.js.map} +1 -1
  87. package/dist/chunks/{generate.runtime-BSxSHNh7.js → generate.runtime-sjFAWbZc.js} +6 -6
  88. package/dist/chunks/{generate.runtime-BSxSHNh7.js.map → generate.runtime-sjFAWbZc.js.map} +1 -1
  89. package/dist/chunks/{generate.runtime-Cxg1b_BK.js → generate.runtime-wiWdXXPi.js} +4 -4
  90. package/dist/chunks/{generate.runtime-Cxg1b_BK.js.map → generate.runtime-wiWdXXPi.js.map} +1 -1
  91. package/dist/chunks/{i18n-BHCytiiO.js → i18n-mnzzcYhz.js} +2 -2
  92. package/dist/chunks/{i18n-BHCytiiO.js.map → i18n-mnzzcYhz.js.map} +1 -1
  93. package/dist/chunks/{modify-file-CRZ_gMg0.js → modify-file-CgJIza72.js} +2 -2
  94. package/dist/chunks/{modify-file-CRZ_gMg0.js.map → modify-file-CgJIza72.js.map} +1 -1
  95. package/dist/chunks/{pocketbase-gUn2UrDd.js → pocketbase-S8lUt0nI.js} +2 -2
  96. package/dist/chunks/{pocketbase-gUn2UrDd.js.map → pocketbase-S8lUt0nI.js.map} +1 -1
  97. package/dist/chunks/{providers-BB3Z2TrN.js → providers-CDUFaOeQ.js} +2 -2
  98. package/dist/chunks/{providers-BB3Z2TrN.js.map → providers-CDUFaOeQ.js.map} +1 -1
  99. package/dist/chunks/{shared-DE-J_b1j.js → shared-BjTRQ5QH.js} +2 -2
  100. package/dist/chunks/{shared-DE-J_b1j.js.map → shared-BjTRQ5QH.js.map} +1 -1
  101. package/dist/chunks/{site-B9hDxucR.js → site-C8Wcg6LT.js} +2 -2
  102. package/dist/chunks/{site-B9hDxucR.js.map → site-C8Wcg6LT.js.map} +1 -1
  103. package/dist/chunks/{table-core-Dua6QnXM.js → table-core-RvMjoXpT.js} +2 -2
  104. package/dist/chunks/{table-core-Dua6QnXM.js.map → table-core-RvMjoXpT.js.map} +1 -1
  105. package/dist/chunks/{test-setup-gJdzWWs_.js → test-setup-CpjhQSl-.js} +3 -3
  106. package/dist/chunks/{test-setup-gJdzWWs_.js.map → test-setup-CpjhQSl-.js.map} +1 -1
  107. package/dist/chunks/{ui-CD61O7Sb.js → ui-CE-8llQS.js} +3 -3
  108. package/dist/chunks/{ui-CD61O7Sb.js.map → ui-CE-8llQS.js.map} +1 -1
  109. package/dist/chunks/{whatsapp-Bt4o4_q2.js → whatsapp-DT10x76l.js} +2 -2
  110. package/dist/chunks/{whatsapp-Bt4o4_q2.js.map → whatsapp-DT10x76l.js.map} +1 -1
  111. package/dist/chunks/{write-result-B7MewKhQ.js → write-result-BguSfKV-.js} +4 -4
  112. package/dist/chunks/{write-result-B7MewKhQ.js.map → write-result-BguSfKV-.js.map} +1 -1
  113. package/dist/index.js +99 -99
  114. package/dist/index.js.map +1 -1
  115. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-B06rPt_j.js","names":["__import_glob__0_0_","__import_glob__0_1_","envEditsFor","currency_server_test_default","META","currency_server_default","getLogger","resolveProvider","suppliedProviderEnv","languageFromPath","mergeResults","filesFromGlob","modifyOutcomeToFile","modifyEnv","normalizeCurrency","normalizeCurrencies","normalizeCountry","sitePath","ensureSiteBusiness","modifyLayoutServerCurrency","modifyLayoutSvelteCurrency","modifyHooksServerCurrency","modifyRootLayoutCurrencySelect","buyPageSnippet","STRIPE_PRODUCTS","STRIPE_PRICES","dedent","withPocketbase","migrationDelay","getMigrationFile","ensureCollectionFields","createCollectionIdempotent","modifyNavUser","modifyUserSignup","_taggedTemplateLiteral","InvalidArgumentError","modifyWuchaleJsFiles","TRANSLATED_LIB_FILES","fs","path","Stripe","setupShopify","logger","options","variantId","creates","syncUsersToStripeCustomers","stripe","stripeSecretKey","users","pb","existing","linkedUserIds","c","result","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","file","create","spec","customersResult","stripeCustomersCollection","paymentMethodsResult","stripePaymentMethodsCollection","transactionsResult","syncResult","navUserPath","userSignupPath","setupWhatsApp","business","given","wuchaleConfig","edit","createsServerRaw","serverCreates","unitTests","a","b","hasVitest","pkg","root","generate","provider","envPath","envVars","modifyEnvVarsFiles","providerEnvVars","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/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 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":";;;;;;;;;;;;;;;;;;;;;;AAQA,eAAsByC,EAAa,GAAkB;CACnD,IAAMC,IAASpC,EAAUqC,CAAO,GAC1BC,IACJ,OAAOD,EAAQ,MAAM,UAAW,WAAWA,EAAQ,MAAM,OAAO,K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CAAC,GAC1DA,EAAa,WAAW,WAAW;GACrC,IAAMC,IAAkBlF,EAAK,KAAKI,EAAQ,MAAM,OAAO,iBAAiB;GACxE,EACE/B,EACE6G,GACApG,EAA0BoG,CAAe,CAC3C,CACF;GACA,IAAMC,IAAiBnF,EAAK,KAC1BI,EAAQ,MACR,OACA,UACA,gBACF;GACA,EACE/B,EACE8G,GACAtG,EAA2BsG,CAAc,CAC3C,CACF;GACA,KAAK,IAAMvC,KAAQiB,EAAcI,EAAU7D,EAAQ,IAAI,CAAC,GACtD,EAAQ,KAAKwC,CAAI;EACrB;CACF;CAEA,IAAMwC,IAAc;EAClB;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB,GAEMC,IACJhB,EAAS,OAAO,WACZ,MAAM9B,EAAYnC,CAAO,IACzBiE,EAAS,OAAO,YACd,MAAMnE,EAAaE,CAAO,IAC1B,MAAMmD,EAAcnD,GAASoD,CAAQ;CAE7C,OAAOrF,EAAa,CAACiH,GAAKC,CAAK,CAAC;AAClC"}
1
+ {"version":3,"file":"generate.runtime-VMTLHWLk.js","names":["__import_glob__0_0_","__import_glob__0_1_","envEditsFor","currency_server_test_default","META","currency_server_default","getLogger","resolveProvider","suppliedProviderEnv","languageFromPath","mergeResults","filesFromGlob","modifyOutcomeToFile","modifyEnv","normalizeCurrency","normalizeCurrencies","normalizeCountry","sitePath","ensureSiteBusiness","modifyLayoutServerCurrency","modifyLayoutSvelteCurrency","modifyHooksServerCurrency","modifyRootLayoutCurrencySelect","buyPageSnippet","STRIPE_PRODUCTS","STRIPE_PRICES","dedent","withPocketbase","migrationDelay","getMigrationFile","ensureCollectionFields","createCollectionIdempotent","modifyNavUser","modifyUserSignup","_taggedTemplateLiteral","InvalidArgumentError","modifyWuchaleJsFiles","TRANSLATED_LIB_FILES","fs","path","Stripe","setupShopify","logger","options","variantId","creates","syncUsersToStripeCustomers","stripe","stripeSecretKey","users","pb","existing","linkedUserIds","c","result","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","file","create","spec","customersResult","stripeCustomersCollection","paymentMethodsResult","stripePaymentMethodsCollection","transactionsResult","syncResult","navUserPath","userSignupPath","setupWhatsApp","business","given","wuchaleConfig","edit","createsServerRaw","serverCreates","unitTests","a","b","hasVitest","pkg","root","generate","provider","envPath","envVars","modifyEnvVarsFiles","providerEnvVars","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/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 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":";;;;;;;;;;;;;;;;;;;;;;AAQA,eAAsByC,EAAa,GAAkB;CACnD,IAAMC,IAASpC,EAAUqC,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,SAAStB,EAAeqB,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;;AChBA,eAAsBE,EACpB,GACA,GACA,GAC0B;CAC1B,IAAMC,IAAS,IAAIP,EAAOQ,CAAe,GACnCC,IAAQ,MAAMC,EAAG,WAAW,OAAO,CAAC,CAAC,YAKxC,GAEGC,IAAW,MAAMD,EACpB,WAAW,kBAAkB,CAAC,CAC9B,YAA0C,GACvCE,IAAgB,IAAI,IAAID,EAAS,KAAK,MAAME,EAAE,IAAI,CAAC,GAEnDC,IAA0B;EAC9B,OAAOL,EAAM;EACb,QAAQG,EAAc;EACtB,SAAS;EACT,QAAQ;EACR,SAAS;CAC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AOrF,EAAa,CAACiH,GAAKC,CAAK,CAAC;AAClC"}
@@ -1,7 +1,7 @@
1
1
  import { a as e, i as t, n, o as r, r as i, s as a, t as o } from "./dispatch-BxlKS_5v.js";
2
2
  import { t as s } from "./errors-DdSUZI8f.js";
3
3
  import { n as c } from "./logger-t1HxmpG2.js";
4
- import { n as l, r as u } from "./modify-file-CRZ_gMg0.js";
4
+ import { n as l, r as u } from "./modify-file-CgJIza72.js";
5
5
  import { t as d } from "./dedent-CCUOcPFW.js";
6
6
  import { _ as f, o as p, r as m } from "./ts-morph-helpers-B4KZXP44.js";
7
7
  import { t as h } from "./svelte-file-DfplF3BU.js";
@@ -323,4 +323,4 @@ async function Z(e) {
323
323
  }
324
324
  export { J as assertPaymentsAppMode, Z as generate };
325
325
 
326
- //# sourceMappingURL=generate.runtime-DhNspd-h.js.map
326
+ //# sourceMappingURL=generate.runtime-XT_JQlTk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-DhNspd-h.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__0_4_","__import_glob__0_5_","__import_glob__0_6_","stripeCustomerHelper","_layout_server_default","_layout_default","nav_user_default","_page_server_default","app_sidebar_default","dispatch_default","InvalidArgumentError","getLogger","keepMissing","modifyOutcomeToFile","dedent","withInMemoryScript","formatLikeSource","ensureImports","SvelteFile","modifyNavUser","stripe_customer_default","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$5","SUBSCRIPTION_CASES_SNIPPET","modifyWebhookServer","filePath","original","addedCases","sf","switchStmt","SyntaxKind","stmt","clauses","defaultClause","c","prefix","last","source","LOAD_LINE","NOT_FOUND_HINT$4","failureHint","helper","helperFrom","clean","template","start","end","findLoad","varDecl","init","fn","modifyAppLayoutServer","Project","QuoteKind","load","body","block","binding","hasLocals","el","userIndex","s","d","statements","ret","returned","text","writer","FAILURE_HINT$1","NOT_FOUND_HINT$3","modifyAppLayoutSvelte","file","SUBSCRIPTION_TYPE","FAILURE_HINT","NOT_FOUND_HINT$2","updateScript","wasAdded","out","decl","nameNode","pattern","elements","typeNode","intersection","member","lit","propTexts","p","t","elementTexts","insertIdx","modifyAppSidebar","scriptChanged","src","templateChanged","modifyByTemplate","notFoundHint","current","idempotencyMarker","stripped","NOT_FOUND_HINT$1","modifyBillingPageServer","NOT_FOUND_HINT","modifyBillingPageSvelte","STRIPE_CUSTOMER_HELPER","BILLING_PAGE","assertPaymentsAppMode","root","previewRaw","_page_default","content","relativePath","generate","logger","options","modifies","pushResult","webhookServerPath","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/enable/subscriptions/modifies/modify-by-template.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/enable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Wire the subscription event handlers into src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n Add imports:\n import { handleSubscriptionCreated } from \"./subscription/created\";\n import { handleSubscriptionUpdated } from \"./subscription/updated\";\n import { handleSubscriptionDeleted } from \"./subscription/deleted\";\n\n Add switch cases inside the event.type switch:\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first — src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\nconst SUBSCRIPTION_CASES_SNIPPET = dedent`\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nexport function modifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n let addedCases = false;\n const { source } = withInMemoryScript(original, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"handleSubscriptionCreated\"],\n moduleSpecifier: \"./subscription/created\",\n },\n {\n namedImports: [\"handleSubscriptionUpdated\"],\n moduleSpecifier: \"./subscription/updated\",\n },\n {\n namedImports: [\"handleSubscriptionDeleted\"],\n moduleSpecifier: \"./subscription/deleted\",\n },\n ]);\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n const clauses = caseBlock.getClauses();\n const defaultClause = clauses.find(\n (c) => c.getKind() === SyntaxKind.DefaultClause,\n );\n\n // Prepend subscription cases in front of the default clause, or append\n // before the closing brace of the case block if there's no default.\n const prefix = `${SUBSCRIPTION_CASES_SNIPPET}\\n\\n`;\n if (defaultClause) {\n defaultClause.replaceWithText(prefix + defaultClause.getText());\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(\n last.getText() + `\\n\\n${SUBSCRIPTION_CASES_SNIPPET}`,\n );\n } else {\n return;\n }\n\n formatLikeSource(sf);\n addedCases = true;\n });\n\n if (!addedCases) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst LOAD_LINE =\n \"const subscription = await loadActiveSubscription(locals, user.id);\";\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.server.ts before enabling subscriptions.\",\n \"Enable auth first — the (app) layout is provided by the velastack-auth baseline.\",\n].join(\"\\n\");\n\nconst failureHint = (helper: string) =>\n [\n \"Could not find the user and the returned object in the (app) layout load.\",\n \"Add the active subscription to it by hand:\",\n \"\",\n helper,\n \"\",\n \"// In load, once `user` is set:\",\n LOAD_LINE,\n \"// ...and return it with the rest:\",\n \"return { ..., subscription };\",\n ].join(\"\\n\");\n\n/**\n * The `loadActiveSubscription` helper, taken from the preview template so the\n * docs and what gets written stay the same.\n */\nfunction helperFrom(template: string): string {\n const clean = template.replace(\n /^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm,\n \"\",\n );\n const start = clean.indexOf(\"async function loadActiveSubscription\");\n const end = clean.indexOf(\"\\n}\\n\", start);\n if (start === -1 || end === -1) {\n throw new Error(\"No loadActiveSubscription in the layout template\");\n }\n return clean.slice(start, end + 2);\n}\n\nfunction findLoad(sf: SourceFile) {\n const varDecl = sf.getVariableDeclaration(\"load\");\n if (varDecl?.getVariableStatement()?.hasExportKeyword()) {\n const init = varDecl.getInitializer();\n const fn =\n varDecl.getInitializerIfKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.FunctionExpression);\n if (fn) return { fn, statement: varDecl.getVariableStatement()! };\n }\n const fn = sf.getFunction(\"load\");\n return fn?.isExported() ? { fn, statement: fn } : undefined;\n}\n\n/**\n * Adds the active subscription to the (app) layout's data: the\n * `loadActiveSubscription` helper, a call to it in `load`, and `subscription`\n * in what `load` returns. Edits the file rather than replacing it, so what\n * other patterns put in the load (teams' `team`/`teams`, say) stays.\n */\nexport function modifyAppLayoutServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"loadActiveSubscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const helper = helperFrom(template);\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n const load = findLoad(sf);\n const body = load?.fn.getBody();\n if (!load || !body || body.getKind() !== SyntaxKind.Block) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n const block = body.asKindOrThrow(SyntaxKind.Block);\n\n // The call needs `locals` and `user`, and goes before the return.\n const params = load.fn.getParameters();\n const binding = params[0]?.getNameNode();\n const hasLocals =\n binding?.getKind() === SyntaxKind.ObjectBindingPattern &&\n binding\n .asKindOrThrow(SyntaxKind.ObjectBindingPattern)\n .getElements()\n .some((el) => el.getName() === \"locals\");\n const userIndex = block.getStatements().findIndex(\n (s) =>\n s.getKind() === SyntaxKind.VariableStatement &&\n s\n .asKindOrThrow(SyntaxKind.VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === \"user\"),\n );\n const statements = block.getStatements();\n const ret = [...statements]\n .reverse()\n .find((s) => s.getKind() === SyntaxKind.ReturnStatement)\n ?.asKind(SyntaxKind.ReturnStatement);\n const returned = ret\n ?.getExpression()\n ?.asKind(SyntaxKind.ObjectLiteralExpression);\n if (!hasLocals || userIndex === -1 || !ret || !returned) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n\n block.insertStatements(statements.indexOf(ret), LOAD_LINE);\n if (!returned.getProperty(\"subscription\")) {\n const text = returned.getText();\n if (text.includes(\"\\n\")) {\n returned.addShorthandPropertyAssignment({ name: \"subscription\" });\n } else {\n // Kept on one line, as written.\n returned.replaceWithText(text.replace(/\\s*\\}$/, \", subscription }\"));\n }\n }\n if (!load.fn.isAsync()) load.fn.setIsAsync(true);\n sf.insertStatements(sf.getStatements().indexOf(load.statement), (writer) =>\n writer.write(helper).blankLine(),\n );\n\n formatLikeSource(sf);\n sf.saveSync();\n return { status: \"success\", changed: sf.getFullText() !== original };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass the subscription prop to <AppSidebar> in src/routes/(app)/+layout.svelte:\",\n \"\",\n \"<AppSidebar user={data.user} subscription={data.subscription} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with an <AppSidebar /> that receives the subscription prop.\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const appended = file.appendToAttributes(\n \"AppSidebar\",\n \" subscription={data.subscription}\",\n );\n if (!appended) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst SUBSCRIPTION_TYPE = \"{ id: string; productName: string | null } | null\";\n\nconst FAILURE_HINT = [\n \"Update src/lib/components/app-sidebar.svelte to forward a subscription prop:\",\n \"\",\n \"1. Add `subscription = null` to the destructured $props() call.\",\n `2. Add \\`subscription?: ${SUBSCRIPTION_TYPE}\\` to the props type.`,\n \"3. Pass `{subscription}` to <NavUser>.\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/lib/components/app-sidebar.svelte before enabling subscriptions.\",\n].join(\"\\n\");\n\nfunction updateScript(source: string): {\n source: string;\n wasAdded: boolean;\n} {\n let wasAdded = false;\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n if (elements.some((e) => e.getName() === \"subscription\")) {\n // Already has subscription prop — no-op.\n return;\n }\n\n // Insert subscription?: ... into the props type literal if present.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^\\s*subscription\\??\\s*:/.test(t))) {\n continue;\n }\n propTexts.push(`subscription?: ${SUBSCRIPTION_TYPE}`);\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Insert `subscription = null` before the first rest/default-only element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elementTexts.length;\n elementTexts.splice(insertIdx, 0, \"subscription = null\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n wasAdded = true;\n }\n formatLikeSource(sf);\n });\n return { source: out, wasAdded };\n}\n\nexport function modifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (\n original.includes(\"subscription?: {\") ||\n original.includes(\"subscription={subscription}\") ||\n original.includes(\"{subscription}\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n if (!file.hasElement(\"NavUser\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const scriptChanged = file.modifyScript((src) => updateScript(src).source);\n\n const templateChanged = !file.hasAttribute(\"NavUser\", \"subscription\")\n ? file.appendToAttributes(\"NavUser\", \" {subscription}\")\n : false;\n\n if (!scriptChanged && !templateChanged) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Overwrites a file with the given template content, guarded by an idempotency\n * marker: if the current file already contains the marker, the modify is a\n * no-op. Used for complex rewrites where surgical AST changes aren't worth it\n * (e.g. pages that are largely replaced).\n *\n * Strips leading `// [!code highlight:N]` and `<!-- [!code highlight:N] -->`\n * lines so the same content can be shared with preview-modifies, which uses\n * those comments for documentation highlighting.\n */\nexport function modifyByTemplate(\n filePath: string,\n template: string,\n idempotencyMarker: string,\n notFoundHint: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: notFoundHint };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (current.includes(idempotencyMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.server.ts is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"selectPlan\", NOT_FOUND_HINT);\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.svelte is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageSvelte(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"availablePlans\", NOT_FOUND_HINT);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { keepMissing, modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { modifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { modifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\nimport stripeCustomerHelper from \"../payments/providers-app-mode/stripe/src/lib/server/stripe-customer.ts?raw\";\n\n// The billing page imports this payments helper, which apps that enabled\n// payments before it existed do not have yet.\nconst STRIPE_CUSTOMER_HELPER = \"src/lib/server/stripe-customer.ts\";\n\n// enable-payments writes the billing page (and the stripe_customers collection\n// subscriptions relate to) only when auth is already on.\nconst BILLING_PAGE = \"src/routes/(app)/billing/+page.server.ts\";\n\n/**\n * Refuses a project whose payments were enabled before auth. Every `requires`\n * flag passes there (auth and payments are both on), yet the billing page and\n * `stripe_customers` don't exist, so this runs before any collection is made.\n */\nexport function assertPaymentsAppMode(root: string): void {\n if (fs.existsSync(path.join(root, BILLING_PAGE))) return;\n throw new InvalidArgumentError(\n [\n \"Subscriptions need payments set up with auth on: they add plans to the billing page\",\n `(${BILLING_PAGE}) and link to the stripe_customers collection, which enable-payments`,\n \"creates only when auth is already enabled. This project enabled payments before auth.\",\n \"\",\n \"Re-enable payments now that auth is on: `vela disable payments`, then `vela enable payments`.\",\n \"disable-payments drops the catalog collections, which the sync workflow refills from Stripe.\",\n ].join(\"\\n\"),\n );\n}\n\n// Share the final-state files between preview (rendered as-is) and runtime\n// (used as overwrite templates for modifies that amount to full rewrites).\nconst previewRaw = import.meta.glob<string>(\"./preview-modifies/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nfunction template(relativePath: string): string {\n const key = `./preview-modifies/${relativePath}`;\n const content = previewRaw[key];\n if (content === undefined) {\n throw new Error(\n `Missing template for ${relativePath} in subscriptions preview-modifies`,\n );\n }\n return content;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n modifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyAppLayoutServer(\n appLayoutServerPath,\n template(\"src/routes/(app)/+layout.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n modifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Modifying app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n modifyBillingPageServer(\n billingPageServerPath,\n template(\"src/routes/(app)/billing/+page.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n modifyBillingPageSvelte(\n billingPageSveltePath,\n template(\"src/routes/(app)/billing/+page.svelte\"),\n ),\n ),\n );\n\n const creates = keepMissing(\n [\n {\n path: STRIPE_CUSTOMER_HELPER,\n language: \"ts\",\n content: stripeCustomerHelper,\n status: \"success\",\n },\n ],\n options.root,\n );\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;AAUA,IAAMA,IAAe,CAAM;;;;;;;;;;;;;;;;;;GAoBrBC,IACJ,0GAEImC,IAA6B,CAAM;;;;;;;;;;;;;AAczC,SAAgBC,EAAoB,GAAiC;CACnE,IAAI,CAACL,EAAG,WAAWM,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAa,SAASrC;CAAe;CAGxD,IAAMsC,IAAWP,EAAG,aAAaM,GAAU,MAAM;CACjD,IAAIC,EAAS,SAAS,2BAA2B,GAC/C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAIC,IAAa,IACX,EAAE,cAAWd,EAAmBa,IAAW,MAAO;EACtD,EAAcE,GAAI;GAChB;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;GACA;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;GACA;IACE,cAAc,CAAC,2BAA2B;IAC1C,iBAAiB;GACnB;EACF,CAAC;EAED,IAAMC,IAAaD,EAChB,qBAAqBE,EAAW,eAAe,CAAC,CAChD,MAAM,MAASC,EAAK,cAAc,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,YAAY,CAAC;EACvE,IAAI,CAACF,GAAY;EAGjB,IAAMG,IADYH,EAAW,aACb,CAAA,CAAU,WAAW,GAC/BI,IAAgBD,EAAQ,MA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AbclC,EACd,CACE;GACE,MAAM8F;GACN,UAAU;GACV,SAASvG;GACT,QAAQ;EACV,CACF,GACAiH,EAAQ,IAIR;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-XT_JQlTk.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__0_4_","__import_glob__0_5_","__import_glob__0_6_","stripeCustomerHelper","_layout_server_default","_layout_default","nav_user_default","_page_server_default","app_sidebar_default","dispatch_default","InvalidArgumentError","getLogger","keepMissing","modifyOutcomeToFile","dedent","withInMemoryScript","formatLikeSource","ensureImports","SvelteFile","modifyNavUser","stripe_customer_default","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$5","SUBSCRIPTION_CASES_SNIPPET","modifyWebhookServer","filePath","original","addedCases","sf","switchStmt","SyntaxKind","stmt","clauses","defaultClause","c","prefix","last","source","LOAD_LINE","NOT_FOUND_HINT$4","failureHint","helper","helperFrom","clean","template","start","end","findLoad","varDecl","init","fn","modifyAppLayoutServer","Project","QuoteKind","load","body","block","binding","hasLocals","el","userIndex","s","d","statements","ret","returned","text","writer","FAILURE_HINT$1","NOT_FOUND_HINT$3","modifyAppLayoutSvelte","file","SUBSCRIPTION_TYPE","FAILURE_HINT","NOT_FOUND_HINT$2","updateScript","wasAdded","out","decl","nameNode","pattern","elements","typeNode","intersection","member","lit","propTexts","p","t","elementTexts","insertIdx","modifyAppSidebar","scriptChanged","src","templateChanged","modifyByTemplate","notFoundHint","current","idempotencyMarker","stripped","NOT_FOUND_HINT$1","modifyBillingPageServer","NOT_FOUND_HINT","modifyBillingPageSvelte","STRIPE_CUSTOMER_HELPER","BILLING_PAGE","assertPaymentsAppMode","root","previewRaw","_page_default","content","relativePath","generate","logger","options","modifies","pushResult","webhookServerPath","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/enable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/enable/subscriptions/modifies/modify-by-template.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/enable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Wire the subscription event handlers into src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n Add imports:\n import { handleSubscriptionCreated } from \"./subscription/created\";\n import { handleSubscriptionUpdated } from \"./subscription/updated\";\n import { handleSubscriptionDeleted } from \"./subscription/deleted\";\n\n Add switch cases inside the event.type switch:\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first — src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\nconst SUBSCRIPTION_CASES_SNIPPET = dedent`\n case \"customer.subscription.created\":\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case \"customer.subscription.updated\":\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case \"customer.subscription.deleted\":\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n`;\n\nexport function modifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n let addedCases = false;\n const { source } = withInMemoryScript(original, (sf) => {\n ensureImports(sf, [\n {\n namedImports: [\"handleSubscriptionCreated\"],\n moduleSpecifier: \"./subscription/created\",\n },\n {\n namedImports: [\"handleSubscriptionUpdated\"],\n moduleSpecifier: \"./subscription/updated\",\n },\n {\n namedImports: [\"handleSubscriptionDeleted\"],\n moduleSpecifier: \"./subscription/deleted\",\n },\n ]);\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n const clauses = caseBlock.getClauses();\n const defaultClause = clauses.find(\n (c) => c.getKind() === SyntaxKind.DefaultClause,\n );\n\n // Prepend subscription cases in front of the default clause, or append\n // before the closing brace of the case block if there's no default.\n const prefix = `${SUBSCRIPTION_CASES_SNIPPET}\\n\\n`;\n if (defaultClause) {\n defaultClause.replaceWithText(prefix + defaultClause.getText());\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(\n last.getText() + `\\n\\n${SUBSCRIPTION_CASES_SNIPPET}`,\n );\n } else {\n return;\n }\n\n formatLikeSource(sf);\n addedCases = true;\n });\n\n if (!addedCases) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst LOAD_LINE =\n \"const subscription = await loadActiveSubscription(locals, user.id);\";\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.server.ts before enabling subscriptions.\",\n \"Enable auth first — the (app) layout is provided by the velastack-auth baseline.\",\n].join(\"\\n\");\n\nconst failureHint = (helper: string) =>\n [\n \"Could not find the user and the returned object in the (app) layout load.\",\n \"Add the active subscription to it by hand:\",\n \"\",\n helper,\n \"\",\n \"// In load, once `user` is set:\",\n LOAD_LINE,\n \"// ...and return it with the rest:\",\n \"return { ..., subscription };\",\n ].join(\"\\n\");\n\n/**\n * The `loadActiveSubscription` helper, taken from the preview template so the\n * docs and what gets written stay the same.\n */\nfunction helperFrom(template: string): string {\n const clean = template.replace(\n /^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm,\n \"\",\n );\n const start = clean.indexOf(\"async function loadActiveSubscription\");\n const end = clean.indexOf(\"\\n}\\n\", start);\n if (start === -1 || end === -1) {\n throw new Error(\"No loadActiveSubscription in the layout template\");\n }\n return clean.slice(start, end + 2);\n}\n\nfunction findLoad(sf: SourceFile) {\n const varDecl = sf.getVariableDeclaration(\"load\");\n if (varDecl?.getVariableStatement()?.hasExportKeyword()) {\n const init = varDecl.getInitializer();\n const fn =\n varDecl.getInitializerIfKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.ArrowFunction) ??\n init?.getFirstDescendantByKind(SyntaxKind.FunctionExpression);\n if (fn) return { fn, statement: varDecl.getVariableStatement()! };\n }\n const fn = sf.getFunction(\"load\");\n return fn?.isExported() ? { fn, statement: fn } : undefined;\n}\n\n/**\n * Adds the active subscription to the (app) layout's data: the\n * `loadActiveSubscription` helper, a call to it in `load`, and `subscription`\n * in what `load` returns. Edits the file rather than replacing it, so what\n * other patterns put in the load (teams' `team`/`teams`, say) stays.\n */\nexport function modifyAppLayoutServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"loadActiveSubscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const helper = helperFrom(template);\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n const load = findLoad(sf);\n const body = load?.fn.getBody();\n if (!load || !body || body.getKind() !== SyntaxKind.Block) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n const block = body.asKindOrThrow(SyntaxKind.Block);\n\n // The call needs `locals` and `user`, and goes before the return.\n const params = load.fn.getParameters();\n const binding = params[0]?.getNameNode();\n const hasLocals =\n binding?.getKind() === SyntaxKind.ObjectBindingPattern &&\n binding\n .asKindOrThrow(SyntaxKind.ObjectBindingPattern)\n .getElements()\n .some((el) => el.getName() === \"locals\");\n const userIndex = block.getStatements().findIndex(\n (s) =>\n s.getKind() === SyntaxKind.VariableStatement &&\n s\n .asKindOrThrow(SyntaxKind.VariableStatement)\n .getDeclarations()\n .some((d) => d.getName() === \"user\"),\n );\n const statements = block.getStatements();\n const ret = [...statements]\n .reverse()\n .find((s) => s.getKind() === SyntaxKind.ReturnStatement)\n ?.asKind(SyntaxKind.ReturnStatement);\n const returned = ret\n ?.getExpression()\n ?.asKind(SyntaxKind.ObjectLiteralExpression);\n if (!hasLocals || userIndex === -1 || !ret || !returned) {\n return { status: \"failed\", message: failureHint(helper) };\n }\n\n block.insertStatements(statements.indexOf(ret), LOAD_LINE);\n if (!returned.getProperty(\"subscription\")) {\n const text = returned.getText();\n if (text.includes(\"\\n\")) {\n returned.addShorthandPropertyAssignment({ name: \"subscription\" });\n } else {\n // Kept on one line, as written.\n returned.replaceWithText(text.replace(/\\s*\\}$/, \", subscription }\"));\n }\n }\n if (!load.fn.isAsync()) load.fn.setIsAsync(true);\n sf.insertStatements(sf.getStatements().indexOf(load.statement), (writer) =>\n writer.write(helper).blankLine(),\n );\n\n formatLikeSource(sf);\n sf.saveSync();\n return { status: \"success\", changed: sf.getFullText() !== original };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Pass the subscription prop to <AppSidebar> in src/routes/(app)/+layout.svelte:\",\n \"\",\n \"<AppSidebar user={data.user} subscription={data.subscription} />\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(app)/+layout.svelte with an <AppSidebar /> that receives the subscription prop.\",\n].join(\"\\n\");\n\nexport function modifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const appended = file.appendToAttributes(\n \"AppSidebar\",\n \" subscription={data.subscription}\",\n );\n if (!appended) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst SUBSCRIPTION_TYPE = \"{ id: string; productName: string | null } | null\";\n\nconst FAILURE_HINT = [\n \"Update src/lib/components/app-sidebar.svelte to forward a subscription prop:\",\n \"\",\n \"1. Add `subscription = null` to the destructured $props() call.\",\n `2. Add \\`subscription?: ${SUBSCRIPTION_TYPE}\\` to the props type.`,\n \"3. Pass `{subscription}` to <NavUser>.\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/lib/components/app-sidebar.svelte before enabling subscriptions.\",\n].join(\"\\n\");\n\nfunction updateScript(source: string): {\n source: string;\n wasAdded: boolean;\n} {\n let wasAdded = false;\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n if (elements.some((e) => e.getName() === \"subscription\")) {\n // Already has subscription prop — no-op.\n return;\n }\n\n // Insert subscription?: ... into the props type literal if present.\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"));\n if (propTexts.some((t) => /^\\s*subscription\\??\\s*:/.test(t))) {\n continue;\n }\n propTexts.push(`subscription?: ${SUBSCRIPTION_TYPE}`);\n lit.replaceWithText(`{ ${propTexts.join(\"; \")}; }`);\n break;\n }\n }\n\n // Insert `subscription = null` before the first rest/default-only element.\n const elementTexts = elements.map((e) => e.getText());\n let insertIdx = elements.findIndex(\n (e) => e.getDotDotDotToken() || e.getInitializer(),\n );\n if (insertIdx === -1) insertIdx = elementTexts.length;\n elementTexts.splice(insertIdx, 0, \"subscription = null\");\n pattern.replaceWithText(`{ ${elementTexts.join(\", \")} }`);\n wasAdded = true;\n }\n formatLikeSource(sf);\n });\n return { source: out, wasAdded };\n}\n\nexport function modifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(filePath, \"utf8\");\n if (\n original.includes(\"subscription?: {\") ||\n original.includes(\"subscription={subscription}\") ||\n original.includes(\"{subscription}\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n if (!file.hasElement(\"NavUser\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const scriptChanged = file.modifyScript((src) => updateScript(src).source);\n\n const templateChanged = !file.hasAttribute(\"NavUser\", \"subscription\")\n ? file.appendToAttributes(\"NavUser\", \" {subscription}\")\n : false;\n\n if (!scriptChanged && !templateChanged) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Overwrites a file with the given template content, guarded by an idempotency\n * marker: if the current file already contains the marker, the modify is a\n * no-op. Used for complex rewrites where surgical AST changes aren't worth it\n * (e.g. pages that are largely replaced).\n *\n * Strips leading `// [!code highlight:N]` and `<!-- [!code highlight:N] -->`\n * lines so the same content can be shared with preview-modifies, which uses\n * those comments for documentation highlighting.\n */\nexport function modifyByTemplate(\n filePath: string,\n template: string,\n idempotencyMarker: string,\n notFoundHint: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: notFoundHint };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (current.includes(idempotencyMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.server.ts is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"selectPlan\", NOT_FOUND_HINT);\n}\n","import { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/routes/(app)/billing/+page.svelte is missing.\",\n \"Enable payments first — subscriptions extends the billing page with plan management.\",\n].join(\"\\n\");\n\nexport function modifyBillingPageSvelte(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(filePath, template, \"availablePlans\", NOT_FOUND_HINT);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { keepMissing, modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { modifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { modifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { modifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { modifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\nimport stripeCustomerHelper from \"../payments/providers-app-mode/stripe/src/lib/server/stripe-customer.ts?raw\";\n\n// The billing page imports this payments helper, which apps that enabled\n// payments before it existed do not have yet.\nconst STRIPE_CUSTOMER_HELPER = \"src/lib/server/stripe-customer.ts\";\n\n// enable-payments writes the billing page (and the stripe_customers collection\n// subscriptions relate to) only when auth is already on.\nconst BILLING_PAGE = \"src/routes/(app)/billing/+page.server.ts\";\n\n/**\n * Refuses a project whose payments were enabled before auth. Every `requires`\n * flag passes there (auth and payments are both on), yet the billing page and\n * `stripe_customers` don't exist, so this runs before any collection is made.\n */\nexport function assertPaymentsAppMode(root: string): void {\n if (fs.existsSync(path.join(root, BILLING_PAGE))) return;\n throw new InvalidArgumentError(\n [\n \"Subscriptions need payments set up with auth on: they add plans to the billing page\",\n `(${BILLING_PAGE}) and link to the stripe_customers collection, which enable-payments`,\n \"creates only when auth is already enabled. This project enabled payments before auth.\",\n \"\",\n \"Re-enable payments now that auth is on: `vela disable payments`, then `vela enable payments`.\",\n \"disable-payments drops the catalog collections, which the sync workflow refills from Stripe.\",\n ].join(\"\\n\"),\n );\n}\n\n// Share the final-state files between preview (rendered as-is) and runtime\n// (used as overwrite templates for modifies that amount to full rewrites).\nconst previewRaw = import.meta.glob<string>(\"./preview-modifies/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nfunction template(relativePath: string): string {\n const key = `./preview-modifies/${relativePath}`;\n const content = previewRaw[key];\n if (content === undefined) {\n throw new Error(\n `Missing template for ${relativePath} in subscriptions preview-modifies`,\n );\n }\n return content;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n modifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n modifyAppLayoutServer(\n appLayoutServerPath,\n template(\"src/routes/(app)/+layout.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n modifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Modifying app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, modifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n modifyBillingPageServer(\n billingPageServerPath,\n template(\"src/routes/(app)/billing/+page.server.ts\"),\n ),\n ),\n );\n\n logger.info(\"Modifying billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n modifyBillingPageSvelte(\n billingPageSveltePath,\n template(\"src/routes/(app)/billing/+page.svelte\"),\n ),\n ),\n );\n\n const creates = keepMissing(\n [\n {\n path: STRIPE_CUSTOMER_HELPER,\n language: \"ts\",\n content: stripeCustomerHelper,\n status: \"success\",\n },\n ],\n options.root,\n );\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches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AEAqE,EAAO,KAAK,gCAAgC;CAC5C,IAAMM,IAAsBnG,EAAK,KAC/B8F,EAAQ,MACR,OACA,UACA,SACA,gBACF;CAQA,AAPAE,EACEzG,EACE4G,GACAjD,EAAsBiD,CAAmB,CAC3C,CACF,GAEAN,EAAO,KAAK,8BAA8B;CAC1C,IAAMO,IAAiBpG,EAAK,KAC1B8F,EAAQ,MACR,OACA,OACA,cACA,oBACF;CAKA,AAJAE,EACEzG,EAAoB6G,GAAgB7B,EAAiB6B,CAAc,CAAC,CACtE,GAEAP,EAAO,KAAK,2BAA2B;CACvC,IAAMQ,IAAcrG,EAAK,KACvB8F,EAAQ,MACR,OACA,OACA,cACA,iBACF;CAGA,AAFAE,EAAWzG,EAAoB8G,GAAaxG,EAAcwG,CAAW,CAAC,CAAC,GAEvER,EAAO,KAAK,mCAAmC;CAC/C,IAAMS,IAAwBtG,EAAK,KACjC8F,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVAE,EACEzG,EACE+G,GACArB,EACEqB,GACA9E,EAAS,0CAA0C,CACrD,CACF,CACF,GAEAqE,EAAO,KAAK,gCAAgC;CAC5C,IAAMU,IAAwBvG,EAAK,KACjC8F,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAuBA,OAtBAE,EACEzG,EACEgH,GACApB,EACEoB,GACA/E,EAAS,uCAAuC,CAClD,CACF,CACF,GAcO;EACL,SAbclC,EACd,CACE;GACE,MAAM8F;GACN,UAAU;GACV,SAASvG;GACT,QAAQ;EACV,CACF,GACAiH,EAAQ,IAIR;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { n as e } from "./logger-t1HxmpG2.js";
2
2
  import { a as t } from "./util-ILWdjRAd.js";
3
- import { r as n } from "./modify-file-CRZ_gMg0.js";
3
+ import { r as n } from "./modify-file-CgJIza72.js";
4
4
  import { t as r } from "./dedent-CCUOcPFW.js";
5
5
  import { _ as i, o as a, r as o, u as s } from "./ts-morph-helpers-B4KZXP44.js";
6
6
  import { t as c } from "./modify-nav-user-D42kWyU6.js";
@@ -157,4 +157,4 @@ async function E(r) {
157
157
  }
158
158
  export { w as SUCCESS_PAGE, E as generate, C as t };
159
159
 
160
- //# sourceMappingURL=generate.runtime-CVqPHddZ.js.map
160
+ //# sourceMappingURL=generate.runtime-XpYi9SlM.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CVqPHddZ.js","names":["successServer","successSvelte","getLogger","languageFromPath","modifyOutcomeToFile","dedent","withInMemoryScript","formatLikeSource","ensureImports","removeImportByModuleSpecifier","addItemToNavUser","_page_server_default","_page_default","fs","path","COMPLETED","ASYNC_PAYMENT","EVENTS","CASES_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","eventSwitch","sf","SyntaxKind","statement","modifyWebhookServer","filePath","original","added","clauses","defaultClause","Node","last","source","unmodifyWebhookServer","isOrders","clause","expression","ranges","i","first","start","end","SUCCESS_PAGE","NAV_USER","generate","logger","options","modifies","pushResult","file","dispatchPath","name","content","navUserPath","wasAdded","newNavUserSnippet"],"sources":["../../src/patterns/enable/orders/modifies/modify-webhook-server.ts","../../src/patterns/enable/orders/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n formatLikeSource,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst COMPLETED = \"./checkout/completed\";\nconst ASYNC_PAYMENT = \"./checkout/async-payment\";\n\n/** The Checkout Session events the order handlers take. */\nconst EVENTS = [\n \"checkout.session.completed\",\n \"checkout.session.async_payment_succeeded\",\n \"checkout.session.async_payment_failed\",\n];\n\nconst CASES_SNIPPET = dedent`\n case 'checkout.session.completed':\n await handleCheckoutSessionCompleted(event.data.object, locals);\n break;\n\n case 'checkout.session.async_payment_succeeded':\n case 'checkout.session.async_payment_failed':\n await handleCheckoutAsyncPayment(event.data.object, locals);\n break;\n`;\n\nconst FAILURE_HINT = dedent`\n Route the Checkout Session events to the order handlers in src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n import { handleCheckoutSessionCompleted } from '${COMPLETED}';\n import { handleCheckoutAsyncPayment } from '${ASYNC_PAYMENT}';\n\n and, inside the \\`switch (event.type)\\`:\n\n ${CASES_SNIPPET.split(\"\\n\").join(\"\\n \")}\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first: src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\n/** The `switch (event.type)` the dispatcher routes on. */\nfunction eventSwitch(sf: import(\"ts-morph\").SourceFile) {\n return sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((statement) =>\n statement.getExpression().getText().includes(\"event.type\"),\n );\n}\n\n/** The order handlers join the dispatcher's switch, ahead of its default. */\nexport function modifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"handleCheckoutSessionCompleted\")) {\n return { status: \"success\", changed: false };\n }\n\n let added = false;\n const { source } = withInMemoryScript(original, (sf) => {\n const statement = eventSwitch(sf);\n if (!statement) return;\n const clauses = statement.getCaseBlock().getClauses();\n const defaultClause = clauses.find(Node.isDefaultClause);\n if (defaultClause) {\n defaultClause.replaceWithText(\n `${CASES_SNIPPET}\\n\\n${defaultClause.getText()}`,\n );\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(`${last.getText()}\\n\\n${CASES_SNIPPET}`);\n } else {\n return;\n }\n ensureImports(sf, [\n {\n namedImports: [\"handleCheckoutSessionCompleted\"],\n moduleSpecifier: COMPLETED,\n },\n {\n namedImports: [\"handleCheckoutAsyncPayment\"],\n moduleSpecifier: ASYNC_PAYMENT,\n },\n ]);\n formatLikeSource(sf);\n added = true;\n });\n if (!added) return { status: \"failed\", message: FAILURE_HINT };\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\n/** Take the order cases and their imports back out of the dispatcher. */\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleCheckoutSessionCompleted\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n const statement = eventSwitch(sf);\n if (statement) {\n // Each run of order clauses goes with the whitespace before it, so the\n // blank line that separated its neighbours is the one that stays.\n const clauses = statement.getCaseBlock().getClauses();\n const isOrders = (clause: (typeof clauses)[number]) => {\n if (!Node.isCaseClause(clause)) return false;\n const expression = clause.getExpression();\n return (\n Node.isStringLiteral(expression) &&\n EVENTS.includes(expression.getLiteralText())\n );\n };\n // Positions first, bottom-up: removing text forgets the nodes after it.\n const ranges: [number, number][] = [];\n for (let i = clauses.length - 1; i >= 0; i--) {\n if (!isOrders(clauses[i])) continue;\n let first = i;\n while (first > 0 && isOrders(clauses[first - 1])) first--;\n const start =\n first > 0 ? clauses[first - 1].getEnd() : clauses[first].getStart();\n ranges.push([start, clauses[i].getEnd()]);\n i = first;\n }\n for (const [start, end] of ranges) sf.removeText(start, end);\n }\n removeImportByModuleSpecifier(sf, COMPLETED);\n removeImportByModuleSpecifier(sf, ASYNC_PAYMENT);\n formatLikeSource(sf);\n });\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: source !== original };\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 { languageFromPath } from \"../../../core/util\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { addItemToNavUser } from \"../payments/modifies/modify-nav-user\";\nimport successServer from \"./preview-modifies/src/routes/(public)/checkout/success/+page.server.ts?raw\";\nimport successSvelte from \"./preview-modifies/src/routes/(public)/checkout/success/+page.svelte?raw\";\n\n/** The success page, which enable-ecommerce wrote and this pattern rewrites to show the order. */\nexport const SUCCESS_PAGE = \"src/routes/(public)/checkout/success\";\n\nconst NAV_USER = path.join(\"src\", \"lib\", \"components\", \"nav-user.svelte\");\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\n \"Routing the Checkout Session events in webhooks/stripe/handlers/dispatch.ts\",\n );\n const dispatchPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(dispatchPath, modifyWebhookServer(dispatchPath)),\n );\n\n // A rewrite rather than an edit: the page's load changes shape (the order\n // and its lines, then Stripe's summary as the fallback).\n logger.info(\"Showing the order on /checkout/success\");\n for (const [name, content] of [\n [\"+page.server.ts\", successServer],\n [\"+page.svelte\", successSvelte],\n ] as const) {\n const file = path.join(options.root, SUCCESS_PAGE, name);\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === content)\n continue;\n modifies.push({\n path: file,\n language: languageFromPath(file),\n content,\n status: \"success\",\n });\n }\n\n if (options.features.auth) {\n logger.info(\"Adding Orders to the user menu\");\n const navUserPath = path.join(options.root, NAV_USER);\n if (fs.existsSync(navUserPath)) {\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"'/orders'\")) {\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n source,\n \"Orders\",\n \"/orders\",\n \"PackageIcon\",\n \"@lucide/svelte/icons/package\",\n );\n if (wasAdded) {\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n modifies.push({\n path: navUserPath,\n language: languageFromPath(navUserPath),\n content: newNavUserSnippet,\n status: \"success\",\n });\n } else {\n modifies.push({\n path: navUserPath,\n language: languageFromPath(navUserPath),\n content: source,\n status: \"failed\",\n message:\n \"Add an Orders item to the navUser array in nav-user.svelte:\\n\\n\" +\n \"import PackageIcon from '@lucide/svelte/icons/package';\\n\" +\n \"{ title: 'Orders', url: '/orders', icon: PackageIcon }\",\n });\n }\n }\n }\n }\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAMe,IAAY,wBACZC,IAAgB,4BAGhBC,IAAS;CACb;CACA;CACA;AACF,GAEMC,IAAgB,CAAM;;;;;;;;;GAWtBC,IAAe,CAAM;;;oDAGyBJ,EAAU;gDACdC,EAAc;;;;IAI1DE,EAAc,MAAM,IAAI,CAAC,CAAC,KAAK,MAAM,EAAE;GAGrCE,IACJ;AAGF,SAASC,EAAY,GAAmC;CACtD,OAAOC,EACJ,qBAAqBC,EAAW,eAAe,CAAC,CAChD,MAAM,MACLC,EAAU,cAAc,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,YAAY,CAC3D;AACJ;AAGA,SAAgBC,EAAoB,GAAiC;CACnE,IAAI,CAACZ,EAAG,WAAWa,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAa,SAASN;CAAe;CAExD,IAAMO,IAAWd,EAAG,aAAaa,GAAU,MAAM;CACjD,IAAIC,EAAS,SAAS,gCAAgC,GACpD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAIC,IAAQ,IACN,EAAE,cAAWtB,EAAmBqB,IAAW,MAAO;EACtD,IAAMH,IAAYH,EAAYC,CAAE;EAChC,IAAI,CAACE,GAAW;EAChB,IAAMK,IAAUL,EAAU,aAAa,CAAC,CAAC,WAAW,GAC9CM,IAAgBD,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KrC,EAAG,aAAaqC,GAAM,MAAM,MAAMG,KAE7DL,EAAS,KAAK;GACZ,MAAME;GACN,UAAU/C,EAAiB+C,CAAI;GAC/B;GACA,QAAQ;EACV,CAAC;CACH;CAEA,IAAIH,EAAQ,SAAS,MAAM;EACzB,EAAO,KAAK,gCAAgC;EAC5C,IAAMO,IAAcxC,EAAK,KAAKiC,EAAQ,MAAMH,CAAQ;EACpD,IAAI/B,EAAG,WAAWyC,CAAW,GAAG;GAC9B,IAAMrB,IAASpB,EAAG,aAAayC,GAAa,MAAM;GAClD,IAAI,CAACrB,EAAO,SAAS,WAAW,GAAG;IACjC,IAAM,EAAE,sBAAmB,gBAAavB,EACtCuB,GACA,UACA,WACA,eACA,8BACF;IACA,AAAIsB,KACF1C,EAAG,cAAcyC,GAAaE,GAAmB,MAAM,GACvDR,EAAS,KAAK;KACZ,MAAMM;KACN,UAAUnD,EAAiBmD,CAAW;KACtC,SAASE;KACT,QAAQ;IACV,CAAC,KAEDR,EAAS,KAAK;KACZ,MAAMM;KACN,UAAUnD,EAAiBmD,CAAW;KACtC,SAASrB;KACT,QAAQ;KACR,SACE;IAGJ,CAAC;GAEL;EACF;CACF;CAEA,OAAO;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
+ {"version":3,"file":"generate.runtime-XpYi9SlM.js","names":["successServer","successSvelte","getLogger","languageFromPath","modifyOutcomeToFile","dedent","withInMemoryScript","formatLikeSource","ensureImports","removeImportByModuleSpecifier","addItemToNavUser","_page_server_default","_page_default","fs","path","COMPLETED","ASYNC_PAYMENT","EVENTS","CASES_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","eventSwitch","sf","SyntaxKind","statement","modifyWebhookServer","filePath","original","added","clauses","defaultClause","Node","last","source","unmodifyWebhookServer","isOrders","clause","expression","ranges","i","first","start","end","SUCCESS_PAGE","NAV_USER","generate","logger","options","modifies","pushResult","file","dispatchPath","name","content","navUserPath","wasAdded","newNavUserSnippet"],"sources":["../../src/patterns/enable/orders/modifies/modify-webhook-server.ts","../../src/patterns/enable/orders/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n formatLikeSource,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst COMPLETED = \"./checkout/completed\";\nconst ASYNC_PAYMENT = \"./checkout/async-payment\";\n\n/** The Checkout Session events the order handlers take. */\nconst EVENTS = [\n \"checkout.session.completed\",\n \"checkout.session.async_payment_succeeded\",\n \"checkout.session.async_payment_failed\",\n];\n\nconst CASES_SNIPPET = dedent`\n case 'checkout.session.completed':\n await handleCheckoutSessionCompleted(event.data.object, locals);\n break;\n\n case 'checkout.session.async_payment_succeeded':\n case 'checkout.session.async_payment_failed':\n await handleCheckoutAsyncPayment(event.data.object, locals);\n break;\n`;\n\nconst FAILURE_HINT = dedent`\n Route the Checkout Session events to the order handlers in src/routes/webhooks/stripe/handlers/dispatch.ts:\n\n import { handleCheckoutSessionCompleted } from '${COMPLETED}';\n import { handleCheckoutAsyncPayment } from '${ASYNC_PAYMENT}';\n\n and, inside the \\`switch (event.type)\\`:\n\n ${CASES_SNIPPET.split(\"\\n\").join(\"\\n \")}\n`;\n\nconst NOT_FOUND_HINT =\n \"Enable payments first: src/routes/webhooks/stripe/handlers/dispatch.ts is created by enable-payments.\";\n\n/** The `switch (event.type)` the dispatcher routes on. */\nfunction eventSwitch(sf: import(\"ts-morph\").SourceFile) {\n return sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((statement) =>\n statement.getExpression().getText().includes(\"event.type\"),\n );\n}\n\n/** The order handlers join the dispatcher's switch, ahead of its default. */\nexport function modifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (original.includes(\"handleCheckoutSessionCompleted\")) {\n return { status: \"success\", changed: false };\n }\n\n let added = false;\n const { source } = withInMemoryScript(original, (sf) => {\n const statement = eventSwitch(sf);\n if (!statement) return;\n const clauses = statement.getCaseBlock().getClauses();\n const defaultClause = clauses.find(Node.isDefaultClause);\n if (defaultClause) {\n defaultClause.replaceWithText(\n `${CASES_SNIPPET}\\n\\n${defaultClause.getText()}`,\n );\n } else if (clauses.length > 0) {\n const last = clauses[clauses.length - 1];\n last.replaceWithText(`${last.getText()}\\n\\n${CASES_SNIPPET}`);\n } else {\n return;\n }\n ensureImports(sf, [\n {\n namedImports: [\"handleCheckoutSessionCompleted\"],\n moduleSpecifier: COMPLETED,\n },\n {\n namedImports: [\"handleCheckoutAsyncPayment\"],\n moduleSpecifier: ASYNC_PAYMENT,\n },\n ]);\n formatLikeSource(sf);\n added = true;\n });\n if (!added) return { status: \"failed\", message: FAILURE_HINT };\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\n/** Take the order cases and their imports back out of the dispatcher. */\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleCheckoutSessionCompleted\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n const statement = eventSwitch(sf);\n if (statement) {\n // Each run of order clauses goes with the whitespace before it, so the\n // blank line that separated its neighbours is the one that stays.\n const clauses = statement.getCaseBlock().getClauses();\n const isOrders = (clause: (typeof clauses)[number]) => {\n if (!Node.isCaseClause(clause)) return false;\n const expression = clause.getExpression();\n return (\n Node.isStringLiteral(expression) &&\n EVENTS.includes(expression.getLiteralText())\n );\n };\n // Positions first, bottom-up: removing text forgets the nodes after it.\n const ranges: [number, number][] = [];\n for (let i = clauses.length - 1; i >= 0; i--) {\n if (!isOrders(clauses[i])) continue;\n let first = i;\n while (first > 0 && isOrders(clauses[first - 1])) first--;\n const start =\n first > 0 ? clauses[first - 1].getEnd() : clauses[first].getStart();\n ranges.push([start, clauses[i].getEnd()]);\n i = first;\n }\n for (const [start, end] of ranges) sf.removeText(start, end);\n }\n removeImportByModuleSpecifier(sf, COMPLETED);\n removeImportByModuleSpecifier(sf, ASYNC_PAYMENT);\n formatLikeSource(sf);\n });\n fs.writeFileSync(filePath, source, \"utf8\");\n return { status: \"success\", changed: source !== original };\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 { languageFromPath } from \"../../../core/util\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { addItemToNavUser } from \"../payments/modifies/modify-nav-user\";\nimport successServer from \"./preview-modifies/src/routes/(public)/checkout/success/+page.server.ts?raw\";\nimport successSvelte from \"./preview-modifies/src/routes/(public)/checkout/success/+page.svelte?raw\";\n\n/** The success page, which enable-ecommerce wrote and this pattern rewrites to show the order. */\nexport const SUCCESS_PAGE = \"src/routes/(public)/checkout/success\";\n\nconst NAV_USER = path.join(\"src\", \"lib\", \"components\", \"nav-user.svelte\");\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\n \"Routing the Checkout Session events in webhooks/stripe/handlers/dispatch.ts\",\n );\n const dispatchPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(dispatchPath, modifyWebhookServer(dispatchPath)),\n );\n\n // A rewrite rather than an edit: the page's load changes shape (the order\n // and its lines, then Stripe's summary as the fallback).\n logger.info(\"Showing the order on /checkout/success\");\n for (const [name, content] of [\n [\"+page.server.ts\", successServer],\n [\"+page.svelte\", successSvelte],\n ] as const) {\n const file = path.join(options.root, SUCCESS_PAGE, name);\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === content)\n continue;\n modifies.push({\n path: file,\n language: languageFromPath(file),\n content,\n status: \"success\",\n });\n }\n\n if (options.features.auth) {\n logger.info(\"Adding Orders to the user menu\");\n const navUserPath = path.join(options.root, NAV_USER);\n if (fs.existsSync(navUserPath)) {\n const source = fs.readFileSync(navUserPath, \"utf8\");\n if (!source.includes(\"'/orders'\")) {\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n source,\n \"Orders\",\n \"/orders\",\n \"PackageIcon\",\n \"@lucide/svelte/icons/package\",\n );\n if (wasAdded) {\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n modifies.push({\n path: navUserPath,\n language: languageFromPath(navUserPath),\n content: newNavUserSnippet,\n status: \"success\",\n });\n } else {\n modifies.push({\n path: navUserPath,\n language: languageFromPath(navUserPath),\n content: source,\n status: \"failed\",\n message:\n \"Add an Orders item to the navUser array in nav-user.svelte:\\n\\n\" +\n \"import PackageIcon from '@lucide/svelte/icons/package';\\n\" +\n \"{ title: 'Orders', url: '/orders', icon: PackageIcon }\",\n });\n }\n }\n }\n }\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAMe,IAAY,wBACZC,IAAgB,4BAGhBC,IAAS;CACb;CACA;CACA;AACF,GAEMC,IAAgB,CAAM;;;;;;;;;GAWtBC,IAAe,CAAM;;;oDAGyBJ,EAAU;gDACdC,EAAc;;;;IAI1DE,EAAc,MAAM,IAAI,CAAC,CAAC,KAAK,MAAM,EAAE;GAGrCE,IACJ;AAGF,SAASC,EAAY,GAAmC;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rB;KACT,QAAQ;KACR,SACE;IAGJ,CAAC;GAEL;EACF;CACF;CAEA,OAAO;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,8 +1,8 @@
1
1
  import { n as e } from "./logger-t1HxmpG2.js";
2
- import { r as t } from "./modify-file-CRZ_gMg0.js";
2
+ import { r as t } from "./modify-file-CgJIza72.js";
3
3
  import { t as n } from "./dedent-CCUOcPFW.js";
4
4
  import { o as r } from "./ts-morph-helpers-B4KZXP44.js";
5
- import { modifyEnvVarsFiles as i } from "./env-vars-CVn2076k.js";
5
+ import { modifyEnvVarsFiles as i } from "./env-vars-BbS_mWyP.js";
6
6
  import { t as a } from "./env-vars-T3_7JNSg.js";
7
7
  import o from "node:fs";
8
8
  import s from "node:path";
@@ -83,4 +83,4 @@ async function g(n) {
83
83
  }
84
84
  export { g as generate };
85
85
 
86
- //# sourceMappingURL=generate.runtime-CyWuhV6m.js.map
86
+ //# sourceMappingURL=generate.runtime-ZgLxGWuy.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CyWuhV6m.js","names":["getLogger","modifyOutcomeToFile","dedent","formatLikeSource","WORKFLOWS_ENV_VARS","fs","path","INIT_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","ensureNamedImport","existing","sourceFile","d","moduleSpecifier","ni","name","typeOnly","hasInitExport","modifyHooksServerWorkflows","hooksServerPath","Project","QuoteKind","generate","logger","options","creates","modifies","hooksFile","envVars","modifyEnvVarsFiles"],"sources":["../../src/patterns/enable/workflows/modifies/hooks.server.ts","../../src/patterns/enable/workflows/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst INIT_SNIPPET = dedent`\n // Runs once when the server starts: executes the workflows in src/lib/workflows.\n export const init: ServerInit = () => startWorker();\n`;\n\nconst FAILURE_HINT = dedent`\n src/hooks.server.ts already exports an init hook. Start the workflow worker from it:\n\n import { startWorker } from '#lib/server/workflows.js';\n\n export const init: ServerInit = async () => {\n await startWorker();\n // ...the rest of your init\n };\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts and start the workflow worker from its init hook:\n\n import type { ServerInit } from '@sveltejs/kit/hooks';\n import { startWorker } from '#lib/server/workflows.js';\n\n export const init: ServerInit = () => startWorker();\n`;\n\nfunction ensureNamedImport(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n name: string,\n typeOnly = false,\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({\n isTypeOnly: typeOnly,\n namedImports: [name],\n moduleSpecifier,\n });\n return;\n }\n if (existing.getNamedImports().some((ni) => ni.getName() === name)) return;\n // A declaration that is already `import type` covers the new name; a value\n // import takes the name as an inline `type` specifier.\n existing.addNamedImport(\n typeOnly && !existing.isTypeOnly() ? { name, isTypeOnly: true } : name,\n );\n}\n\nfunction hasInitExport(sourceFile: SourceFile): boolean {\n if (sourceFile.getVariableDeclaration(\"init\")) return true;\n if (sourceFile.getFunction(\"init\")) return true;\n return sourceFile\n .getExportDeclarations()\n .some((d) => d.getNamedExports().some((e) => e.getName() === \"init\"));\n}\n\n/**\n * Adds the `init` hook that starts the workflow worker. Projects created from\n * the base template already have it; this is the upgrade path for older ones.\n */\nexport function modifyHooksServerWorkflows(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"startWorker\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n if (hasInitExport(sourceFile)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureNamedImport(sourceFile, \"@sveltejs/kit/hooks\", \"ServerInit\", true);\n ensureNamedImport(sourceFile, \"#lib/server/workflows.js\", \"startWorker\");\n\n // After everything else, so the hook reads as the last thing the server does on start.\n sourceFile.addStatements(`\\n${INIT_SNIPPET}`);\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServerWorkflows } from \"./modifies/hooks.server\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { WORKFLOWS_ENV_VARS } from \"./env-vars\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksFile = modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerWorkflows(hooksServerPath),\n );\n if (hooksFile) modifies.push(hooksFile);\n\n // SvelteKit 3 exposes only declared variables; the template declares these\n // already, an older project gets whichever it is missing.\n logger.info(\"Declaring the workflow variables in src/env.ts\");\n const envVars = modifyEnvVarsFiles(options.root, WORKFLOWS_ENV_VARS);\n if (envVars.create) creates.push(envVars.create);\n if (envVars.modify) modifies.push(envVars.modify);\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":";;;;;;;;;;AAMA,IAAMO,IAAe,CAAM;;;GAKrBC,IAAe,CAAM;;;;;;;;;G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;EAAW,SAAS;CAAK;AAC5C;;AC3FA,eAAsBW,EAAS,GAAkB;CAC/C,IAAMC,IAASxB,EAAUyB,CAAO,GAC1BC,IAAkB,CAAC,GACnBC,IAAmB,CAAC;CAE1B,EAAO,KAAK,2BAA2B;CACvC,IAAMP,IAAkBd,EAAK,KAAKmB,EAAQ,MAAM,OAAO,iBAAiB,GAClEG,IAAY3B,EAChBmB,GACAD,EAA2BC,CAAe,CAC5C;CAKA,AAJIQ,KAAWD,EAAS,KAAKC,CAAS,GAItCJ,EAAO,KAAK,gDAAgD;CAC5D,IAAMK,IAAUC,EAAmBL,EAAQ,MAAMrB,CAAkB;CAInE,OAHIyB,EAAQ,UAAQH,EAAQ,KAAKG,EAAQ,MAAM,GAC3CA,EAAQ,UAAQF,EAAS,KAAKE,EAAQ,MAAM,GAEzC;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-ZgLxGWuy.js","names":["getLogger","modifyOutcomeToFile","dedent","formatLikeSource","WORKFLOWS_ENV_VARS","fs","path","INIT_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","ensureNamedImport","existing","sourceFile","d","moduleSpecifier","ni","name","typeOnly","hasInitExport","modifyHooksServerWorkflows","hooksServerPath","Project","QuoteKind","generate","logger","options","creates","modifies","hooksFile","envVars","modifyEnvVarsFiles"],"sources":["../../src/patterns/enable/workflows/modifies/hooks.server.ts","../../src/patterns/enable/workflows/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, type SourceFile } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst INIT_SNIPPET = dedent`\n // Runs once when the server starts: executes the workflows in src/lib/workflows.\n export const init: ServerInit = () => startWorker();\n`;\n\nconst FAILURE_HINT = dedent`\n src/hooks.server.ts already exports an init hook. Start the workflow worker from it:\n\n import { startWorker } from '#lib/server/workflows.js';\n\n export const init: ServerInit = async () => {\n await startWorker();\n // ...the rest of your init\n };\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts and start the workflow worker from its init hook:\n\n import type { ServerInit } from '@sveltejs/kit/hooks';\n import { startWorker } from '#lib/server/workflows.js';\n\n export const init: ServerInit = () => startWorker();\n`;\n\nfunction ensureNamedImport(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n name: string,\n typeOnly = false,\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({\n isTypeOnly: typeOnly,\n namedImports: [name],\n moduleSpecifier,\n });\n return;\n }\n if (existing.getNamedImports().some((ni) => ni.getName() === name)) return;\n // A declaration that is already `import type` covers the new name; a value\n // import takes the name as an inline `type` specifier.\n existing.addNamedImport(\n typeOnly && !existing.isTypeOnly() ? { name, isTypeOnly: true } : name,\n );\n}\n\nfunction hasInitExport(sourceFile: SourceFile): boolean {\n if (sourceFile.getVariableDeclaration(\"init\")) return true;\n if (sourceFile.getFunction(\"init\")) return true;\n return sourceFile\n .getExportDeclarations()\n .some((d) => d.getNamedExports().some((e) => e.getName() === \"init\"));\n}\n\n/**\n * Adds the `init` hook that starts the workflow worker. Projects created from\n * the base template already have it; this is the upgrade path for older ones.\n */\nexport function modifyHooksServerWorkflows(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"startWorker\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n if (hasInitExport(sourceFile)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n ensureNamedImport(sourceFile, \"@sveltejs/kit/hooks\", \"ServerInit\", true);\n ensureNamedImport(sourceFile, \"#lib/server/workflows.js\", \"startWorker\");\n\n // After everything else, so the hook reads as the last thing the server does on start.\n sourceFile.addStatements(`\\n${INIT_SNIPPET}`);\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServerWorkflows } from \"./modifies/hooks.server\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { WORKFLOWS_ENV_VARS } from \"./env-vars\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksFile = modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerWorkflows(hooksServerPath),\n );\n if (hooksFile) modifies.push(hooksFile);\n\n // SvelteKit 3 exposes only declared variables; the template declares these\n // already, an older project gets whichever it is missing.\n logger.info(\"Declaring the workflow variables in src/env.ts\");\n const envVars = modifyEnvVarsFiles(options.root, WORKFLOWS_ENV_VARS);\n if (envVars.create) creates.push(envVars.create);\n if (envVars.modify) modifies.push(envVars.modify);\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":";;;;;;;;;;AAMA,IAAMO,IAAe,CAAM;;;GAKrBC,IAAe,CAAM;;;;;;;;;GAWrBC,IAAiB,CAAM;;;;;;;;AAS7B,SAASC,EACP,GACA,GACA,GACA,IAAW,IACX;CACA,IAAMC,IAAW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AAO,GAC1BC,IAAkB,CAAC,GACnBC,IAAmB,CAAC;CAE1B,EAAO,KAAK,2BAA2B;CACvC,IAAMP,IAAkBd,EAAK,KAAKmB,EAAQ,MAAM,OAAO,iBAAiB,GAClEG,IAAY3B,EAChBmB,GACAD,EAA2BC,CAAe,CAC5C;CAKA,AAJIQ,KAAWD,EAAS,KAAKC,CAAS,GAItCJ,EAAO,KAAK,gDAAgD;CAC5D,IAAMK,IAAUC,EAAmBL,EAAQ,MAAMrB,CAAkB;CAInE,OAHIyB,EAAQ,UAAQH,EAAQ,KAAKG,EAAQ,MAAM,GAC3CA,EAAQ,UAAQF,EAAS,KAAKE,EAAQ,MAAM,GAEzC;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { n as e } from "./logger-t1HxmpG2.js";
2
- import { r as t } from "./modify-file-CRZ_gMg0.js";
2
+ import { r as t } from "./modify-file-CgJIza72.js";
3
3
  import { t as n } from "./dedent-CCUOcPFW.js";
4
4
  import { o as r } from "./ts-morph-helpers-B4KZXP44.js";
5
5
  import i from "node:fs";
@@ -82,4 +82,4 @@ async function d(n) {
82
82
  }
83
83
  export { d as generate };
84
84
 
85
- //# sourceMappingURL=generate.runtime-BgGeOqYG.js.map
85
+ //# sourceMappingURL=generate.runtime-bsuqrKOm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-BgGeOqYG.js","names":["getLogger","modifyOutcomeToFile","dedent","formatLikeSource","fs","path","FAILURE_HINT","NOT_FOUND_HINT","modifyHooksServer","hooksServerPath","originalSource","sourceFile","Project","callExpr","SyntaxKind","ce","args","firstArg","optionsObj","apiProp","apiInit","apiObj","generate","logger","options","modifies","file"],"sources":["../../src/patterns/enable/api/modifies/hooks.server.ts","../../src/patterns/enable/api/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the api option in hooks.server.ts:\n\n handlePocketbase({\n api: { enabled: true },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from 'velastack/handle';\n\n export const handle = handlePocketbase({\n api: { enabled: true },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ api: { enabled: true } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ api: { enabled: true } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const apiProp = optionsObj.getProperty(\"api\");\n\n if (!apiProp) {\n optionsObj.addPropertyAssignment({\n name: \"api\",\n initializer: `{ enabled: true }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n if (apiProp.getKind() === SyntaxKind.PropertyAssignment) {\n const apiInit = (\n apiProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (apiInit && apiInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const apiObj = apiInit as import(\"ts-morph\").ObjectLiteralExpression;\n const enabledProp = apiObj.getProperty(\"enabled\");\n if (!enabledProp) {\n apiObj.addPropertyAssignment({ name: \"enabled\", initializer: \"true\" });\n }\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const file = modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServer(hooksServerPath),\n );\n if (file) modifies.push(file);\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":";;;;;;;;AAMA,IAAMM,IAAe,CAAM;;;;;;GAQrBC,IAAiB,CAAM;;;;;;;;;AAU7B,SAAgBC,EAAkB,GAAwC;CACxE,IAAI,CAACJ,EAAG,WAAWK,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAa,SAASF;CAAe;CAGxD,IAAMG,IAAiBN,EAAG,aAAaK,GAAiB,MAAM,GAExDE,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBH,CAAe,GAExDI,IAAWF,EACd,qBAAqBG,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAOC,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,kBAAkB;CAEnE,IAAI,CAACF,GACH,OAAO;EAAE,QAAQ;EAAU,SAAS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S,KAAKC,CAAI,GAErB;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
+ {"version":3,"file":"generate.runtime-bsuqrKOm.js","names":["getLogger","modifyOutcomeToFile","dedent","formatLikeSource","fs","path","FAILURE_HINT","NOT_FOUND_HINT","modifyHooksServer","hooksServerPath","originalSource","sourceFile","Project","callExpr","SyntaxKind","ce","args","firstArg","optionsObj","apiProp","apiInit","apiObj","generate","logger","options","modifies","file"],"sources":["../../src/patterns/enable/api/modifies/hooks.server.ts","../../src/patterns/enable/api/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the api option in hooks.server.ts:\n\n handlePocketbase({\n api: { enabled: true },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from 'velastack/handle';\n\n export const handle = handlePocketbase({\n api: { enabled: true },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ api: { enabled: true } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ api: { enabled: true } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const apiProp = optionsObj.getProperty(\"api\");\n\n if (!apiProp) {\n optionsObj.addPropertyAssignment({\n name: \"api\",\n initializer: `{ enabled: true }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n if (apiProp.getKind() === SyntaxKind.PropertyAssignment) {\n const apiInit = (\n apiProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (apiInit && apiInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const apiObj = apiInit as import(\"ts-morph\").ObjectLiteralExpression;\n const enabledProp = apiObj.getProperty(\"enabled\");\n if (!enabledProp) {\n apiObj.addPropertyAssignment({ name: \"enabled\", initializer: \"true\" });\n }\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const file = modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServer(hooksServerPath),\n );\n if (file) modifies.push(file);\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}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