@velastack/patterns 0.2.12 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +4 -3
  2. package/dist/chunks/{collections-CcL5bbBk.js → collections-CgdvZXmh.js} +17 -17
  3. package/dist/chunks/{collections-CcL5bbBk.js.map → collections-CgdvZXmh.js.map} +1 -1
  4. package/dist/chunks/{compose-handle-D16KmBVd.js → compose-handle-Cg9jnCsS.js} +21 -21
  5. package/dist/chunks/{compose-handle-D16KmBVd.js.map → compose-handle-Cg9jnCsS.js.map} +1 -1
  6. package/dist/chunks/dispatch-BRnt8PcW.js +6 -0
  7. package/dist/chunks/dispatch-BRnt8PcW.js.map +1 -0
  8. package/dist/chunks/generate-BkQ1xMDp.js +30 -0
  9. package/dist/chunks/generate-BkQ1xMDp.js.map +1 -0
  10. package/dist/chunks/{generate-Va1sxVPG.js → generate-DRA63W0r.js} +17 -64
  11. package/dist/chunks/generate-DRA63W0r.js.map +1 -0
  12. package/dist/chunks/generate-_LvrYK6i.js +55 -0
  13. package/dist/chunks/generate-_LvrYK6i.js.map +1 -0
  14. package/dist/chunks/generate-iQP31-m1.js +252 -0
  15. package/dist/chunks/generate-iQP31-m1.js.map +1 -0
  16. package/dist/chunks/{generate.runtime-j1gfY6Xq.js → generate.runtime-B0hhtyAL.js} +2 -2
  17. package/dist/chunks/{generate.runtime-j1gfY6Xq.js.map → generate.runtime-B0hhtyAL.js.map} +1 -1
  18. package/dist/chunks/{generate.runtime-CSXj-ebM.js → generate.runtime-B49wetSx.js} +12 -12
  19. package/dist/chunks/{generate.runtime-CSXj-ebM.js.map → generate.runtime-B49wetSx.js.map} +1 -1
  20. package/dist/chunks/{generate.runtime-DAkg7Fy5.js → generate.runtime-B7LRx-BU.js} +2 -2
  21. package/dist/chunks/{generate.runtime-DAkg7Fy5.js.map → generate.runtime-B7LRx-BU.js.map} +1 -1
  22. package/dist/chunks/generate.runtime-BKo-Nidn.js +38 -0
  23. package/dist/chunks/generate.runtime-BKo-Nidn.js.map +1 -0
  24. package/dist/chunks/{generate.runtime-Zh5n8XpR.js → generate.runtime-BORbegw_.js} +106 -96
  25. package/dist/chunks/generate.runtime-BORbegw_.js.map +1 -0
  26. package/dist/chunks/{generate.runtime-BL7uKgW7.js → generate.runtime-BbIN0tUZ.js} +16 -16
  27. package/dist/chunks/{generate.runtime-BL7uKgW7.js.map → generate.runtime-BbIN0tUZ.js.map} +1 -1
  28. package/dist/chunks/{generate.runtime-CwzHEcKv.js → generate.runtime-BnWE4qsu.js} +24 -24
  29. package/dist/chunks/generate.runtime-BnWE4qsu.js.map +1 -0
  30. package/dist/chunks/{generate.runtime-CiTmbkAk.js → generate.runtime-BwhGDnGu.js} +3 -3
  31. package/dist/chunks/generate.runtime-BwhGDnGu.js.map +1 -0
  32. package/dist/chunks/{generate.runtime-BdPtilz4.js → generate.runtime-CCg2Pjcv.js} +13 -13
  33. package/dist/chunks/{generate.runtime-BdPtilz4.js.map → generate.runtime-CCg2Pjcv.js.map} +1 -1
  34. package/dist/chunks/{generate.runtime-BbNMkG4j.js → generate.runtime-CRYjWJRe.js} +9 -9
  35. package/dist/chunks/{generate.runtime-BbNMkG4j.js.map → generate.runtime-CRYjWJRe.js.map} +1 -1
  36. package/dist/chunks/generate.runtime-CcuAXuV2.js +60 -0
  37. package/dist/chunks/generate.runtime-CcuAXuV2.js.map +1 -0
  38. package/dist/chunks/{generate.runtime-DPIH5sSI.js → generate.runtime-D0icLb5j.js} +51 -48
  39. package/dist/chunks/{generate.runtime-DPIH5sSI.js.map → generate.runtime-D0icLb5j.js.map} +1 -1
  40. package/dist/chunks/{generate.runtime-CJVy-mMN.js → generate.runtime-D2e_KRj0.js} +2 -2
  41. package/dist/chunks/{generate.runtime-CJVy-mMN.js.map → generate.runtime-D2e_KRj0.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-DnWw9tL1.js → generate.runtime-D44gjxRA.js} +105 -102
  43. package/dist/chunks/generate.runtime-D44gjxRA.js.map +1 -0
  44. package/dist/chunks/{generate.runtime-1gbaOucO.js → generate.runtime-D8vgh5MH.js} +48 -7
  45. package/dist/chunks/generate.runtime-D8vgh5MH.js.map +1 -0
  46. package/dist/chunks/generate.runtime-DAmYsIvF.js +32 -0
  47. package/dist/chunks/generate.runtime-DAmYsIvF.js.map +1 -0
  48. package/dist/chunks/{generate.runtime-CVLtEsXb.js → generate.runtime-DNaQxed-.js} +35 -35
  49. package/dist/chunks/{generate.runtime-CVLtEsXb.js.map → generate.runtime-DNaQxed-.js.map} +1 -1
  50. package/dist/chunks/{generate.runtime-d9HT4v-7.js → generate.runtime-DOuufRLr.js} +4 -4
  51. package/dist/chunks/generate.runtime-DOuufRLr.js.map +1 -0
  52. package/dist/chunks/{generate.runtime-A8wfItN7.js → generate.runtime-DSqkXvps.js} +12 -12
  53. package/dist/chunks/{generate.runtime-A8wfItN7.js.map → generate.runtime-DSqkXvps.js.map} +1 -1
  54. package/dist/chunks/{generate.runtime-BX53l-rL.js → generate.runtime-DhkaXTq3.js} +3 -3
  55. package/dist/chunks/{generate.runtime-BX53l-rL.js.map → generate.runtime-DhkaXTq3.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-Dywp4xth.js → generate.runtime-DoZdSh9W.js} +2 -2
  57. package/dist/chunks/{generate.runtime-Dywp4xth.js.map → generate.runtime-DoZdSh9W.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-T9DZJH8m.js → generate.runtime-S5RIgbQx.js} +103 -100
  59. package/dist/chunks/generate.runtime-S5RIgbQx.js.map +1 -0
  60. package/dist/chunks/{generate.runtime-CN3v78hx.js → generate.runtime-WmSMWL15.js} +17 -17
  61. package/dist/chunks/{generate.runtime-CN3v78hx.js.map → generate.runtime-WmSMWL15.js.map} +1 -1
  62. package/dist/chunks/generate.runtime-acRmiU7e.js +81 -0
  63. package/dist/chunks/generate.runtime-acRmiU7e.js.map +1 -0
  64. package/dist/chunks/{generate.runtime-l-Tiahb2.js → generate.runtime-flFRYzpi.js} +34 -59
  65. package/dist/chunks/generate.runtime-flFRYzpi.js.map +1 -0
  66. package/dist/chunks/generate.runtime-gtpOuLNO.js +110 -0
  67. package/dist/chunks/generate.runtime-gtpOuLNO.js.map +1 -0
  68. package/dist/chunks/{generate.runtime-Dx8Mcs2i.js → generate.runtime-kLxeDGnS.js} +13 -13
  69. package/dist/chunks/{generate.runtime-Dx8Mcs2i.js.map → generate.runtime-kLxeDGnS.js.map} +1 -1
  70. package/dist/chunks/{generate.runtime-BqxVaq5P.js → generate.runtime-wA1G3tQ4.js} +18 -18
  71. package/dist/chunks/{generate.runtime-BqxVaq5P.js.map → generate.runtime-wA1G3tQ4.js.map} +1 -1
  72. package/dist/chunks/{modify-file-BlWTOkCH.js → modify-file-GQD6uNgI.js} +52 -10
  73. package/dist/chunks/modify-file-GQD6uNgI.js.map +1 -0
  74. package/dist/chunks/{pocketbase-ewxQLtse.js → pocketbase-CeG5BMN2.js} +59 -52
  75. package/dist/chunks/{pocketbase-ewxQLtse.js.map → pocketbase-CeG5BMN2.js.map} +1 -1
  76. package/dist/chunks/providers-DO9kMyzB.js +69 -0
  77. package/dist/chunks/providers-DO9kMyzB.js.map +1 -0
  78. package/dist/chunks/rolldown-runtime-DArdT4gl.js +23 -0
  79. package/dist/chunks/{shared-Bm3eMFy-.js → shared-BwHQM-a9.js} +2 -2
  80. package/dist/chunks/{shared-Bm3eMFy-.js.map → shared-BwHQM-a9.js.map} +1 -1
  81. package/dist/chunks/site-D027dpBm.js +55 -0
  82. package/dist/chunks/site-D027dpBm.js.map +1 -0
  83. package/dist/chunks/{ui-CD-psDWi.js → ui-B4Tuit-7.js} +2 -2
  84. package/dist/chunks/{ui-CD-psDWi.js.map → ui-B4Tuit-7.js.map} +1 -1
  85. package/dist/chunks/{write-result-DBKv-Q7J.js → write-result-DewHCNhM.js} +2 -2
  86. package/dist/chunks/{write-result-DBKv-Q7J.js.map → write-result-DewHCNhM.js.map} +1 -1
  87. package/dist/index.d.ts +268 -62
  88. package/dist/index.js +2265 -2246
  89. package/dist/index.js.map +1 -1
  90. package/package.json +3 -3
  91. package/dist/chunks/dispatch-B5PfQ2CA.js +0 -6
  92. package/dist/chunks/dispatch-B5PfQ2CA.js.map +0 -1
  93. package/dist/chunks/generate-Va1sxVPG.js.map +0 -1
  94. package/dist/chunks/generate.runtime-1gbaOucO.js.map +0 -1
  95. package/dist/chunks/generate.runtime-Bb64J0ab.js +0 -87
  96. package/dist/chunks/generate.runtime-Bb64J0ab.js.map +0 -1
  97. package/dist/chunks/generate.runtime-CiTmbkAk.js.map +0 -1
  98. package/dist/chunks/generate.runtime-CwzHEcKv.js.map +0 -1
  99. package/dist/chunks/generate.runtime-Dj22Kx0W.js +0 -107
  100. package/dist/chunks/generate.runtime-Dj22Kx0W.js.map +0 -1
  101. package/dist/chunks/generate.runtime-DnWw9tL1.js.map +0 -1
  102. package/dist/chunks/generate.runtime-T9DZJH8m.js.map +0 -1
  103. package/dist/chunks/generate.runtime-Zh5n8XpR.js.map +0 -1
  104. package/dist/chunks/generate.runtime-d9HT4v-7.js.map +0 -1
  105. package/dist/chunks/generate.runtime-l-Tiahb2.js.map +0 -1
  106. package/dist/chunks/modify-file-BlWTOkCH.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate.runtime-D8vgh5MH.js","names":[],"sources":["../../src/patterns/enable/i18n/modifies/vite-config.ts","../../src/patterns/enable/i18n/modifies/svelte-config.ts","../../src/patterns/enable/i18n/modifies/hooks.server.ts","../../src/patterns/enable/i18n/modifies/app-html.ts","../../src/patterns/enable/i18n/modifies/gitignore.ts","../../src/patterns/enable/i18n/modifies/root-layout.svelte.ts","../../src/patterns/enable/i18n/welcome-catalog.ts","../../src/patterns/enable/i18n/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Add the wuchale plugin to your Vite config:\",\n \"\",\n \"import { wuchale } from 'wuchale/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [wuchale(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the wuchale plugin:\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { wuchale } from 'wuchale/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [wuchale()],\",\n \"});\",\n].join(\"\\n\");\n\nexport function modifyViteConfig(viteConfigPath: string): ModifyOutcome {\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"wuchale/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"wuchale\"],\n moduleSpecifier: \"wuchale/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as import(\"ts-morph\").ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: \"[wuchale()]\",\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (\n pluginsProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"[wuchale()]\",\n );\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasWuchale = arr\n .getElements()\n .some((el) => el.getText().replace(/\\s/g, \"\") === \"wuchale()\");\n\n if (!hasWuchale) {\n arr.insertElement(0, \"wuchale()\");\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n sourceFile.formatText();\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import { SyntaxKind, type PropertyAssignment } from \"ts-morph\";\nimport {\n getOrCreateObjectLiteralProperty,\n modifyConfig,\n type ConfigModifyResult,\n} from \"../../../../runtime/config-target\";\n\nconst FAILURE_HINT = [\n \"Add the $locales alias to your config (sveltekit() arg in vite.config, or svelte.config):\",\n \"\",\n \"alias: {\",\n \" $locales: 'src/locales',\",\n \"},\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Add the $locales alias by passing config to the sveltekit() plugin in vite.config.ts:\",\n \"\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { defineConfig } from 'vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [sveltekit({ alias: { $locales: 'src/locales' } })],\",\n \"});\",\n].join(\"\\n\");\n\n/** Ensure the `$locales` alias points at `src/locales`. */\nexport function modifySvelteConfig(root: string): ConfigModifyResult {\n return modifyConfig(\n root,\n { notFound: NOT_FOUND_HINT, failed: FAILURE_HINT },\n (target) => {\n const kit = target.kitContainer();\n if (!kit) return false;\n const aliasObj = getOrCreateObjectLiteralProperty(kit, \"alias\", \"{}\");\n if (!aliasObj) return false;\n\n const existing = aliasObj.getProperty(\"$locales\");\n if (!existing) {\n aliasObj.addPropertyAssignment({\n name: \"$locales\",\n initializer: \"'src/locales'\",\n });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n\n const init = (existing as PropertyAssignment).getInitializer();\n const current = init?.getText()?.replace(/['\"`]/g, \"\");\n if (current !== \"src/locales\") {\n (existing as PropertyAssignment).setInitializer(\"'src/locales'\");\n }\n return true;\n },\n );\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { addHandle } from \"../../../../runtime/compose-handle\";\nimport { ensureNamedImport } from \"../../../../runtime/ts-morph-helpers\";\n\nconst I18N_HANDLE = \"handleWuchale\";\n\nconst FAILURE_HINT = dedent`\n Wrap your exported handle with the wuchale i18n handler:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import { runWithLocale, loadLocales } from 'wuchale/load-utils/server';\n import { getLocale } from '$locales/main.url';\n import { locales } from '$locales/data';\n import * as main from '$locales/main.loader.server.svelte.js';\n import * as js from '$locales/js.loader.server.js';\n\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n\n const handleWuchale = async ({ event, resolve }: any) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }: { html: string }) =>\n html.replace('%sveltekit.lang%', locale),\n }),\n );\n };\n\n export const handle = sequence(handleWuchale, /* your existing handle */);\n`;\n\n/**\n * The whole file, for a project that had no server hooks: a fresh `sv create`\n * app or a static site. `disable-i18n` deletes it again once the i18n handle\n * is all that is left.\n */\nexport const HOOKS_SERVER_SNIPPET = dedent`\n import type { Handle } from '@sveltejs/kit';\n import { runWithLocale, loadLocales } from 'wuchale/load-utils/server';\n import { getLocale } from '$locales/main.url';\n import { locales } from '$locales/data';\n import * as main from '$locales/main.loader.server.svelte.js';\n import * as js from '$locales/js.loader.server.js';\n\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n\n const handleWuchale: Handle = async ({ event, resolve }) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }) => html.replace('%sveltekit.lang%', locale)\n })\n );\n };\n\n export const handle = handleWuchale;\n`;\n\nfunction ensureNamespaceImport(\n sourceFile: import(\"ts-morph\").SourceFile,\n moduleSpecifier: string,\n ns: string,\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({ namespaceImport: ns, moduleSpecifier });\n}\n\nexport function modifyHooksServerI18n(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n // SvelteKit loads the first `hooks.server.*` it finds, and `.js` sorts\n // first, so a new `.ts` beside it would never run.\n if (fs.existsSync(hooksServerPath.replace(/\\.ts$/, \".js\"))) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n fs.mkdirSync(path.dirname(hooksServerPath), { recursive: true });\n fs.writeFileSync(hooksServerPath, HOOKS_SERVER_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (original.includes(\"runWithLocale\") || original.includes(\"loadLocales(\")) {\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 // Composed first: an unsupported handle leaves the file untouched.\n const composed = addHandle(sourceFile, { expression: I18N_HANDLE });\n if (composed.status === \"unsupported\" || !composed.statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n const handleStmt = composed.statement;\n\n ensureNamedImport(sourceFile, \"wuchale/load-utils/server\", \"runWithLocale\");\n ensureNamedImport(sourceFile, \"wuchale/load-utils/server\", \"loadLocales\");\n ensureNamedImport(sourceFile, \"$locales/main.url\", \"getLocale\");\n ensureNamedImport(sourceFile, \"$locales/data\", \"locales\");\n ensureNamespaceImport(\n sourceFile,\n \"$locales/main.loader.server.svelte.js\",\n \"main\",\n );\n ensureNamespaceImport(sourceFile, \"$locales/js.loader.server.js\", \"js\");\n\n const startupSnippet = dedent`\n loadLocales(main.key, main.loadCount, main.loadCatalog, locales);\n loadLocales(js.key, js.loadCount, js.loadCatalog, locales);\n `;\n\n const i18nHandleSnippet = dedent`\n const ${I18N_HANDLE} = async ({ event, resolve }: any) => {\n const locale = getLocale(event.url);\n return await runWithLocale(locale, () =>\n resolve(event, {\n transformPageChunk: ({ html }: { html: string }) =>\n html.replace('%sveltekit.lang%', locale)\n })\n );\n };\n `;\n\n // Above the handle and its JSDoc, so `handleWuchale` is declared before\n // the handle reads it.\n sourceFile.insertText(\n handleStmt.getStart(true),\n `${startupSnippet}\\n\\n${i18nHandleSnippet}\\n\\n`,\n );\n\n sourceFile.formatText();\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst FAILURE_HINT = [\n \"Add the sveltekit lang placeholder to the <html> tag:\",\n \"\",\n '<html lang=\"%sveltekit.lang%\">',\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/app.html with a lang placeholder:\",\n \"\",\n \"<!doctype html>\",\n '<html lang=\"%sveltekit.lang%\">',\n \" <head>\",\n ' <meta charset=\"utf-8\" />',\n \" %sveltekit.head%\",\n \" </head>\",\n ' <body data-sveltekit-preload-data=\"hover\">',\n ' <div style=\"display: contents\">%sveltekit.body%</div>',\n \" </body>\",\n \"</html>\",\n].join(\"\\n\");\n\nexport function modifyAppHtml(appHtmlPath: string): ModifyOutcome {\n if (!fs.existsSync(appHtmlPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(appHtmlPath, \"utf8\");\n if (\n original.includes('lang=\"%sveltekit.lang%\"') ||\n original.includes(\"lang='%sveltekit.lang%'\")\n ) {\n return { status: \"success\", changed: false };\n }\n\n const updated = original.replace(/<html(\\s[^>]*?)?>/i, (match) => {\n // A static lang (the templates ship lang=\"en\") is replaced by the\n // placeholder so the server hook can fill in the negotiated locale.\n if (/\\slang\\s*=/i.test(match)) {\n return match.replace(\n /\\slang\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/i,\n ' lang=\"%sveltekit.lang%\"',\n );\n }\n return match.replace(/<html/i, '<html lang=\"%sveltekit.lang%\"');\n });\n\n if (updated === original) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n fs.writeFileSync(appHtmlPath, updated);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"Create a .gitignore with the wuchale cache ignored:\",\n \"\",\n \"# Wuchale\",\n \"src/locales/.wuchale\",\n].join(\"\\n\");\n\nexport function modifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n if (original.includes(\"src/locales/.wuchale\")) {\n return { status: \"success\", changed: false };\n }\n\n const block = dedent`\n # Wuchale\n src/locales/.wuchale\n `;\n\n const needsNewline = original.length > 0 && !original.endsWith(\"\\n\");\n const updated = original + (needsNewline ? \"\\n\" : \"\") + \"\\n\" + block + \"\\n\";\n fs.writeFileSync(gitignorePath, updated);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { Ui } from \"../../../../core/field/ui\";\n\nconst LANGUAGE_SELECT_SNIPPET = `<Navbar.Item>\n\t\t\t\t<LanguageSelect />\n\t\t\t</Navbar.Item>\n\t\t\t`;\n\nconst PLAIN_LANGUAGE_SELECT_SNIPPET = \"<LanguageSelect />\";\n\nconst IMPORT_SNIPPET = dedent`\n import LanguageSelect from '$lib/components/language-select.svelte';\n`;\n\nconst FAILURE_HINT = [\n \"Add the language select inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Import to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the end of <Navbar.List>:\",\n LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes a language select inside <Navbar.List>.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup at the end of <Navbar.List>:\",\n LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nconst PLAIN_FAILURE_HINT = [\n \"Add the language select to your root layout.\",\n \"\",\n \"Import to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add wherever it should render, e.g. above {@render children()}:\",\n \"\",\n PLAIN_LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nconst PLAIN_NOT_FOUND_HINT = [\n \"Create a root layout that includes the language select.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup above {@render children()}:\",\n \"\",\n PLAIN_LANGUAGE_SELECT_SNIPPET,\n].join(\"\\n\");\n\nfunction addImport(file: SvelteFile): void {\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n defaultImport: \"LanguageSelect\",\n moduleSpecifier: \"$lib/components/language-select.svelte\",\n },\n ]);\n });\n return out;\n });\n}\n\n/**\n * A vela layout gets the select as the last `<Navbar.List>` item. A plain one\n * (a project vela did not create) has no navbar, so the select goes above the\n * layout's children.\n */\nexport function modifyRootLayoutLanguageSelect(\n layoutPath: string,\n ui: Ui = \"shadcn\",\n): ModifyOutcome {\n const plain = ui === \"plain\";\n if (!fs.existsSync(layoutPath)) {\n return {\n status: \"not-found\",\n message: plain ? PLAIN_NOT_FOUND_HINT : NOT_FOUND_HINT,\n };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"LanguageSelect\")) {\n return { status: \"success\", changed: false };\n }\n\n if (plain) {\n // Without a <script> the import has nowhere to go, and the markup alone\n // would not compile.\n if (!file.getScript()) {\n return { status: \"failed\", message: PLAIN_FAILURE_HINT };\n }\n if (!file.insertBeforeChildren(PLAIN_LANGUAGE_SELECT_SNIPPET)) {\n return { status: \"failed\", message: PLAIN_FAILURE_HINT };\n }\n addImport(file);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n }\n\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n addImport(file);\n file.insertBeforeClosingTag(\"Navbar.List\", LANGUAGE_SELECT_SNIPPET);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File } from \"../../../core/types\";\nimport type { Ui } from \"../../../core/field/ui\";\n\nconst PAGE_PATH = \"src/routes/+page.svelte\";\nconst CATALOG_PATH = \"src/locales/es.po\";\n\n/** `src/routes/+page.svelte` as `sv create` writes it. */\nconst WELCOME_PAGE = [\n \"<h1>Welcome to SvelteKit</h1>\",\n '<p>Visit <a href=\"https://svelte.dev/docs/kit\">svelte.dev/docs/kit</a> to read the documentation</p>',\n].join(\"\\n\");\n\ninterface Entry {\n reference: string;\n msgid: string;\n msgstr: string;\n}\n\nconst PAGE_ENTRIES: Entry[] = [\n {\n reference: PAGE_PATH,\n msgid: \"Welcome to SvelteKit\",\n msgstr: \"Bienvenido a SvelteKit\",\n },\n {\n reference: PAGE_PATH,\n msgid: \"Visit <0>svelte.dev/docs/kit</0> to read the documentation\",\n msgstr: \"Visita <0>svelte.dev/docs/kit</0> para leer la documentación\",\n },\n];\n\n// The native <select>'s aria-label. The shadcn select has no text of its own:\n// locale names come from Intl.DisplayNames.\nconst PLAIN_SELECT_ENTRY: Entry = {\n reference: \"src/lib/components/language-select.svelte\",\n msgid: \"Language\",\n msgstr: \"Idioma\",\n};\n\n// What wuchale writes for `es`. It rewrites the file on the first extraction,\n// keeping these translations and adding the source locale's catalog.\nconst HEADER = [\n 'msgid \"\"',\n 'msgstr \"\"',\n '\"Source-Language: en\\\\n\"',\n '\"Language: es\\\\n\"',\n '\"MIME-Version: 1.0\\\\n\"',\n '\"Content-Type: text/plain; charset=utf-8\\\\n\"',\n '\"Content-Transfer-Encoding: 8bit\\\\n\"',\n '\"Plural-Forms: nplurals=3\\\\n\"',\n '\"X-Plurals-Order: one, many, other\\\\n\"',\n].join(\"\\n\");\n\n// Whitespace is ignored so a page prettier has rewrapped still counts.\nconst normalize = (source: string) => source.replace(/\\s+/g, \"\");\n\n/**\n * A Spanish catalog for the `sv create` welcome page, so the language select\n * visibly does something on a fresh project. Anything else in the project is\n * left for the user to translate. Null unless the page is untouched, and never\n * over an existing catalog.\n */\nexport function welcomePageCatalog(root: string, ui: Ui): File | null {\n if (fs.existsSync(path.join(root, CATALOG_PATH))) return null;\n\n const pagePath = path.join(root, PAGE_PATH);\n if (!fs.existsSync(pagePath)) return null;\n const page = fs.readFileSync(pagePath, \"utf8\");\n if (normalize(page) !== normalize(WELCOME_PAGE)) return null;\n\n const entries =\n ui === \"plain\" ? [...PAGE_ENTRIES, PLAIN_SELECT_ENTRY] : PAGE_ENTRIES;\n const blocks = entries.map((entry) =>\n [\n `#: ${entry.reference}`,\n `msgid \"${entry.msgid}\"`,\n `msgstr \"${entry.msgstr}\"`,\n ].join(\"\\n\"),\n );\n\n return {\n path: CATALOG_PATH,\n language: \"text\",\n content: [HEADER, ...blocks].join(\"\\n\\n\") + \"\\n\",\n status: \"success\",\n };\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 { resolveUi } from \"../../../core/field/ui\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport { modifySvelteConfig } from \"./modifies/svelte-config\";\nimport { modifyHooksServerI18n } from \"./modifies/hooks.server\";\nimport { modifyAppHtml } from \"./modifies/app-html\";\nimport { modifyGitignore } from \"./modifies/gitignore\";\nimport { ensureRootLayoutI18n } from \"./modifies/+layout\";\nimport { modifyRootLayoutLanguageSelect } from \"./modifies/root-layout.svelte\";\nimport { welcomePageCatalog } from \"./welcome-catalog\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n pushResult(\n modifyOutcomeToFile(viteConfigPath, modifyViteConfig(viteConfigPath)),\n );\n\n logger.info(\"Modifying config for i18n alias\");\n const alias = modifySvelteConfig(options.root);\n pushResult(modifyOutcomeToFile(alias.filePath, alias.outcome));\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerI18n(hooksServerPath),\n ),\n );\n\n logger.info(\"Modifying app.html\");\n const appHtmlPath = path.join(options.root, \"src\", \"app.html\");\n pushResult(modifyOutcomeToFile(appHtmlPath, modifyAppHtml(appHtmlPath)));\n\n logger.info(\"Modifying root +layout.ts\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.ts\");\n pushResult(modifyOutcomeToFile(layoutPath, ensureRootLayoutI18n(layoutPath)));\n\n logger.info(\"Modifying root layout language select\");\n const rootLayoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const ui = resolveUi(options);\n // With no layout at all, a plain project's not-found hint names the\n // +layout.svelte it would have rather than vela's root-layout.svelte.\n const rootLayoutPath =\n rootLayoutCandidates.find((p) => fs.existsSync(p)) ??\n (ui === \"plain\" ? rootLayoutCandidates[3] : rootLayoutCandidates[0]);\n pushResult(\n modifyOutcomeToFile(\n rootLayoutPath,\n modifyRootLayoutLanguageSelect(rootLayoutPath, ui),\n ),\n );\n\n logger.info(\"Updating .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n pushResult(\n modifyOutcomeToFile(gitignorePath, modifyGitignore(gitignorePath)),\n );\n\n const catalog = welcomePageCatalog(options.root, ui);\n if (catalog) logger.info(\"Translating the welcome page into Spanish\");\n\n return {\n creates: catalog ? [catalog] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAIA,IAAM,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EAAiB,GAAuC;CACtE,IAAI,CAAC,EAAG,WAAW,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAOxD,IAAM,IAAa,IAJC,EAAQ;EAC1B,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAW,EAAU,OAAO;CACtD,CACmB,CAAA,CAAQ,oBAAoB,CAAc,GAEzD,IAAU,IAC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AC,CAAC,GAE5E,EAAO,KAAK,uCAAuC;CACnD,IAAM,IAAuB;EAC3B,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,YAAY,oBAAoB;EACzE,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,oBAAoB;EAC7D,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,YAAY,gBAAgB;EACrE,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAC3D,GACM,IAAK,EAAU,CAAO,GAGtB,IACJ,EAAqB,MAAM,MAAM,EAAG,WAAW,CAAC,CAAC,MAChD,MAAO,UAAU,EAAqB,KAAK,EAAqB;CAQnE,AAPA,EACE,EACE,GACA,EAA+B,GAAgB,CAAE,CACnD,CACF,GAEA,EAAO,KAAK,qBAAqB;CACjC,IAAM,IAAgB,EAAK,KAAK,EAAQ,MAAM,YAAY;CAC1D,EACE,EAAoB,GAAe,EAAgB,CAAa,CAAC,CACnE;CAEA,IAAM,IAAU,EAAmB,EAAQ,MAAM,CAAE;CAGnD,OAFI,KAAS,EAAO,KAAK,2CAA2C,GAE7D;EACL,SAAS,IAAU,CAAC,CAAO,IAAI,CAAC;EAChC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -0,0 +1,32 @@
