@velastack/patterns 0.14.0 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/dist/chunks/{collections-D-xbHi4M.js → collections-B_-NTtLW.js} +2 -2
  2. package/dist/chunks/{collections-D-xbHi4M.js.map → collections-B_-NTtLW.js.map} +1 -1
  3. package/dist/chunks/{constants-DpK-r_m5.js → constants-CTp-0HKk.js} +21 -31
  4. package/dist/chunks/{constants-DpK-r_m5.js.map → constants-CTp-0HKk.js.map} +1 -1
  5. package/dist/chunks/{currency.server-BwuXG0a9.js → currency.server-DOX4Rzyb.js} +2 -2
  6. package/dist/chunks/{currency.server-BwuXG0a9.js.map → currency.server-DOX4Rzyb.js.map} +1 -1
  7. package/dist/chunks/{env-vars-CVn2076k.js → env-vars-BbS_mWyP.js} +3 -3
  8. package/dist/chunks/{env-vars-CVn2076k.js.map → env-vars-BbS_mWyP.js.map} +1 -1
  9. package/dist/chunks/{generate-CuOm66dn.js → generate-4iujJNAW.js} +3 -3
  10. package/dist/chunks/{generate-CuOm66dn.js.map → generate-4iujJNAW.js.map} +1 -1
  11. package/dist/chunks/{generate-BCYvhyF9.js → generate-B4uDCW5D.js} +2 -2
  12. package/dist/chunks/{generate-BCYvhyF9.js.map → generate-B4uDCW5D.js.map} +1 -1
  13. package/dist/chunks/{generate-oZ1QeqPr.js → generate-BJY8AtAp.js} +2 -2
  14. package/dist/chunks/{generate-oZ1QeqPr.js.map → generate-BJY8AtAp.js.map} +1 -1
  15. package/dist/chunks/{generate-F4FDWvFo.js → generate-Bwkx_usZ.js} +2 -2
  16. package/dist/chunks/{generate-F4FDWvFo.js.map → generate-Bwkx_usZ.js.map} +1 -1
  17. package/dist/chunks/{generate-CY_Ii_bz.js → generate-JkvSNTy-.js} +2 -2
  18. package/dist/chunks/{generate-CY_Ii_bz.js.map → generate-JkvSNTy-.js.map} +1 -1
  19. package/dist/chunks/{generate.runtime-mE0knt2T.js → generate.runtime-27KTIg_o.js} +3 -3
  20. package/dist/chunks/{generate.runtime-mE0knt2T.js.map → generate.runtime-27KTIg_o.js.map} +1 -1
  21. package/dist/chunks/{generate.runtime-erWI6j7m.js → generate.runtime-B7XOa9_A.js} +3 -3
  22. package/dist/chunks/{generate.runtime-erWI6j7m.js.map → generate.runtime-B7XOa9_A.js.map} +1 -1
  23. package/dist/chunks/{generate.runtime-Dtae524O.js → generate.runtime-B8-ORwxT.js} +6 -6
  24. package/dist/chunks/{generate.runtime-Dtae524O.js.map → generate.runtime-B8-ORwxT.js.map} +1 -1
  25. package/dist/chunks/{generate.runtime-CqCXFeWH.js → generate.runtime-BFX_8erf.js} +6 -6
  26. package/dist/chunks/{generate.runtime-CqCXFeWH.js.map → generate.runtime-BFX_8erf.js.map} +1 -1
  27. package/dist/chunks/{generate.runtime-cYh0CQ5d.js → generate.runtime-BROXlbeJ.js} +3 -3
  28. package/dist/chunks/{generate.runtime-cYh0CQ5d.js.map → generate.runtime-BROXlbeJ.js.map} +1 -1
  29. package/dist/chunks/{generate.runtime-Bv_16lWi.js → generate.runtime-BU-4sjyu.js} +4 -4
  30. package/dist/chunks/{generate.runtime-Bv_16lWi.js.map → generate.runtime-BU-4sjyu.js.map} +1 -1
  31. package/dist/chunks/{generate.runtime-DZUPtJVF.js → generate.runtime-BXNBWGYr.js} +2 -2
  32. package/dist/chunks/{generate.runtime-DZUPtJVF.js.map → generate.runtime-BXNBWGYr.js.map} +1 -1
  33. package/dist/chunks/{generate.runtime-DICcLOts.js → generate.runtime-BlEy2fFF.js} +3 -3
  34. package/dist/chunks/{generate.runtime-DICcLOts.js.map → generate.runtime-BlEy2fFF.js.map} +1 -1
  35. package/dist/chunks/{generate.runtime-CMuxVUIY.js → generate.runtime-CBVcsole.js} +2 -2
  36. package/dist/chunks/{generate.runtime-CMuxVUIY.js.map → generate.runtime-CBVcsole.js.map} +1 -1
  37. package/dist/chunks/{generate.runtime-CjqX4tDg.js → generate.runtime-CCaCaXNu.js} +2 -2
  38. package/dist/chunks/{generate.runtime-CjqX4tDg.js.map → generate.runtime-CCaCaXNu.js.map} +1 -1
  39. package/dist/chunks/{generate.runtime-CM3bj0nP.js → generate.runtime-Cm75waRD.js} +2 -2
  40. package/dist/chunks/{generate.runtime-CM3bj0nP.js.map → generate.runtime-Cm75waRD.js.map} +1 -1
  41. package/dist/chunks/{generate.runtime-Cg-dfN9B.js → generate.runtime-CuvdtjKc.js} +2 -2
  42. package/dist/chunks/{generate.runtime-Cg-dfN9B.js.map → generate.runtime-CuvdtjKc.js.map} +1 -1
  43. package/dist/chunks/{generate.runtime-TCVlsBbJ.js → generate.runtime-D0lI3Gt8.js} +4 -4
  44. package/dist/chunks/{generate.runtime-TCVlsBbJ.js.map → generate.runtime-D0lI3Gt8.js.map} +1 -1
  45. package/dist/chunks/{generate.runtime-22jW8aVT.js → generate.runtime-D6l6uLiY.js} +2 -2
  46. package/dist/chunks/{generate.runtime-22jW8aVT.js.map → generate.runtime-D6l6uLiY.js.map} +1 -1
  47. package/dist/chunks/{generate.runtime-CsP4c8GY.js → generate.runtime-D77ueFKY.js} +5 -5
  48. package/dist/chunks/{generate.runtime-CsP4c8GY.js.map → generate.runtime-D77ueFKY.js.map} +1 -1
  49. package/dist/chunks/{generate.runtime-CZKIKP3B.js → generate.runtime-D9OC1RXu.js} +2 -2
  50. package/dist/chunks/{generate.runtime-CZKIKP3B.js.map → generate.runtime-D9OC1RXu.js.map} +1 -1
  51. package/dist/chunks/{generate.runtime-pbIrEsa7.js → generate.runtime-DLoYscQO.js} +3 -3
  52. package/dist/chunks/{generate.runtime-pbIrEsa7.js.map → generate.runtime-DLoYscQO.js.map} +1 -1
  53. package/dist/chunks/{generate.runtime-EB8vpc7D.js → generate.runtime-DhSH1o8H.js} +3 -3
  54. package/dist/chunks/{generate.runtime-EB8vpc7D.js.map → generate.runtime-DhSH1o8H.js.map} +1 -1
  55. package/dist/chunks/{generate.runtime-Bz9z0VPR.js → generate.runtime-DiEiFoxR.js} +3 -3
  56. package/dist/chunks/{generate.runtime-Bz9z0VPR.js.map → generate.runtime-DiEiFoxR.js.map} +1 -1
  57. package/dist/chunks/{generate.runtime-C37djibw.js → generate.runtime-Dm7IEo2h.js} +3 -3
  58. package/dist/chunks/{generate.runtime-C37djibw.js.map → generate.runtime-Dm7IEo2h.js.map} +1 -1
  59. package/dist/chunks/{generate.runtime-Db7JwGTb.js → generate.runtime-Dn0_y2iV.js} +4 -4
  60. package/dist/chunks/{generate.runtime-Db7JwGTb.js.map → generate.runtime-Dn0_y2iV.js.map} +1 -1
  61. package/dist/chunks/{generate.runtime-DfHFd8xs.js → generate.runtime-DuAYqKxl.js} +2 -2
  62. package/dist/chunks/{generate.runtime-DfHFd8xs.js.map → generate.runtime-DuAYqKxl.js.map} +1 -1
  63. package/dist/chunks/{generate.runtime-hq8xt0m_.js → generate.runtime-Duw_JI_b.js} +2 -2
  64. package/dist/chunks/{generate.runtime-hq8xt0m_.js.map → generate.runtime-Duw_JI_b.js.map} +1 -1
  65. package/dist/chunks/{generate.runtime-Ct7cG8va.js → generate.runtime-DxyQqNpu.js} +4 -4
  66. package/dist/chunks/{generate.runtime-Ct7cG8va.js.map → generate.runtime-DxyQqNpu.js.map} +1 -1
  67. package/dist/chunks/{generate.runtime-Cry-DBNl.js → generate.runtime-PDnSxiek.js} +6 -6
  68. package/dist/chunks/{generate.runtime-Cry-DBNl.js.map → generate.runtime-PDnSxiek.js.map} +1 -1
  69. package/dist/chunks/{generate.runtime-YFyuyFhh.js → generate.runtime-RTGpwxcS.js} +5 -5
  70. package/dist/chunks/{generate.runtime-YFyuyFhh.js.map → generate.runtime-RTGpwxcS.js.map} +1 -1
  71. package/dist/chunks/{generate.runtime-DkS7CBmK.js → generate.runtime-TQmspB4Z.js} +4 -4
  72. package/dist/chunks/{generate.runtime-DkS7CBmK.js.map → generate.runtime-TQmspB4Z.js.map} +1 -1
  73. package/dist/chunks/{generate.runtime-j_5K3Uue.js → generate.runtime-UtkANHk1.js} +3 -3
  74. package/dist/chunks/{generate.runtime-j_5K3Uue.js.map → generate.runtime-UtkANHk1.js.map} +1 -1
  75. package/dist/chunks/{generate.runtime-B06rPt_j.js → generate.runtime-VMTLHWLk.js} +7 -7
  76. package/dist/chunks/{generate.runtime-B06rPt_j.js.map → generate.runtime-VMTLHWLk.js.map} +1 -1
  77. package/dist/chunks/{generate.runtime-DhNspd-h.js → generate.runtime-XT_JQlTk.js} +2 -2
  78. package/dist/chunks/{generate.runtime-DhNspd-h.js.map → generate.runtime-XT_JQlTk.js.map} +1 -1
  79. package/dist/chunks/{generate.runtime-CVqPHddZ.js → generate.runtime-XpYi9SlM.js} +2 -2
  80. package/dist/chunks/{generate.runtime-CVqPHddZ.js.map → generate.runtime-XpYi9SlM.js.map} +1 -1
  81. package/dist/chunks/{generate.runtime-CyWuhV6m.js → generate.runtime-ZgLxGWuy.js} +3 -3
  82. package/dist/chunks/{generate.runtime-CyWuhV6m.js.map → generate.runtime-ZgLxGWuy.js.map} +1 -1
  83. package/dist/chunks/{generate.runtime-BgGeOqYG.js → generate.runtime-bsuqrKOm.js} +2 -2
  84. package/dist/chunks/{generate.runtime-BgGeOqYG.js.map → generate.runtime-bsuqrKOm.js.map} +1 -1
  85. package/dist/chunks/{generate.runtime-Cco2mFW2.js → generate.runtime-nXjFqHyb.js} +4 -4
  86. package/dist/chunks/{generate.runtime-Cco2mFW2.js.map → generate.runtime-nXjFqHyb.js.map} +1 -1
  87. package/dist/chunks/{generate.runtime-BSxSHNh7.js → generate.runtime-sjFAWbZc.js} +6 -6
  88. package/dist/chunks/{generate.runtime-BSxSHNh7.js.map → generate.runtime-sjFAWbZc.js.map} +1 -1
  89. package/dist/chunks/{generate.runtime-Cxg1b_BK.js → generate.runtime-wiWdXXPi.js} +4 -4
  90. package/dist/chunks/{generate.runtime-Cxg1b_BK.js.map → generate.runtime-wiWdXXPi.js.map} +1 -1
  91. package/dist/chunks/{i18n-BHCytiiO.js → i18n-mnzzcYhz.js} +2 -2
  92. package/dist/chunks/{i18n-BHCytiiO.js.map → i18n-mnzzcYhz.js.map} +1 -1
  93. package/dist/chunks/{modify-file-CRZ_gMg0.js → modify-file-CgJIza72.js} +2 -2
  94. package/dist/chunks/{modify-file-CRZ_gMg0.js.map → modify-file-CgJIza72.js.map} +1 -1
  95. package/dist/chunks/{pocketbase-gUn2UrDd.js → pocketbase-S8lUt0nI.js} +2 -2
  96. package/dist/chunks/{pocketbase-gUn2UrDd.js.map → pocketbase-S8lUt0nI.js.map} +1 -1
  97. package/dist/chunks/{providers-BB3Z2TrN.js → providers-CDUFaOeQ.js} +2 -2
  98. package/dist/chunks/{providers-BB3Z2TrN.js.map → providers-CDUFaOeQ.js.map} +1 -1
  99. package/dist/chunks/{shared-DE-J_b1j.js → shared-BjTRQ5QH.js} +2 -2
  100. package/dist/chunks/{shared-DE-J_b1j.js.map → shared-BjTRQ5QH.js.map} +1 -1
  101. package/dist/chunks/{site-B9hDxucR.js → site-C8Wcg6LT.js} +2 -2
  102. package/dist/chunks/{site-B9hDxucR.js.map → site-C8Wcg6LT.js.map} +1 -1
  103. package/dist/chunks/{table-core-Dua6QnXM.js → table-core-RvMjoXpT.js} +2 -2
  104. package/dist/chunks/{table-core-Dua6QnXM.js.map → table-core-RvMjoXpT.js.map} +1 -1
  105. package/dist/chunks/{test-setup-gJdzWWs_.js → test-setup-CpjhQSl-.js} +3 -3
  106. package/dist/chunks/{test-setup-gJdzWWs_.js.map → test-setup-CpjhQSl-.js.map} +1 -1
  107. package/dist/chunks/{ui-CD61O7Sb.js → ui-CE-8llQS.js} +3 -3
  108. package/dist/chunks/{ui-CD61O7Sb.js.map → ui-CE-8llQS.js.map} +1 -1
  109. package/dist/chunks/{whatsapp-Bt4o4_q2.js → whatsapp-DT10x76l.js} +2 -2
  110. package/dist/chunks/{whatsapp-Bt4o4_q2.js.map → whatsapp-DT10x76l.js.map} +1 -1
  111. package/dist/chunks/{write-result-B7MewKhQ.js → write-result-BguSfKV-.js} +4 -4
  112. package/dist/chunks/{write-result-B7MewKhQ.js.map → write-result-BguSfKV-.js.map} +1 -1
  113. package/dist/index.js +99 -99
  114. package/dist/index.js.map +1 -1
  115. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-pbIrEsa7.js","names":["FAILURE_HINT","NOT_FOUND_HINT","FAILURE_HINT","FAILURE_HINT","getLogger","modifyOutcomeToFile","probeFirstExisting","VITE_CONFIG_CANDIDATES","resolveMode","withInMemoryScript","ensureImports","dedent","hasProperty","newProject","findLoadFunction","returnedObject","ensureNamedImports","hasSpreadOf","findFinalReturn","inspectEventParameter","ensureImportSpec","SvelteFile","fs","path","FAILURE_HINT$3","NOT_FOUND_HINT$1","elementName","text","modifyViteConfig","call","pluginArgs","viteConfigPath","sourceFile","Project","QuoteKind","changed","failed","d","configArg","SyntaxKind","ce","configObj","pluginsProp","pluginsInit","arr","elements","el","sveltekitIndex","formatLikeSource","DEFAULT_LOCALE","REQUEST_LOCALE","eventName","WUCHALE_LOCALE","cmsSnippet","locale","importLine","parts","spec","createdLayoutServer","imports","snippet","FAILURE_HINT$2","modifyLayoutServer","layoutServerPath","fn","body","Node","event","returned","object","spreadIndex","property","returnIndex","destructuring","typeText","FAILURE_HINT$1","modifyLayoutUniversal","layoutPath","dataExpression","expression","element","IMPORT_SNIPPET","MARKUP_SNIPPET","NOT_FOUND_HINT","FAILURE_HINT","modifyLayoutSvelte","file","out","source","sf","readWuchaleLocales","configPath","root","match","locales","m","vitePluginArgs","mode","list","generate","logger","options","modifies","i18n","pushResult","requestLocale","layoutUniversalPath","layoutSveltePath"],"sources":["../../src/patterns/enable/cms/modifies/vite-config.ts","../../src/patterns/enable/cms/modifies/layout.server.ts","../../src/patterns/enable/cms/modifies/layout.ts","../../src/patterns/enable/cms/modifies/layout.svelte.ts","../../src/patterns/enable/cms/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n type PropertyAssignment,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = [\n \"Add the CMS plugin to your Vite config, ahead of sveltekit():\",\n \"\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the CMS plugin ahead of sveltekit():\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit()],\",\n \"});\",\n].join(\"\\n\");\n\nfunction elementName(text: string): string {\n return text.replace(/\\s/g, \"\");\n}\n\n/**\n * Registers `cms(...)` from `@velastack/cms/vite` in the Vite plugin list, just\n * ahead of `sveltekit()`. Only the plugin array is touched, so the inline\n * `sveltekit({ ... })` shape the templates use is left alone.\n */\nexport function modifyViteConfig(\n viteConfigPath: string,\n pluginArgs = \"\",\n): ModifyOutcome {\n const call = `cms(${pluginArgs})`;\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"@velastack/cms/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"cms\"],\n moduleSpecifier: \"@velastack/cms/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: `[${call}]`,\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (pluginsProp as PropertyAssignment).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as PropertyAssignment).setInitializer(`[${call}]`);\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as ArrayLiteralExpression;\n const elements = arr.getElements();\n const hasCms = elements.some((el) =>\n elementName(el.getText()).startsWith(\"cms(\"),\n );\n\n if (!hasCms) {\n const sveltekitIndex = elements.findIndex((el) =>\n elementName(el.getText()).startsWith(\"sveltekit(\"),\n );\n arr.insertElement(sveltekitIndex === -1 ? 0 : sveltekitIndex, call);\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n ensureImportSpec,\n ensureNamedImports,\n findFinalReturn,\n findLoadFunction,\n hasProperty,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"../../../../runtime/load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport interface LayoutServerLocale {\n /**\n * Expression passed as `locale` to `loadCms`, given the name of the load's\n * event parameter: `() => \"'en'\"` or `(event) => \\`getLocale(${event}.url)\\``.\n */\n expression: (eventName: string) => string;\n /** Imports the expression depends on. */\n imports?: ImportSpec[];\n}\n\n/** A single-locale site: the literal default locale. */\nexport const DEFAULT_LOCALE: LayoutServerLocale = {\n expression: () => \"'en'\",\n};\n\n/**\n * A wuchale site: the language enable-i18n's handle chose for the request,\n * from the URL on a public page and the visitor's preference elsewhere, so\n * the content is in the language the rest of the page is in.\n */\nexport const REQUEST_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `${eventName}.locals.locale`,\n};\n\n/**\n * A wuchale site enabled before the handle set `locals.locale`: the locale\n * its reroute resolved from the URL.\n */\nexport const WUCHALE_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `getLocale(${eventName}.url)`,\n imports: [\n { namedImports: [\"getLocale\"], moduleSpecifier: \"#locales/main.url.js\" },\n ],\n};\n\nfunction cmsSnippet(eventName: string, locale: string): string {\n return dedent`\n const { cms, notFound, gone, redirectTo } = await loadCms(${eventName}, { locale: ${locale} });\n if (redirectTo) redirect(308, redirectTo);\n if (gone) error(410, 'Gone');\n if (notFound) error(404, 'Not found');\n `;\n}\n\nfunction importLine(spec: ImportSpec): string {\n const parts: string[] = [];\n if (spec.defaultImport) parts.push(spec.defaultImport);\n if (spec.namespaceImport) parts.push(`* as ${spec.namespaceImport}`);\n if (spec.namedImports?.length)\n parts.push(`{ ${spec.namedImports.join(\", \")} }`);\n return `import ${parts.join(\", \")} from '${spec.moduleSpecifier}';`;\n}\n\n/**\n * A root `+layout.server.ts` written from scratch, for a project that has\n * none — the static template keeps its layout load universal.\n */\nexport function createdLayoutServer(locale: LayoutServerLocale): string {\n const imports = [\n \"import { error, redirect } from '@sveltejs/kit';\",\n \"import { loadCms } from '#lib/cms.js';\",\n ...(locale.imports ?? []).map(importLine),\n \"import type { LayoutServerLoad } from './$types';\",\n ].join(\"\\n\");\n const snippet = cmsSnippet(\"event\", locale.expression(\"event\"))\n .split(\"\\n\")\n .join(\"\\n\\t\");\n\n return dedent`\n ${imports}\n\n export const load: LayoutServerLoad = async (event) => {\n \t${snippet}\n\n \treturn { cms };\n };\n `.concat(\"\\n\");\n}\n\nconst FAILURE_HINT = [\n \"Call loadCms from the root +layout.server.ts load and return `cms`:\",\n \"\",\n createdLayoutServer(DEFAULT_LOCALE).trimEnd(),\n \"\",\n \"loadCms needs the whole event, so a destructured parameter has to become\",\n \"`event` with the destructuring moved into the body.\",\n].join(\"\\n\");\n\n/**\n * Wires `loadCms` into the root `+layout.server.ts`, creating the file when\n * the project has none:\n *\n * - `loadCms` needs the whole request event, so a destructured parameter is\n * renamed to `event` and the destructuring becomes the first statement.\n * - The tombstone triple (`redirectTo`, `gone`, `notFound`) is handled just\n * before the return.\n * - `cms` is added to the returned object, ahead of any spread so nothing\n * later can shadow it.\n *\n * Anything else — no exported `load`, an expression-bodied arrow, several\n * returns, a non-literal return — is reported as `failed` with the snippet to\n * paste, and the file is left exactly as it was.\n */\nexport function modifyLayoutServer(\n layoutServerPath: string,\n locale: LayoutServerLocale = DEFAULT_LOCALE,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n fs.mkdirSync(path.dirname(layoutServerPath), { recursive: true });\n fs.writeFileSync(layoutServerPath, createdLayoutServer(locale));\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (original.includes(\"loadCms(\")) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutServerPath);\n\n // --- Inspect everything before touching anything. ---\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"failed\", message: FAILURE_HINT };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n const object = returned && returnedObject(returned);\n if (!returned || !object) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const eventName = event.kind === \"identifier\" ? event.name : \"event\";\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n if (!hasProperty(object, \"cms\")) {\n const spreadIndex = object\n .getProperties()\n .findIndex((property) => Node.isSpreadAssignment(property));\n if (spreadIndex === -1) {\n object.addShorthandPropertyAssignment({ name: \"cms\" });\n } else {\n object.insertShorthandPropertyAssignment(spreadIndex, { name: \"cms\" });\n }\n }\n\n // insertStatements counts comment lines, which getStatements() skips.\n const returnIndex = body.getStatementsWithComments().indexOf(returned);\n body.insertStatements(\n returnIndex,\n `\\n${cmsSnippet(eventName, locale.expression(eventName))}\\n`,\n );\n\n if (event.kind === \"binding\") {\n const destructuring = event.pattern.getText();\n body.insertStatements(0, `const ${destructuring} = ${eventName};`);\n const typeText = event.param.getTypeNode()?.getText();\n event.param.replaceWithText(\n typeText ? `${eventName}: ${typeText}` : eventName,\n );\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: eventName });\n }\n\n if (!fn.isAsync()) fn.setIsAsync(true);\n\n ensureNamedImports(sourceFile, \"@sveltejs/kit\", [\"error\", \"redirect\"]);\n ensureNamedImports(sourceFile, \"#lib/cms.js\", [\"loadCms\"]);\n for (const spec of locale.imports ?? []) {\n ensureImportSpec(sourceFile, spec);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n findFinalReturn,\n findLoadFunction,\n hasSpreadOf,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"../../../../runtime/load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Forward the server load's data through the root +layout.ts, so \\`cms\\` reaches\n the page:\n\n export const load = async ({ url, data }) => {\n // ...existing code...\n return { ...data, /* existing keys */ };\n };\n`;\n\n/**\n * Make a universal root \\`+layout.ts\\` forward its server load's data.\n *\n * SvelteKit hands a universal load the server load's result as \\`data\\`, and\n * only what the universal load returns reaches the page. A layout that\n * returns its own object without spreading \\`data\\` — the static template\n * does — would drop \\`cms\\` on the floor once \\`+layout.server.ts\\` exists.\n *\n * No file, or a file without a \\`load\\`, needs nothing: server data flows\n * through on its own.\n */\nexport function modifyLayoutUniversal(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutPath);\n\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"success\", changed: false };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n if (!returned) return { status: \"failed\", message: FAILURE_HINT };\n\n const dataExpression =\n event.kind === \"identifier\" ? `${event.name}.data` : \"data\";\n\n // `return data;` already forwards everything.\n const expression = returned.getExpression();\n if (expression && expression.getText() === dataExpression) {\n return { status: \"success\", changed: false };\n }\n\n const object = returnedObject(returned);\n if (!object) return { status: \"failed\", message: FAILURE_HINT };\n if (hasSpreadOf(object, dataExpression)) {\n return { status: \"success\", changed: false };\n }\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n // First, so the layout's own keys still win over anything the server sent.\n object.insertSpreadAssignment(0, { expression: dataExpression });\n\n if (event.kind === \"binding\") {\n const hasData = event.pattern\n .getElements()\n .some((element) => element.getName() === \"data\");\n if (!hasData) {\n const text = event.pattern.getText();\n event.pattern.replaceWithText(text.replace(/^\\{\\s*/, \"{ data, \"));\n }\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: \"{ data }\" });\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { AdminBar } from '@velastack/cms';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<AdminBar />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <AdminBar /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <AdminBar /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/**\n * Mounts `<AdminBar />` at the top level of the root layout, ahead of\n * `{@render children()}` so the bar is in the DOM before the page content.\n * Falls back to appending when the layout has no render tag or slot.\n */\nexport function modifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"AdminBar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { namedImports: [\"AdminBar\"], moduleSpecifier: \"@velastack/cms\" },\n ]);\n });\n return out;\n });\n\n if (!file.insertBeforeChildren(MARKUP_SNIPPET)) {\n file.appendMarkup(MARKUP_SNIPPET);\n }\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { resolveMode, type CmsMode } from \"./generate\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport {\n DEFAULT_LOCALE,\n REQUEST_LOCALE,\n WUCHALE_LOCALE,\n modifyLayoutServer,\n} from \"./modifies/layout.server\";\nimport { modifyLayoutUniversal } from \"./modifies/layout\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\n/** The locale list from `wuchale.config.js`, or null when it cannot be read. */\nexport function readWuchaleLocales(root: string): string[] | null {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return null;\n const match = fs\n .readFileSync(configPath, \"utf8\")\n .match(/locales:\\s*\\[([^\\]]*)\\]/);\n if (!match) return null;\n const locales = [...match[1].matchAll(/['\"]([^'\"]+)['\"]/g)].map((m) => m[1]);\n return locales.length > 0 ? locales : null;\n}\n\n/**\n * Arguments for the `cms()` Vite plugin.\n *\n * A hosted CMS needs the endpoint and locales at build time so media can be\n * downloaded into the prerendered site. An app hosting the backend itself\n * needs nothing: the media steps are no-ops without an endpoint.\n */\nexport function vitePluginArgs(mode: CmsMode, locales: string[]): string {\n if (mode.local) return \"\";\n const list = locales.map((locale) => `'${locale}'`).join(\", \");\n return `{ endpoint: '${mode.endpoint}', locales: [${list}] }`;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const mode = resolveMode(options);\n const i18n = options.features.i18n;\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n const locales = (i18n && readWuchaleLocales(options.root)) || [\"en\"];\n pushResult(\n modifyOutcomeToFile(\n viteConfigPath,\n modifyViteConfig(viteConfigPath, vitePluginArgs(mode, locales)),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n // `src/lib/locale.ts` came with the handle that sets `locals.locale`.\n const requestLocale = fs.existsSync(\n path.join(options.root, \"src\", \"lib\", \"locale.ts\"),\n );\n const locale = !i18n\n ? DEFAULT_LOCALE\n : requestLocale\n ? REQUEST_LOCALE\n : WUCHALE_LOCALE;\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n modifyLayoutServer(layoutServerPath, locale),\n ),\n );\n\n // A universal root layout has to pass the server load's data along, or\n // `cms` never reaches the page. The static template has one.\n logger.info(\"Modifying src/routes/+layout.ts\");\n const layoutUniversalPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutUniversalPath,\n modifyLayoutUniversal(layoutUniversalPath),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutSveltePath, modifyLayoutSvelte(layoutSveltePath)),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAMA,IAAe,kNAUfC,IAAiB;AAYvB,SAASyB,EAAY,GAAsB;CACzC,OAAOC,EAAK,QAAQ,OAAO,EAAE;AAC/B;AAOA,SAAgBC,EACd,GACA,IAAa,IACE;CACf,IAAMC,IAAO,OAAOC,EAAW;CAC/B,IAAI,CAACR,EAAG,WAAWS,CAAc,GA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C5E,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
+ {"version":3,"file":"generate.runtime-DLoYscQO.js","names":["FAILURE_HINT","NOT_FOUND_HINT","FAILURE_HINT","FAILURE_HINT","getLogger","modifyOutcomeToFile","probeFirstExisting","VITE_CONFIG_CANDIDATES","resolveMode","withInMemoryScript","ensureImports","dedent","hasProperty","newProject","findLoadFunction","returnedObject","ensureNamedImports","hasSpreadOf","findFinalReturn","inspectEventParameter","ensureImportSpec","SvelteFile","fs","path","FAILURE_HINT$3","NOT_FOUND_HINT$1","elementName","text","modifyViteConfig","call","pluginArgs","viteConfigPath","sourceFile","Project","QuoteKind","changed","failed","d","configArg","SyntaxKind","ce","configObj","pluginsProp","pluginsInit","arr","elements","el","sveltekitIndex","formatLikeSource","DEFAULT_LOCALE","REQUEST_LOCALE","eventName","WUCHALE_LOCALE","cmsSnippet","locale","importLine","parts","spec","createdLayoutServer","imports","snippet","FAILURE_HINT$2","modifyLayoutServer","layoutServerPath","fn","body","Node","event","returned","object","spreadIndex","property","returnIndex","destructuring","typeText","FAILURE_HINT$1","modifyLayoutUniversal","layoutPath","dataExpression","expression","element","IMPORT_SNIPPET","MARKUP_SNIPPET","NOT_FOUND_HINT","FAILURE_HINT","modifyLayoutSvelte","file","out","source","sf","readWuchaleLocales","configPath","root","match","locales","m","vitePluginArgs","mode","list","generate","logger","options","modifies","i18n","pushResult","requestLocale","layoutUniversalPath","layoutSveltePath"],"sources":["../../src/patterns/enable/cms/modifies/vite-config.ts","../../src/patterns/enable/cms/modifies/layout.server.ts","../../src/patterns/enable/cms/modifies/layout.ts","../../src/patterns/enable/cms/modifies/layout.svelte.ts","../../src/patterns/enable/cms/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n type PropertyAssignment,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = [\n \"Add the CMS plugin to your Vite config, ahead of sveltekit():\",\n \"\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the CMS plugin ahead of sveltekit():\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit()],\",\n \"});\",\n].join(\"\\n\");\n\nfunction elementName(text: string): string {\n return text.replace(/\\s/g, \"\");\n}\n\n/**\n * Registers `cms(...)` from `@velastack/cms/vite` in the Vite plugin list, just\n * ahead of `sveltekit()`. Only the plugin array is touched, so the inline\n * `sveltekit({ ... })` shape the templates use is left alone.\n */\nexport function modifyViteConfig(\n viteConfigPath: string,\n pluginArgs = \"\",\n): ModifyOutcome {\n const call = `cms(${pluginArgs})`;\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"@velastack/cms/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"cms\"],\n moduleSpecifier: \"@velastack/cms/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: `[${call}]`,\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (pluginsProp as PropertyAssignment).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as PropertyAssignment).setInitializer(`[${call}]`);\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as ArrayLiteralExpression;\n const elements = arr.getElements();\n const hasCms = elements.some((el) =>\n elementName(el.getText()).startsWith(\"cms(\"),\n );\n\n if (!hasCms) {\n const sveltekitIndex = elements.findIndex((el) =>\n elementName(el.getText()).startsWith(\"sveltekit(\"),\n );\n arr.insertElement(sveltekitIndex === -1 ? 0 : sveltekitIndex, call);\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n ensureImportSpec,\n ensureNamedImports,\n findFinalReturn,\n findLoadFunction,\n hasProperty,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"../../../../runtime/load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport interface LayoutServerLocale {\n /**\n * Expression passed as `locale` to `loadCms`, given the name of the load's\n * event parameter: `() => \"'en'\"` or `(event) => \\`getLocale(${event}.url)\\``.\n */\n expression: (eventName: string) => string;\n /** Imports the expression depends on. */\n imports?: ImportSpec[];\n}\n\n/** A single-locale site: the literal default locale. */\nexport const DEFAULT_LOCALE: LayoutServerLocale = {\n expression: () => \"'en'\",\n};\n\n/**\n * A wuchale site: the language enable-i18n's handle chose for the request,\n * from the URL on a public page and the visitor's preference elsewhere, so\n * the content is in the language the rest of the page is in.\n */\nexport const REQUEST_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `${eventName}.locals.locale`,\n};\n\n/**\n * A wuchale site enabled before the handle set `locals.locale`: the locale\n * its reroute resolved from the URL.\n */\nexport const WUCHALE_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `getLocale(${eventName}.url)`,\n imports: [\n { namedImports: [\"getLocale\"], moduleSpecifier: \"#locales/main.url.js\" },\n ],\n};\n\nfunction cmsSnippet(eventName: string, locale: string): string {\n return dedent`\n const { cms, notFound, gone, redirectTo } = await loadCms(${eventName}, { locale: ${locale} });\n if (redirectTo) redirect(308, redirectTo);\n if (gone) error(410, 'Gone');\n if (notFound) error(404, 'Not found');\n `;\n}\n\nfunction importLine(spec: ImportSpec): string {\n const parts: string[] = [];\n if (spec.defaultImport) parts.push(spec.defaultImport);\n if (spec.namespaceImport) parts.push(`* as ${spec.namespaceImport}`);\n if (spec.namedImports?.length)\n parts.push(`{ ${spec.namedImports.join(\", \")} }`);\n return `import ${parts.join(\", \")} from '${spec.moduleSpecifier}';`;\n}\n\n/**\n * A root `+layout.server.ts` written from scratch, for a project that has\n * none — the static template keeps its layout load universal.\n */\nexport function createdLayoutServer(locale: LayoutServerLocale): string {\n const imports = [\n \"import { error, redirect } from '@sveltejs/kit';\",\n \"import { loadCms } from '#lib/cms.js';\",\n ...(locale.imports ?? []).map(importLine),\n \"import type { LayoutServerLoad } from './$types';\",\n ].join(\"\\n\");\n const snippet = cmsSnippet(\"event\", locale.expression(\"event\"))\n .split(\"\\n\")\n .join(\"\\n\\t\");\n\n return dedent`\n ${imports}\n\n export const load: LayoutServerLoad = async (event) => {\n \t${snippet}\n\n \treturn { cms };\n };\n `.concat(\"\\n\");\n}\n\nconst FAILURE_HINT = [\n \"Call loadCms from the root +layout.server.ts load and return `cms`:\",\n \"\",\n createdLayoutServer(DEFAULT_LOCALE).trimEnd(),\n \"\",\n \"loadCms needs the whole event, so a destructured parameter has to become\",\n \"`event` with the destructuring moved into the body.\",\n].join(\"\\n\");\n\n/**\n * Wires `loadCms` into the root `+layout.server.ts`, creating the file when\n * the project has none:\n *\n * - `loadCms` needs the whole request event, so a destructured parameter is\n * renamed to `event` and the destructuring becomes the first statement.\n * - The tombstone triple (`redirectTo`, `gone`, `notFound`) is handled just\n * before the return.\n * - `cms` is added to the returned object, ahead of any spread so nothing\n * later can shadow it.\n *\n * Anything else — no exported `load`, an expression-bodied arrow, several\n * returns, a non-literal return — is reported as `failed` with the snippet to\n * paste, and the file is left exactly as it was.\n */\nexport function modifyLayoutServer(\n layoutServerPath: string,\n locale: LayoutServerLocale = DEFAULT_LOCALE,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n fs.mkdirSync(path.dirname(layoutServerPath), { recursive: true });\n fs.writeFileSync(layoutServerPath, createdLayoutServer(locale));\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (original.includes(\"loadCms(\")) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutServerPath);\n\n // --- Inspect everything before touching anything. ---\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"failed\", message: FAILURE_HINT };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n const object = returned && returnedObject(returned);\n if (!returned || !object) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const eventName = event.kind === \"identifier\" ? event.name : \"event\";\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n if (!hasProperty(object, \"cms\")) {\n const spreadIndex = object\n .getProperties()\n .findIndex((property) => Node.isSpreadAssignment(property));\n if (spreadIndex === -1) {\n object.addShorthandPropertyAssignment({ name: \"cms\" });\n } else {\n object.insertShorthandPropertyAssignment(spreadIndex, { name: \"cms\" });\n }\n }\n\n // insertStatements counts comment lines, which getStatements() skips.\n const returnIndex = body.getStatementsWithComments().indexOf(returned);\n body.insertStatements(\n returnIndex,\n `\\n${cmsSnippet(eventName, locale.expression(eventName))}\\n`,\n );\n\n if (event.kind === \"binding\") {\n const destructuring = event.pattern.getText();\n body.insertStatements(0, `const ${destructuring} = ${eventName};`);\n const typeText = event.param.getTypeNode()?.getText();\n event.param.replaceWithText(\n typeText ? `${eventName}: ${typeText}` : eventName,\n );\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: eventName });\n }\n\n if (!fn.isAsync()) fn.setIsAsync(true);\n\n ensureNamedImports(sourceFile, \"@sveltejs/kit\", [\"error\", \"redirect\"]);\n ensureNamedImports(sourceFile, \"#lib/cms.js\", [\"loadCms\"]);\n for (const spec of locale.imports ?? []) {\n ensureImportSpec(sourceFile, spec);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n findFinalReturn,\n findLoadFunction,\n hasSpreadOf,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"../../../../runtime/load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Forward the server load's data through the root +layout.ts, so \\`cms\\` reaches\n the page:\n\n export const load = async ({ url, data }) => {\n // ...existing code...\n return { ...data, /* existing keys */ };\n };\n`;\n\n/**\n * Make a universal root \\`+layout.ts\\` forward its server load's data.\n *\n * SvelteKit hands a universal load the server load's result as \\`data\\`, and\n * only what the universal load returns reaches the page. A layout that\n * returns its own object without spreading \\`data\\` — the static template\n * does — would drop \\`cms\\` on the floor once \\`+layout.server.ts\\` exists.\n *\n * No file, or a file without a \\`load\\`, needs nothing: server data flows\n * through on its own.\n */\nexport function modifyLayoutUniversal(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutPath);\n\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"success\", changed: false };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n if (!returned) return { status: \"failed\", message: FAILURE_HINT };\n\n const dataExpression =\n event.kind === \"identifier\" ? `${event.name}.data` : \"data\";\n\n // `return data;` already forwards everything.\n const expression = returned.getExpression();\n if (expression && expression.getText() === dataExpression) {\n return { status: \"success\", changed: false };\n }\n\n const object = returnedObject(returned);\n if (!object) return { status: \"failed\", message: FAILURE_HINT };\n if (hasSpreadOf(object, dataExpression)) {\n return { status: \"success\", changed: false };\n }\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n // First, so the layout's own keys still win over anything the server sent.\n object.insertSpreadAssignment(0, { expression: dataExpression });\n\n if (event.kind === \"binding\") {\n const hasData = event.pattern\n .getElements()\n .some((element) => element.getName() === \"data\");\n if (!hasData) {\n const text = event.pattern.getText();\n event.pattern.replaceWithText(text.replace(/^\\{\\s*/, \"{ data, \"));\n }\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: \"{ data }\" });\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { AdminBar } from '@velastack/cms';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<AdminBar />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <AdminBar /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <AdminBar /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/**\n * Mounts `<AdminBar />` at the top level of the root layout, ahead of\n * `{@render children()}` so the bar is in the DOM before the page content.\n * Falls back to appending when the layout has no render tag or slot.\n */\nexport function modifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"AdminBar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { namedImports: [\"AdminBar\"], moduleSpecifier: \"@velastack/cms\" },\n ]);\n });\n return out;\n });\n\n if (!file.insertBeforeChildren(MARKUP_SNIPPET)) {\n file.appendMarkup(MARKUP_SNIPPET);\n }\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { resolveMode, type CmsMode } from \"./generate\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport {\n DEFAULT_LOCALE,\n REQUEST_LOCALE,\n WUCHALE_LOCALE,\n modifyLayoutServer,\n} from \"./modifies/layout.server\";\nimport { modifyLayoutUniversal } from \"./modifies/layout\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\n/** The locale list from `wuchale.config.js`, or null when it cannot be read. */\nexport function readWuchaleLocales(root: string): string[] | null {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return null;\n const match = fs\n .readFileSync(configPath, \"utf8\")\n .match(/locales:\\s*\\[([^\\]]*)\\]/);\n if (!match) return null;\n const locales = [...match[1].matchAll(/['\"]([^'\"]+)['\"]/g)].map((m) => m[1]);\n return locales.length > 0 ? locales : null;\n}\n\n/**\n * Arguments for the `cms()` Vite plugin.\n *\n * A hosted CMS needs the endpoint and locales at build time so media can be\n * downloaded into the prerendered site. An app hosting the backend itself\n * needs nothing: the media steps are no-ops without an endpoint.\n */\nexport function vitePluginArgs(mode: CmsMode, locales: string[]): string {\n if (mode.local) return \"\";\n const list = locales.map((locale) => `'${locale}'`).join(\", \");\n return `{ endpoint: '${mode.endpoint}', locales: [${list}] }`;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const mode = resolveMode(options);\n const i18n = options.features.i18n;\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n const locales = (i18n && readWuchaleLocales(options.root)) || [\"en\"];\n pushResult(\n modifyOutcomeToFile(\n viteConfigPath,\n modifyViteConfig(viteConfigPath, vitePluginArgs(mode, locales)),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n // `src/lib/locale.ts` came with the handle that sets `locals.locale`.\n const requestLocale = fs.existsSync(\n path.join(options.root, \"src\", \"lib\", \"locale.ts\"),\n );\n const locale = !i18n\n ? DEFAULT_LOCALE\n : requestLocale\n ? REQUEST_LOCALE\n : WUCHALE_LOCALE;\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n modifyLayoutServer(layoutServerPath, locale),\n ),\n );\n\n // A universal root layout has to pass the server load's data along, or\n // `cms` never reaches the page. The static template has one.\n logger.info(\"Modifying src/routes/+layout.ts\");\n const layoutUniversalPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutUniversalPath,\n modifyLayoutUniversal(layoutUniversalPath),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutSveltePath, modifyLayoutSvelte(layoutSveltePath)),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAMA,IAAe,kNAUfC,IAAiB;AAYvB,SAASyB,EAAY,GAAsB;CACzC,OAAOC,EAAK,QAAQ,OAAO,EAAE;AAC/B;AAOA,SAAgBC,EACd,GACA,IAAa,IACE;CACf,IAAMC,IAAO,OAAOC,EAAW;CAC/B,IAAI,CAACR,EAAG,WAAWS,C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AAC,CAC5E,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { n as e } from "./logger-t1HxmpG2.js";
2
- import { r as t } from "./modify-file-CRZ_gMg0.js";
3
- import { t as n } from "./shared-DE-J_b1j.js";
2
+ import { r as t } from "./modify-file-CgJIza72.js";
3
+ import { t as n } from "./shared-BjTRQ5QH.js";
4
4
  import { _ as r, h as i, o as a, u as o } from "./ts-morph-helpers-B4KZXP44.js";
5
5
  import { t as s } from "./svelte-file-DfplF3BU.js";
6
6
  import { t as c } from "./unmodify-load-CdWXJ_Ac.js";
@@ -206,4 +206,4 @@ async function O(r) {
206
206
  }
207
207
  export { O as generate };
208
208
 
209
- //# sourceMappingURL=generate.runtime-EB8vpc7D.js.map
209
+ //# sourceMappingURL=generate.runtime-DhSH1o8H.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-EB8vpc7D.js","names":["paymentsBillingPageServerTemplate","paymentsBillingPageSvelteTemplate","getLogger","modifyOutcomeToFile","planDropsForCollections","withInMemoryScript","removeTopLevelStatementByIdentifier","formatLikeSource","removeImportByModuleSpecifier","SvelteFile","removeFromLoad","propsStatement","bindingText","_page_server_default","_page_default","fs","path","SUBSCRIPTION_CASE_VALUES","unmodifyWebhookServer","filePath","original","sf","switchStmt","SyntaxKind","stmt","toRemove","clause","expr","literal","c","spaced","source","unmodifyAppLayoutSvelte","file","updateScript","out","decl","init","nameNode","pattern","elements","hasSub","typeNode","intersection","member","lit","propTexts","p","t","remaining","unmodifyAppSidebar","hasSubPropType","hasSubProp","hasNavUserSubAttr","unmodifyAppLayoutServer","fromLoad","Project","QuoteKind","unmodifyNavUser","content","binding","kept","revertByTemplate","current","enabledMarker","stripped","template","unmodifyBillingPageServer","paymentsBillingPageServerTemplate","unmodifyBillingPageSvelte","paymentsBillingPageSvelteTemplate","generate","logger","options","modifies","pushResult","webhookServerPath","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/disable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-nav-user.ts","../../src/patterns/disable/subscriptions/modifies/revert-by-template.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/disable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst SUBSCRIPTION_CASE_VALUES = new Set([\n \"customer.subscription.created\",\n \"customer.subscription.updated\",\n \"customer.subscription.deleted\",\n]);\n\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n removeImportByModuleSpecifier(sf, \"./subscription/created\");\n removeImportByModuleSpecifier(sf, \"./subscription/updated\");\n removeImportByModuleSpecifier(sf, \"./subscription/deleted\");\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n // Collect matching case clauses first — removing invalidates node refs.\n const toRemove = caseBlock\n .getClauses()\n .filter((clause) => {\n if (clause.getKind() !== SyntaxKind.CaseClause) return false;\n const caseClause = clause.asKindOrThrow(SyntaxKind.CaseClause);\n const expr = caseClause.getExpression();\n const literal =\n expr.asKind(SyntaxKind.StringLiteral) ??\n expr.asKind(SyntaxKind.NoSubstitutionTemplateLiteral);\n if (!literal) return false;\n return SUBSCRIPTION_CASE_VALUES.has(literal.getLiteralValue());\n })\n .map((c) => c.asKindOrThrow(SyntaxKind.CaseClause));\n\n for (const clause of toRemove.reverse()) {\n clause.remove();\n }\n\n formatLikeSource(sf);\n });\n\n // Removing the clauses takes the blank line before `default:` with them.\n const spaced = source.replace(/(break;)\\n(\\s*default:)/, \"$1\\n\\n$2\");\n\n if (spaced === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, spaced, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const removed = file.removeAttribute(\"AppSidebar\", \"subscription\");\n if (!removed) {\n return { status: \"success\", changed: false };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction updateScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n const hasSub = elements.some((e) => e.getName() === \"subscription\");\n\n // Strip subscription from the props type literal (the specific type\n // added by enable-subscriptions — leave unrelated `subscription` props\n // alone).\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"))\n .filter((t) => !/^\\s*subscription\\??\\s*:/.test(t));\n lit.replaceWithText(\n propTexts.length ? `{ ${propTexts.join(\"; \")}; }` : \"{}\",\n );\n break;\n }\n }\n\n if (hasSub) {\n const remaining = elements\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n pattern.replaceWithText(`{ ${remaining.join(\", \")} }`);\n }\n }\n formatLikeSource(sf);\n });\n return out;\n}\n\nexport function unmodifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(filePath, \"utf8\");\n const hasSubPropType = /subscription\\??\\s*:\\s*\\{/.test(source);\n const hasSubProp = /\\bsubscription\\s*=\\s*null\\b/.test(source);\n\n const file = new SvelteFile(source);\n const hasNavUserSubAttr =\n file.hasElement(\"NavUser\") && file.hasAttribute(\"NavUser\", \"subscription\");\n\n if (!hasSubPropType && !hasSubProp && !hasNavUserSubAttr) {\n return { status: \"success\", changed: false };\n }\n\n if (hasSubPropType || hasSubProp) {\n file.modifyScript(updateScript);\n }\n if (hasNavUserSubAttr) {\n file.removeAttribute(\"NavUser\", \"subscription\");\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeFromLoad } from \"../../../../runtime/unmodify-load\";\nimport {\n formatLikeSource,\n removeTopLevelStatementByIdentifier,\n} from \"../../../../runtime/ts-morph-helpers\";\n\n/**\n * Takes out what enable-subscriptions added to the (app) layout load: the\n * `subscription` it loads and returns, and the `loadActiveSubscription`\n * helper. The rest of the load (what other patterns added) stays.\n */\nexport function unmodifyAppLayoutServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"loadActiveSubscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const fromLoad = removeFromLoad(filePath, {\n variables: [\"subscription\"],\n dependsKeys: [],\n returnProps: [\"subscription\"],\n });\n if (fromLoad.status !== \"success\") return fromLoad;\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n removeTopLevelStatementByIdentifier(sf, \"loadActiveSubscription\");\n formatLikeSource(sf);\n sf.saveSync();\n\n return {\n status: \"success\",\n changed: fs.readFileSync(filePath, \"utf8\") !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { withInMemoryScript } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n bindingText,\n propsStatement,\n} from \"../../../enable/subscriptions/modifies/modify-nav-user\";\n\n/**\n * Takes the plan label out of nav-user: the lines showing it, `planLabel`\n * and the `subscription` prop. What other patterns added stays.\n */\nexport function unmodifyNavUser(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"planLabel\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n file.modifyScript(\n (content) =>\n withInMemoryScript(\n // With the blank line enable-subscriptions put before it.\n content.replace(\n /\\n[ \\t]*\\n[ \\t]*const planLabel = \\$derived\\([^\\n]*\\);/,\n \"\",\n ),\n (sf) => {\n const decl = propsStatement(sf)?.getDeclarations()[0];\n const binding = decl\n ?.getNameNode()\n .asKind(SyntaxKind.ObjectBindingPattern);\n const kept = binding\n ?.getElements()\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n if (binding && kept) {\n binding.replaceWithText(bindingText(binding.getText(), kept));\n }\n decl\n ?.getTypeNode()\n ?.asKind(SyntaxKind.TypeLiteral)\n ?.getProperty(\"subscription\")\n ?.remove();\n },\n ).source,\n );\n\n // The lines under the name, with the line break before them.\n const out = file\n .toString()\n .replace(/\\n[ \\t]*<span class=\"[^\"]*\">\\s*\\{planLabel\\}\\s*<\\/span>/g, \"\");\n\n fs.writeFileSync(filePath, out, \"utf8\");\n return { status: \"success\", changed: out !== original };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Rewrites a file to the given `template` if the current content still shows\n * the `enabledMarker` (meaning enable-subscriptions is applied). If the marker\n * is absent (already reverted or never applied), it's a no-op.\n *\n * Strips leading `// [!code highlight:N]` / `<!-- [!code highlight:N] -->`\n * lines so templates can be pulled from `preview-modifies/` directories which\n * use those for documentation highlighting.\n */\nexport function revertByTemplate(\n filePath: string,\n template: string,\n enabledMarker: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (!current.includes(enabledMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageServer(\n filePath: string,\n paymentsBillingPageServerTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageServerTemplate,\n \"selectPlan\",\n );\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageSvelte(\n filePath: string,\n paymentsBillingPageSvelteTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageSvelteTemplate,\n \"availablePlans\",\n );\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\nimport { unmodifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { unmodifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { unmodifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { unmodifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { unmodifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\n\n// Pull the \"post-payments\" state of files that enable-subscriptions fully\n// overwrote. For the billing pages, that's exactly what enable-payments\n// writes in creates-app-mode; for nav-user it's the payments preview-modifies\n// snapshot (with highlight annotations stripped by the revert helper).\nimport paymentsBillingPageServerTemplate from \"../../enable/payments/providers-app-mode/stripe/src/routes/(app)/billing/+page.server.ts?raw\";\nimport paymentsBillingPageSvelteTemplate from \"../../enable/payments/providers-app-mode/stripe/src/routes/(app)/billing/+page.svelte?raw\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n unmodifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n unmodifyAppLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n unmodifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Reverting app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, unmodifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n logger.info(\"Reverting billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n unmodifyBillingPageServer(\n billingPageServerPath,\n paymentsBillingPageServerTemplate,\n ),\n ),\n );\n\n logger.info(\"Reverting billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n unmodifyBillingPageSvelte(\n billingPageSveltePath,\n paymentsBillingPageSvelteTemplate,\n ),\n ),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"stripe_subscriptions\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AASA,IAAMiB,oBAA2B,IAAI,IAAI;CACvC;CACA;CACA;AACF,CAAC;AAED,SAAgBC,EAAsB,GAAiC;CACrE,IAAI,CAACH,EAAG,WAAWI,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAE7C,IAAMC,IAAWL,EAAG,aAAaI,GAAU,MAAM;CACjD,IAAI,CAACC,EAAS,SAAS,2BAA2B,GAChD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,EAAE,cAAWf,EAAmBe,IAAW,MAAO;EAGtD,AAFAZ,EAA8Ba,GAAI,wBAAwB,GAC1Db,EAA8Ba,GAAI,wBAAwB,GAC1Db,EAA8Ba,GAAI,wBAAwB;EAE1D,IAAMC,IAAaD,EAChB,qBAAqBE,EAAW,eAAe,CAAC,CAChD,MAAM,MAASC,EAAK,cAAc,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,YAAY,CAAC;EACvE,IAAI,CAACF,GAAY;EAIjB,IAAMG,IAFYH,EAAW,aAEZ,CAAA,CACd,WAAW,CAAC,CACZ,QAAQ,MAA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EACEc,GACAjF,CACF,CACF,CACF,GAEAwE,EAAO,KAAK,gCAAgC;CAC5C,IAAMU,IAAwBlE,EAAK,KACjCyD,EAAQ,MACR,OACA,UACA,SACA,WACA,cACF;CAgBA,OAfAE,EACExE,EACE+E,GACAb,EACEa,GACAjF,CACF,CACF,CACF,GAOO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4BG,EAC5B,CAAC,sBAAsB,GACvBqE,CACF;CAWA;AACF"}
1
+ {"version":3,"file":"generate.runtime-DhSH1o8H.js","names":["paymentsBillingPageServerTemplate","paymentsBillingPageSvelteTemplate","getLogger","modifyOutcomeToFile","planDropsForCollections","withInMemoryScript","removeTopLevelStatementByIdentifier","formatLikeSource","removeImportByModuleSpecifier","SvelteFile","removeFromLoad","propsStatement","bindingText","_page_server_default","_page_default","fs","path","SUBSCRIPTION_CASE_VALUES","unmodifyWebhookServer","filePath","original","sf","switchStmt","SyntaxKind","stmt","toRemove","clause","expr","literal","c","spaced","source","unmodifyAppLayoutSvelte","file","updateScript","out","decl","init","nameNode","pattern","elements","hasSub","typeNode","intersection","member","lit","propTexts","p","t","remaining","unmodifyAppSidebar","hasSubPropType","hasSubProp","hasNavUserSubAttr","unmodifyAppLayoutServer","fromLoad","Project","QuoteKind","unmodifyNavUser","content","binding","kept","revertByTemplate","current","enabledMarker","stripped","template","unmodifyBillingPageServer","paymentsBillingPageServerTemplate","unmodifyBillingPageSvelte","paymentsBillingPageSvelteTemplate","generate","logger","options","modifies","pushResult","webhookServerPath","appLayoutServerPath","appLayoutSveltePath","appSidebarPath","navUserPath","billingPageServerPath","billingPageSveltePath"],"sources":["../../src/patterns/disable/subscriptions/modifies/modify-webhook-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-svelte.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-sidebar.ts","../../src/patterns/disable/subscriptions/modifies/modify-app-layout-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-nav-user.ts","../../src/patterns/disable/subscriptions/modifies/revert-by-template.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-server.ts","../../src/patterns/disable/subscriptions/modifies/modify-billing-page-svelte.ts","../../src/patterns/disable/subscriptions/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeImportByModuleSpecifier,\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst SUBSCRIPTION_CASE_VALUES = new Set([\n \"customer.subscription.created\",\n \"customer.subscription.updated\",\n \"customer.subscription.deleted\",\n]);\n\nexport function unmodifyWebhookServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"handleSubscriptionCreated\")) {\n return { status: \"success\", changed: false };\n }\n\n const { source } = withInMemoryScript(original, (sf) => {\n removeImportByModuleSpecifier(sf, \"./subscription/created\");\n removeImportByModuleSpecifier(sf, \"./subscription/updated\");\n removeImportByModuleSpecifier(sf, \"./subscription/deleted\");\n\n const switchStmt = sf\n .getDescendantsOfKind(SyntaxKind.SwitchStatement)\n .find((stmt) => stmt.getExpression().getText().includes(\"event.type\"));\n if (!switchStmt) return;\n\n const caseBlock = switchStmt.getCaseBlock();\n // Collect matching case clauses first — removing invalidates node refs.\n const toRemove = caseBlock\n .getClauses()\n .filter((clause) => {\n if (clause.getKind() !== SyntaxKind.CaseClause) return false;\n const caseClause = clause.asKindOrThrow(SyntaxKind.CaseClause);\n const expr = caseClause.getExpression();\n const literal =\n expr.asKind(SyntaxKind.StringLiteral) ??\n expr.asKind(SyntaxKind.NoSubstitutionTemplateLiteral);\n if (!literal) return false;\n return SUBSCRIPTION_CASE_VALUES.has(literal.getLiteralValue());\n })\n .map((c) => c.asKindOrThrow(SyntaxKind.CaseClause));\n\n for (const clause of toRemove.reverse()) {\n clause.remove();\n }\n\n formatLikeSource(sf);\n });\n\n // Removing the clauses takes the blank line before `default:` with them.\n const spaced = source.replace(/(break;)\\n(\\s*default:)/, \"$1\\n\\n$2\");\n\n if (spaced === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, spaced, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyAppLayoutSvelte(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(filePath);\n if (!file.hasElement(\"AppSidebar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.hasAttribute(\"AppSidebar\", \"subscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const removed = file.removeAttribute(\"AppSidebar\", \"subscription\");\n if (!removed) {\n return { status: \"success\", changed: false };\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n withInMemoryScript,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nfunction updateScript(source: string): string {\n const { source: out } = withInMemoryScript(source, (sf) => {\n for (const decl of sf.getVariableDeclarations()) {\n const init = decl.getInitializer();\n if (!init || init.getText() !== \"$props()\") continue;\n\n const nameNode = decl.getNameNode();\n if (nameNode.getKind() !== SyntaxKind.ObjectBindingPattern) continue;\n const pattern = nameNode.asKindOrThrow(SyntaxKind.ObjectBindingPattern);\n const elements = pattern.getElements();\n const hasSub = elements.some((e) => e.getName() === \"subscription\");\n\n // Strip subscription from the props type literal (the specific type\n // added by enable-subscriptions — leave unrelated `subscription` props\n // alone).\n const typeNode = decl.getTypeNode();\n if (typeNode?.getKind() === SyntaxKind.IntersectionType) {\n const intersection = typeNode.asKindOrThrow(\n SyntaxKind.IntersectionType,\n );\n for (const member of intersection.getTypeNodes()) {\n if (member.getKind() !== SyntaxKind.TypeLiteral) continue;\n const lit = member.asKindOrThrow(SyntaxKind.TypeLiteral);\n const propTexts = lit\n .getProperties()\n .map((p) => p.getText().replace(/[;,]\\s*$/, \"\"))\n .filter((t) => !/^\\s*subscription\\??\\s*:/.test(t));\n lit.replaceWithText(\n propTexts.length ? `{ ${propTexts.join(\"; \")}; }` : \"{}\",\n );\n break;\n }\n }\n\n if (hasSub) {\n const remaining = elements\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n pattern.replaceWithText(`{ ${remaining.join(\", \")} }`);\n }\n }\n formatLikeSource(sf);\n });\n return out;\n}\n\nexport function unmodifyAppSidebar(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(filePath, \"utf8\");\n const hasSubPropType = /subscription\\??\\s*:\\s*\\{/.test(source);\n const hasSubProp = /\\bsubscription\\s*=\\s*null\\b/.test(source);\n\n const file = new SvelteFile(source);\n const hasNavUserSubAttr =\n file.hasElement(\"NavUser\") && file.hasAttribute(\"NavUser\", \"subscription\");\n\n if (!hasSubPropType && !hasSubProp && !hasNavUserSubAttr) {\n return { status: \"success\", changed: false };\n }\n\n if (hasSubPropType || hasSubProp) {\n file.modifyScript(updateScript);\n }\n if (hasNavUserSubAttr) {\n file.removeAttribute(\"NavUser\", \"subscription\");\n }\n\n file.writeTo(filePath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeFromLoad } from \"../../../../runtime/unmodify-load\";\nimport {\n formatLikeSource,\n removeTopLevelStatementByIdentifier,\n} from \"../../../../runtime/ts-morph-helpers\";\n\n/**\n * Takes out what enable-subscriptions added to the (app) layout load: the\n * `subscription` it loads and returns, and the `loadActiveSubscription`\n * helper. The rest of the load (what other patterns added) stays.\n */\nexport function unmodifyAppLayoutServer(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"loadActiveSubscription\")) {\n return { status: \"success\", changed: false };\n }\n\n const fromLoad = removeFromLoad(filePath, {\n variables: [\"subscription\"],\n dependsKeys: [],\n returnProps: [\"subscription\"],\n });\n if (fromLoad.status !== \"success\") return fromLoad;\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sf = project.addSourceFileAtPath(filePath);\n removeTopLevelStatementByIdentifier(sf, \"loadActiveSubscription\");\n formatLikeSource(sf);\n sf.saveSync();\n\n return {\n status: \"success\",\n changed: fs.readFileSync(filePath, \"utf8\") !== original,\n };\n}\n","import fs from \"node:fs\";\nimport { SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { withInMemoryScript } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n bindingText,\n propsStatement,\n} from \"../../../enable/subscriptions/modifies/modify-nav-user\";\n\n/**\n * Takes the plan label out of nav-user: the lines showing it, `planLabel`\n * and the `subscription` prop. What other patterns added stays.\n */\nexport function unmodifyNavUser(filePath: string): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n if (!original.includes(\"planLabel\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = new SvelteFile(original);\n file.modifyScript(\n (content) =>\n withInMemoryScript(\n // With the blank line enable-subscriptions put before it.\n content.replace(\n /\\n[ \\t]*\\n[ \\t]*const planLabel = \\$derived\\([^\\n]*\\);/,\n \"\",\n ),\n (sf) => {\n const decl = propsStatement(sf)?.getDeclarations()[0];\n const binding = decl\n ?.getNameNode()\n .asKind(SyntaxKind.ObjectBindingPattern);\n const kept = binding\n ?.getElements()\n .filter((e) => e.getName() !== \"subscription\")\n .map((e) => e.getText());\n if (binding && kept) {\n binding.replaceWithText(bindingText(binding.getText(), kept));\n }\n decl\n ?.getTypeNode()\n ?.asKind(SyntaxKind.TypeLiteral)\n ?.getProperty(\"subscription\")\n ?.remove();\n },\n ).source,\n );\n\n // The lines under the name, with the line break before them.\n const out = file\n .toString()\n .replace(/\\n[ \\t]*<span class=\"[^\"]*\">\\s*\\{planLabel\\}\\s*<\\/span>/g, \"\");\n\n fs.writeFileSync(filePath, out, \"utf8\");\n return { status: \"success\", changed: out !== original };\n}\n","import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Rewrites a file to the given `template` if the current content still shows\n * the `enabledMarker` (meaning enable-subscriptions is applied). If the marker\n * is absent (already reverted or never applied), it's a no-op.\n *\n * Strips leading `// [!code highlight:N]` / `<!-- [!code highlight:N] -->`\n * lines so templates can be pulled from `preview-modifies/` directories which\n * use those for documentation highlighting.\n */\nexport function revertByTemplate(\n filePath: string,\n template: string,\n enabledMarker: string,\n): ModifyOutcome {\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const current = fs.readFileSync(filePath, \"utf8\");\n if (!current.includes(enabledMarker)) {\n return { status: \"success\", changed: false };\n }\n const stripped = template\n .replace(/^[ \\t]*\\/\\/[ \\t]*\\[!code highlight:\\d+\\][ \\t]*\\r?\\n/gm, \"\")\n .replace(\n /^[ \\t]*<!--[ \\t]*\\[!code highlight:\\d+\\][ \\t]*-->[ \\t]*\\r?\\n/gm,\n \"\",\n );\n if (current === stripped) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(filePath, stripped, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageServer(\n filePath: string,\n paymentsBillingPageServerTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageServerTemplate,\n \"selectPlan\",\n );\n}\n","import { revertByTemplate } from \"./revert-by-template\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyBillingPageSvelte(\n filePath: string,\n paymentsBillingPageSvelteTemplate: string,\n): ModifyOutcome {\n return revertByTemplate(\n filePath,\n paymentsBillingPageSvelteTemplate,\n \"availablePlans\",\n );\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\nimport { unmodifyWebhookServer } from \"./modifies/modify-webhook-server\";\nimport { unmodifyAppLayoutSvelte } from \"./modifies/modify-app-layout-svelte\";\nimport { unmodifyAppSidebar } from \"./modifies/modify-app-sidebar\";\nimport { unmodifyAppLayoutServer } from \"./modifies/modify-app-layout-server\";\nimport { unmodifyNavUser } from \"./modifies/modify-nav-user\";\nimport { unmodifyBillingPageServer } from \"./modifies/modify-billing-page-server\";\nimport { unmodifyBillingPageSvelte } from \"./modifies/modify-billing-page-svelte\";\n\n// Pull the \"post-payments\" state of files that enable-subscriptions fully\n// overwrote. For the billing pages, that's exactly what enable-payments\n// writes in creates-app-mode; for nav-user it's the payments preview-modifies\n// snapshot (with highlight annotations stripped by the revert helper).\nimport paymentsBillingPageServerTemplate from \"../../enable/payments/providers-app-mode/stripe/src/routes/(app)/billing/+page.server.ts?raw\";\nimport paymentsBillingPageSvelteTemplate from \"../../enable/payments/providers-app-mode/stripe/src/routes/(app)/billing/+page.svelte?raw\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting webhooks/stripe/handlers/dispatch.ts\");\n const webhookServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"webhooks\",\n \"stripe\",\n \"handlers\",\n \"dispatch.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n webhookServerPath,\n unmodifyWebhookServer(webhookServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n unmodifyAppLayoutServer(appLayoutServerPath),\n ),\n );\n\n logger.info(\"Reverting (app)/+layout.svelte\");\n const appLayoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutSveltePath,\n unmodifyAppLayoutSvelte(appLayoutSveltePath),\n ),\n );\n\n logger.info(\"Reverting app-sidebar.svelte\");\n const appSidebarPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"app-sidebar.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appSidebarPath, unmodifyAppSidebar(appSidebarPath)),\n );\n\n logger.info(\"Reverting nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, unmodifyNavUser(navUserPath)));\n\n logger.info(\"Reverting billing/+page.server.ts\");\n const billingPageServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageServerPath,\n unmodifyBillingPageServer(\n billingPageServerPath,\n paymentsBillingPageServerTemplate,\n ),\n ),\n );\n\n logger.info(\"Reverting billing/+page.svelte\");\n const billingPageSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"billing\",\n \"+page.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(\n billingPageSveltePath,\n unmodifyBillingPageSvelte(\n billingPageSveltePath,\n paymentsBillingPageSvelteTemplate,\n ),\n ),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"stripe_subscriptions\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AASA,IAAMiB,oBAA2B,IAAI,IAAI;CACvC;CACA;CACA;AACF,CAAC;AAED,SAAgBC,EAAsB,GAAiC;CACrE,IAAI,CAACH,EAAG,WAAWI,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAE7C,IAAMC,IAAWL,EAAG,aAAaI,GAAU,MAAM;CACjD,IAAI,CAACC,EAAS,SAAS,2BAA2B,GAChD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,EAAE,cAAWf,EAAmBe,IAAW,MAAO;EAGtD,AAFAZ,EAA8Ba,GAAI,wBAAwB,GAC1Db,EAA8Ba,GAAI,wBAAwB,GAC1Db,EAA8Ba,GAAI,wBAAwB;EAE1D,IAAMC,IAAaD,EAChB,qBAAqBE,EAAW,eAAe,CAAC,CAChD,MAAM,MAASC,EAAK,cAAc,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,YAAY,CAAC;EACvE,IAAI,CAACF,GAAY;EAIjB,IAAMG,IAFYH,EAAW,aAEZ,CAAA,CACd,WAAW,CAAC,CACZ,QAAQ,MAAW;GAClB,IAAII,EAAO,QAAQ,MAAMH,EAAW,YAAY,OAAO;GAEvD,IAAMI,IADaD,EAAO,cAAcH,EAAW,UACtC,CAAA,CAAW,cAAc,GAChCK,IACJD,EAAK,OAAOJ,EAAW,aAAa,KACpCI,EAAK,OAAOJ,EAAW,6BAA6B;GAEtD,OADKK,IACEX,EAAyB,IAAIW,EAAQ,gBAAgB,CAAC,IADxC;EAEvB,CAAC,C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C;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4BG,EAC5B,CAAC,sBAAsB,GACvBqE,CACF;CAWA;AACF"}
@@ -1,9 +1,9 @@
1
1
  import { n as e } from "./logger-t1HxmpG2.js";
2
- import { r as t } from "./modify-file-CRZ_gMg0.js";
2
+ import { r as t } from "./modify-file-CgJIza72.js";
3
3
  import { _ as n, g as r, n as i, o as a, p as o, u as s } from "./ts-morph-helpers-B4KZXP44.js";
4
4
  import { t as c } from "./svelte-file-DfplF3BU.js";
5
5
  import { r as l } from "./lib-specifier-C3M0WTev.js";
6
- import { t as u } from "./shared-DE-J_b1j.js";
6
+ import { t as u } from "./shared-BjTRQ5QH.js";
7
7
  import d from "node:fs";
8
8
  import f from "node:path";
9
9
  import { Project as p, SyntaxKind as m } from "ts-morph";
@@ -105,4 +105,4 @@ async function v(n) {
105
105
  }
106
106
  export { v as generate };
107
107
 
108
- //# sourceMappingURL=generate.runtime-Bz9z0VPR.js.map
108
+ //# sourceMappingURL=generate.runtime-DiEiFoxR.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-Bz9z0VPR.js","names":["getLogger","modifyOutcomeToFile","withInMemoryScript","removeUnusedBindingElement","ensureBlankLineAfterImports","formatLikeSource","removePropsBindingIfUnused","removeImportByModuleSpecifier","SvelteFile","libModule","planDropsForCollections","fs","path","unmodifyLayoutServer","layoutPath","originalSource","sourceFile","Project","literals","SyntaxKind","obj","userProp","unmodifyRootLayoutSvelte","source","file","markup","out","content","sf","unmodifyHooksServer","hooksServerPath","callExpr","ce","firstArg","optionsObj","authProp","generate","logger","options","modifies","pushResult","layoutServerFile","layoutCandidates","layoutFile","p","hooksServerFile"],"sources":["../../src/patterns/disable/auth/modifies/+layout.server.ts","../../src/patterns/disable/auth/modifies/root-layout.svelte.ts","../../src/patterns/disable/auth/modifies/hooks.server.ts","../../src/patterns/disable/auth/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeUnusedBindingElement,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nexport function unmodifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n if (!originalSource.includes(\"locals.pb.authStore.record\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n const literals = sourceFile.getDescendantsOfKind(\n SyntaxKind.ObjectLiteralExpression,\n );\n for (const obj of literals) {\n const userProp = obj.getProperty(\"user\");\n if (!userProp || userProp.getKind() !== SyntaxKind.PropertyAssignment) {\n continue;\n }\n const value = (userProp as import(\"ts-morph\").PropertyAssignment)\n .getInitializer()\n ?.getText();\n if (value === \"locals.pb.authStore.record\") {\n userProp.remove();\n }\n }\n // `user` was often the layout's only use of `locals`, which enable-auth\n // destructured for it.\n removeUnusedBindingElement(sourceFile, \"locals\");\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n removePropsBindingIfUnused,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nexport function unmodifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(layoutPath, \"utf8\");\n const file = new SvelteFile(source);\n if (!file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n // The whole navbar item enable-auth added goes, not just the menu inside\n // it; a layout that placed the menu without one loses only the menu.\n if (!file.removeElementContaining(\"Navbar.Item\", \"AuthMenu.Root\")) {\n file.removeElement(\"AuthMenu.Root\");\n }\n const markup = file.toString().replace(/<script[\\s\\S]*?<\\/script>/g, \"\");\n\n file.modifyScript((content) => {\n const { source: out } = withInMemoryScript(content, (sf) => {\n removeImportByModuleSpecifier(sf, libModule(\"components/ui/auth-menu\"));\n removeImportByModuleSpecifier(\n sf,\n libModule(\"components/user-avatar.svelte\"),\n );\n // Layouts from before UserAvatar import the avatar parts directly.\n removeImportByModuleSpecifier(sf, libModule(\"components/ui/avatar\"));\n // enable-auth added `data` for the menu's `data.user`.\n removePropsBindingIfUnused(sf, \"data\", markup);\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n if (!callExpr) return { status: \"success\", changed: false };\n\n const [firstArg] = callExpr.getArguments();\n if (!firstArg || firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n return { status: \"success\", changed: false };\n }\n\n authProp.remove();\n\n if (optionsObj.getProperties().length === 0) {\n callExpr.removeArgument(0);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyLayoutServer } from \"./modifies/+layout.server\";\nimport { unmodifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutServerFile,\n unmodifyLayoutServer(layoutServerFile),\n ),\n );\n\n logger.info(\"Reverting root layout\");\n const layoutCandidates = [\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 layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, unmodifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, unmodifyHooksServer(hooksServerFile)),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"oauth_accounts\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collection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,GAC1BC,IAAmB,CAAC,GACpBC,KAAc,MAAsB;EACxC,AAAIhB,KAAMe,EAAS,KAAKf,CAAI;CAC9B;CAEA,EAAO,KAAK,6BAA6B;CACzC,IAAMiB,IAAmB7B,EAAK,KAC5B0B,EAAQ,MACR,OACA,UACA,mBACF;CAQA,AAPAE,EACEvC,EACEwC,GACA5B,EAAqB4B,CAAgB,CACvC,CACF,GAEAJ,EAAO,KAAK,uBAAuB;CACnC,IAAMK,IAAmB;EACvB9B,EAAK,KAAK0B,EAAQ,MAAM,OAAO,UAAU,YAAY,oBAAoB;EACzE1B,EAAK,KAAK0B,EAAQ,MAAM,OAAO,UAAU,oBAAoB;EAC7D1B,EAAK,KAAK0B,EAAQ,MAAM,OAAO,UAAU,YAAY,gBAAgB;EACrE1B,EAAK,KAAK0B,EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAC3D,GACMK,IACJD,EAAiB,MAAM,MAAM/B,EAAG,WAAWiC,CAAC,CAAC,KAAKF,EAAiB;CAKrE,AAJAF,EACEvC,EAAoB0C,GAAYrB,EAAyBqB,CAAU,CAAC,CACtE,GAEAN,EAAO,KAAK,2BAA2B;CACvC,IAAMQ,IAAkBjC,EAAK,KAAK0B,EAAQ,MAAM,OAAO,iBAAiB;CAUxE,OATAE,EACEvC,EAAoB4C,GAAiBhB,EAAoBgB,CAAe,CAAC,CAC3E,GAOO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4BnC,EAC5B,CAAC,gBAAgB,GACjB4B,CACF;CAWA;AACF"}
1
+ {"version":3,"file":"generate.runtime-DiEiFoxR.js","names":["getLogger","modifyOutcomeToFile","withInMemoryScript","removeUnusedBindingElement","ensureBlankLineAfterImports","formatLikeSource","removePropsBindingIfUnused","removeImportByModuleSpecifier","SvelteFile","libModule","planDropsForCollections","fs","path","unmodifyLayoutServer","layoutPath","originalSource","sourceFile","Project","literals","SyntaxKind","obj","userProp","unmodifyRootLayoutSvelte","source","file","markup","out","content","sf","unmodifyHooksServer","hooksServerPath","callExpr","ce","firstArg","optionsObj","authProp","generate","logger","options","modifies","pushResult","layoutServerFile","layoutCandidates","layoutFile","p","hooksServerFile"],"sources":["../../src/patterns/disable/auth/modifies/+layout.server.ts","../../src/patterns/disable/auth/modifies/root-layout.svelte.ts","../../src/patterns/disable/auth/modifies/hooks.server.ts","../../src/patterns/disable/auth/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeUnusedBindingElement,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nexport function unmodifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n if (!originalSource.includes(\"locals.pb.authStore.record\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n const literals = sourceFile.getDescendantsOfKind(\n SyntaxKind.ObjectLiteralExpression,\n );\n for (const obj of literals) {\n const userProp = obj.getProperty(\"user\");\n if (!userProp || userProp.getKind() !== SyntaxKind.PropertyAssignment) {\n continue;\n }\n const value = (userProp as import(\"ts-morph\").PropertyAssignment)\n .getInitializer()\n ?.getText();\n if (value === \"locals.pb.authStore.record\") {\n userProp.remove();\n }\n }\n // `user` was often the layout's only use of `locals`, which enable-auth\n // destructured for it.\n removeUnusedBindingElement(sourceFile, \"locals\");\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n removePropsBindingIfUnused,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nexport function unmodifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const source = fs.readFileSync(layoutPath, \"utf8\");\n const file = new SvelteFile(source);\n if (!file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n // The whole navbar item enable-auth added goes, not just the menu inside\n // it; a layout that placed the menu without one loses only the menu.\n if (!file.removeElementContaining(\"Navbar.Item\", \"AuthMenu.Root\")) {\n file.removeElement(\"AuthMenu.Root\");\n }\n const markup = file.toString().replace(/<script[\\s\\S]*?<\\/script>/g, \"\");\n\n file.modifyScript((content) => {\n const { source: out } = withInMemoryScript(content, (sf) => {\n removeImportByModuleSpecifier(sf, libModule(\"components/ui/auth-menu\"));\n removeImportByModuleSpecifier(\n sf,\n libModule(\"components/user-avatar.svelte\"),\n );\n // Layouts from before UserAvatar import the avatar parts directly.\n removeImportByModuleSpecifier(sf, libModule(\"components/ui/avatar\"));\n // enable-auth added `data` for the menu's `data.user`.\n removePropsBindingIfUnused(sf, \"data\", markup);\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n if (!callExpr) return { status: \"success\", changed: false };\n\n const [firstArg] = callExpr.getArguments();\n if (!firstArg || firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n return { status: \"success\", changed: false };\n }\n\n authProp.remove();\n\n if (optionsObj.getProperties().length === 0) {\n callExpr.removeArgument(0);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyLayoutServer } from \"./modifies/+layout.server\";\nimport { unmodifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutServerFile,\n unmodifyLayoutServer(layoutServerFile),\n ),\n );\n\n logger.info(\"Reverting root layout\");\n const layoutCandidates = [\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 layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, unmodifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, unmodifyHooksServer(hooksServerFile)),\n );\n\n const collectionDrops = await planDropsForCollections(\n [\"oauth_accounts\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAQA,SAAgBa,EAAqB,GAAmC;CACtE,IAAI,CAACF,EAAG,WAAWG,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAiBJ,EAAG,aAAaG,GAAY,MAAM;CACzD,IAAI,CAACC,EAAe,SAAS,4BAA4B,GACvD,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAI7C,IAAMC,IAAa,IADCC,EACD,CAAA,CAAQ,oBAAoBH,CAAU,GAEnDI,IAAWF,EAAW,qBAC1BG,EAAW,uBACb;CACA,KAAK,IAAMC,KAAOF,GAAU;EAC1B,IAAMG,IAAWD,EAAI,YAAY,MAAM;EACvC,AAAKC,KAAYA,EAAS,QAAQ,MAAMF,EAAW,sBAGpCE,EACZ,eAAe,CAAC,EACf,QAAQ,MACE,gCACZA,EAAS,OAAO;CAEpB;CAQA,OALAlB,EAA2Ba,GAAY,QAAQ,GAE/CX,EAAiBW,CAAU,GAC3BA,EAAW,SAAS,GAEb;EACL,QAAQ;EACR,SAASA,EAAW,YAAY,MAAMD;CACxC;AACF;;ACpCA,SAAgBO,EAAyB,GAAmC;CAC1E,IAAI,CAACX,EAAG,WAAWG,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMS,IAASZ,EAAG,a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ACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAA,MAb4BnC,EAC5B,CAAC,gBAAgB,GACjB4B,CACF;CAWA;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { n as e } from "./logger-t1HxmpG2.js";
2
2
  import { a as t, c as n, l as r } from "./providers-tjlFH5di.js";
3
- import { modifyEnvVarsFiles as i } from "./env-vars-CVn2076k.js";
4
- import { r as a } from "./modify-file-CRZ_gMg0.js";
3
+ import { modifyEnvVarsFiles as i } from "./env-vars-BbS_mWyP.js";
4
+ import { r as a } from "./modify-file-CgJIza72.js";
5
5
  import { t as o } from "./env-AxyRWcC_.js";
6
6
  import { r as s, t as c } from "./generate-CKuUg3p-.js";
7
7
  import { t as l } from "./dedent-CCUOcPFW.js";
@@ -80,4 +80,4 @@ async function x(l) {
80
80
  }
81
81
  export { x as generate };
82
82
 
83
- //# sourceMappingURL=generate.runtime-C37djibw.js.map
83
+ //# sourceMappingURL=generate.runtime-Dm7IEo2h.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-C37djibw.js","names":["getLogger","providerEnvVars","resolveProvider","suppliedProviderEnv","modifyOutcomeToFile","modifyEnv","envEditsFor","META","dedent","SvelteFile","withInMemoryScript","ensureImports","fs","path","MODULE_SPECIFIER","IMPORT_SNIPPET","MARKUP_SNIPPET","NOT_FOUND_HINT","FAILURE_HINT","modifyLayoutSvelte","layoutPath","file","out","source","sf","generate","logger","options","provider","creates","modifies","pushResult","envVars","modifyEnvVarsFiles","envPath"],"sources":["../../src/patterns/enable/analytics/modifies/layout.svelte.ts","../../src/patterns/enable/analytics/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst MODULE_SPECIFIER = \"#lib/components/analytics/analytics.svelte\";\n\nconst IMPORT_SNIPPET = dedent`\n import Analytics from '${MODULE_SPECIFIER}';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<Analytics />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <Analytics /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <Analytics /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/**\n * Mounts `<Analytics />` at the top level of the root layout, ahead of\n * `{@render children()}`. The component is the same path for every provider,\n * so this modifier is provider-agnostic and a re-run with another provider\n * leaves the layout alone.\n */\nexport function modifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"Analytics\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { defaultImport: \"Analytics\", moduleSpecifier: MODULE_SPECIFIER },\n ]);\n });\n return out;\n });\n\n if (!file.insertBeforeChildren(MARKUP_SNIPPET)) {\n file.appendMarkup(MARKUP_SNIPPET);\n }\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n providerEnvVars,\n resolveProvider,\n suppliedProviderEnv,\n} from \"../../../core/providers\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnv } from \"../../../runtime/env\";\nimport { envEditsFor, META } from \"./generate\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const provider = resolveProvider(META, options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.svelte\");\n pushResult(modifyOutcomeToFile(layoutPath, modifyLayoutSvelte(layoutPath)));\n\n // SvelteKit 3 exposes only declared variables, and only `public: true`\n // ones through `$app/env/public`, where the component imports them.\n logger.info(\"Declaring the analytics variables in src/env.ts\");\n const envVars = modifyEnvVarsFiles(options.root, providerEnvVars(provider));\n if (envVars.create) creates.push(envVars.create);\n pushResult(envVars.modify);\n\n logger.info(\"Updating .env\");\n const envPath = path.join(options.root, \".env\");\n pushResult(\n modifyOutcomeToFile(\n envPath,\n modifyEnv(envPath, envEditsFor(provider, suppliedProviderEnv(options))),\n ),\n );\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AASA,IAAMc,IAAmB,8CAEnBC,IAAiB,CAAM;2BACFD,EAAiB;GAGtCE,IAAiB,qBAEjBC,IAAiB;CACrB;CACA;CACA;CACA;CACAF;CACA;CACA;CACAC,EAAe,KAAK;AACtB,CAAC,CAAC,KAAK,IAAI,GAELE,IAAe;CACnB;CACA;CACA;CACA;CACAH;CACA;CACA;CACAC,EAAe,KAAK;AACtB,CAAC,CAAC,KAAK,IAAI;AAQX,SAAgBG,EAAmB,GAAmC;C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APAI,EACE3B,EACE8B,GACA7B,EAAU6B,GAAS5B,EAAYsB,GAAUzB,EAAoBwB,CAAO,CAAC,CAAC,CACxE,CACF,GAEO;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-Dm7IEo2h.js","names":["getLogger","providerEnvVars","resolveProvider","suppliedProviderEnv","modifyOutcomeToFile","modifyEnv","envEditsFor","META","dedent","SvelteFile","withInMemoryScript","ensureImports","fs","path","MODULE_SPECIFIER","IMPORT_SNIPPET","MARKUP_SNIPPET","NOT_FOUND_HINT","FAILURE_HINT","modifyLayoutSvelte","layoutPath","file","out","source","sf","generate","logger","options","provider","creates","modifies","pushResult","envVars","modifyEnvVarsFiles","envPath"],"sources":["../../src/patterns/enable/analytics/modifies/layout.svelte.ts","../../src/patterns/enable/analytics/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst MODULE_SPECIFIER = \"#lib/components/analytics/analytics.svelte\";\n\nconst IMPORT_SNIPPET = dedent`\n import Analytics from '${MODULE_SPECIFIER}';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<Analytics />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <Analytics /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <Analytics /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/**\n * Mounts `<Analytics />` at the top level of the root layout, ahead of\n * `{@render children()}`. The component is the same path for every provider,\n * so this modifier is provider-agnostic and a re-run with another provider\n * leaves the layout alone.\n */\nexport function modifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"Analytics\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { defaultImport: \"Analytics\", moduleSpecifier: MODULE_SPECIFIER },\n ]);\n });\n return out;\n });\n\n if (!file.insertBeforeChildren(MARKUP_SNIPPET)) {\n file.appendMarkup(MARKUP_SNIPPET);\n }\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n providerEnvVars,\n resolveProvider,\n suppliedProviderEnv,\n} from \"../../../core/providers\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnv } from \"../../../runtime/env\";\nimport { envEditsFor, META } from \"./generate\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const provider = resolveProvider(META, options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.svelte\");\n pushResult(modifyOutcomeToFile(layoutPath, modifyLayoutSvelte(layoutPath)));\n\n // SvelteKit 3 exposes only declared variables, and only `public: true`\n // ones through `$app/env/public`, where the component imports them.\n logger.info(\"Declaring the analytics variables in src/env.ts\");\n const envVars = modifyEnvVarsFiles(options.root, providerEnvVars(provider));\n if (envVars.create) creates.push(envVars.create);\n pushResult(envVars.modify);\n\n logger.info(\"Updating .env\");\n const envPath = path.join(options.root, \".env\");\n pushResult(\n modifyOutcomeToFile(\n envPath,\n modifyEnv(envPath, envEditsFor(provider, suppliedProviderEnv(options))),\n ),\n );\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AASA,IAAMc,IAAmB,8CAEnBC,IAAiB,CAAM;2BACFD,EAAiB;GAGtCE,IAAiB,qBAEjBC,IAAiB;CACrB;CACA;CACA;CACA;CACAF;CACA;CACA;CACAC,EAAe,KAAK;AACtB,CAAC,CAAC,KAAK,IAAI,GAELE,IAAe;CACnB;CACA;CACA;CACA;CACAH;CACA;CACA;CACAC,EAAe,KAAK;AACtB,CAAC,CAAC,KAAK,IAAI;AAQX,SAAgBG,EAAmB,GAAmC;CACpE,IAAI,CAACP,EAAG,WAAWQ,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAASH;CAAe;CAGxD,IAAMI,IAAOZ,EAAW,SAASW,CAAU;CAqB3C,OApBIC,EAAK,WAAW,WAAW,IACtB;EAAE,QAAQ;EAAW,SAAS;CAAM,IAExCA,EAAK,UAAU,KAIpBA,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQC,MAAQZ,EAAmBa,IAAS,MAAO;GACzD,EAAcC,GAAI,CAChB;IAAE,eAAe;IAAa,iBAAiBV;GAAiB,CAClE,CAAC;EACH,CAAC;EACD,OAAOQ;CACT,CAAC,GAEID,EAAK,qBAAqBL,CAAc,KAC3CK,EAAK,aAAaL,CAAc,GAElCK,EAAK,QAAQD,CAAU,GAChB;EAAE,QAAQ;EAAW,SAASC,EAAK,WAAW;CAAE,KAhB9C;EAAE,QAAQ;EAAU,SAASH;CAAa;AAiBrD;;AC1DA,eAAsBO,EAAS,GAAkB;CAC/C,IAAMC,IAAS1B,EAAU2B,CAAO,GAC1BC,IAAW1B,EAAgBK,GAAMoB,CAAO,GACxCE,IAAkB,CAAC,GACnBC,IAAmB,CAAC,GAEpBC,KAAc,MAAsB;EACxC,AAAIV,KAAMS,EAAS,KAAKT,CAAI;CAC9B;CAEA,EAAO,KAAK,qCAAqC;CACjD,IAAMD,IAAaP,EAAK,KAAKc,EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAK5E,AAJAI,EAAW3B,EAAoBgB,GAAYD,EAAmBC,CAAU,CAAC,CAAC,GAI1EM,EAAO,KAAK,iDAAiD;CAC7D,IAAMM,IAAUC,EAAmBN,EAAQ,MAAM1B,EAAgB2B,CAAQ,CAAC;CAI1E,AAHII,EAAQ,UAAQH,EAAQ,KAAKG,EAAQ,MAAM,GAC/CD,EAAWC,EAAQ,MAAM,GAEzBN,EAAO,KAAK,eAAe;CAC3B,IAAMQ,IAAUrB,EAAK,KAAKc,EAAQ,MAAM,MAAM;CAQ9C,OAPAI,EACE3B,EACE8B,GACA7B,EAAU6B,GAAS5B,EAAYsB,GAAUzB,EAAoBwB,CAAO,CAAC,CAAC,CACxE,CACF,GAEO;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,11 +1,11 @@
1
1
  import { n as e } from "./logger-t1HxmpG2.js";
2
- import { r as t } from "./modify-file-CRZ_gMg0.js";
3
- import { c as n, i as r, n as i, o as a, r as o, t as s } from "./test-setup-gJdzWWs_.js";
2
+ import { r as t } from "./modify-file-CgJIza72.js";
3
+ import { c as n, i as r, n as i, o as a, r as o, t as s } from "./test-setup-CpjhQSl-.js";
4
4
  import { a as c } from "./util-ILWdjRAd.js";
5
5
  import { t as l } from "./dedent-CCUOcPFW.js";
6
6
  import { r as u } from "./compose-handle-Da7m6lV_.js";
7
7
  import { c as d, i as f, n as p, o as m } from "./ts-morph-helpers-B4KZXP44.js";
8
- import { modifyEnvVarsFiles as h } from "./env-vars-CVn2076k.js";
8
+ import { modifyEnvVarsFiles as h } from "./env-vars-BbS_mWyP.js";
9
9
  import { t as g } from "./env-vars-CUh4mLM_.js";
10
10
  import _ from "node:fs";
11
11
  import v from "node:path";
@@ -158,4 +158,4 @@ async function k(l) {
158
158
  }
159
159
  export { k as generate };
160
160
 
161
- //# sourceMappingURL=generate.runtime-Db7JwGTb.js.map
161
+ //# sourceMappingURL=generate.runtime-Dn0_y2iV.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-Db7JwGTb.js","names":["getLogger","modifyOutcomeToFile","modifySvelteConfig","modifyTestSetup","WITH_BACKEND","modifyGitignore","hasVitestConfig","VITEST_CONFIG","languageFromPath","dedent","replaceHandle","pruneUnusedImports","ensureNamedImport","ensureBlankLineAfterImports","formatLikeSource","BACKEND_ENV_VARS","fs","path","POCKETBASE_TYPES","VITEST_CONFIGS","ext","modifyTsconfigBackend","filePath","root","original","vitestConfig","name","wanted","config","entry","include","normalize","has","existing","next","insertAfter","index","after","i","indent","POCKETBASE_ENV_NAMES","POCKETBASE_HANDLE","FAILURE_HINT","modifyHooksServerBackend","hooksServerPath","sourceFile","Project","QuoteKind","composed","statement","Node","doc","generate","logger","options","modifies","creates","create","adapter","svelteConfigFile","hooksServerFile","envVars","modifyEnvVarsFiles","gitignorePath","gitignoreFile","testSetupPath","testSetupFile","tsconfigPath","tsconfigFile"],"sources":["../../src/patterns/enable/backend/modifies/tsconfig.ts","../../src/patterns/enable/backend/modifies/hooks.server.ts","../../src/patterns/enable/backend/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/** Where `vela sync` writes PocketBase's generated types (`Schemas`, the typed client). */\nexport const POCKETBASE_TYPES = \".svelte-kit/types/pocketbase/*.d.ts\";\n\nconst VITEST_CONFIGS = [\"ts\", \"mts\", \"js\", \"mjs\"].map(\n (ext) => `vitest.config.${ext}`,\n);\n\n/**\n * SvelteKit 3's `$app/tsconfig` lists no files: the project's own `include`\n * decides what is type-checked, and `sv create` writes `[\"src\",\n * \"vite.config.ts\"]`. A backend adds three things that have to be in it, as\n * they are in vela's minimal template: `test` (the server-test context that\n * every `server.test.ts` reads), the vitest config, and PocketBase's generated\n * types, without which `Schemas` is missing from `@velastack/pocketbase`.\n *\n * Entries already there stay, in their order. A tsconfig with no `include`\n * checks everything already; one that is not plain JSON (comments) is left\n * alone with the entries to add.\n */\nexport function modifyTsconfigBackend(root: string): ModifyOutcome {\n const filePath = path.join(root, \"tsconfig.json\");\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n const vitestConfig =\n VITEST_CONFIGS.find((name) => fs.existsSync(path.join(root, name))) ??\n \"vitest.config.ts\";\n const wanted = [\"test\", vitestConfig, POCKETBASE_TYPES];\n\n let config: Record<string, unknown>;\n try {\n config = JSON.parse(original) as Record<string, unknown>;\n } catch {\n return {\n status: \"failed\",\n message: `Add these to the \"include\" array of tsconfig.json: ${wanted\n .map((entry) => JSON.stringify(entry))\n .join(\", \")}`,\n };\n }\n const include = config.include;\n if (include === undefined) {\n return { status: \"success\", changed: false };\n }\n if (!Array.isArray(include)) {\n return {\n status: \"failed\",\n message: `tsconfig.json \"include\" is not an array; it needs ${wanted.join(\", \")}`,\n };\n }\n\n const normalize = (entry: unknown) =>\n typeof entry === \"string\" ? entry.replace(/^\\.\\//, \"\") : entry;\n const has = (entry: string) =>\n include.some((existing) => normalize(existing) === entry);\n const next = [...include] as unknown[];\n const insertAfter = (entry: string, after: (e: unknown) => boolean) => {\n if (has(entry)) return;\n let index = -1;\n next.forEach((e, i) => {\n if (after(e)) index = i;\n });\n next.splice(index === -1 ? next.length : index + 1, 0, entry);\n };\n insertAfter(\"test\", (e) => normalize(e) === \"src\");\n insertAfter(vitestConfig, (e) =>\n /^vite\\.config\\.[cm]?[jt]s$/.test(String(normalize(e))),\n );\n insertAfter(POCKETBASE_TYPES, () => false);\n\n if (next.length === include.length) {\n return { status: \"success\", changed: false };\n }\n config.include = next;\n const indent = original.match(/^\\{\\s*\\n([\\t ]+)/)?.[1] ?? \"\\t\";\n fs.writeFileSync(filePath, `${JSON.stringify(config, null, indent)}\\n`);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node, Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { replaceHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureBlankLineAfterImports,\n ensureNamedImport,\n pruneUnusedImports,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\n/** The variables the handle reads, imported from `$app/env/private`. */\nexport const POCKETBASE_ENV_NAMES = [\n \"POCKETBASE_URL\",\n \"POCKETBASE_SUPERUSER_EMAIL\",\n \"POCKETBASE_SUPERUSER_PASSWORD\",\n] as const;\n\n/** The handle `creates/src/hooks.server.ts` exports, for a file that already exists. */\nexport const POCKETBASE_HANDLE = dedent`\n handlePocketbase({\n \tpocketbaseUrl: POCKETBASE_URL,\n \tsuperuserEmail: POCKETBASE_SUPERUSER_EMAIL,\n \tsuperuserPassword: POCKETBASE_SUPERUSER_PASSWORD\n })\n`;\n\nconst FAILURE_HINT = dedent`\n Add the PocketBase handle to the exported handle in src/hooks.server.ts:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import {\n \tPOCKETBASE_URL,\n \tPOCKETBASE_SUPERUSER_EMAIL,\n \tPOCKETBASE_SUPERUSER_PASSWORD\n } from '$app/env/private';\n import { handlePocketbase } from '@velastack/pocketbase';\n\n export const handle = sequence(\n \t/* your existing handle */,\n \t${POCKETBASE_HANDLE.replace(/\\n/g, \"\\n\\t\")}\n );\n`;\n\n/**\n * Compose the PocketBase handle into a `hooks.server.ts` the project already\n * has, instead of the create overwriting it: a static site's, or one i18n or\n * content negotiation wrote. It takes `handleStatic()`'s place, since\n * `handlePocketbase` does what that did and more; otherwise it goes last, so\n * the handles already there keep running first.\n */\nexport function modifyHooksServerBackend(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n // The create writes it.\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const composed = replaceHandle(sourceFile, \"handleStatic\", {\n expression: POCKETBASE_HANDLE,\n name: \"handlePocketbase\",\n position: \"last\",\n });\n if (composed.status === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (composed.status === \"unchanged\") {\n return { status: \"success\", changed: false };\n }\n\n // The static template's comment explains handleStatic(). Where that was the\n // whole handle, replaceHandle already dropped it; in a sequence (i18n or\n // negotiation composed in since) it is still there, describing a handle\n // that is gone.\n const statement = composed.statement;\n if (statement && Node.isJSDocable(statement)) {\n for (const doc of statement.getJsDocs()) {\n if (doc.getText().includes(\"vela legal\")) doc.remove();\n }\n }\n\n pruneUnusedImports(sourceFile, [\"@velastack/kit\"]);\n for (const name of POCKETBASE_ENV_NAMES) {\n ensureNamedImport(sourceFile, \"$app/env/private\", name);\n }\n ensureNamedImport(sourceFile, \"@velastack/pocketbase\", \"handlePocketbase\");\n\n formatLikeSource(sourceFile);\n ensureBlankLineAfterImports(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\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 { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifySvelteConfig } from \"./modifies/svelte-config\";\nimport { modifyGitignore } from \"./modifies/gitignore\";\nimport { modifyTsconfigBackend } from \"./modifies/tsconfig\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n hasVitestConfig,\n modifyTestSetup,\n VITEST_CONFIG,\n WITH_BACKEND,\n} from \"./modifies/test-setup\";\nimport { modifyHooksServerBackend } from \"./modifies/hooks.server\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { BACKEND_ENV_VARS } from \"./env-vars\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const creates: File[] = [];\n const create = (filePath: string, content: string) =>\n creates.push({\n path: filePath,\n language: languageFromPath(filePath),\n content,\n status: \"success\",\n });\n\n logger.info(\"Modifying adapter config\");\n const adapter = modifySvelteConfig(options.root);\n const svelteConfigFile = modifyOutcomeToFile(\n adapter.filePath,\n adapter.outcome,\n );\n if (svelteConfigFile) modifies.push(svelteConfigFile);\n\n // A hooks.server.ts the project already has keeps its handles; the create\n // only writes the file where there is none (see `keepMissing` in index.ts).\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksServerFile = modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerBackend(hooksServerPath),\n );\n if (hooksServerFile) {\n logger.info(\"Modifying hooks.server.ts\");\n modifies.push(hooksServerFile);\n }\n\n // SvelteKit 3 exposes only declared variables: the handle above reads\n // these three from `$app/env/private`.\n logger.info(\"Declaring the PocketBase variables in src/env.ts\");\n const envVars = modifyEnvVarsFiles(options.root, BACKEND_ENV_VARS);\n if (envVars.create) creates.push(envVars.create);\n if (envVars.modify) modifies.push(envVars.modify);\n\n logger.info(\"Modifying .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n const gitignoreFile = modifyOutcomeToFile(\n gitignorePath,\n modifyGitignore(gitignorePath),\n );\n if (gitignoreFile) modifies.push(gitignoreFile);\n\n // A backend brings server tests with it. The static template and a project\n // vela did not create have no harness at all, so what is missing is created:\n // the setup file, and the vitest config that loads it.\n const testSetupPath = path.join(options.root, \"test\", \"setup.ts\");\n if (fs.existsSync(testSetupPath)) {\n logger.info(\"Modifying test/setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetupPath,\n modifyTestSetup(testSetupPath),\n );\n if (testSetupFile) modifies.push(testSetupFile);\n } else {\n logger.info(\"Creating test/setup.ts\");\n create(\"test/setup.ts\", WITH_BACKEND);\n }\n\n if (!hasVitestConfig(options.root)) {\n logger.info(\"Creating vitest.config.ts\");\n create(\"vitest.config.ts\", VITEST_CONFIG);\n }\n\n // Kit 3's tsconfig lists no files, so the test harness and PocketBase's\n // generated types are type-checked only when the project's include names them.\n const tsconfigPath = path.join(options.root, \"tsconfig.json\");\n const tsconfigFile = modifyOutcomeToFile(\n tsconfigPath,\n modifyTsconfigBackend(options.root),\n );\n if (tsconfigFile) {\n logger.info(\"Modifying tsconfig.json\");\n modifies.push(tsconfigFile);\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,IAAakB,IAAmB,uCAE1BC,IAAiB;CAAC;CAAM;CAAO;CAAM;AAAK,CAAC,CAAC,KAC/C,MAAQ,iBAAiBC,GAC5B;AAcA,SAAgBC,EAAsB,GAA6B;CACjE,IAAMC,IAAWL,EAAK,KAAKM,GAAM,eAAe;CAChD,IAAI,CAACP,EAAG,WAAWM,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAE7C,IAAME,IAAWR,EAAG,aAAaM,GAAU,MAAM,GAC3CG,IACJN,EAAe,MAAM,MAASH,EAAG,WAAWC,EAAK,KAAKM,GAAMG,CAAI,CAAC,CAAC,KAClE,oBACIC,IAAS;EAAC;EAAQ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AAO,KAAK,2BAA2B,GACvCI,EAAO,oBAAoBlD,CAAa;CAK1C,IAAM4D,IAAelD,EAAK,KAAKqC,EAAQ,MAAM,eAAe,GACtDc,IAAenE,EACnBkE,GACA9C,EAAsBiC,EAAQ,IAAI,CACpC;CAMA,OALIc,MACFf,EAAO,KAAK,yBAAyB,GACrCE,EAAS,KAAKa,CAAY,IAGrB;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-Dn0_y2iV.js","names":["getLogger","modifyOutcomeToFile","modifySvelteConfig","modifyTestSetup","WITH_BACKEND","modifyGitignore","hasVitestConfig","VITEST_CONFIG","languageFromPath","dedent","replaceHandle","pruneUnusedImports","ensureNamedImport","ensureBlankLineAfterImports","formatLikeSource","BACKEND_ENV_VARS","fs","path","POCKETBASE_TYPES","VITEST_CONFIGS","ext","modifyTsconfigBackend","filePath","root","original","vitestConfig","name","wanted","config","entry","include","normalize","has","existing","next","insertAfter","index","after","i","indent","POCKETBASE_ENV_NAMES","POCKETBASE_HANDLE","FAILURE_HINT","modifyHooksServerBackend","hooksServerPath","sourceFile","Project","QuoteKind","composed","statement","Node","doc","generate","logger","options","modifies","creates","create","adapter","svelteConfigFile","hooksServerFile","envVars","modifyEnvVarsFiles","gitignorePath","gitignoreFile","testSetupPath","testSetupFile","tsconfigPath","tsconfigFile"],"sources":["../../src/patterns/enable/backend/modifies/tsconfig.ts","../../src/patterns/enable/backend/modifies/hooks.server.ts","../../src/patterns/enable/backend/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/** Where `vela sync` writes PocketBase's generated types (`Schemas`, the typed client). */\nexport const POCKETBASE_TYPES = \".svelte-kit/types/pocketbase/*.d.ts\";\n\nconst VITEST_CONFIGS = [\"ts\", \"mts\", \"js\", \"mjs\"].map(\n (ext) => `vitest.config.${ext}`,\n);\n\n/**\n * SvelteKit 3's `$app/tsconfig` lists no files: the project's own `include`\n * decides what is type-checked, and `sv create` writes `[\"src\",\n * \"vite.config.ts\"]`. A backend adds three things that have to be in it, as\n * they are in vela's minimal template: `test` (the server-test context that\n * every `server.test.ts` reads), the vitest config, and PocketBase's generated\n * types, without which `Schemas` is missing from `@velastack/pocketbase`.\n *\n * Entries already there stay, in their order. A tsconfig with no `include`\n * checks everything already; one that is not plain JSON (comments) is left\n * alone with the entries to add.\n */\nexport function modifyTsconfigBackend(root: string): ModifyOutcome {\n const filePath = path.join(root, \"tsconfig.json\");\n if (!fs.existsSync(filePath)) {\n return { status: \"success\", changed: false };\n }\n const original = fs.readFileSync(filePath, \"utf8\");\n const vitestConfig =\n VITEST_CONFIGS.find((name) => fs.existsSync(path.join(root, name))) ??\n \"vitest.config.ts\";\n const wanted = [\"test\", vitestConfig, POCKETBASE_TYPES];\n\n let config: Record<string, unknown>;\n try {\n config = JSON.parse(original) as Record<string, unknown>;\n } catch {\n return {\n status: \"failed\",\n message: `Add these to the \"include\" array of tsconfig.json: ${wanted\n .map((entry) => JSON.stringify(entry))\n .join(\", \")}`,\n };\n }\n const include = config.include;\n if (include === undefined) {\n return { status: \"success\", changed: false };\n }\n if (!Array.isArray(include)) {\n return {\n status: \"failed\",\n message: `tsconfig.json \"include\" is not an array; it needs ${wanted.join(\", \")}`,\n };\n }\n\n const normalize = (entry: unknown) =>\n typeof entry === \"string\" ? entry.replace(/^\\.\\//, \"\") : entry;\n const has = (entry: string) =>\n include.some((existing) => normalize(existing) === entry);\n const next = [...include] as unknown[];\n const insertAfter = (entry: string, after: (e: unknown) => boolean) => {\n if (has(entry)) return;\n let index = -1;\n next.forEach((e, i) => {\n if (after(e)) index = i;\n });\n next.splice(index === -1 ? next.length : index + 1, 0, entry);\n };\n insertAfter(\"test\", (e) => normalize(e) === \"src\");\n insertAfter(vitestConfig, (e) =>\n /^vite\\.config\\.[cm]?[jt]s$/.test(String(normalize(e))),\n );\n insertAfter(POCKETBASE_TYPES, () => false);\n\n if (next.length === include.length) {\n return { status: \"success\", changed: false };\n }\n config.include = next;\n const indent = original.match(/^\\{\\s*\\n([\\t ]+)/)?.[1] ?? \"\\t\";\n fs.writeFileSync(filePath, `${JSON.stringify(config, null, indent)}\\n`);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node, Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { replaceHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureBlankLineAfterImports,\n ensureNamedImport,\n pruneUnusedImports,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\n/** The variables the handle reads, imported from `$app/env/private`. */\nexport const POCKETBASE_ENV_NAMES = [\n \"POCKETBASE_URL\",\n \"POCKETBASE_SUPERUSER_EMAIL\",\n \"POCKETBASE_SUPERUSER_PASSWORD\",\n] as const;\n\n/** The handle `creates/src/hooks.server.ts` exports, for a file that already exists. */\nexport const POCKETBASE_HANDLE = dedent`\n handlePocketbase({\n \tpocketbaseUrl: POCKETBASE_URL,\n \tsuperuserEmail: POCKETBASE_SUPERUSER_EMAIL,\n \tsuperuserPassword: POCKETBASE_SUPERUSER_PASSWORD\n })\n`;\n\nconst FAILURE_HINT = dedent`\n Add the PocketBase handle to the exported handle in src/hooks.server.ts:\n\n import { sequence } from '@sveltejs/kit/hooks';\n import {\n \tPOCKETBASE_URL,\n \tPOCKETBASE_SUPERUSER_EMAIL,\n \tPOCKETBASE_SUPERUSER_PASSWORD\n } from '$app/env/private';\n import { handlePocketbase } from '@velastack/pocketbase';\n\n export const handle = sequence(\n \t/* your existing handle */,\n \t${POCKETBASE_HANDLE.replace(/\\n/g, \"\\n\\t\")}\n );\n`;\n\n/**\n * Compose the PocketBase handle into a `hooks.server.ts` the project already\n * has, instead of the create overwriting it: a static site's, or one i18n or\n * content negotiation wrote. It takes `handleStatic()`'s place, since\n * `handlePocketbase` does what that did and more; otherwise it goes last, so\n * the handles already there keep running first.\n */\nexport function modifyHooksServerBackend(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n // The create writes it.\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const composed = replaceHandle(sourceFile, \"handleStatic\", {\n expression: POCKETBASE_HANDLE,\n name: \"handlePocketbase\",\n position: \"last\",\n });\n if (composed.status === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (composed.status === \"unchanged\") {\n return { status: \"success\", changed: false };\n }\n\n // The static template's comment explains handleStatic(). Where that was the\n // whole handle, replaceHandle already dropped it; in a sequence (i18n or\n // negotiation composed in since) it is still there, describing a handle\n // that is gone.\n const statement = composed.statement;\n if (statement && Node.isJSDocable(statement)) {\n for (const doc of statement.getJsDocs()) {\n if (doc.getText().includes(\"vela legal\")) doc.remove();\n }\n }\n\n pruneUnusedImports(sourceFile, [\"@velastack/kit\"]);\n for (const name of POCKETBASE_ENV_NAMES) {\n ensureNamedImport(sourceFile, \"$app/env/private\", name);\n }\n ensureNamedImport(sourceFile, \"@velastack/pocketbase\", \"handlePocketbase\");\n\n formatLikeSource(sourceFile);\n ensureBlankLineAfterImports(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\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 { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifySvelteConfig } from \"./modifies/svelte-config\";\nimport { modifyGitignore } from \"./modifies/gitignore\";\nimport { modifyTsconfigBackend } from \"./modifies/tsconfig\";\nimport { languageFromPath } from \"../../../core/util\";\nimport {\n hasVitestConfig,\n modifyTestSetup,\n VITEST_CONFIG,\n WITH_BACKEND,\n} from \"./modifies/test-setup\";\nimport { modifyHooksServerBackend } from \"./modifies/hooks.server\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { BACKEND_ENV_VARS } from \"./env-vars\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const creates: File[] = [];\n const create = (filePath: string, content: string) =>\n creates.push({\n path: filePath,\n language: languageFromPath(filePath),\n content,\n status: \"success\",\n });\n\n logger.info(\"Modifying adapter config\");\n const adapter = modifySvelteConfig(options.root);\n const svelteConfigFile = modifyOutcomeToFile(\n adapter.filePath,\n adapter.outcome,\n );\n if (svelteConfigFile) modifies.push(svelteConfigFile);\n\n // A hooks.server.ts the project already has keeps its handles; the create\n // only writes the file where there is none (see `keepMissing` in index.ts).\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksServerFile = modifyOutcomeToFile(\n hooksServerPath,\n modifyHooksServerBackend(hooksServerPath),\n );\n if (hooksServerFile) {\n logger.info(\"Modifying hooks.server.ts\");\n modifies.push(hooksServerFile);\n }\n\n // SvelteKit 3 exposes only declared variables: the handle above reads\n // these three from `$app/env/private`.\n logger.info(\"Declaring the PocketBase variables in src/env.ts\");\n const envVars = modifyEnvVarsFiles(options.root, BACKEND_ENV_VARS);\n if (envVars.create) creates.push(envVars.create);\n if (envVars.modify) modifies.push(envVars.modify);\n\n logger.info(\"Modifying .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n const gitignoreFile = modifyOutcomeToFile(\n gitignorePath,\n modifyGitignore(gitignorePath),\n );\n if (gitignoreFile) modifies.push(gitignoreFile);\n\n // A backend brings server tests with it. The static template and a project\n // vela did not create have no harness at all, so what is missing is created:\n // the setup file, and the vitest config that loads it.\n const testSetupPath = path.join(options.root, \"test\", \"setup.ts\");\n if (fs.existsSync(testSetupPath)) {\n logger.info(\"Modifying test/setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetupPath,\n modifyTestSetup(testSetupPath),\n );\n if (testSetupFile) modifies.push(testSetupFile);\n } else {\n logger.info(\"Creating test/setup.ts\");\n create(\"test/setup.ts\", WITH_BACKEND);\n }\n\n if (!hasVitestConfig(options.root)) {\n logger.info(\"Creating vitest.config.ts\");\n create(\"vitest.config.ts\", VITEST_CONFIG);\n }\n\n // Kit 3's tsconfig lists no files, so the test harness and PocketBase's\n // generated types are type-checked only when the project's include names them.\n const tsconfigPath = path.join(options.root, \"tsconfig.json\");\n const tsconfigFile = modifyOutcomeToFile(\n tsconfigPath,\n modifyTsconfigBackend(options.root),\n );\n if (tsconfigFile) {\n logger.info(\"Modifying tsconfig.json\");\n modifies.push(tsconfigFile);\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,IAAakB,IAAmB,uCAE1BC,IAAiB;CAAC;CAAM;CAAO;CAAM;AAAK,CAAC,CAAC,KAC/C,MAAQ,iBAAiBC,GAC5B;AAcA,SAAgBC,EAAsB,GAA6B;CACjE,IAAMC,IAAWL,EAAK,KAAKM,GAAM,eAAe;CAChD,IAAI,CAACP,EAAG,WAAWM,CAAQ,GACzB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAE7C,IAAME,IAAWR,EAAG,aAAaM,GAAU,MAAM,GAC3CG,IACJN,EAAe,MAAM,MAASH,EAAG,WAAWC,EAAK,KAAKM,GAAMG,CAAI,CAAC,CAAC,KAClE,oBACIC,IAAS;EAAC;EAAQF;EAAcP;CAAgB,GAElDU;CACJ,IAAI;EACF,IAAS,KAAK,MAAMJ,CAAQ;CAC9B,QAAQ;EACN,OAAO;GACL,QAAQ;GACR,SAAS,sDAAsDG,EAC5D,KAAK,MAAU,KAAK,UAA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AI,CACpC;CAMA,OALIc,MACFf,EAAO,KAAK,yBAAyB,GACrCE,EAAS,KAAKa,CAAY,IAGrB;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { n as e } from "./logger-t1HxmpG2.js";
2
- import { r as t } from "./modify-file-CRZ_gMg0.js";
2
+ import { r as t } from "./modify-file-CgJIza72.js";
3
3
  import { t as n } from "./modify-utils--zro3IGe.js";
4
4
  import { t as r } from "./dedent-CCUOcPFW.js";
5
5
  import { o as i, t as a } from "./ts-morph-helpers-B4KZXP44.js";
@@ -152,4 +152,4 @@ async function y(r) {
152
152
  }
153
153
  export { y as generate };
154
154
 
155
- //# sourceMappingURL=generate.runtime-DfHFd8xs.js.map
155
+ //# sourceMappingURL=generate.runtime-DuAYqKxl.js.map