1
+ import { o as e } from "./generate-iQP31-m1.js";
2
+ import { n as t } from "./logger-CQONztPm.js";
3
+ import { n } from "./shared-BwHQM-a9.js";
4
+ import { n as r, t as i } from "./generate-_LvrYK6i.js";
5
+ import { n as a } from "./env-BPfk1VAw.js";
6
+ import { envRevertOutcomeToFile as o } from "./modify-file-GQD6uNgI.js";
7
+ import s from "node:fs";
8
+ import c from "node:path";
9
+ //#region src/patterns/disable/ai/generate.runtime.ts
10
+ async function l(l) {
11
+ let u = t(l), d = [], f = [], p = e(l);
12
+ for (let e of r(l)) {
13
+ let t = `${e}/+page.svelte`;
14
+ e !== p && s.existsSync(c.join(l.root, t)) && f.push(n(t));
15
+ }
16
+ u.info("Removing the AI provider's API key from .env");
17
+ let m = c.join(l.root, ".env"), h = o(m, a(m, i()));
18
+ return h.modify && d.push(h.modify), h.delete && f.push(h.delete), {
19
+ creates: [],
20
+ modifies: d,
21
+ deletes: f,
22
+ components: [],
23
+ packages: [],
24
+ collections: [],
25
+ collectionPatches: [],
26
+ collectionDrops: []
27
+ };
28
+ }
29
+ //#endregion
30
+ export { l as generate };
31
+
32
+ //# sourceMappingURL=generate.runtime-DAmYsIvF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate.runtime-DAmYsIvF.js","names":[],"sources":["../../src/patterns/disable/ai/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyEnvRemove } from \"../../../runtime/env\";\nimport { envRevertOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { demoDir } from \"../../enable/ai/generate\";\nimport { allEnvEdits, demoDirs } from \"./generate\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const deletes: File[] = [];\n\n // The base result names the page in the current default group; a page\n // generated before auth was enabled sits in the other one.\n const current = demoDir(options);\n for (const dir of demoDirs(options)) {\n const page = `${dir}/+page.svelte`;\n if (dir !== current && fs.existsSync(path.join(options.root, page))) {\n deletes.push(toDeleteEntry(page));\n }\n }\n\n logger.info(\"Removing the AI provider's API key from .env\");\n const envPath = path.join(options.root, \".env\");\n const env = envRevertOutcomeToFile(\n envPath,\n modifyEnvRemove(envPath, allEnvEdits()),\n );\n if (env.modify) modifies.push(env.modify);\n if (env.delete) deletes.push(env.delete);\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,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,CAAO,GAC1B,IAAmB,CAAC,GACpB,IAAkB,CAAC,GAInB,IAAU,EAAQ,CAAO;CAC/B,KAAK,IAAM,KAAO,EAAS,CAAO,GAAG;EACnC,IAAM,IAAO,GAAG,EAAI;EACpB,AAAI,MAAQ,KAAW,EAAG,WAAW,EAAK,KAAK,EAAQ,MAAM,CAAI,CAAC,KAChE,EAAQ,KAAK,EAAc,CAAI,CAAC;CAEpC;CAEA,EAAO,KAAK,8CAA8C;CAC1D,IAAM,IAAU,EAAK,KAAK,EAAQ,MAAM,MAAM,GACxC,IAAM,EACV,GACA,EAAgB,GAAS,EAAY,CAAC,CACxC;CAIA,OAHI,EAAI,UAAQ,EAAS,KAAK,EAAI,MAAM,GACpC,EAAI,UAAQ,EAAQ,KAAK,EAAI,MAAM,GAEhC;EACL,SAAS,CAAC;EACV;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -2,11 +2,11 @@ import { a as e } from "./util-BLYliuUK.js";
2
2
  import { t } from "./dedent-Gq6Krl4n.js";
3
3
  import { t as n } from "./taggedTemplateLiteral-Dx0fjWiw.js";
4
4
  import { n as r } from "./logger-CQONztPm.js";
5
- import { modifyOutcomeToFile as i, t as a } from "./modify-file-BlWTOkCH.js";
6
- import { t as o } from "./svelte-file-B3RfgVdt.js";
7
- import { t as s } from "./env-BPfk1VAw.js";
8
- import { getMigrationFile as c, migrationDelay as l, withPocketbase as u } from "./pocketbase-ewxQLtse.js";
9
- import { createCollectionIdempotent as d } from "./collections-CcL5bbBk.js";
5
+ import { t as i } from "./env-BPfk1VAw.js";
6
+ import { modifyOutcomeToFile as a, t as o } from "./modify-file-GQD6uNgI.js";
7
+ import { t as s } from "./svelte-file-B3RfgVdt.js";
8
+ import { i as c, n as l, t as u } from "./pocketbase-CeG5BMN2.js";
9
+ import { createCollectionIdempotent as d } from "./collections-CgdvZXmh.js";
10
10
  import f from "node:fs";
11
11
  import p from "node:path";
12
12
  import { Project as m, QuoteKind as h, SyntaxKind as g } from "ts-morph";
@@ -27,14 +27,14 @@ var v = [
27
27
  v
28
28
  ].join("\n");
29
29
  function x(e, t, n, r, i) {
30
- let s = new o(e), c = !1, l = (e) => {
30
+ let a = new s(e), c = !1, l = (e) => {
31
31
  c || e((e) => {
32
- let o = a(e, t, n, r, i);
33
- return o.wasAdded && (c = !0), o.source;
32
+ let a = o(e, t, n, r, i);
33
+ return a.wasAdded && (c = !0), a.source;
34
34
  });
35
35
  };
36
- return l((e) => s.modifyModuleScript(e)), c || l((e) => s.modifyScript(e)), {
37
- newNavUserSnippet: s.toString(),
36
+ return l((e) => a.modifyModuleScript(e)), c || l((e) => a.modifyScript(e)), {
37
+ newNavUserSnippet: a.toString(),
38
38
  wasAdded: c
39
39
  };
40
40
  }
@@ -205,7 +205,7 @@ var j;
205
205
  async function M(t, n, r, i, a = !0) {
206
206
  if (!a) return;
207
207
  await l();
208
- let o = c(n, r, i);
208
+ let o = u(n, r, i);
209
209
  o && t.push({
210
210
  path: o,
211
211
  language: e(o),
@@ -217,10 +217,10 @@ function N(e) {
217
217
  return t(j ||= n(["\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=\"", "\" />\n </section>\n "]), e);
218
218
  }
219
219
  async function P(e) {
220
- let { stripeSecretKey: t, stripePublishableKey: n, stripeWebhookSecret: a, stripePriceId: o } = e.input, c = e.features.auth, l = r(e), f = [], m = [], h = (e) => {
220
+ let { stripeSecretKey: t, stripePublishableKey: n, stripeWebhookSecret: o, stripePriceId: s } = e.input, l = e.features.auth, u = r(e), f = [], m = [], h = (e) => {
221
221
  e && m.push(e);
222
222
  };
223
- l.info("Writing Stripe credentials to .env");
223
+ u.info("Writing Stripe credentials to .env");
224
224
  let g = [
225
225
  {
226
226
  type: "comment",
@@ -239,12 +239,12 @@ async function P(e) {
239
239
  {
240
240
  type: "var",
241
241
  key: "STRIPE_WEBHOOK_SECRET",
242
- value: a
242
+ value: o
243
243
  }
244
244
  ], _ = p.join(e.root, ".env");
245
- h(i(_, s(_, g))), await u(e.root, async (n) => {
246
- let r = (e) => d(n, e, l);
247
- l.info("Creating stripe_products collection");
245
+ h(a(_, i(_, g))), await c(e.root, async (n) => {
246
+ let r = (e) => d(n, e, u);
247
+ u.info("Creating stripe_products collection");
248
248
  let i = await r({
249
249
  name: "stripe_products",
250
250
  type: "base",
@@ -286,7 +286,7 @@ async function P(e) {
286
286
  }
287
287
  ]
288
288
  });
289
- await M(f, "stripe_products", "created", e, i.created), l.info("Creating stripe_prices collection");
289
+ await M(f, "stripe_products", "created", e, i.created), u.info("Creating stripe_prices collection");
290
290
  let a = await r({
291
291
  name: "stripe_prices",
292
292
  type: "base",
@@ -348,8 +348,8 @@ async function P(e) {
348
348
  }
349
349
  ]
350
350
  });
351
- if (await M(f, "stripe_prices", "created", e, a.created), c) {
352
- l.info("Creating stripe_customers collection");
351
+ if (await M(f, "stripe_prices", "created", e, a.created), l) {
352
+ u.info("Creating stripe_customers collection");
353
353
  let i = await r({
354
354
  name: "stripe_customers",
355
355
  type: "base",
@@ -384,7 +384,7 @@ async function P(e) {
384
384
  }
385
385
  ]
386
386
  }), a = i.collection;
387
- await M(f, "stripe_customers", "created", e, i.created), l.info("Creating stripe_payment_methods collection");
387
+ await M(f, "stripe_customers", "created", e, i.created), u.info("Creating stripe_payment_methods collection");
388
388
  let o = await r({
389
389
  name: "stripe_payment_methods",
390
390
  type: "base",
@@ -440,7 +440,7 @@ async function P(e) {
440
440
  }
441
441
  ]
442
442
  }), s = o.collection;
443
- await M(f, "stripe_payment_methods", "created", e, o.created), l.info("Linking default_payment_method on stripe_customers"), await n.collections.update("stripe_customers", { fields: [
443
+ await M(f, "stripe_payment_methods", "created", e, o.created), u.info("Linking default_payment_method on stripe_customers"), await n.collections.update("stripe_customers", { fields: [
444
444
  {
445
445
  name: "id",
446
446
  pattern: "^[a-zA-Z0-9_]+$",
@@ -477,7 +477,7 @@ async function P(e) {
477
477
  onUpdate: !0,
478
478
  type: "autodate"
479
479
  }
480
- ] }), await M(f, "stripe_customers", "updated", e), l.info("Creating transactions collection");
480
+ ] }), await M(f, "stripe_customers", "updated", e), u.info("Creating transactions collection");
481
481
  let c = await r({
482
482
  name: "transactions",
483
483
  type: "base",
@@ -548,13 +548,13 @@ async function P(e) {
548
548
  }
549
549
  ]
550
550
  });
551
- await M(f, "transactions", "created", e, c.created), l.info("Syncing existing PocketBase users to Stripe customers");
552
- let u = await O(n, t, l);
553
- l.info(`Synced ${u.total} users (created ${u.created}, reused ${u.reused}, skipped ${u.skipped})`);
551
+ await M(f, "transactions", "created", e, c.created), u.info("Syncing existing PocketBase users to Stripe customers");
552
+ let l = await O(n, t, u);
553
+ u.info(`Synced ${l.total} users (created ${l.created}, reused ${l.reused}, skipped ${l.skipped})`);
554
554
  }
555
- }), o ? l.info(`Fetching Stripe product/price ${o}`) : l.info("Creating test Stripe product and price");
556
- let { product: v, price: y, existing: b } = o ? await A(t, o) : await k(t);
557
- if (b && l.info("Stripe product/price already exists, skipping creation"), l.info("Seeding Stripe product/price records"), await u(e.root, async (e) => {
555
+ }), s ? u.info(`Fetching Stripe product/price ${s}`) : u.info("Creating test Stripe product and price");
556
+ let { product: v, price: y, existing: b } = s ? await A(t, s) : await k(t);
557
+ if (b && u.info("Stripe product/price already exists, skipping creation"), u.info("Seeding Stripe product/price records"), await c(e.root, async (e) => {
558
558
  try {
559
559
  await e.collection("stripe_products").getOne(v.id);
560
560
  } catch {
@@ -579,17 +579,17 @@ async function P(e) {
579
579
  active: y.active
580
580
  });
581
581
  }
582
- }), l.info("Creating payment +page.svelte"), f.push({
582
+ }), u.info("Creating payment +page.svelte"), f.push({
583
583
  path: "src/routes/(public)/payment/+page.svelte",
584
584
  language: "svelte",
585
585
  content: N(y.id),
586
586
  status: "success"
587
- }), c) {
588
- l.info("Modifying nav-user.svelte");
587
+ }), l) {
588
+ u.info("Modifying nav-user.svelte");
589
589
  let t = p.join(e.root, "src", "lib", "components", "nav-user.svelte");
590
- h(i(t, S(t))), l.info("Modifying signup +page.server.ts");
590
+ h(a(t, S(t))), u.info("Modifying signup +page.server.ts");
591
591
  let n = p.join(e.root, "src", "routes", "(public)", "(auth)", "signup", "+page.server.ts");
592
- h(i(n, D(n)));
592
+ h(a(n, D(n)));
593
593
  }
594
594
  return {
595
595
  creates: f,
@@ -605,4 +605,4 @@ async function P(e) {
605
605
  //#endregion
606
606
  export { P as generate };
607
607
 
608
- //# sourceMappingURL=generate.runtime-CVLtEsXb.js.map
608
+ //# sourceMappingURL=generate.runtime-DNaQxed-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-CVLtEsXb.js","names":[],"sources":["../../src/patterns/enable/payments/modifies/modify-nav-user.ts","../../src/patterns/enable/payments/modifies/modify-user-signup.ts","../../src/patterns/enable/payments/runtime/stripe.ts","../../src/patterns/enable/payments/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BILLING_NAV_SNIPPET = [\n \"import CreditCardIcon from '@lucide/svelte/icons/credit-card';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Billing', url: '/billing', icon: CreditCardIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Billing nav item to nav-user.svelte:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Billing entry:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Billing\",\n \"/billing\",\n \"CreditCardIcon\",\n \"@lucide/svelte/icons/credit-card\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst WORKFLOW_MODULE = \"$lib/workflows/link-stripe-customer\";\n\nconst RUN_SNIPPET = dedent`\n // Queued here, done in the background: the Stripe calls retry on their own,\n // and the key means a retry never makes a second customer for this user.\n await linkStripeCustomer.run(\n { userId: user.id, email: form.data.email },\n { idempotencyKey: user.id }\n );\n`;\n\nconst FAILURE_HINT = [\n \"Could not locate the requestVerification call in signup +page.server.ts.\",\n \"Start the workflow once the user exists:\",\n \"\",\n `import { linkStripeCustomer } from '${WORKFLOW_MODULE}';`,\n \"\",\n RUN_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments.\",\n].join(\"\\n\");\n\n/**\n * Starts the link-stripe-customer workflow right after the user is created.\n * The work itself lives in src/lib/workflows/link-stripe-customer.ts.\n */\nexport function modifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n if (originalSource.includes(\"linkStripeCustomer\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n const requestVerificationCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => {\n const expr = ce.getExpression();\n return (\n expr.getKind() === SyntaxKind.PropertyAccessExpression &&\n expr.getText().includes(\"requestVerification\")\n );\n });\n\n if (!requestVerificationCall) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const statement = requestVerificationCall.getFirstAncestorByKind(\n SyntaxKind.ExpressionStatement,\n );\n\n if (!statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n sourceFile.addImportDeclaration({\n namedImports: [\"linkStripeCustomer\"],\n moduleSpecifier: WORKFLOW_MODULE,\n });\n\n statement.replaceWithText(RUN_SNIPPET + \"\\n\\n\" + statement.getText());\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\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\n .collection(\"users\")\n .getFullList<{ id: string; email: string }>();\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 if (!user.email) {\n logger.info(`Skipping user ${user.id} with no email`);\n result.skipped += 1;\n continue;\n }\n\n const matching = await stripe.customers.list({\n email: user.email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n });\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 ${user.email}`);\n } else {\n customer = await stripe.customers.create({ email: user.email });\n result.created += 1;\n logger.info(`Created Stripe customer ${customer.id} for ${user.email}`);\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 ${user.email}: ${(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 { languageFromPath } from \"../../../core/util\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { createCollectionIdempotent } from \"../../../runtime/collections\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { modifyEnv, type EnvEdit } from \"./modifies/modify-env\";\nimport {\n createTestProductAndPrice,\n getProductAndPriceById,\n syncUsersToStripeCustomers,\n} from \"./runtime/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\nexport async function generate(options: Options) {\n const {\n stripeSecretKey,\n stripePublishableKey,\n stripeWebhookSecret,\n stripePriceId,\n } = options.input as {\n stripeSecretKey: string;\n stripePublishableKey: string;\n stripeWebhookSecret: string;\n stripePriceId?: string;\n };\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 logger.info(\"Writing Stripe credentials to .env\");\n const envEdits: EnvEdit[] = [\n { type: \"comment\", key: \"Stripe credentials\" },\n { type: \"var\", key: \"STRIPE_SECRET_KEY\", value: stripeSecretKey },\n {\n type: \"var\",\n key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\",\n value: stripePublishableKey,\n },\n { type: \"var\", key: \"STRIPE_WEBHOOK_SECRET\", value: stripeWebhookSecret },\n ];\n\n const envPath = path.join(options.root, \".env\");\n pushResult(modifyOutcomeToFile(envPath, modifyEnv(envPath, envEdits)));\n\n await withPocketbase(options.root, async (pb) => {\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating stripe_products collection\");\n const productsResult = await create({\n name: \"stripe_products\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"name\", required: false, type: \"text\" },\n { name: \"active\", required: false, type: \"text\" },\n { name: \"default_price\", required: false, type: \"text\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_products\",\n \"created\",\n options,\n productsResult.created,\n );\n\n logger.info(\"Creating stripe_prices collection\");\n const pricesResult = await create({\n name: \"stripe_prices\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"billing_scheme\", required: false, type: \"text\" },\n { name: \"currency\", required: false, type: \"text\" },\n { name: \"product\", required: false, type: \"text\" },\n { name: \"recurring\", required: false, type: \"json\" },\n { name: \"type\", required: false, type: \"text\" },\n { name: \"unit_amount\", required: false, type: \"number\" },\n { name: \"active\", required: false, type: \"bool\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_prices\",\n \"created\",\n options,\n pricesResult.created,\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"],"mappings":";;;;;;;;;;;;;;AAKA,IAAM,IAAsB;CAC1B;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EACd,GACA,GACA,GACA,GACA,GACkD;CAClD,IAAM,IAAO,IAAI,EAAW,CAAc,GACtC,IAAW,IAET,KAAU,MAAgD;EAC1D,KACJ,GAAK,MAAW;GACd,IAAM,IAAS,EACb,GACA,GACA,GACA,GACA,CACF;GAEA,OADI,EAAO,aAAU,IAAW,KACzB,EAAO;EAChB,CAAC;CACH;CAKA,OAHA,GAAQ,MAAO,EAAK,mBAAmB,CAAE,CAAC,GACrC,KA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S,EAAM;IACf,WAAW,EAAM;IACjB,MAAM,EAAM;IACZ,aAAa,EAAM;IACnB,QAAQ,EAAM;GAChB,CAAC;EACH;CACF,CAAC,GAED,EAAO,KAAK,+BAA+B,GAC3C,EAAQ,KAAK;EACX,MAAM;EACN,UAAU;EACV,SAAS,EAAmB,EAAM,EAAE;EACpC,QAAQ;CACV,CAAC,GAEG,GAAW;EACb,EAAO,KAAK,2BAA2B;EACvC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;EAGA,AAFA,EAAW,EAAoB,GAAa,EAAc,CAAW,CAAC,CAAC,GAEvE,EAAO,KAAK,kCAAkC;EAC9C,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,YACA,UACA,UACA,iBACF;EACA,EACE,EAAoB,GAAgB,EAAiB,CAAc,CAAC,CACtE;CACF;CAEA,OAAO;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-DNaQxed-.js","names":[],"sources":["../../src/patterns/enable/payments/modifies/modify-nav-user.ts","../../src/patterns/enable/payments/modifies/modify-user-signup.ts","../../src/patterns/enable/payments/runtime/stripe.ts","../../src/patterns/enable/payments/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BILLING_NAV_SNIPPET = [\n \"import CreditCardIcon from '@lucide/svelte/icons/credit-card';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Billing', url: '/billing', icon: CreditCardIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Billing nav item to nav-user.svelte:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Billing entry:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Billing\",\n \"/billing\",\n \"CreditCardIcon\",\n \"@lucide/svelte/icons/credit-card\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst WORKFLOW_MODULE = \"$lib/workflows/link-stripe-customer\";\n\nconst RUN_SNIPPET = dedent`\n // Queued here, done in the background: the Stripe calls retry on their own,\n // and the key means a retry never makes a second customer for this user.\n await linkStripeCustomer.run(\n { userId: user.id, email: form.data.email },\n { idempotencyKey: user.id }\n );\n`;\n\nconst FAILURE_HINT = [\n \"Could not locate the requestVerification call in signup +page.server.ts.\",\n \"Start the workflow once the user exists:\",\n \"\",\n `import { linkStripeCustomer } from '${WORKFLOW_MODULE}';`,\n \"\",\n RUN_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments.\",\n].join(\"\\n\");\n\n/**\n * Starts the link-stripe-customer workflow right after the user is created.\n * The work itself lives in src/lib/workflows/link-stripe-customer.ts.\n */\nexport function modifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n if (originalSource.includes(\"linkStripeCustomer\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n const requestVerificationCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => {\n const expr = ce.getExpression();\n return (\n expr.getKind() === SyntaxKind.PropertyAccessExpression &&\n expr.getText().includes(\"requestVerification\")\n );\n });\n\n if (!requestVerificationCall) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const statement = requestVerificationCall.getFirstAncestorByKind(\n SyntaxKind.ExpressionStatement,\n );\n\n if (!statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n sourceFile.addImportDeclaration({\n namedImports: [\"linkStripeCustomer\"],\n moduleSpecifier: WORKFLOW_MODULE,\n });\n\n statement.replaceWithText(RUN_SNIPPET + \"\\n\\n\" + statement.getText());\n\n sourceFile.formatText();\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\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\n .collection(\"users\")\n .getFullList<{ id: string; email: string }>();\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 if (!user.email) {\n logger.info(`Skipping user ${user.id} with no email`);\n result.skipped += 1;\n continue;\n }\n\n const matching = await stripe.customers.list({\n email: user.email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n });\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 ${user.email}`);\n } else {\n customer = await stripe.customers.create({ email: user.email });\n result.created += 1;\n logger.info(`Created Stripe customer ${customer.id} for ${user.email}`);\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 ${user.email}: ${(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 { languageFromPath } from \"../../../core/util\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { createCollectionIdempotent } from \"../../../runtime/collections\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyNavUser } from \"./modifies/modify-nav-user\";\nimport { modifyUserSignup } from \"./modifies/modify-user-signup\";\nimport { modifyEnv, type EnvEdit } from \"./modifies/modify-env\";\nimport {\n createTestProductAndPrice,\n getProductAndPriceById,\n syncUsersToStripeCustomers,\n} from \"./runtime/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\nexport async function generate(options: Options) {\n const {\n stripeSecretKey,\n stripePublishableKey,\n stripeWebhookSecret,\n stripePriceId,\n } = options.input as {\n stripeSecretKey: string;\n stripePublishableKey: string;\n stripeWebhookSecret: string;\n stripePriceId?: string;\n };\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 logger.info(\"Writing Stripe credentials to .env\");\n const envEdits: EnvEdit[] = [\n { type: \"comment\", key: \"Stripe credentials\" },\n { type: \"var\", key: \"STRIPE_SECRET_KEY\", value: stripeSecretKey },\n {\n type: \"var\",\n key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\",\n value: stripePublishableKey,\n },\n { type: \"var\", key: \"STRIPE_WEBHOOK_SECRET\", value: stripeWebhookSecret },\n ];\n\n const envPath = path.join(options.root, \".env\");\n pushResult(modifyOutcomeToFile(envPath, modifyEnv(envPath, envEdits)));\n\n await withPocketbase(options.root, async (pb) => {\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating stripe_products collection\");\n const productsResult = await create({\n name: \"stripe_products\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"name\", required: false, type: \"text\" },\n { name: \"active\", required: false, type: \"text\" },\n { name: \"default_price\", required: false, type: \"text\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_products\",\n \"created\",\n options,\n productsResult.created,\n );\n\n logger.info(\"Creating stripe_prices collection\");\n const pricesResult = await create({\n name: \"stripe_prices\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"billing_scheme\", required: false, type: \"text\" },\n { name: \"currency\", required: false, type: \"text\" },\n { name: \"product\", required: false, type: \"text\" },\n { name: \"recurring\", required: false, type: \"json\" },\n { name: \"type\", required: false, type: \"text\" },\n { name: \"unit_amount\", required: false, type: \"number\" },\n { name: \"active\", required: false, type: \"bool\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_prices\",\n \"created\",\n options,\n pricesResult.created,\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"],"mappings":";;;;;;;;;;;;;;AAKA,IAAM,IAAsB;CAC1B;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EACd,GACA,GACA,GACA,GACA,GACkD;CAClD,IAAM,IAAO,IAAI,EAAW,CAAc,GACtC,IAAW,IAET,KAAU,MAAgD;EAC1D,KACJ,GAAK,MAAW;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,eAAe,CAAC,CAAC,OAAO,EAAM,EAAE;EACtD,QAAgB;GACd,MAAM,EAAG,WAAW,eAAe,CAAC,CAAC,OAAO;IAC1C,IAAI,EAAM;IACV,gBAAgB,EAAM;IACtB,UAAU,EAAM;IAChB,SAAS,EAAM;IACf,WAAW,EAAM;IACjB,MAAM,EAAM;IACZ,aAAa,EAAM;IACnB,QAAQ,EAAM;GAChB,CAAC;EACH;CACF,CAAC,GAED,EAAO,KAAK,+BAA+B,GAC3C,EAAQ,KAAK;EACX,MAAM;EACN,UAAU;EACV,SAAS,EAAmB,EAAM,EAAE;EACpC,QAAQ;CACV,CAAC,GAEG,GAAW;EACb,EAAO,KAAK,2BAA2B;EACvC,IAAM,IAAc,EAAK,KACvB,EAAQ,MACR,OACA,OACA,cACA,iBACF;EAGA,AAFA,EAAW,EAAoB,GAAa,EAAc,CAAW,CAAC,CAAC,GAEvE,EAAO,KAAK,kCAAkC;EAC9C,IAAM,IAAiB,EAAK,KAC1B,EAAQ,MACR,OACA,UACA,YACA,UACA,UACA,iBACF;EACA,EACE,EAAoB,GAAgB,EAAiB,CAAc,CAAC,CACtE;CACF;CAEA,OAAO;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { t as e } from "./dedent-Gq6Krl4n.js";
2
2
  import { n as t } from "./logger-CQONztPm.js";
3
- import { a as n, i as r, n as i, o as a, r as o, s, t as c } from "./dispatch-B5PfQ2CA.js";
4
- import { f as l, modifyOutcomeToFile as u, r as d } from "./modify-file-BlWTOkCH.js";
3
+ import { a as n, i as r, n as i, o as a, r as o, s, t as c } from "./dispatch-BRnt8PcW.js";
4
+ import { h as l, modifyOutcomeToFile as u, r as d } from "./modify-file-GQD6uNgI.js";
5
5
  import { t as f } from "./svelte-file-B3RfgVdt.js";
6
6
  import p from "node:fs";
7
7
  import m from "node:path";
@@ -113,7 +113,7 @@ function S(e, t) {
113
113
  var C = [
114
114
  "Pass the subscription prop to <AppSidebar> in src/routes/(app)/+layout.svelte:",
115
115
  "",
116
- "<AppSidebar user={data.user} meta={data.meta} subscription={data.subscription} />"
116
+ "<AppSidebar user={data.user} subscription={data.subscription} />"
117
117
  ].join("\n"), w = ["Create src/routes/(app)/+layout.svelte with an <AppSidebar /> that receives the subscription prop."].join("\n");
118
118
  function T(e) {
119
119
  if (!p.existsSync(e)) return {
@@ -265,4 +265,4 @@ async function z(e) {
265
265
  //#endregion
266
266
  export { z as generate };
267
267
 
268
- //# sourceMappingURL=generate.runtime-d9HT4v-7.js.map
268
+ //# sourceMappingURL=generate.runtime-DOuufRLr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate.runtime-DOuufRLr.js","names":[],"sources":["../../src/patterns/enable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/enable/subscriptions/modifies/modify-by-template.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-nav-user.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} 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 sf.formatText();\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 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 \"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\nexport function modifyAppLayoutServer(\n filePath: string,\n template: string,\n): ModifyOutcome {\n return modifyByTemplate(\n filePath,\n template,\n \"loadActiveSubscription\",\n NOT_FOUND_HINT,\n );\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 { withInMemoryScript } 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 sf.formatText();\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 { modifyByTemplate } from \"./modify-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst NOT_FOUND_HINT = [\n \"src/lib/components/nav-user.svelte is missing.\",\n \"Enable auth and payments first; subscriptions layers a plan label on top of the existing nav-user.\",\n].join(\"\\n\");\n\nexport function modifyNavUser(\n filePath: string,\n template: string,\n): ModifyOutcome {\n // `planLabel` is unique to subscriptions — safe idempotency marker.\n return modifyByTemplate(filePath, template, \"planLabel\", 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.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 path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { 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\";\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(\n modifyOutcomeToFile(\n navUserPath,\n modifyNavUser(\n navUserPath,\n template(\"src/lib/components/nav-user.svelte\"),\n ),\n ),\n );\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 return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n }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AC/C,IAAM,IAAwB,EAAK,KACjC,EAAQ,MACR,OACA,UACA,SACA,WACA,iBACF;CAWA,AAVA,EACE,EACE,GACA,EACE,GACA,EAAS,0CAA0C,CACrD,CACF,CACF,GAEA,EAAO,KAAK,gCAAgC;CAC5C,IAAM,IAAwB,EAAK,KACjC,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAWA,OAVA,EACE,EACE,GACA,EACE,GACA,EAAS,uCAAuC,CAClD,CACF,CACF,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { n as e } from "./logger-CQONztPm.js";
2
- import { t } from "./shared-Bm3eMFy-.js";
3
- import { f as n, modifyOutcomeToFile as r, n as i, s as a } from "./modify-file-BlWTOkCH.js";
2
+ import { t } from "./shared-BwHQM-a9.js";
3
+ import { c as n, h as r, modifyOutcomeToFile as i, n as a } from "./modify-file-GQD6uNgI.js";
4
4
  import { t as o } from "./svelte-file-B3RfgVdt.js";
5
5
  import { t as s } from "./unmodify-load-W1ePZQHr.js";
6
6
  import c from "node:fs";
@@ -16,14 +16,14 @@ function u(e) {
16
16
  status: "success",
17
17
  changed: !1
18
18
  };
19
- let r = o.fromPath(e);
20
- r.modifyScript((e) => {
21
- let { source: t } = n(e, (e) => {
22
- a(e, "$lib/components/notifications-bell.svelte"), i(e);
19
+ let i = o.fromPath(e);
20
+ i.modifyScript((e) => {
21
+ let { source: t } = r(e, (e) => {
22
+ n(e, "$lib/components/notifications-bell.svelte"), a(e);
23
23
  });
24
24
  return t;
25
25
  });
26
- let s = r.toString();
26
+ let s = i.toString();
27
27
  return s = s.replace(/\n*[ \t]*<div class="ml-auto px-4">\s*<NotificationsBell\s*\/>\s*<\/div>[ \t]*/g, ""), s = s.replace(/[ \t]*<NotificationsBell\s*\/>[ \t]*\r?\n?/g, ""), c.writeFileSync(e, s, "utf8"), {
28
28
  status: "success",
29
29
  changed: s !== t
@@ -41,14 +41,14 @@ function d(e) {
41
41
  //#endregion
42
42
  //#region src/patterns/disable/notifications/generate.runtime.ts
43
43
  async function f(n) {
44
- let i = e(n), a = [], o = (e) => {
44
+ let r = e(n), a = [], o = (e) => {
45
45
  e && a.push(e);
46
46
  };
47
- i.info("Reverting (app) +layout.svelte");
47
+ r.info("Reverting (app) +layout.svelte");
48
48
  let s = l.join(n.root, "src", "routes", "(app)", "+layout.svelte");
49
- o(r(s, u(s))), i.info("Reverting (app) +layout.server.ts");
49
+ o(i(s, u(s))), r.info("Reverting (app) +layout.server.ts");
50
50
  let c = l.join(n.root, "src", "routes", "(app)", "+layout.server.ts");
51
- return o(r(c, d(c))), {
51
+ return o(i(c, d(c))), {
52
52
  creates: [],
53
53
  modifies: a,
54
54
  deletes: [],
@@ -62,4 +62,4 @@ async function f(n) {
62
62
  //#endregion
63
63
  export { f as generate };
64
64
 
65
- //# sourceMappingURL=generate.runtime-A8wfItN7.js.map
65
+ //# sourceMappingURL=generate.runtime-DSqkXvps.js.map