@velastack/patterns 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/README.md +15 -3
  2. package/dist/chunks/{_layout-D-FzWqn0.js → _layout-DQhSAhfF.js} +3 -3
  3. package/dist/chunks/{_layout-D-FzWqn0.js.map → _layout-DQhSAhfF.js.map} +1 -1
  4. package/dist/chunks/{auth-pages-B52ei-4z.js → auth-pages-jsyDV1GR.js} +7 -10
  5. package/dist/chunks/{auth-pages-B52ei-4z.js.map → auth-pages-jsyDV1GR.js.map} +1 -1
  6. package/dist/chunks/{collections-B_DisSfA.js → collections-BYcVyY9O.js} +39 -35
  7. package/dist/chunks/collections-BYcVyY9O.js.map +1 -0
  8. package/dist/chunks/collections-BrEA7a62.js +309 -0
  9. package/dist/chunks/collections-BrEA7a62.js.map +1 -0
  10. package/dist/chunks/{compose-handle-BDlZ7Pif.js → compose-handle-BBlamPfx.js} +18 -22
  11. package/dist/chunks/{compose-handle-BDlZ7Pif.js.map → compose-handle-BBlamPfx.js.map} +1 -1
  12. package/dist/chunks/{config-target-rHgjaA8u.js → config-target-BgyFkbFL.js} +2 -2
  13. package/dist/chunks/{config-target-rHgjaA8u.js.map → config-target-BgyFkbFL.js.map} +1 -1
  14. package/dist/chunks/constants-Bdx8mp7v.js +6 -0
  15. package/dist/chunks/constants-Bdx8mp7v.js.map +1 -0
  16. package/dist/chunks/dedent-Gq6Krl4n.js.map +1 -1
  17. package/dist/chunks/{env-BPfk1VAw.js → env-BugddEjd.js} +5 -9
  18. package/dist/chunks/{env-BPfk1VAw.js.map → env-BugddEjd.js.map} +1 -1
  19. package/dist/chunks/{env-vars-cqQU0ECK.js → env-vars-0hvKe55u.js} +6 -11
  20. package/dist/chunks/{env-vars-cqQU0ECK.js.map → env-vars-0hvKe55u.js.map} +1 -1
  21. package/dist/chunks/generate-BOQA-Flq.js +171 -0
  22. package/dist/chunks/generate-BOQA-Flq.js.map +1 -0
  23. package/dist/chunks/{generate-CXoQPz7n.js → generate-CNabcEBx.js} +2 -2
  24. package/dist/chunks/{generate-CXoQPz7n.js.map → generate-CNabcEBx.js.map} +1 -1
  25. package/dist/chunks/{generate-jx5Iuq5w.js → generate-CO88bEvs.js} +54 -53
  26. package/dist/chunks/generate-CO88bEvs.js.map +1 -0
  27. package/dist/chunks/{generate-Bm_jOMtF.js → generate-Df7t5Nbk.js} +3 -3
  28. package/dist/chunks/{generate-Bm_jOMtF.js.map → generate-Df7t5Nbk.js.map} +1 -1
  29. package/dist/chunks/{generate-Cqwa8kD9.js → generate-DoHn_xJZ.js} +2 -2
  30. package/dist/chunks/{generate-Cqwa8kD9.js.map → generate-DoHn_xJZ.js.map} +1 -1
  31. package/dist/chunks/generate-DyV5R8NP.js.map +1 -1
  32. package/dist/chunks/{generate-D3mSFPdT.js → generate-l2JZTRKb.js} +2 -2
  33. package/dist/chunks/{generate-D3mSFPdT.js.map → generate-l2JZTRKb.js.map} +1 -1
  34. package/dist/chunks/{generate.runtime-FGYc365Q.js → generate.runtime-1ldXcpiD.js} +6 -6
  35. package/dist/chunks/{generate.runtime-FGYc365Q.js.map → generate.runtime-1ldXcpiD.js.map} +1 -1
  36. package/dist/chunks/{generate.runtime-B2r11K7S.js → generate.runtime-B53OTMcE.js} +6 -6
  37. package/dist/chunks/{generate.runtime-B2r11K7S.js.map → generate.runtime-B53OTMcE.js.map} +1 -1
  38. package/dist/chunks/{generate.runtime-DCqf7nYM.js → generate.runtime-B84ymwlD.js} +7 -7
  39. package/dist/chunks/{generate.runtime-DCqf7nYM.js.map → generate.runtime-B84ymwlD.js.map} +1 -1
  40. package/dist/chunks/{generate.runtime-Dug2UIhV.js → generate.runtime-BOl3LpPB.js} +10 -13
  41. package/dist/chunks/{generate.runtime-Dug2UIhV.js.map → generate.runtime-BOl3LpPB.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-BxDUtkpT.js → generate.runtime-BP31tAcD.js} +5 -5
  43. package/dist/chunks/{generate.runtime-BxDUtkpT.js.map → generate.runtime-BP31tAcD.js.map} +1 -1
  44. package/dist/chunks/{generate.runtime-DdcVnK8J.js → generate.runtime-BoYwV0nt.js} +133 -121
  45. package/dist/chunks/generate.runtime-BoYwV0nt.js.map +1 -0
  46. package/dist/chunks/{generate.runtime-wGRE1zwZ.js → generate.runtime-BqCbJ-No.js} +4 -4
  47. package/dist/chunks/{generate.runtime-wGRE1zwZ.js.map → generate.runtime-BqCbJ-No.js.map} +1 -1
  48. package/dist/chunks/{generate.runtime-BVavIXtX.js → generate.runtime-Bvjj3zn0.js} +6 -6
  49. package/dist/chunks/{generate.runtime-BVavIXtX.js.map → generate.runtime-Bvjj3zn0.js.map} +1 -1
  50. package/dist/chunks/{generate.runtime-_c7daMAw.js → generate.runtime-ByPcr9vJ.js} +4 -4
  51. package/dist/chunks/{generate.runtime-_c7daMAw.js.map → generate.runtime-ByPcr9vJ.js.map} +1 -1
  52. package/dist/chunks/{generate.runtime-Dmob2wFf.js → generate.runtime-C4LUUuq7.js} +5 -5
  53. package/dist/chunks/{generate.runtime-Dmob2wFf.js.map → generate.runtime-C4LUUuq7.js.map} +1 -1
  54. package/dist/chunks/{generate.runtime-wziCW3ct.js → generate.runtime-CGjDfO1P.js} +5 -5
  55. package/dist/chunks/{generate.runtime-wziCW3ct.js.map → generate.runtime-CGjDfO1P.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-DYdkrHJ1.js → generate.runtime-CHQ_MQJQ.js} +6 -6
  57. package/dist/chunks/{generate.runtime-DYdkrHJ1.js.map → generate.runtime-CHQ_MQJQ.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-aN5QWygO.js → generate.runtime-CHS5lyHL.js} +39 -36
  59. package/dist/chunks/generate.runtime-CHS5lyHL.js.map +1 -0
  60. package/dist/chunks/{generate.runtime-CyGR8VTx.js → generate.runtime-CHUCMVa2.js} +3 -3
  61. package/dist/chunks/{generate.runtime-CyGR8VTx.js.map → generate.runtime-CHUCMVa2.js.map} +1 -1
  62. package/dist/chunks/{generate.runtime-BxUGDXIK.js → generate.runtime-CVWCUn52.js} +6 -6
  63. package/dist/chunks/{generate.runtime-BxUGDXIK.js.map → generate.runtime-CVWCUn52.js.map} +1 -1
  64. package/dist/chunks/generate.runtime-C_5Ghjri.js +17 -0
  65. package/dist/chunks/generate.runtime-C_5Ghjri.js.map +1 -0
  66. package/dist/chunks/{generate.runtime-CRhD98rs.js → generate.runtime-Cv3unKap.js} +5 -5
  67. package/dist/chunks/{generate.runtime-CRhD98rs.js.map → generate.runtime-Cv3unKap.js.map} +1 -1
  68. package/dist/chunks/{generate.runtime-CkmledBw.js → generate.runtime-D677SB4v.js} +12 -20
  69. package/dist/chunks/{generate.runtime-CkmledBw.js.map → generate.runtime-D677SB4v.js.map} +1 -1
  70. package/dist/chunks/{generate.runtime-DeniHg8L.js → generate.runtime-DERcpgc-.js} +5 -5
  71. package/dist/chunks/{generate.runtime-DeniHg8L.js.map → generate.runtime-DERcpgc-.js.map} +1 -1
  72. package/dist/chunks/{generate.runtime-x-o4LS8d.js → generate.runtime-DJ5uF6EN.js} +4 -4
  73. package/dist/chunks/{generate.runtime-x-o4LS8d.js.map → generate.runtime-DJ5uF6EN.js.map} +1 -1
  74. package/dist/chunks/{generate.runtime-CYBs0JgY.js → generate.runtime-Dfz53sSK.js} +5 -5
  75. package/dist/chunks/{generate.runtime-CYBs0JgY.js.map → generate.runtime-Dfz53sSK.js.map} +1 -1
  76. package/dist/chunks/{generate.runtime-CWnIiXwV.js → generate.runtime-DiqfbDfk.js} +3 -3
  77. package/dist/chunks/{generate.runtime-CWnIiXwV.js.map → generate.runtime-DiqfbDfk.js.map} +1 -1
  78. package/dist/chunks/{generate.runtime-CHb4znYx.js → generate.runtime-Dq6yS7tN.js} +6 -6
  79. package/dist/chunks/{generate.runtime-CHb4znYx.js.map → generate.runtime-Dq6yS7tN.js.map} +1 -1
  80. package/dist/chunks/{generate.runtime-BRCzUO94.js → generate.runtime-T7JLE4Wc.js} +10 -14
  81. package/dist/chunks/{generate.runtime-BRCzUO94.js.map → generate.runtime-T7JLE4Wc.js.map} +1 -1
  82. package/dist/chunks/{generate.runtime-Du4uf98c.js → generate.runtime-WPq7bHRA.js} +3 -3
  83. package/dist/chunks/{generate.runtime-Du4uf98c.js.map → generate.runtime-WPq7bHRA.js.map} +1 -1
  84. package/dist/chunks/{generate.runtime-kpqW3dVO.js → generate.runtime-WeDv05E2.js} +8 -8
  85. package/dist/chunks/{generate.runtime-kpqW3dVO.js.map → generate.runtime-WeDv05E2.js.map} +1 -1
  86. package/dist/chunks/{generate.runtime-N1KtAG8C.js → generate.runtime-aKNvrk3M.js} +90 -175
  87. package/dist/chunks/generate.runtime-aKNvrk3M.js.map +1 -0
  88. package/dist/chunks/{generate.runtime-Bh9Z2cRN.js → generate.runtime-e_BkDyP0.js} +3 -3
  89. package/dist/chunks/{generate.runtime-Bh9Z2cRN.js.map → generate.runtime-e_BkDyP0.js.map} +1 -1
  90. package/dist/chunks/{generate.runtime-DY5vQ3aZ.js → generate.runtime-gZ4wfYBP.js} +8 -8
  91. package/dist/chunks/{generate.runtime-DY5vQ3aZ.js.map → generate.runtime-gZ4wfYBP.js.map} +1 -1
  92. package/dist/chunks/{generate.runtime-DUo-pLRr.js → generate.runtime-oUJUQRdg.js} +7 -7
  93. package/dist/chunks/{generate.runtime-DUo-pLRr.js.map → generate.runtime-oUJUQRdg.js.map} +1 -1
  94. package/dist/chunks/{generate.runtime-gFr2Gsjz.js → generate.runtime-q17D7QUT.js} +5 -5
  95. package/dist/chunks/{generate.runtime-gFr2Gsjz.js.map → generate.runtime-q17D7QUT.js.map} +1 -1
  96. package/dist/chunks/{generate.runtime-B4u9C2YH.js → generate.runtime-rLlDp4R6.js} +5 -5
  97. package/dist/chunks/{generate.runtime-B4u9C2YH.js.map → generate.runtime-rLlDp4R6.js.map} +1 -1
  98. package/dist/chunks/{generate.runtime-bpH3DB0t.js → generate.runtime-zr6uIHCd.js} +3 -3
  99. package/dist/chunks/{generate.runtime-bpH3DB0t.js.map → generate.runtime-zr6uIHCd.js.map} +1 -1
  100. package/dist/chunks/{modify-file-289rStJ2.js → modify-file-B4uJzOEj.js} +4 -4
  101. package/dist/chunks/{modify-file-289rStJ2.js.map → modify-file-B4uJzOEj.js.map} +1 -1
  102. package/dist/chunks/{modify-nav-user-B8h8WTrM.js → modify-nav-user-CJ1LevSU.js} +2 -2
  103. package/dist/chunks/{modify-nav-user-B8h8WTrM.js.map → modify-nav-user-CJ1LevSU.js.map} +1 -1
  104. package/dist/chunks/{modify-svelte-config-remote-DhuRX4FI.js → modify-svelte-config-remote-CEyYydL7.js} +2 -2
  105. package/dist/chunks/{modify-svelte-config-remote-DhuRX4FI.js.map → modify-svelte-config-remote-CEyYydL7.js.map} +1 -1
  106. package/dist/chunks/{modify-user-signup-BbqTiUuA.js → modify-user-signup-DLtopazD.js} +2 -2
  107. package/dist/chunks/{modify-user-signup-BbqTiUuA.js.map → modify-user-signup-DLtopazD.js.map} +1 -1
  108. package/dist/chunks/{package-imports-Bbw3iMPg.js → package-imports-B9Asv3ZH.js} +3 -3
  109. package/dist/chunks/{package-imports-Bbw3iMPg.js.map → package-imports-B9Asv3ZH.js.map} +1 -1
  110. package/dist/chunks/{pocketbase-B017Cqjq.js → pocketbase-BtN-wL8f.js} +9 -17
  111. package/dist/chunks/{pocketbase-B017Cqjq.js.map → pocketbase-BtN-wL8f.js.map} +1 -1
  112. package/dist/chunks/{providers-CN5J5_fY.js → providers-DRwJnSzb.js} +2 -2
  113. package/dist/chunks/{providers-CN5J5_fY.js.map → providers-DRwJnSzb.js.map} +1 -1
  114. package/dist/chunks/{rolldown-runtime-DArdT4gl.js → rolldown-runtime-5HNE8Q1r.js} +1 -1
  115. package/dist/chunks/{shared-BPlAVf-T.js → shared-BbxLil4g.js} +2 -2
  116. package/dist/chunks/{shared-BPlAVf-T.js.map → shared-BbxLil4g.js.map} +1 -1
  117. package/dist/chunks/{site-DkU1-VRq.js → site-Dw2KIRJu.js} +2 -2
  118. package/dist/chunks/{site-DkU1-VRq.js.map → site-Dw2KIRJu.js.map} +1 -1
  119. package/dist/chunks/{table-core-vXEjJDYP.js → table-core-BHFT-uMX.js} +3 -3
  120. package/dist/chunks/{table-core-vXEjJDYP.js.map → table-core-BHFT-uMX.js.map} +1 -1
  121. package/dist/chunks/{taggedTemplateLiteral-CswN2AAa.js → taggedTemplateLiteral-KSUnuvOk.js} +1 -1
  122. package/dist/chunks/{test-setup-CAfgVlwc.js → test-setup-BVJwm22s.js} +5 -5
  123. package/dist/chunks/{test-setup-CAfgVlwc.js.map → test-setup-BVJwm22s.js.map} +1 -1
  124. package/dist/chunks/{ts-morph-helpers-Bepc-Es2.js → ts-morph-helpers-CHI9wAil.js} +7 -11
  125. package/dist/chunks/{ts-morph-helpers-Bepc-Es2.js.map → ts-morph-helpers-CHI9wAil.js.map} +1 -1
  126. package/dist/chunks/{ui-CTdsenEv.js → ui-gG8i_Mzk.js} +3 -3
  127. package/dist/chunks/{ui-CTdsenEv.js.map → ui-gG8i_Mzk.js.map} +1 -1
  128. package/dist/chunks/{unmodify-load-Bl5vXQiL.js → unmodify-load-Buak-r1f.js} +2 -2
  129. package/dist/chunks/{unmodify-load-Bl5vXQiL.js.map → unmodify-load-Buak-r1f.js.map} +1 -1
  130. package/dist/chunks/{whatsapp-5qJ_xCV1.js → whatsapp-DbjOxHaZ.js} +2 -2
  131. package/dist/chunks/{whatsapp-5qJ_xCV1.js.map → whatsapp-DbjOxHaZ.js.map} +1 -1
  132. package/dist/chunks/write-result-DcqMefuP.js +499 -0
  133. package/dist/chunks/write-result-DcqMefuP.js.map +1 -0
  134. package/dist/chunks/wuchale-config-c3Q4JVSF.js +50 -0
  135. package/dist/chunks/wuchale-config-c3Q4JVSF.js.map +1 -0
  136. package/dist/index.d.ts +173 -19
  137. package/dist/index.js +2330 -2505
  138. package/dist/index.js.map +1 -1
  139. package/package.json +2 -2
  140. package/dist/chunks/collections-B_DisSfA.js.map +0 -1
  141. package/dist/chunks/constants-iej3WkEa.js +0 -6
  142. package/dist/chunks/constants-iej3WkEa.js.map +0 -1
  143. package/dist/chunks/generate-8FS2ROOJ.js +0 -170
  144. package/dist/chunks/generate-8FS2ROOJ.js.map +0 -1
  145. package/dist/chunks/generate-jx5Iuq5w.js.map +0 -1
  146. package/dist/chunks/generate.runtime-DdcVnK8J.js.map +0 -1
  147. package/dist/chunks/generate.runtime-N1KtAG8C.js.map +0 -1
  148. package/dist/chunks/generate.runtime-aN5QWygO.js.map +0 -1
  149. package/dist/chunks/shopify-page-D-VFwGxI.js +0 -11
  150. package/dist/chunks/shopify-page-D-VFwGxI.js.map +0 -1
  151. package/dist/chunks/write-result-0HYIr5a6.js +0 -511
  152. package/dist/chunks/write-result-0HYIr5a6.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-B2r11K7S.js","names":["languageFromPath","BACKEND_ENV_VARS","pruneUnusedImports","ensureNamedImport","ensureBlankLineAfterImports","formatLikeSource","modifyOutcomeToFile","replaceHandle","modifySvelteConfig","modifyTestSetup","WITH_BACKEND","modifyGitignore","hasVitestConfig","VITEST_CONFIG","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","getLogger","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,IAAagB,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;EAAc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,KAAK,2BAA2B,GACvCK,EAAO,oBAAoB3C,CAAa;CAK1C,IAAMqD,IAAenD,EAAK,KAAKsC,EAAQ,MAAM,eAAe,GACtDc,IAAe7D,EACnB4D,GACA/C,EAAsBkC,EAAQ,IAAI,CACpC;CAMA,OALIc,MACFhB,EAAO,KAAK,yBAAyB,GACrCG,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-B53OTMcE.js","names":["languageFromPath","BACKEND_ENV_VARS","pruneUnusedImports","ensureNamedImport","ensureBlankLineAfterImports","formatLikeSource","modifyOutcomeToFile","replaceHandle","modifySvelteConfig","modifyTestSetup","WITH_BACKEND","modifyGitignore","hasVitestConfig","VITEST_CONFIG","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","getLogger","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,IAAagB,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,UAAUE,CAAK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CACpC;CAMA,OALIc,MACFhB,EAAO,KAAK,yBAAyB,GACrCG,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,13 +1,13 @@
1
1
  import { r as e } from "./lib-specifier-Cngo1zF_.js";
2
2
  import { t } from "./dedent-Gq6Krl4n.js";
3
3
  import { n } from "./logger-CQONztPm.js";
4
- import { _ as r, c as i, d as a, h as o, m as s, n as c, o as l, s as u, u as d } from "./ts-morph-helpers-Bepc-Es2.js";
5
- import { a as f, r as p } from "./modify-file-289rStJ2.js";
4
+ import { _ as r, c as i, d as a, h as o, m as s, n as c, o as l, s as u, u as d } from "./ts-morph-helpers-CHI9wAil.js";
5
+ import { a as f, r as p } from "./modify-file-B4uJzOEj.js";
6
6
  import { t as m } from "./svelte-file-Dv5-bl79.js";
7
- import { n as h } from "./compose-handle-BDlZ7Pif.js";
8
- import { a as g, o as _, s as v, t as y } from "./config-target-rHgjaA8u.js";
9
- import { i as b } from "./package-imports-Bbw3iMPg.js";
10
- import { r as x, t as S } from "./_layout-D-FzWqn0.js";
7
+ import { n as h } from "./compose-handle-BBlamPfx.js";
8
+ import { a as g, o as _, s as v, t as y } from "./config-target-BgyFkbFL.js";
9
+ import { r as b } from "./package-imports-B9Asv3ZH.js";
10
+ import { r as x, t as S } from "./_layout-DQhSAhfF.js";
11
11
  import C from "node:fs";
12
12
  import w from "node:path";
13
13
  import { Project as T, QuoteKind as E, SyntaxKind as D } from "ts-morph";
@@ -323,4 +323,4 @@ async function X(e) {
323
323
  //#endregion
324
324
  export { X as generate };
325
325
 
326
- //# sourceMappingURL=generate.runtime-DCqf7nYM.js.map
326
+ //# sourceMappingURL=generate.runtime-B84ymwlD.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-DCqf7nYM.js","names":["FAILURE_HINT","I18N_MODULES","FAILURE_HINT","libModule","withInMemoryScript","pruneUnusedImports","removeNamedImportIfUnused","removeTopLevelStatementByIdentifier","removeStatementWithComments","ensureBlankLineAfterImports","formatLikeSource","isEffectivelyEmpty","removeImportByModuleSpecifier","revertOutcomeToFile","modifyOutcomeToFile","SvelteFile","removeHandle","probeFirstExisting","resolveConfigTarget","saveTarget","VITE_CONFIG_CANDIDATES","removePackageImports","LOCALES_IMPORTS","LOAD_STATEMENT","fs","path","unmodifyGitignore","gitignorePath","original","lines","out","i","line","j","hasWuchale","updated","unmodifyViteConfig","viteConfigPath","sourceFile","Project","QuoteKind","removed","arr","SyntaxKind","index","el","HINTS","unmodifyLocalesAlias","res","root","aliasProp","target","aliasObj","locales","p","localesModule","escaped","name","pattern","specifier","I18N_HANDLE","FAILURE_HINT$2","I18N_MODULES$1","unmodifyHooksServerI18n","hooksServerPath","stmt","s","moduleSpecifier","DELOCALIZE_HELPER","FAILURE_HINT$1","I18N_MODULES","I18N_ONLY_REROUTE","COMPOSED_REROUTE","unmodifyHooksI18n","hooksPath","helperStatement","rerouteDecl","initText","composed","rerouteStatement","unmodifyAppHtml","appHtmlPath","FAILURE_HINT","SIDE_EFFECT_MODULES","BINDING_MODULES","normalize","source","unmodifyRootLayoutI18n","layoutPath","loadStatement","d","unmodifyRootLayoutLanguageSelect","file","sf","generate","logger","getLogger","options","modifies","deletes","pushResult","imports","alias","hooksServerRevert","hooksRevert","layoutRevert","rootLayoutCandidates","candidate"],"sources":["../../src/patterns/disable/i18n/modifies/gitignore.ts","../../src/patterns/disable/i18n/modifies/vite-config.ts","../../src/patterns/disable/i18n/modifies/locales-alias.ts","../../src/patterns/disable/i18n/modifies/locales-module.ts","../../src/patterns/disable/i18n/modifies/hooks.server.ts","../../src/patterns/disable/i18n/modifies/hooks.ts","../../src/patterns/disable/i18n/modifies/app-html.ts","../../src/patterns/disable/i18n/modifies/+layout.ts","../../src/patterns/disable/i18n/modifies/root-layout.svelte.ts","../../src/patterns/disable/i18n/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n if (!original.includes(\"src/locales/.wuchale\")) {\n return { status: \"success\", changed: false };\n }\n\n const lines = original.split(\"\\n\");\n const out: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line === \"# Wuchale\") {\n let j = i + 1;\n let hasWuchale = false;\n while (j < lines.length && lines[j].trim() !== \"\") {\n if (lines[j] === \"src/locales/.wuchale\") {\n hasWuchale = true;\n }\n j++;\n }\n if (hasWuchale) {\n i = j;\n continue;\n }\n }\n if (line === \"src/locales/.wuchale\") continue;\n out.push(line);\n }\n\n let updated = out.join(\"\\n\");\n updated = updated.replace(/\\n{3,}/g, \"\\n\\n\");\n\n if (updated === original) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(gitignorePath, updated);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeImportByModuleSpecifier,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\n/** Remove `wuchale()` from the Vite plugins and its import. */\nexport function unmodifyViteConfig(viteConfigPath: string): ModifyOutcome {\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(viteConfigPath, \"utf8\");\n if (!original.includes(\"wuchale\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n // One removal at a time: manipulating the tree invalidates sibling nodes.\n for (;;) {\n let removed = false;\n for (const arr of sourceFile.getDescendantsOfKind(\n SyntaxKind.ArrayLiteralExpression,\n )) {\n const index = arr\n .getElements()\n .findIndex((el) => el.getText().replace(/\\s/g, \"\") === \"wuchale()\");\n if (index >= 0) {\n arr.removeElement(index);\n removed = true;\n break;\n }\n }\n if (!removed) break;\n }\n\n removeImportByModuleSpecifier(sourceFile, \"wuchale/vite\");\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import { SyntaxKind } from \"ts-morph\";\nimport {\n resolveConfigTarget,\n saveTarget,\n type ConfigModifyResult,\n} from \"../../../../runtime/config-target\";\n\nconst HINTS = {\n notFound: \"No SvelteKit config to revert.\",\n failed:\n \"Remove the $locales alias from the sveltekit() arg in vite.config by hand.\",\n};\n\n/**\n * Remove the `$locales` alias enable-i18n wrote before SvelteKit 3, which\n * `sv migrate sveltekit-3` moves into the inline `sveltekit({...})` arg;\n * `alias` goes too once it is empty. Projects enabled since then map\n * `#locales/*` in package.json `imports` instead.\n */\nexport function unmodifyLocalesAlias(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, HINTS);\n // Nothing to revert in a project without a config.\n if (res.status === \"not-found\") {\n return {\n filePath: res.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n if (res.status === \"failed\") {\n return {\n filePath: res.filePath,\n outcome: { status: \"failed\", message: res.message },\n };\n }\n\n const { target } = res;\n const aliasProp = target.configObject\n .getProperty(\"alias\")\n ?.asKind(SyntaxKind.PropertyAssignment);\n const aliasObj = aliasProp\n ?.getInitializer()\n ?.asKind(SyntaxKind.ObjectLiteralExpression);\n const locales = aliasObj\n ?.getProperties()\n .find((p) => p.getText().replace(/['\"]/g, \"\").startsWith(\"$locales\"));\n if (aliasProp && aliasObj && locales) {\n locales.remove();\n if (aliasObj.getProperties().length === 0) aliasProp.remove();\n }\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n","/**\n * Matches an import of wuchale's `src/locales/<name>.js` the way enable-i18n\n * writes it (`#locales/main.url.js`), and the `$locales/main.url` alias form\n * it wrote before SvelteKit 3, so disabling works on either.\n */\nexport function localesModule(name: string): (specifier: string) => boolean {\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(`^[$#]locales/${escaped}(\\\\.js)?$`);\n return (specifier) => pattern.test(specifier);\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n removeNamedImportIfUnused,\n removeTopLevelStatementByIdentifier,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { localesModule } from \"./locales-module\";\n\nconst I18N_HANDLE = \"handleWuchale\";\nconst FAILURE_HINT = dedent`\n Take handleWuchale out of the exported handle in src/hooks.server.ts, then\n remove its declaration, the loadLocales(...) calls and the wuchale and\n #locales imports.\n`;\n\nconst I18N_MODULES = [\n \"wuchale/load-utils/server\",\n localesModule(\"main.url\"),\n localesModule(\"data\"),\n localesModule(\"main.loader.server.svelte\"),\n localesModule(\"js.loader.server\"),\n];\n\n/**\n * Undo `modifyHooksServerI18n`: drop the locale bootstrap, the wuchale handle\n * and its imports, and unwrap `sequence(handleWuchale, ...)`. A file that\n * enable-i18n created comes out empty, for the caller to delete.\n */\nexport function unmodifyHooksServerI18n(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (!original.includes(I18N_HANDLE) && !original.includes(\"loadLocales(\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // loadLocales(...) bootstrap calls, one at a time (removal invalidates siblings).\n for (;;) {\n const stmt = sourceFile\n .getStatements()\n .find(\n (s) =>\n s.getKind() === SyntaxKind.ExpressionStatement &&\n /^loadLocales\\s*\\(/.test(s.getText()),\n );\n if (!stmt) break;\n stmt.remove();\n }\n\n // `export const handle = handleWuchale` goes altogether; a sequence loses\n // the argument, or unwraps to the handle it composed with.\n const removed = removeHandle(sourceFile, I18N_HANDLE);\n if (removed.status === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n removeTopLevelStatementByIdentifier(sourceFile, I18N_HANDLE);\n for (const moduleSpecifier of I18N_MODULES) {\n removeImportByModuleSpecifier(sourceFile, moduleSpecifier);\n }\n removeNamedImportIfUnused(sourceFile, \"@sveltejs/kit/hooks\", \"sequence\");\n removeNamedImportIfUnused(sourceFile, \"@sveltejs/kit/hooks\", \"Handle\");\n // A project from before SvelteKit 3 imports it from the package root.\n removeNamedImportIfUnused(sourceFile, \"@sveltejs/kit\", \"Handle\");\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 dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureBlankLineAfterImports,\n isEffectivelyEmpty,\n pruneUnusedImports,\n removeTopLevelStatementByIdentifier,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { localesModule } from \"./locales-module\";\n\nconst DELOCALIZE_HELPER = \"rerouteDeLocalize\";\n\nconst FAILURE_HINT = dedent`\n Take rerouteDeLocalize out of the exported reroute in src/hooks.ts, then\n remove its declaration and the wuchale and #locales imports.\n`;\n\nconst I18N_MODULES = [\n \"wuchale/url\",\n localesModule(\"main.url\"),\n localesModule(\"data\"),\n];\n\n/** The two reroutes `modifyHooksI18n` writes: on its own, and composed. */\nconst I18N_ONLY_REROUTE =\n /^\\(\\s*\\{\\s*url\\s*\\}\\s*\\)\\s*=>\\s*rerouteDeLocalize\\(\\s*url\\.pathname\\s*\\)$/;\nconst COMPOSED_REROUTE =\n /^\\(\\s*\\{\\s*url\\s*\\}\\s*\\)\\s*=>\\s*rerouteDeLocalize\\(\\s*negotiateReroute\\(\\s*url\\.pathname\\s*\\)\\s*\\)$/;\n\n/**\n * Undo `modifyHooksI18n`: drop the de-localizer and its imports, leaving the\n * negotiation reroute it may have been composed with. A file that enable-i18n\n * created comes out empty, for the caller to delete.\n */\nexport function unmodifyHooksI18n(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (!original.includes(DELOCALIZE_HELPER)) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const helperStatement = sourceFile\n .getVariableDeclaration(DELOCALIZE_HELPER)\n ?.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n const initText = rerouteDecl?.getInitializer()?.getText() ?? \"\";\n const composed = COMPOSED_REROUTE.test(initText);\n const rerouteStatement =\n composed || I18N_ONLY_REROUTE.test(initText)\n ? rerouteDecl?.getFirstAncestorByKind(SyntaxKind.VariableStatement)\n : undefined;\n\n // Anything else reading the de-localizer is code enable-i18n did not write,\n // so undoing it is the developer's call.\n const otherReaders = sourceFile\n .getStatements()\n .filter(\n (s) =>\n s !== helperStatement &&\n s !== rerouteStatement &&\n s.getText().includes(DELOCALIZE_HELPER),\n );\n if (otherReaders.length > 0) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n if (composed) {\n // content-negotiation's reroute is underneath; it stays.\n rerouteDecl?.setInitializer(\"({ url }) => negotiateReroute(url.pathname)\");\n } else if (rerouteStatement) {\n removeTopLevelStatementByIdentifier(sourceFile, \"reroute\");\n }\n\n removeTopLevelStatementByIdentifier(sourceFile, DELOCALIZE_HELPER);\n pruneUnusedImports(sourceFile, I18N_MODULES);\n\n if (isEffectivelyEmpty(sourceFile)) {\n // Emptied rather than removed: the runtime turns an empty hooks.ts into a\n // delete entry, so the removal is written and reported like any other.\n fs.writeFileSync(hooksPath, \"\", \"utf8\");\n return { status: \"success\", changed: true };\n }\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 type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Put a real language back. `%sveltekit.lang%` is not a SvelteKit\n * placeholder; only the wuchale hook replaced it, so without that hook it\n * would be served literally.\n */\nexport function unmodifyAppHtml(appHtmlPath: string): ModifyOutcome {\n if (!fs.existsSync(appHtmlPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(appHtmlPath, \"utf8\");\n const updated = original.replace(\n /lang\\s*=\\s*(?:\"%sveltekit\\.lang%\"|'%sveltekit\\.lang%')/g,\n 'lang=\"en\"',\n );\n if (updated === original) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(appHtmlPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, type Statement } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { LOAD_STATEMENT } from \"../../../enable/i18n/modifies/+layout\";\nimport {\n ensureBlankLineAfterImports,\n isEffectivelyEmpty,\n pruneUnusedImports,\n removeImportByModuleSpecifier,\n removeStatementWithComments,\n formatLikeSource,\n type ModuleMatch,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { localesModule } from \"./locales-module\";\n\nconst FAILURE_HINT = dedent`\n src/routes/+layout.ts still loads wuchale locales. Remove these from it:\n\n import { browser } from '$app/env';\n import { loadLocale } from 'wuchale/load-utils';\n import { getLocale } from '#locales/main.url.js';\n import '#locales/main.loader.svelte.js';\n import '#locales/js.loader.js';\n\n and the loadLocale(...) call inside load().\n`;\n\nconst SIDE_EFFECT_MODULES = [\n localesModule(\"main.loader.svelte\"),\n localesModule(\"js.loader\"),\n];\nconst BINDING_MODULES: ModuleMatch[] = [\n // `$app/env`, or the module it replaced before SvelteKit 3.\n (specifier) => /^\\$app\\/env(ironment)?$/.test(specifier),\n \"wuchale/load-utils\",\n localesModule(\"main.url\"),\n];\n\nfunction normalize(source: string): string {\n return source.replace(/[\"']/g, \"'\").replace(/\\s+/g, \"\");\n}\n\n/**\n * Undo `ensureRootLayoutI18n`: drop the wuchale load and its imports, leaving\n * whatever else the file holds. A file enable-i18n wrote whole comes out\n * empty, for the caller to delete.\n */\nexport function unmodifyRootLayoutI18n(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutPath, \"utf8\");\n if (!original.includes(\"loadLocale\") && !/[$#]locales\\//.test(original)) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n const loadStatement: Statement | undefined =\n sourceFile\n .getVariableStatements()\n .find((s) => s.getDeclarations().some((d) => d.getName() === \"load\")) ??\n sourceFile.getFunction(\"load\");\n\n if (loadStatement) {\n // A load that grew code of its own needs a hand; only the one enable-i18n\n // wrote is safe to take out wholesale.\n if (normalize(loadStatement.getText()) !== normalize(LOAD_STATEMENT)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n removeStatementWithComments(sourceFile, loadStatement);\n }\n\n for (const moduleSpecifier of SIDE_EFFECT_MODULES) {\n removeImportByModuleSpecifier(sourceFile, moduleSpecifier);\n }\n pruneUnusedImports(sourceFile, BINDING_MODULES);\n\n if (isEffectivelyEmpty(sourceFile)) {\n // Emptied rather than removed: the runtime turns an empty +layout.ts into\n // a delete entry, so the removal is written and reported like any other.\n fs.writeFileSync(layoutPath, \"\", \"utf8\");\n return { status: \"success\", changed: true };\n }\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 { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\n/** Take the language select (and the nav item enable-i18n wrapped it in) back out. */\nexport function unmodifyRootLayoutLanguageSelect(\n layoutPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutPath, \"utf8\");\n if (!original.includes(\"LanguageSelect\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(\n sf,\n libModule(\"components/language-select.svelte\"),\n );\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n let updated = file.toString();\n updated = updated.replace(\n /[ \\t]*<Navbar\\.Item>\\s*<LanguageSelect\\s*\\/>\\s*<\\/Navbar\\.Item>[ \\t]*\\r?\\n?/g,\n \"\",\n );\n updated = updated.replace(/[ \\t]*<LanguageSelect\\s*\\/>[ \\t]*\\r?\\n?/g, \"\");\n\n fs.writeFileSync(layoutPath, updated, \"utf8\");\n return { status: \"success\", changed: updated !== original };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n modifyOutcomeToFile,\n revertOutcomeToFile,\n} from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { unmodifyGitignore } from \"./modifies/gitignore\";\nimport { unmodifyViteConfig } from \"./modifies/vite-config\";\nimport { unmodifyLocalesAlias } from \"./modifies/locales-alias\";\nimport { removePackageImports } from \"../../../runtime/package-imports\";\nimport { LOCALES_IMPORTS } from \"../../enable/i18n/modifies/package-imports\";\nimport { unmodifyHooksServerI18n } from \"./modifies/hooks.server\";\nimport { unmodifyHooksI18n } from \"./modifies/hooks\";\nimport { unmodifyAppHtml } from \"./modifies/app-html\";\nimport { unmodifyRootLayoutI18n } from \"./modifies/+layout\";\nimport { unmodifyRootLayoutLanguageSelect } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const deletes: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n pushResult(\n modifyOutcomeToFile(viteConfigPath, unmodifyViteConfig(viteConfigPath)),\n );\n\n logger.info(\"Removing #locales from package.json imports\");\n // Only while it still maps where enable-i18n pointed it.\n const imports = removePackageImports(\n options.root,\n Object.keys(LOCALES_IMPORTS),\n LOCALES_IMPORTS,\n );\n pushResult(modifyOutcomeToFile(imports.filePath, imports.outcome));\n\n // A project enabled before SvelteKit 3 has the `$locales` alias instead,\n // moved into the sveltekit() arg by `vela migrate sveltekit-3`.\n logger.info(\"Reverting the legacy $locales alias\");\n const alias = unmodifyLocalesAlias(options.root);\n pushResult(modifyOutcomeToFile(alias.filePath, alias.outcome));\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n // enable-i18n may have created it; emptied, it goes.\n const hooksServerRevert = revertOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerI18n(hooksServerPath),\n );\n pushResult(hooksServerRevert.modify);\n if (hooksServerRevert.delete) deletes.push(hooksServerRevert.delete);\n\n logger.info(\"Reverting hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n // The de-localizing reroute may be all it holds; emptied, it goes.\n const hooksRevert = revertOutcomeToFile(\n hooksPath,\n unmodifyHooksI18n(hooksPath),\n );\n pushResult(hooksRevert.modify);\n if (hooksRevert.delete) deletes.push(hooksRevert.delete);\n\n logger.info(\"Reverting app.html\");\n const appHtmlPath = path.join(options.root, \"src\", \"app.html\");\n pushResult(modifyOutcomeToFile(appHtmlPath, unmodifyAppHtml(appHtmlPath)));\n\n logger.info(\"Reverting root +layout.ts\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.ts\");\n // enable-i18n may have written the whole file; emptied, it goes.\n const layoutRevert = revertOutcomeToFile(\n layoutPath,\n unmodifyRootLayoutI18n(layoutPath),\n );\n pushResult(layoutRevert.modify);\n if (layoutRevert.delete) deletes.push(layoutRevert.delete);\n\n logger.info(\"Reverting root layout language select\");\n const rootLayoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n for (const candidate of rootLayoutCandidates) {\n if (!fs.existsSync(candidate)) continue;\n pushResult(\n modifyOutcomeToFile(\n candidate,\n unmodifyRootLayoutLanguageSelect(candidate),\n ),\n );\n }\n\n logger.info(\"Reverting .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n pushResult(\n modifyOutcomeToFile(gitignorePath, unmodifyGitignore(gitignorePath)),\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":";;;;;;;;;;;;;;AAGA,SAAgB0B,EAAkB,GAAsC;CACtE,IAAI,CAACF,EAAG,WAAWG,CAAa,GAC9B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAWJ,EAAG,aAAaG,GAAe,MAAM;CACtD,IAAI,CAACC,EAAS,SAAS,sBAAsB,GAC3C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAQD,EAAS,MAAM,IAAI,GAC3BE,IAAgB,CAAC;CACvB,KAAK,IAAIC,IAAI,GAAGA,IAAIF,EAAM,QAAQ,KAAK;EACrC,IAAMG,IAAOH,EAAME;EACnB,IAAIC,MAAS,aAAa;GACxB,IAAIC,IAAIF,IAAI,GACRG,IAAa;GACjB,OAAOD,IAAIJ,EAAM,UAAUA,EAAMI,EAAE,CAAC,KAAK,MAAM,KAI7C,AAHIJ,EAAMI,OAAO,2BACf,IAAa,KAEf;GAEF,IAAIC,GAAY;IACd,IAAID;IACJ;GACF;EACF;EACA,AAAID,MAAS,0BACbF,EAAI,KAAKE,CAAI;CACf;CAEA,IAAIG,IAAUL,EAAI,KAAK,IAAI;CAQ3B,OAPA,IAAUK,EAAQ,QAAQ,WAAW,MAAM,GAEvCA,MAAYP,IACP;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7CJ,EAAG,cAAcG,GAAeQ,CAAO,GAChC;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;;;ACnCA,SAAgBC,EAAmB,GAAuC;CACxE,IAAI,CAACZ,EAAG,WAAWa,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMT,IAAWJ,EAAG,aAAaa,GAAgB,MAAM;CACvD,IAAI,CAACT,EAAS,SAAS,SAAS,GAC9B,OAAO;EAAE,QAAQ;EAAW,SA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;CAK1D,OAJAG,EACEtF,EAAoBa,GAAeD,EAAkBC,CAAa,CAAC,CACrE,GAEO;EACL,SAAS,CAAC;EACV;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-B84ymwlD.js","names":["FAILURE_HINT","I18N_MODULES","FAILURE_HINT","libModule","withInMemoryScript","pruneUnusedImports","removeNamedImportIfUnused","removeTopLevelStatementByIdentifier","removeStatementWithComments","ensureBlankLineAfterImports","formatLikeSource","isEffectivelyEmpty","removeImportByModuleSpecifier","revertOutcomeToFile","modifyOutcomeToFile","SvelteFile","removeHandle","probeFirstExisting","resolveConfigTarget","saveTarget","VITE_CONFIG_CANDIDATES","removePackageImports","LOCALES_IMPORTS","LOAD_STATEMENT","fs","path","unmodifyGitignore","gitignorePath","original","lines","out","i","line","j","hasWuchale","updated","unmodifyViteConfig","viteConfigPath","sourceFile","Project","QuoteKind","removed","arr","SyntaxKind","index","el","HINTS","unmodifyLocalesAlias","res","root","aliasProp","target","aliasObj","locales","p","localesModule","escaped","name","pattern","specifier","I18N_HANDLE","FAILURE_HINT$2","I18N_MODULES$1","unmodifyHooksServerI18n","hooksServerPath","stmt","s","moduleSpecifier","DELOCALIZE_HELPER","FAILURE_HINT$1","I18N_MODULES","I18N_ONLY_REROUTE","COMPOSED_REROUTE","unmodifyHooksI18n","hooksPath","helperStatement","rerouteDecl","initText","composed","rerouteStatement","unmodifyAppHtml","appHtmlPath","FAILURE_HINT","SIDE_EFFECT_MODULES","BINDING_MODULES","normalize","source","unmodifyRootLayoutI18n","layoutPath","loadStatement","d","unmodifyRootLayoutLanguageSelect","file","sf","generate","logger","getLogger","options","modifies","deletes","pushResult","imports","alias","hooksServerRevert","hooksRevert","layoutRevert","rootLayoutCandidates","candidate"],"sources":["../../src/patterns/disable/i18n/modifies/gitignore.ts","../../src/patterns/disable/i18n/modifies/vite-config.ts","../../src/patterns/disable/i18n/modifies/locales-alias.ts","../../src/patterns/disable/i18n/modifies/locales-module.ts","../../src/patterns/disable/i18n/modifies/hooks.server.ts","../../src/patterns/disable/i18n/modifies/hooks.ts","../../src/patterns/disable/i18n/modifies/app-html.ts","../../src/patterns/disable/i18n/modifies/+layout.ts","../../src/patterns/disable/i18n/modifies/root-layout.svelte.ts","../../src/patterns/disable/i18n/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nexport function unmodifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n if (!original.includes(\"src/locales/.wuchale\")) {\n return { status: \"success\", changed: false };\n }\n\n const lines = original.split(\"\\n\");\n const out: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line === \"# Wuchale\") {\n let j = i + 1;\n let hasWuchale = false;\n while (j < lines.length && lines[j].trim() !== \"\") {\n if (lines[j] === \"src/locales/.wuchale\") {\n hasWuchale = true;\n }\n j++;\n }\n if (hasWuchale) {\n i = j;\n continue;\n }\n }\n if (line === \"src/locales/.wuchale\") continue;\n out.push(line);\n }\n\n let updated = out.join(\"\\n\");\n updated = updated.replace(/\\n{3,}/g, \"\\n\\n\");\n\n if (updated === original) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(gitignorePath, updated);\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n removeImportByModuleSpecifier,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\n/** Remove `wuchale()` from the Vite plugins and its import. */\nexport function unmodifyViteConfig(viteConfigPath: string): ModifyOutcome {\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(viteConfigPath, \"utf8\");\n if (!original.includes(\"wuchale\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n // One removal at a time: manipulating the tree invalidates sibling nodes.\n for (;;) {\n let removed = false;\n for (const arr of sourceFile.getDescendantsOfKind(\n SyntaxKind.ArrayLiteralExpression,\n )) {\n const index = arr\n .getElements()\n .findIndex((el) => el.getText().replace(/\\s/g, \"\") === \"wuchale()\");\n if (index >= 0) {\n arr.removeElement(index);\n removed = true;\n break;\n }\n }\n if (!removed) break;\n }\n\n removeImportByModuleSpecifier(sourceFile, \"wuchale/vite\");\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== original,\n };\n}\n","import { SyntaxKind } from \"ts-morph\";\nimport {\n resolveConfigTarget,\n saveTarget,\n type ConfigModifyResult,\n} from \"../../../../runtime/config-target\";\n\nconst HINTS = {\n notFound: \"No SvelteKit config to revert.\",\n failed:\n \"Remove the $locales alias from the sveltekit() arg in vite.config by hand.\",\n};\n\n/**\n * Remove the `$locales` alias enable-i18n wrote before SvelteKit 3, which\n * `sv migrate sveltekit-3` moves into the inline `sveltekit({...})` arg;\n * `alias` goes too once it is empty. Projects enabled since then map\n * `#locales/*` in package.json `imports` instead.\n */\nexport function unmodifyLocalesAlias(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, HINTS);\n // Nothing to revert in a project without a config.\n if (res.status === \"not-found\") {\n return {\n filePath: res.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n if (res.status === \"failed\") {\n return {\n filePath: res.filePath,\n outcome: { status: \"failed\", message: res.message },\n };\n }\n\n const { target } = res;\n const aliasProp = target.configObject\n .getProperty(\"alias\")\n ?.asKind(SyntaxKind.PropertyAssignment);\n const aliasObj = aliasProp\n ?.getInitializer()\n ?.asKind(SyntaxKind.ObjectLiteralExpression);\n const locales = aliasObj\n ?.getProperties()\n .find((p) => p.getText().replace(/['\"]/g, \"\").startsWith(\"$locales\"));\n if (aliasProp && aliasObj && locales) {\n locales.remove();\n if (aliasObj.getProperties().length === 0) aliasProp.remove();\n }\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n","/**\n * Matches an import of wuchale's `src/locales/<name>.js` the way enable-i18n\n * writes it (`#locales/main.url.js`), and the `$locales/main.url` alias form\n * it wrote before SvelteKit 3, so disabling works on either.\n */\nexport function localesModule(name: string): (specifier: string) => boolean {\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(`^[$#]locales/${escaped}(\\\\.js)?$`);\n return (specifier) => pattern.test(specifier);\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n removeNamedImportIfUnused,\n removeTopLevelStatementByIdentifier,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { localesModule } from \"./locales-module\";\n\nconst I18N_HANDLE = \"handleWuchale\";\nconst FAILURE_HINT = dedent`\n Take handleWuchale out of the exported handle in src/hooks.server.ts, then\n remove its declaration, the loadLocales(...) calls and the wuchale and\n #locales imports.\n`;\n\nconst I18N_MODULES = [\n \"wuchale/load-utils/server\",\n localesModule(\"main.url\"),\n localesModule(\"data\"),\n localesModule(\"main.loader.server.svelte\"),\n localesModule(\"js.loader.server\"),\n];\n\n/**\n * Undo `modifyHooksServerI18n`: drop the locale bootstrap, the wuchale handle\n * and its imports, and unwrap `sequence(handleWuchale, ...)`. A file that\n * enable-i18n created comes out empty, for the caller to delete.\n */\nexport function unmodifyHooksServerI18n(\n hooksServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksServerPath, \"utf8\");\n if (!original.includes(I18N_HANDLE) && !original.includes(\"loadLocales(\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // loadLocales(...) bootstrap calls, one at a time (removal invalidates siblings).\n for (;;) {\n const stmt = sourceFile\n .getStatements()\n .find(\n (s) =>\n s.getKind() === SyntaxKind.ExpressionStatement &&\n /^loadLocales\\s*\\(/.test(s.getText()),\n );\n if (!stmt) break;\n stmt.remove();\n }\n\n // `export const handle = handleWuchale` goes altogether; a sequence loses\n // the argument, or unwraps to the handle it composed with.\n const removed = removeHandle(sourceFile, I18N_HANDLE);\n if (removed.status === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n removeTopLevelStatementByIdentifier(sourceFile, I18N_HANDLE);\n for (const moduleSpecifier of I18N_MODULES) {\n removeImportByModuleSpecifier(sourceFile, moduleSpecifier);\n }\n removeNamedImportIfUnused(sourceFile, \"@sveltejs/kit/hooks\", \"sequence\");\n removeNamedImportIfUnused(sourceFile, \"@sveltejs/kit/hooks\", \"Handle\");\n // A project from before SvelteKit 3 imports it from the package root.\n removeNamedImportIfUnused(sourceFile, \"@sveltejs/kit\", \"Handle\");\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 dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureBlankLineAfterImports,\n isEffectivelyEmpty,\n pruneUnusedImports,\n removeTopLevelStatementByIdentifier,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { localesModule } from \"./locales-module\";\n\nconst DELOCALIZE_HELPER = \"rerouteDeLocalize\";\n\nconst FAILURE_HINT = dedent`\n Take rerouteDeLocalize out of the exported reroute in src/hooks.ts, then\n remove its declaration and the wuchale and #locales imports.\n`;\n\nconst I18N_MODULES = [\n \"wuchale/url\",\n localesModule(\"main.url\"),\n localesModule(\"data\"),\n];\n\n/** The two reroutes `modifyHooksI18n` writes: on its own, and composed. */\nconst I18N_ONLY_REROUTE =\n /^\\(\\s*\\{\\s*url\\s*\\}\\s*\\)\\s*=>\\s*rerouteDeLocalize\\(\\s*url\\.pathname\\s*\\)$/;\nconst COMPOSED_REROUTE =\n /^\\(\\s*\\{\\s*url\\s*\\}\\s*\\)\\s*=>\\s*rerouteDeLocalize\\(\\s*negotiateReroute\\(\\s*url\\.pathname\\s*\\)\\s*\\)$/;\n\n/**\n * Undo `modifyHooksI18n`: drop the de-localizer and its imports, leaving the\n * negotiation reroute it may have been composed with. A file that enable-i18n\n * created comes out empty, for the caller to delete.\n */\nexport function unmodifyHooksI18n(hooksPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(hooksPath, \"utf8\");\n if (!original.includes(DELOCALIZE_HELPER)) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(hooksPath);\n\n const helperStatement = sourceFile\n .getVariableDeclaration(DELOCALIZE_HELPER)\n ?.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n\n const rerouteDecl = sourceFile.getVariableDeclaration(\"reroute\");\n const initText = rerouteDecl?.getInitializer()?.getText() ?? \"\";\n const composed = COMPOSED_REROUTE.test(initText);\n const rerouteStatement =\n composed || I18N_ONLY_REROUTE.test(initText)\n ? rerouteDecl?.getFirstAncestorByKind(SyntaxKind.VariableStatement)\n : undefined;\n\n // Anything else reading the de-localizer is code enable-i18n did not write,\n // so undoing it is the developer's call.\n const otherReaders = sourceFile\n .getStatements()\n .filter(\n (s) =>\n s !== helperStatement &&\n s !== rerouteStatement &&\n s.getText().includes(DELOCALIZE_HELPER),\n );\n if (otherReaders.length > 0) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n if (composed) {\n // content-negotiation's reroute is underneath; it stays.\n rerouteDecl?.setInitializer(\"({ url }) => negotiateReroute(url.pathname)\");\n } else if (rerouteStatement) {\n removeTopLevelStatementByIdentifier(sourceFile, \"reroute\");\n }\n\n removeTopLevelStatementByIdentifier(sourceFile, DELOCALIZE_HELPER);\n pruneUnusedImports(sourceFile, I18N_MODULES);\n\n if (isEffectivelyEmpty(sourceFile)) {\n // Emptied rather than removed: the runtime turns an empty hooks.ts into a\n // delete entry, so the removal is written and reported like any other.\n fs.writeFileSync(hooksPath, \"\", \"utf8\");\n return { status: \"success\", changed: true };\n }\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 type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * Put a real language back. `%sveltekit.lang%` is not a SvelteKit\n * placeholder; only the wuchale hook replaced it, so without that hook it\n * would be served literally.\n */\nexport function unmodifyAppHtml(appHtmlPath: string): ModifyOutcome {\n if (!fs.existsSync(appHtmlPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(appHtmlPath, \"utf8\");\n const updated = original.replace(\n /lang\\s*=\\s*(?:\"%sveltekit\\.lang%\"|'%sveltekit\\.lang%')/g,\n 'lang=\"en\"',\n );\n if (updated === original) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(appHtmlPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, type Statement } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { LOAD_STATEMENT } from \"../../../enable/i18n/modifies/+layout\";\nimport {\n ensureBlankLineAfterImports,\n isEffectivelyEmpty,\n pruneUnusedImports,\n removeImportByModuleSpecifier,\n removeStatementWithComments,\n formatLikeSource,\n type ModuleMatch,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { localesModule } from \"./locales-module\";\n\nconst FAILURE_HINT = dedent`\n src/routes/+layout.ts still loads wuchale locales. Remove these from it:\n\n import { browser } from '$app/env';\n import { loadLocale } from 'wuchale/load-utils';\n import { getLocale } from '#locales/main.url.js';\n import '#locales/main.loader.svelte.js';\n import '#locales/js.loader.js';\n\n and the loadLocale(...) call inside load().\n`;\n\nconst SIDE_EFFECT_MODULES = [\n localesModule(\"main.loader.svelte\"),\n localesModule(\"js.loader\"),\n];\nconst BINDING_MODULES: ModuleMatch[] = [\n // `$app/env`, or the module it replaced before SvelteKit 3.\n (specifier) => /^\\$app\\/env(ironment)?$/.test(specifier),\n \"wuchale/load-utils\",\n localesModule(\"main.url\"),\n];\n\nfunction normalize(source: string): string {\n return source.replace(/[\"']/g, \"'\").replace(/\\s+/g, \"\");\n}\n\n/**\n * Undo `ensureRootLayoutI18n`: drop the wuchale load and its imports, leaving\n * whatever else the file holds. A file enable-i18n wrote whole comes out\n * empty, for the caller to delete.\n */\nexport function unmodifyRootLayoutI18n(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutPath, \"utf8\");\n if (!original.includes(\"loadLocale\") && !/[$#]locales\\//.test(original)) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n const loadStatement: Statement | undefined =\n sourceFile\n .getVariableStatements()\n .find((s) => s.getDeclarations().some((d) => d.getName() === \"load\")) ??\n sourceFile.getFunction(\"load\");\n\n if (loadStatement) {\n // A load that grew code of its own needs a hand; only the one enable-i18n\n // wrote is safe to take out wholesale.\n if (normalize(loadStatement.getText()) !== normalize(LOAD_STATEMENT)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n removeStatementWithComments(sourceFile, loadStatement);\n }\n\n for (const moduleSpecifier of SIDE_EFFECT_MODULES) {\n removeImportByModuleSpecifier(sourceFile, moduleSpecifier);\n }\n pruneUnusedImports(sourceFile, BINDING_MODULES);\n\n if (isEffectivelyEmpty(sourceFile)) {\n // Emptied rather than removed: the runtime turns an empty +layout.ts into\n // a delete entry, so the removal is written and reported like any other.\n fs.writeFileSync(layoutPath, \"\", \"utf8\");\n return { status: \"success\", changed: true };\n }\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 { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\n/** Take the language select (and the nav item enable-i18n wrapped it in) back out. */\nexport function unmodifyRootLayoutLanguageSelect(\n layoutPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutPath, \"utf8\");\n if (!original.includes(\"LanguageSelect\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(\n sf,\n libModule(\"components/language-select.svelte\"),\n );\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n let updated = file.toString();\n updated = updated.replace(\n /[ \\t]*<Navbar\\.Item>\\s*<LanguageSelect\\s*\\/>\\s*<\\/Navbar\\.Item>[ \\t]*\\r?\\n?/g,\n \"\",\n );\n updated = updated.replace(/[ \\t]*<LanguageSelect\\s*\\/>[ \\t]*\\r?\\n?/g, \"\");\n\n fs.writeFileSync(layoutPath, updated, \"utf8\");\n return { status: \"success\", changed: updated !== original };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n modifyOutcomeToFile,\n revertOutcomeToFile,\n} from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { unmodifyGitignore } from \"./modifies/gitignore\";\nimport { unmodifyViteConfig } from \"./modifies/vite-config\";\nimport { unmodifyLocalesAlias } from \"./modifies/locales-alias\";\nimport { removePackageImports } from \"../../../runtime/package-imports\";\nimport { LOCALES_IMPORTS } from \"../../enable/i18n/modifies/package-imports\";\nimport { unmodifyHooksServerI18n } from \"./modifies/hooks.server\";\nimport { unmodifyHooksI18n } from \"./modifies/hooks\";\nimport { unmodifyAppHtml } from \"./modifies/app-html\";\nimport { unmodifyRootLayoutI18n } from \"./modifies/+layout\";\nimport { unmodifyRootLayoutLanguageSelect } from \"./modifies/root-layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const deletes: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n pushResult(\n modifyOutcomeToFile(viteConfigPath, unmodifyViteConfig(viteConfigPath)),\n );\n\n logger.info(\"Removing #locales from package.json imports\");\n // Only while it still maps where enable-i18n pointed it.\n const imports = removePackageImports(\n options.root,\n Object.keys(LOCALES_IMPORTS),\n LOCALES_IMPORTS,\n );\n pushResult(modifyOutcomeToFile(imports.filePath, imports.outcome));\n\n // A project enabled before SvelteKit 3 has the `$locales` alias instead,\n // moved into the sveltekit() arg by `vela migrate sveltekit-3`.\n logger.info(\"Reverting the legacy $locales alias\");\n const alias = unmodifyLocalesAlias(options.root);\n pushResult(modifyOutcomeToFile(alias.filePath, alias.outcome));\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n // enable-i18n may have created it; emptied, it goes.\n const hooksServerRevert = revertOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerI18n(hooksServerPath),\n );\n pushResult(hooksServerRevert.modify);\n if (hooksServerRevert.delete) deletes.push(hooksServerRevert.delete);\n\n logger.info(\"Reverting hooks.ts\");\n const hooksPath = path.join(options.root, \"src\", \"hooks.ts\");\n // The de-localizing reroute may be all it holds; emptied, it goes.\n const hooksRevert = revertOutcomeToFile(\n hooksPath,\n unmodifyHooksI18n(hooksPath),\n );\n pushResult(hooksRevert.modify);\n if (hooksRevert.delete) deletes.push(hooksRevert.delete);\n\n logger.info(\"Reverting app.html\");\n const appHtmlPath = path.join(options.root, \"src\", \"app.html\");\n pushResult(modifyOutcomeToFile(appHtmlPath, unmodifyAppHtml(appHtmlPath)));\n\n logger.info(\"Reverting root +layout.ts\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.ts\");\n // enable-i18n may have written the whole file; emptied, it goes.\n const layoutRevert = revertOutcomeToFile(\n layoutPath,\n unmodifyRootLayoutI18n(layoutPath),\n );\n pushResult(layoutRevert.modify);\n if (layoutRevert.delete) deletes.push(layoutRevert.delete);\n\n logger.info(\"Reverting root layout language select\");\n const rootLayoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n for (const candidate of rootLayoutCandidates) {\n if (!fs.existsSync(candidate)) continue;\n pushResult(\n modifyOutcomeToFile(\n candidate,\n unmodifyRootLayoutLanguageSelect(candidate),\n ),\n );\n }\n\n logger.info(\"Reverting .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n pushResult(\n modifyOutcomeToFile(gitignorePath, unmodifyGitignore(gitignorePath)),\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":";;;;;;;;;;;;;;AAGA,SAAgB0B,EAAkB,GAAsC;CACtE,IAAI,CAACF,EAAG,WAAWG,CAAa,GAC9B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAWJ,EAAG,aAAaG,GAAe,MAAM;CACtD,IAAI,CAACC,EAAS,SAAS,sBAAsB,GAC3C,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAQD,EAAS,MAAM,IAAI,GAC3BE,IAAgB,CAAC;CACvB,KAAK,IAAIC,IAAI,GAAGA,IAAIF,EAAM,QAAQ,KAAK;EACrC,IAAMG,IAAOH,EAAME;EACnB,IAAIC,MAAS,aAAa;GACxB,IAAIC,IAAIF,IAAI,GACRG,IAAa;GACjB,OAAOD,IAAIJ,EAAM,UAAUA,EAAMI,EAAE,CAAC,KAAK,MAAM,KAI7C,AAHIJ,EAAMI,OAAO,2BACf,IAAa,KAEf;GAEF,IAAIC,GAAY;IACd,IAAID;IACJ;GACF;EACF;EACA,AAAID,MAAS,0BACbF,EAAI,KAAKE,CAAI;CACf;CAEA,IAAIG,IAAUL,EAAI,KAAK,IAAI;CAQ3B,OAPA,IAAUK,EAAQ,QAAQ,WAAW,MAAM,GAEvCA,MAAYP,IACP;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7CJ,EAAG,cAAcG,GAAeQ,CAAO,GAChC;EAAE,QAAQ;EAAW,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EAAK,KAAKwE,EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAC3D;CACA,KAAK,IAAMU,KAAaD,GACtB,AAAKlF,EAAG,WAAWmF,CAAS,KAC5BP,EACEtF,EACE6F,GACAhB,EAAiCgB,CAAS,CAC5C,CACF;CAGF,EAAO,KAAK,sBAAsB;CAClC,IAAMhF,IAAgBF,EAAK,KAAKwE,EAAQ,MAAM,YAAY;CAK1D,OAJAG,EACEtF,EAAoBa,GAAeD,EAAkBC,CAAa,CAAC,CACrE,GAEO;EACL,SAAS,CAAC;EACV;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,10 +1,10 @@
1
1
  import { t as e } from "./dedent-Gq6Krl4n.js";
2
2
  import { n as t } from "./logger-CQONztPm.js";
3
- import { n } from "./generate-Cqwa8kD9.js";
4
- import { _ as r, o as i, r as a } from "./ts-morph-helpers-Bepc-Es2.js";
5
- import { r as o } from "./modify-file-289rStJ2.js";
3
+ import { n } from "./generate-DoHn_xJZ.js";
4
+ import { _ as r, o as i, r as a } from "./ts-morph-helpers-CHI9wAil.js";
5
+ import { r as o } from "./modify-file-B4uJzOEj.js";
6
6
  import { t as s } from "./svelte-file-Dv5-bl79.js";
7
- import { a as c, t as l } from "./config-target-rHgjaA8u.js";
7
+ import { a as c, t as l } from "./config-target-BgyFkbFL.js";
8
8
  import u from "node:fs";
9
9
  import d from "node:path";
10
10
  import { Node as f, Project as p, QuoteKind as m, SyntaxKind as h } from "ts-morph";
@@ -85,14 +85,11 @@ function b() {
85
85
  }
86
86
  function x(e, t, n) {
87
87
  let r = e.getImportDeclarations().find((e) => e.getModuleSpecifierValue() === t);
88
- if (!r) {
89
- e.addImportDeclaration({
90
- namedImports: n,
91
- moduleSpecifier: t
92
- });
93
- return;
94
- }
95
- for (let e of n) r.getNamedImports().some((t) => t.getName() === e) || r.addNamedImport(e);
88
+ if (!r) e.addImportDeclaration({
89
+ namedImports: n,
90
+ moduleSpecifier: t
91
+ });
92
+ else for (let e of n) r.getNamedImports().some((t) => t.getName() === e) || r.addNamedImport(e);
96
93
  }
97
94
  function S(e, t) {
98
95
  t.namedImports?.length && x(e, t.moduleSpecifier, t.namedImports), !e.getImportDeclarations().find((e) => e.getModuleSpecifierValue() === t.moduleSpecifier) && e.addImportDeclaration({
@@ -397,4 +394,4 @@ async function q(e) {
397
394
  //#endregion
398
395
  export { q as generate };
399
396
 
400
- //# sourceMappingURL=generate.runtime-Dug2UIhV.js.map
397
+ //# sourceMappingURL=generate.runtime-BOl3LpPB.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate.runtime-Dug2UIhV.js","names":["FAILURE_HINT","NOT_FOUND_HINT","FAILURE_HINT","FAILURE_HINT","dedent","getLogger","withInMemoryScript","formatLikeSource","ensureImports","modifyOutcomeToFile","SvelteFile","probeFirstExisting","VITE_CONFIG_CANDIDATES","fs","path","FAILURE_HINT$3","NOT_FOUND_HINT$1","elementName","text","modifyViteConfig","call","pluginArgs","viteConfigPath","sourceFile","Project","QuoteKind","changed","failed","d","configArg","SyntaxKind","ce","configObj","pluginsProp","pluginsInit","arr","elements","el","sveltekitIndex","newProject","ensureNamedImports","existing","moduleSpecifier","names","name","ni","ensureImportSpec","spec","unwrapFunction","Node","node","arg","fn","findLoadFunction","declaration","variable","initializer","isFunctionNode","findFinalReturn","statements","body","last","r","returnedObject","expression","statement","hasProperty","object","property","hasSpreadOf","expressionText","inspectEventParameter","params","param","nameNode","DEFAULT_LOCALE","WUCHALE_LOCALE","eventName","cmsSnippet","locale","importLine","parts","createdLayoutServer","imports","snippet","FAILURE_HINT$2","modifyLayoutServer","layoutServerPath","event","returned","spreadIndex","returnIndex","destructuring","typeText","FAILURE_HINT$1","modifyLayoutUniversal","layoutPath","dataExpression","element","IMPORT_SNIPPET","MARKUP_SNIPPET","NOT_FOUND_HINT","FAILURE_HINT","modifyLayoutSvelte","file","out","source","sf","readWuchaleLocales","configPath","root","match","locales","m","vitePluginArgs","mode","list","generate","logger","options","modifies","resolveMode","i18n","pushResult","layoutUniversalPath","layoutSveltePath"],"sources":["../../src/patterns/enable/cms/modifies/vite-config.ts","../../src/patterns/enable/cms/modifies/load-function.ts","../../src/patterns/enable/cms/modifies/layout.server.ts","../../src/patterns/enable/cms/modifies/layout.ts","../../src/patterns/enable/cms/modifies/layout.svelte.ts","../../src/patterns/enable/cms/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n type PropertyAssignment,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = [\n \"Add the CMS plugin to your Vite config, ahead of sveltekit():\",\n \"\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the CMS plugin ahead of sveltekit():\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit()],\",\n \"});\",\n].join(\"\\n\");\n\nfunction elementName(text: string): string {\n return text.replace(/\\s/g, \"\");\n}\n\n/**\n * Registers `cms(...)` from `@velastack/cms/vite` in the Vite plugin list, just\n * ahead of `sveltekit()`. Only the plugin array is touched, so the inline\n * `sveltekit({ ... })` shape the templates use is left alone.\n */\nexport function modifyViteConfig(\n viteConfigPath: string,\n pluginArgs = \"\",\n): ModifyOutcome {\n const call = `cms(${pluginArgs})`;\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"@velastack/cms/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"cms\"],\n moduleSpecifier: \"@velastack/cms/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: `[${call}]`,\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (pluginsProp as PropertyAssignment).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as PropertyAssignment).setInitializer(`[${call}]`);\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as ArrayLiteralExpression;\n const elements = arr.getElements();\n const hasCms = elements.some((el) =>\n elementName(el.getText()).startsWith(\"cms(\"),\n );\n\n if (!hasCms) {\n const sveltekitIndex = elements.findIndex((el) =>\n elementName(el.getText()).startsWith(\"sveltekit(\"),\n );\n arr.insertElement(sveltekitIndex === -1 ? 0 : sveltekitIndex, call);\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrowFunction,\n type Block,\n type FunctionDeclaration,\n type FunctionExpression,\n type ObjectLiteralExpression,\n type ParameterDeclaration,\n type ReturnStatement,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\n\n/**\n * What the two layout modifiers have in common: finding a SvelteKit `load`,\n * working out how it receives its event, and locating the object it returns.\n */\n\nexport type LoadFunction =\n ArrowFunction | FunctionExpression | FunctionDeclaration;\n\nexport function newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\nexport function ensureNamedImports(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n names: string[],\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({ namedImports: names, moduleSpecifier });\n return;\n }\n for (const name of names) {\n const has = existing.getNamedImports().some((ni) => ni.getName() === name);\n if (!has) existing.addNamedImport(name);\n }\n}\n\nexport function ensureImportSpec(sourceFile: SourceFile, spec: ImportSpec) {\n if (spec.namedImports?.length) {\n ensureNamedImports(sourceFile, spec.moduleSpecifier, spec.namedImports);\n }\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({\n moduleSpecifier: spec.moduleSpecifier,\n defaultImport: spec.defaultImport,\n namespaceImport: spec.namespaceImport,\n });\n}\n\n/** Peel wrappers (`loadFlash(fn)`, `(fn)`, `fn satisfies X`) down to the function. */\nfunction unwrapFunction(node: Node): ArrowFunction | FunctionExpression | null {\n if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) {\n return node;\n }\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isSatisfiesExpression(node)\n ) {\n return unwrapFunction(node.getExpression());\n }\n if (Node.isCallExpression(node)) {\n for (const arg of node.getArguments()) {\n const fn = unwrapFunction(arg);\n if (fn) return fn;\n }\n }\n return null;\n}\n\n/** The exported `load`, whether declared as a function or wrapped in a const. */\nexport function findLoadFunction(sourceFile: SourceFile): LoadFunction | null {\n const declaration = sourceFile.getFunction(\"load\");\n if (declaration) {\n return declaration.isExported() ? declaration : null;\n }\n\n const variable = sourceFile.getVariableDeclaration(\"load\");\n if (!variable) return null;\n if (!variable.getVariableStatement()?.isExported()) return null;\n\n const initializer = variable.getInitializer();\n return initializer ? unwrapFunction(initializer) : null;\n}\n\nfunction isFunctionNode(node: Node): boolean {\n return (\n Node.isArrowFunction(node) ||\n Node.isFunctionExpression(node) ||\n Node.isFunctionDeclaration(node) ||\n Node.isMethodDeclaration(node)\n );\n}\n\n/**\n * The single, final `return <expression>` of the load body, or null when the\n * body has early returns — those would need any insertion hoisted above them,\n * and guessing where is worse than refusing.\n */\nexport function findFinalReturn(\n fn: LoadFunction,\n body: Block,\n): ReturnStatement | null {\n const statements = body.getStatements();\n const last = statements[statements.length - 1];\n if (!last || !Node.isReturnStatement(last)) return null;\n\n const returns = body\n .getDescendantsOfKind(SyntaxKind.ReturnStatement)\n .filter((r) => r.getFirstAncestor(isFunctionNode) === fn);\n if (returns.length !== 1) return null;\n\n return last;\n}\n\n/** The object literal a return statement yields, unwrapping parentheses. */\nexport function returnedObject(\n statement: ReturnStatement,\n): ObjectLiteralExpression | null {\n let expression = statement.getExpression();\n while (expression && Node.isParenthesizedExpression(expression)) {\n expression = expression.getExpression();\n }\n if (!expression || !Node.isObjectLiteralExpression(expression)) return null;\n return expression;\n}\n\nexport function hasProperty(\n object: ObjectLiteralExpression,\n name: string,\n): boolean {\n return object.getProperties().some((property) => {\n if (\n Node.isPropertyAssignment(property) ||\n Node.isShorthandPropertyAssignment(property)\n ) {\n return property.getName() === name;\n }\n return false;\n });\n}\n\nexport function hasSpreadOf(\n object: ObjectLiteralExpression,\n expressionText: string,\n): boolean {\n return object\n .getProperties()\n .some(\n (property) =>\n Node.isSpreadAssignment(property) &&\n property.getExpression().getText() === expressionText,\n );\n}\n\n/** How a load receives its event: not at all, by name, or destructured. */\nexport type EventParameter =\n | { kind: \"none\" }\n | { kind: \"identifier\"; name: string; param: ParameterDeclaration }\n | {\n kind: \"binding\";\n pattern: import(\"ts-morph\").ObjectBindingPattern;\n param: ParameterDeclaration;\n }\n | { kind: \"unsupported\" };\n\nexport function inspectEventParameter(fn: LoadFunction): EventParameter {\n const params = fn.getParameters();\n if (params.length === 0) return { kind: \"none\" };\n if (params.length > 1) return { kind: \"unsupported\" };\n\n const param = params[0];\n if (param.getInitializer() || param.isRestParameter()) {\n return { kind: \"unsupported\" };\n }\n const nameNode = param.getNameNode();\n if (Node.isIdentifier(nameNode)) {\n return { kind: \"identifier\", name: nameNode.getText(), param };\n }\n if (Node.isObjectBindingPattern(nameNode)) {\n return { kind: \"binding\", pattern: nameNode, param };\n }\n return { kind: \"unsupported\" };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n ensureImportSpec,\n ensureNamedImports,\n findFinalReturn,\n findLoadFunction,\n hasProperty,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport interface LayoutServerLocale {\n /**\n * Expression passed as `locale` to `loadCms`, given the name of the load's\n * event parameter: `() => \"'en'\"` or `(event) => \\`getLocale(${event}.url)\\``.\n */\n expression: (eventName: string) => string;\n /** Imports the expression depends on. */\n imports?: ImportSpec[];\n}\n\n/** A single-locale site: the literal default locale. */\nexport const DEFAULT_LOCALE: LayoutServerLocale = {\n expression: () => \"'en'\",\n};\n\n/** A wuchale site: the locale enable-i18n's reroute already resolved from the URL. */\nexport const WUCHALE_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `getLocale(${eventName}.url)`,\n imports: [\n { namedImports: [\"getLocale\"], moduleSpecifier: \"#locales/main.url.js\" },\n ],\n};\n\nfunction cmsSnippet(eventName: string, locale: string): string {\n return dedent`\n const { cms, notFound, gone, redirectTo } = await loadCms(${eventName}, { locale: ${locale} });\n if (redirectTo) redirect(308, redirectTo);\n if (gone) error(410, 'Gone');\n if (notFound) error(404, 'Not found');\n `;\n}\n\nfunction importLine(spec: ImportSpec): string {\n const parts: string[] = [];\n if (spec.defaultImport) parts.push(spec.defaultImport);\n if (spec.namespaceImport) parts.push(`* as ${spec.namespaceImport}`);\n if (spec.namedImports?.length)\n parts.push(`{ ${spec.namedImports.join(\", \")} }`);\n return `import ${parts.join(\", \")} from '${spec.moduleSpecifier}';`;\n}\n\n/**\n * A root `+layout.server.ts` written from scratch, for a project that has\n * none — the static template keeps its layout load universal.\n */\nexport function createdLayoutServer(locale: LayoutServerLocale): string {\n const imports = [\n \"import { error, redirect } from '@sveltejs/kit';\",\n \"import { loadCms } from '#lib/cms.js';\",\n ...(locale.imports ?? []).map(importLine),\n \"import type { LayoutServerLoad } from './$types';\",\n ].join(\"\\n\");\n const snippet = cmsSnippet(\"event\", locale.expression(\"event\"))\n .split(\"\\n\")\n .join(\"\\n\\t\");\n\n return dedent`\n ${imports}\n\n export const load: LayoutServerLoad = async (event) => {\n \t${snippet}\n\n \treturn { cms };\n };\n `.concat(\"\\n\");\n}\n\nconst FAILURE_HINT = [\n \"Call loadCms from the root +layout.server.ts load and return `cms`:\",\n \"\",\n createdLayoutServer(DEFAULT_LOCALE).trimEnd(),\n \"\",\n \"loadCms needs the whole event, so a destructured parameter has to become\",\n \"`event` with the destructuring moved into the body.\",\n].join(\"\\n\");\n\n/**\n * Wires `loadCms` into the root `+layout.server.ts`, creating the file when\n * the project has none:\n *\n * - `loadCms` needs the whole request event, so a destructured parameter is\n * renamed to `event` and the destructuring becomes the first statement.\n * - The tombstone triple (`redirectTo`, `gone`, `notFound`) is handled just\n * before the return.\n * - `cms` is added to the returned object, ahead of any spread so nothing\n * later can shadow it.\n *\n * Anything else — no exported `load`, an expression-bodied arrow, several\n * returns, a non-literal return — is reported as `failed` with the snippet to\n * paste, and the file is left exactly as it was.\n */\nexport function modifyLayoutServer(\n layoutServerPath: string,\n locale: LayoutServerLocale = DEFAULT_LOCALE,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n fs.mkdirSync(path.dirname(layoutServerPath), { recursive: true });\n fs.writeFileSync(layoutServerPath, createdLayoutServer(locale));\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (original.includes(\"loadCms(\")) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutServerPath);\n\n // --- Inspect everything before touching anything. ---\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"failed\", message: FAILURE_HINT };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n const object = returned && returnedObject(returned);\n if (!returned || !object) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const eventName = event.kind === \"identifier\" ? event.name : \"event\";\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n if (!hasProperty(object, \"cms\")) {\n const spreadIndex = object\n .getProperties()\n .findIndex((property) => Node.isSpreadAssignment(property));\n if (spreadIndex === -1) {\n object.addShorthandPropertyAssignment({ name: \"cms\" });\n } else {\n object.insertShorthandPropertyAssignment(spreadIndex, { name: \"cms\" });\n }\n }\n\n // insertStatements counts comment lines, which getStatements() skips.\n const returnIndex = body.getStatementsWithComments().indexOf(returned);\n body.insertStatements(\n returnIndex,\n `\\n${cmsSnippet(eventName, locale.expression(eventName))}\\n`,\n );\n\n if (event.kind === \"binding\") {\n const destructuring = event.pattern.getText();\n body.insertStatements(0, `const ${destructuring} = ${eventName};`);\n const typeText = event.param.getTypeNode()?.getText();\n event.param.replaceWithText(\n typeText ? `${eventName}: ${typeText}` : eventName,\n );\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: eventName });\n }\n\n if (!fn.isAsync()) fn.setIsAsync(true);\n\n ensureNamedImports(sourceFile, \"@sveltejs/kit\", [\"error\", \"redirect\"]);\n ensureNamedImports(sourceFile, \"#lib/cms.js\", [\"loadCms\"]);\n for (const spec of locale.imports ?? []) {\n ensureImportSpec(sourceFile, spec);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n findFinalReturn,\n findLoadFunction,\n hasSpreadOf,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Forward the server load's data through the root +layout.ts, so \\`cms\\` reaches\n the page:\n\n export const load = async ({ url, data }) => {\n // ...existing code...\n return { ...data, /* existing keys */ };\n };\n`;\n\n/**\n * Make a universal root \\`+layout.ts\\` forward its server load's data.\n *\n * SvelteKit hands a universal load the server load's result as \\`data\\`, and\n * only what the universal load returns reaches the page. A layout that\n * returns its own object without spreading \\`data\\` — the static template\n * does — would drop \\`cms\\` on the floor once \\`+layout.server.ts\\` exists.\n *\n * No file, or a file without a \\`load\\`, needs nothing: server data flows\n * through on its own.\n */\nexport function modifyLayoutUniversal(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutPath);\n\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"success\", changed: false };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n if (!returned) return { status: \"failed\", message: FAILURE_HINT };\n\n const dataExpression =\n event.kind === \"identifier\" ? `${event.name}.data` : \"data\";\n\n // `return data;` already forwards everything.\n const expression = returned.getExpression();\n if (expression && expression.getText() === dataExpression) {\n return { status: \"success\", changed: false };\n }\n\n const object = returnedObject(returned);\n if (!object) return { status: \"failed\", message: FAILURE_HINT };\n if (hasSpreadOf(object, dataExpression)) {\n return { status: \"success\", changed: false };\n }\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n // First, so the layout's own keys still win over anything the server sent.\n object.insertSpreadAssignment(0, { expression: dataExpression });\n\n if (event.kind === \"binding\") {\n const hasData = event.pattern\n .getElements()\n .some((element) => element.getName() === \"data\");\n if (!hasData) {\n const text = event.pattern.getText();\n event.pattern.replaceWithText(text.replace(/^\\{\\s*/, \"{ data, \"));\n }\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: \"{ data }\" });\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { AdminBar } from '@velastack/cms';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<AdminBar />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <AdminBar /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <AdminBar /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/**\n * Mounts `<AdminBar />` at the top level of the root layout, ahead of\n * `{@render children()}` so the bar is in the DOM before the page content.\n * Falls back to appending when the layout has no render tag or slot.\n */\nexport function modifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"AdminBar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { namedImports: [\"AdminBar\"], moduleSpecifier: \"@velastack/cms\" },\n ]);\n });\n return out;\n });\n\n if (!file.insertBeforeChildren(MARKUP_SNIPPET)) {\n file.appendMarkup(MARKUP_SNIPPET);\n }\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { resolveMode, type CmsMode } from \"./generate\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport {\n DEFAULT_LOCALE,\n WUCHALE_LOCALE,\n modifyLayoutServer,\n} from \"./modifies/layout.server\";\nimport { modifyLayoutUniversal } from \"./modifies/layout\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\n/** The locale list from `wuchale.config.js`, or null when it cannot be read. */\nexport function readWuchaleLocales(root: string): string[] | null {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return null;\n const match = fs\n .readFileSync(configPath, \"utf8\")\n .match(/locales:\\s*\\[([^\\]]*)\\]/);\n if (!match) return null;\n const locales = [...match[1].matchAll(/['\"]([^'\"]+)['\"]/g)].map((m) => m[1]);\n return locales.length > 0 ? locales : null;\n}\n\n/**\n * Arguments for the `cms()` Vite plugin.\n *\n * A hosted CMS needs the endpoint and locales at build time so media can be\n * downloaded into the prerendered site. An app hosting the backend itself\n * needs nothing: the media steps are no-ops without an endpoint.\n */\nexport function vitePluginArgs(mode: CmsMode, locales: string[]): string {\n if (mode.local) return \"\";\n const list = locales.map((locale) => `'${locale}'`).join(\", \");\n return `{ endpoint: '${mode.endpoint}', locales: [${list}] }`;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const mode = resolveMode(options);\n const i18n = options.features.i18n;\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n const locales = (i18n && readWuchaleLocales(options.root)) || [\"en\"];\n pushResult(\n modifyOutcomeToFile(\n viteConfigPath,\n modifyViteConfig(viteConfigPath, vitePluginArgs(mode, locales)),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const locale = i18n ? WUCHALE_LOCALE : DEFAULT_LOCALE;\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n modifyLayoutServer(layoutServerPath, locale),\n ),\n );\n\n // A universal root layout has to pass the server load's data along, or\n // `cms` never reaches the page. The static template has one.\n logger.info(\"Modifying src/routes/+layout.ts\");\n const layoutUniversalPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutUniversalPath,\n modifyLayoutUniversal(layoutUniversalPath),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutSveltePath, modifyLayoutSvelte(layoutSveltePath)),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAMA,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAELC,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAASgB,EAAY,GAAsB;CACzC,OAAOC,EAAK,QAAQ,OAAO,EAAE;AAC/B;AAOA,SAAgBC,EACd,GACA,IAAa,IACE;CACf,IAAMC,IAAO,OAAOC,EAAW;CAC/B,IAAI,CAACR,EAAG,WAAWS,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAa,SAASrB;CAAe;CAOxD,IAAMsB,IAAa,IAJCC,EAAQ;EAC1B,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAWC,EAAU,OAAO;CACtD,CACmB,CAAA,CAAQ,oBAAoBH,CAAc,GAEzDI,IAAU,IACVC,IAAS;CAMb,AAJkBJ,EACf,sBAAsB,CAAC,CACvB,MAAM,MAAMK,EAAE,wBAAwB,MAAM,qBAE1C,MACHL,EAAW,wBAAwB,GAAG;EACpC,cAAc,CAAC,KAAK;EACpB,iBAAiB;CACnB,CAAC,GACD,IAAU;CAOZ,IAAMM,IAJmBN,EACtB,qBAAqBO,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAOC,EAAG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AAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate.runtime-BOl3LpPB.js","names":["FAILURE_HINT","NOT_FOUND_HINT","FAILURE_HINT","FAILURE_HINT","dedent","getLogger","withInMemoryScript","formatLikeSource","ensureImports","modifyOutcomeToFile","SvelteFile","probeFirstExisting","VITE_CONFIG_CANDIDATES","fs","path","FAILURE_HINT$3","NOT_FOUND_HINT$1","elementName","text","modifyViteConfig","call","pluginArgs","viteConfigPath","sourceFile","Project","QuoteKind","changed","failed","d","configArg","SyntaxKind","ce","configObj","pluginsProp","pluginsInit","arr","elements","el","sveltekitIndex","newProject","ensureNamedImports","existing","moduleSpecifier","names","name","ni","ensureImportSpec","spec","unwrapFunction","Node","node","arg","fn","findLoadFunction","declaration","variable","initializer","isFunctionNode","findFinalReturn","statements","body","last","r","returnedObject","expression","statement","hasProperty","object","property","hasSpreadOf","expressionText","inspectEventParameter","params","param","nameNode","DEFAULT_LOCALE","WUCHALE_LOCALE","eventName","cmsSnippet","locale","importLine","parts","createdLayoutServer","imports","snippet","FAILURE_HINT$2","modifyLayoutServer","layoutServerPath","event","returned","spreadIndex","returnIndex","destructuring","typeText","FAILURE_HINT$1","modifyLayoutUniversal","layoutPath","dataExpression","element","IMPORT_SNIPPET","MARKUP_SNIPPET","NOT_FOUND_HINT","FAILURE_HINT","modifyLayoutSvelte","file","out","source","sf","readWuchaleLocales","configPath","root","match","locales","m","vitePluginArgs","mode","list","generate","logger","options","modifies","resolveMode","i18n","pushResult","layoutUniversalPath","layoutSveltePath"],"sources":["../../src/patterns/enable/cms/modifies/vite-config.ts","../../src/patterns/enable/cms/modifies/load-function.ts","../../src/patterns/enable/cms/modifies/layout.server.ts","../../src/patterns/enable/cms/modifies/layout.ts","../../src/patterns/enable/cms/modifies/layout.svelte.ts","../../src/patterns/enable/cms/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n type PropertyAssignment,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = [\n \"Add the CMS plugin to your Vite config, ahead of sveltekit():\",\n \"\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit(), /* ...existing plugins */],\",\n \"});\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a Vite config with the CMS plugin ahead of sveltekit():\",\n \"\",\n \"import { defineConfig } from 'vite';\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { cms } from '@velastack/cms/vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [cms(), sveltekit()],\",\n \"});\",\n].join(\"\\n\");\n\nfunction elementName(text: string): string {\n return text.replace(/\\s/g, \"\");\n}\n\n/**\n * Registers `cms(...)` from `@velastack/cms/vite` in the Vite plugin list, just\n * ahead of `sveltekit()`. Only the plugin array is touched, so the inline\n * `sveltekit({ ... })` shape the templates use is left alone.\n */\nexport function modifyViteConfig(\n viteConfigPath: string,\n pluginArgs = \"\",\n): ModifyOutcome {\n const call = `cms(${pluginArgs})`;\n if (!fs.existsSync(viteConfigPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(viteConfigPath);\n\n let changed = false;\n let failed = false;\n\n const hasImport = sourceFile\n .getImportDeclarations()\n .some((d) => d.getModuleSpecifierValue() === \"@velastack/cms/vite\");\n\n if (!hasImport) {\n sourceFile.insertImportDeclaration(0, {\n namedImports: [\"cms\"],\n moduleSpecifier: \"@velastack/cms/vite\",\n });\n changed = true;\n }\n\n const defineConfigCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"defineConfig\");\n\n const configArg = defineConfigCall?.getArguments()?.[0];\n const configObj =\n configArg?.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (configArg as ObjectLiteralExpression)\n : null;\n\n if (!configObj) {\n failed = true;\n } else {\n const pluginsProp = configObj.getProperty(\"plugins\");\n if (!pluginsProp) {\n configObj.addPropertyAssignment({\n name: \"plugins\",\n initializer: `[${call}]`,\n });\n changed = true;\n } else if (pluginsProp.getKind() !== SyntaxKind.PropertyAssignment) {\n failed = true;\n } else {\n const pluginsInit = (pluginsProp as PropertyAssignment).getInitializer();\n\n if (!pluginsInit) {\n (pluginsProp as PropertyAssignment).setInitializer(`[${call}]`);\n changed = true;\n } else if (pluginsInit.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n failed = true;\n } else {\n const arr = pluginsInit as ArrayLiteralExpression;\n const elements = arr.getElements();\n const hasCms = elements.some((el) =>\n elementName(el.getText()).startsWith(\"cms(\"),\n );\n\n if (!hasCms) {\n const sveltekitIndex = elements.findIndex((el) =>\n elementName(el.getText()).startsWith(\"sveltekit(\"),\n );\n arr.insertElement(sveltekitIndex === -1 ? 0 : sveltekitIndex, call);\n changed = true;\n }\n }\n }\n }\n\n if (changed) {\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n }\n\n if (failed) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n return { status: \"success\", changed };\n}\n","import {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type ArrowFunction,\n type Block,\n type FunctionDeclaration,\n type FunctionExpression,\n type ObjectLiteralExpression,\n type ParameterDeclaration,\n type ReturnStatement,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\n\n/**\n * What the two layout modifiers have in common: finding a SvelteKit `load`,\n * working out how it receives its event, and locating the object it returns.\n */\n\nexport type LoadFunction =\n ArrowFunction | FunctionExpression | FunctionDeclaration;\n\nexport function newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\nexport function ensureNamedImports(\n sourceFile: SourceFile,\n moduleSpecifier: string,\n names: string[],\n) {\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === moduleSpecifier);\n if (!existing) {\n sourceFile.addImportDeclaration({ namedImports: names, moduleSpecifier });\n return;\n }\n for (const name of names) {\n const has = existing.getNamedImports().some((ni) => ni.getName() === name);\n if (!has) existing.addNamedImport(name);\n }\n}\n\nexport function ensureImportSpec(sourceFile: SourceFile, spec: ImportSpec) {\n if (spec.namedImports?.length) {\n ensureNamedImports(sourceFile, spec.moduleSpecifier, spec.namedImports);\n }\n const existing = sourceFile\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) return;\n sourceFile.addImportDeclaration({\n moduleSpecifier: spec.moduleSpecifier,\n defaultImport: spec.defaultImport,\n namespaceImport: spec.namespaceImport,\n });\n}\n\n/** Peel wrappers (`loadFlash(fn)`, `(fn)`, `fn satisfies X`) down to the function. */\nfunction unwrapFunction(node: Node): ArrowFunction | FunctionExpression | null {\n if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) {\n return node;\n }\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isSatisfiesExpression(node)\n ) {\n return unwrapFunction(node.getExpression());\n }\n if (Node.isCallExpression(node)) {\n for (const arg of node.getArguments()) {\n const fn = unwrapFunction(arg);\n if (fn) return fn;\n }\n }\n return null;\n}\n\n/** The exported `load`, whether declared as a function or wrapped in a const. */\nexport function findLoadFunction(sourceFile: SourceFile): LoadFunction | null {\n const declaration = sourceFile.getFunction(\"load\");\n if (declaration) {\n return declaration.isExported() ? declaration : null;\n }\n\n const variable = sourceFile.getVariableDeclaration(\"load\");\n if (!variable) return null;\n if (!variable.getVariableStatement()?.isExported()) return null;\n\n const initializer = variable.getInitializer();\n return initializer ? unwrapFunction(initializer) : null;\n}\n\nfunction isFunctionNode(node: Node): boolean {\n return (\n Node.isArrowFunction(node) ||\n Node.isFunctionExpression(node) ||\n Node.isFunctionDeclaration(node) ||\n Node.isMethodDeclaration(node)\n );\n}\n\n/**\n * The single, final `return <expression>` of the load body, or null when the\n * body has early returns — those would need any insertion hoisted above them,\n * and guessing where is worse than refusing.\n */\nexport function findFinalReturn(\n fn: LoadFunction,\n body: Block,\n): ReturnStatement | null {\n const statements = body.getStatements();\n const last = statements[statements.length - 1];\n if (!last || !Node.isReturnStatement(last)) return null;\n\n const returns = body\n .getDescendantsOfKind(SyntaxKind.ReturnStatement)\n .filter((r) => r.getFirstAncestor(isFunctionNode) === fn);\n if (returns.length !== 1) return null;\n\n return last;\n}\n\n/** The object literal a return statement yields, unwrapping parentheses. */\nexport function returnedObject(\n statement: ReturnStatement,\n): ObjectLiteralExpression | null {\n let expression = statement.getExpression();\n while (expression && Node.isParenthesizedExpression(expression)) {\n expression = expression.getExpression();\n }\n if (!expression || !Node.isObjectLiteralExpression(expression)) return null;\n return expression;\n}\n\nexport function hasProperty(\n object: ObjectLiteralExpression,\n name: string,\n): boolean {\n return object.getProperties().some((property) => {\n if (\n Node.isPropertyAssignment(property) ||\n Node.isShorthandPropertyAssignment(property)\n ) {\n return property.getName() === name;\n }\n return false;\n });\n}\n\nexport function hasSpreadOf(\n object: ObjectLiteralExpression,\n expressionText: string,\n): boolean {\n return object\n .getProperties()\n .some(\n (property) =>\n Node.isSpreadAssignment(property) &&\n property.getExpression().getText() === expressionText,\n );\n}\n\n/** How a load receives its event: not at all, by name, or destructured. */\nexport type EventParameter =\n | { kind: \"none\" }\n | { kind: \"identifier\"; name: string; param: ParameterDeclaration }\n | {\n kind: \"binding\";\n pattern: import(\"ts-morph\").ObjectBindingPattern;\n param: ParameterDeclaration;\n }\n | { kind: \"unsupported\" };\n\nexport function inspectEventParameter(fn: LoadFunction): EventParameter {\n const params = fn.getParameters();\n if (params.length === 0) return { kind: \"none\" };\n if (params.length > 1) return { kind: \"unsupported\" };\n\n const param = params[0];\n if (param.getInitializer() || param.isRestParameter()) {\n return { kind: \"unsupported\" };\n }\n const nameNode = param.getNameNode();\n if (Node.isIdentifier(nameNode)) {\n return { kind: \"identifier\", name: nameNode.getText(), param };\n }\n if (Node.isObjectBindingPattern(nameNode)) {\n return { kind: \"binding\", pattern: nameNode, param };\n }\n return { kind: \"unsupported\" };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport type { ImportSpec } from \"../../../../runtime/ts-morph-helpers\";\nimport {\n ensureImportSpec,\n ensureNamedImports,\n findFinalReturn,\n findLoadFunction,\n hasProperty,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport interface LayoutServerLocale {\n /**\n * Expression passed as `locale` to `loadCms`, given the name of the load's\n * event parameter: `() => \"'en'\"` or `(event) => \\`getLocale(${event}.url)\\``.\n */\n expression: (eventName: string) => string;\n /** Imports the expression depends on. */\n imports?: ImportSpec[];\n}\n\n/** A single-locale site: the literal default locale. */\nexport const DEFAULT_LOCALE: LayoutServerLocale = {\n expression: () => \"'en'\",\n};\n\n/** A wuchale site: the locale enable-i18n's reroute already resolved from the URL. */\nexport const WUCHALE_LOCALE: LayoutServerLocale = {\n expression: (eventName) => `getLocale(${eventName}.url)`,\n imports: [\n { namedImports: [\"getLocale\"], moduleSpecifier: \"#locales/main.url.js\" },\n ],\n};\n\nfunction cmsSnippet(eventName: string, locale: string): string {\n return dedent`\n const { cms, notFound, gone, redirectTo } = await loadCms(${eventName}, { locale: ${locale} });\n if (redirectTo) redirect(308, redirectTo);\n if (gone) error(410, 'Gone');\n if (notFound) error(404, 'Not found');\n `;\n}\n\nfunction importLine(spec: ImportSpec): string {\n const parts: string[] = [];\n if (spec.defaultImport) parts.push(spec.defaultImport);\n if (spec.namespaceImport) parts.push(`* as ${spec.namespaceImport}`);\n if (spec.namedImports?.length)\n parts.push(`{ ${spec.namedImports.join(\", \")} }`);\n return `import ${parts.join(\", \")} from '${spec.moduleSpecifier}';`;\n}\n\n/**\n * A root `+layout.server.ts` written from scratch, for a project that has\n * none — the static template keeps its layout load universal.\n */\nexport function createdLayoutServer(locale: LayoutServerLocale): string {\n const imports = [\n \"import { error, redirect } from '@sveltejs/kit';\",\n \"import { loadCms } from '#lib/cms.js';\",\n ...(locale.imports ?? []).map(importLine),\n \"import type { LayoutServerLoad } from './$types';\",\n ].join(\"\\n\");\n const snippet = cmsSnippet(\"event\", locale.expression(\"event\"))\n .split(\"\\n\")\n .join(\"\\n\\t\");\n\n return dedent`\n ${imports}\n\n export const load: LayoutServerLoad = async (event) => {\n \t${snippet}\n\n \treturn { cms };\n };\n `.concat(\"\\n\");\n}\n\nconst FAILURE_HINT = [\n \"Call loadCms from the root +layout.server.ts load and return `cms`:\",\n \"\",\n createdLayoutServer(DEFAULT_LOCALE).trimEnd(),\n \"\",\n \"loadCms needs the whole event, so a destructured parameter has to become\",\n \"`event` with the destructuring moved into the body.\",\n].join(\"\\n\");\n\n/**\n * Wires `loadCms` into the root `+layout.server.ts`, creating the file when\n * the project has none:\n *\n * - `loadCms` needs the whole request event, so a destructured parameter is\n * renamed to `event` and the destructuring becomes the first statement.\n * - The tombstone triple (`redirectTo`, `gone`, `notFound`) is handled just\n * before the return.\n * - `cms` is added to the returned object, ahead of any spread so nothing\n * later can shadow it.\n *\n * Anything else — no exported `load`, an expression-bodied arrow, several\n * returns, a non-literal return — is reported as `failed` with the snippet to\n * paste, and the file is left exactly as it was.\n */\nexport function modifyLayoutServer(\n layoutServerPath: string,\n locale: LayoutServerLocale = DEFAULT_LOCALE,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n fs.mkdirSync(path.dirname(layoutServerPath), { recursive: true });\n fs.writeFileSync(layoutServerPath, createdLayoutServer(locale));\n return { status: \"success\", changed: true };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (original.includes(\"loadCms(\")) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutServerPath);\n\n // --- Inspect everything before touching anything. ---\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"failed\", message: FAILURE_HINT };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n const object = returned && returnedObject(returned);\n if (!returned || !object) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const eventName = event.kind === \"identifier\" ? event.name : \"event\";\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n if (!hasProperty(object, \"cms\")) {\n const spreadIndex = object\n .getProperties()\n .findIndex((property) => Node.isSpreadAssignment(property));\n if (spreadIndex === -1) {\n object.addShorthandPropertyAssignment({ name: \"cms\" });\n } else {\n object.insertShorthandPropertyAssignment(spreadIndex, { name: \"cms\" });\n }\n }\n\n // insertStatements counts comment lines, which getStatements() skips.\n const returnIndex = body.getStatementsWithComments().indexOf(returned);\n body.insertStatements(\n returnIndex,\n `\\n${cmsSnippet(eventName, locale.expression(eventName))}\\n`,\n );\n\n if (event.kind === \"binding\") {\n const destructuring = event.pattern.getText();\n body.insertStatements(0, `const ${destructuring} = ${eventName};`);\n const typeText = event.param.getTypeNode()?.getText();\n event.param.replaceWithText(\n typeText ? `${eventName}: ${typeText}` : eventName,\n );\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: eventName });\n }\n\n if (!fn.isAsync()) fn.setIsAsync(true);\n\n ensureNamedImports(sourceFile, \"@sveltejs/kit\", [\"error\", \"redirect\"]);\n ensureNamedImports(sourceFile, \"#lib/cms.js\", [\"loadCms\"]);\n for (const spec of locale.imports ?? []) {\n ensureImportSpec(sourceFile, spec);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Node } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n findFinalReturn,\n findLoadFunction,\n hasSpreadOf,\n inspectEventParameter,\n newProject,\n returnedObject,\n} from \"./load-function\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Forward the server load's data through the root +layout.ts, so \\`cms\\` reaches\n the page:\n\n export const load = async ({ url, data }) => {\n // ...existing code...\n return { ...data, /* existing keys */ };\n };\n`;\n\n/**\n * Make a universal root \\`+layout.ts\\` forward its server load's data.\n *\n * SvelteKit hands a universal load the server load's result as \\`data\\`, and\n * only what the universal load returns reaches the page. A layout that\n * returns its own object without spreading \\`data\\` — the static template\n * does — would drop \\`cms\\` on the floor once \\`+layout.server.ts\\` exists.\n *\n * No file, or a file without a \\`load\\`, needs nothing: server data flows\n * through on its own.\n */\nexport function modifyLayoutUniversal(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(layoutPath);\n\n const fn = findLoadFunction(sourceFile);\n if (!fn) return { status: \"success\", changed: false };\n\n const body = fn.getBody();\n if (!body || !Node.isBlock(body)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const event = inspectEventParameter(fn);\n if (event.kind === \"unsupported\") {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const returned = findFinalReturn(fn, body);\n if (!returned) return { status: \"failed\", message: FAILURE_HINT };\n\n const dataExpression =\n event.kind === \"identifier\" ? `${event.name}.data` : \"data\";\n\n // `return data;` already forwards everything.\n const expression = returned.getExpression();\n if (expression && expression.getText() === dataExpression) {\n return { status: \"success\", changed: false };\n }\n\n const object = returnedObject(returned);\n if (!object) return { status: \"failed\", message: FAILURE_HINT };\n if (hasSpreadOf(object, dataExpression)) {\n return { status: \"success\", changed: false };\n }\n\n // --- Mutate bottom-up so earlier node references stay valid. ---\n // First, so the layout's own keys still win over anything the server sent.\n object.insertSpreadAssignment(0, { expression: dataExpression });\n\n if (event.kind === \"binding\") {\n const hasData = event.pattern\n .getElements()\n .some((element) => element.getName() === \"data\");\n if (!hasData) {\n const text = event.pattern.getText();\n event.pattern.replaceWithText(text.replace(/^\\{\\s*/, \"{ data, \"));\n }\n } else if (event.kind === \"none\") {\n fn.addParameter({ name: \"{ data }\" });\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst IMPORT_SNIPPET = dedent`\n import { AdminBar } from '@velastack/cms';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<AdminBar />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <AdminBar /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <AdminBar /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/**\n * Mounts `<AdminBar />` at the top level of the root layout, ahead of\n * `{@render children()}` so the bar is in the DOM before the page content.\n * Falls back to appending when the layout has no render tag or slot.\n */\nexport function modifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"AdminBar\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { namedImports: [\"AdminBar\"], moduleSpecifier: \"@velastack/cms\" },\n ]);\n });\n return out;\n });\n\n if (!file.insertBeforeChildren(MARKUP_SNIPPET)) {\n file.appendMarkup(MARKUP_SNIPPET);\n }\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n probeFirstExisting,\n VITE_CONFIG_CANDIDATES,\n} from \"../../../runtime/config-target\";\nimport { resolveMode, type CmsMode } from \"./generate\";\nimport { modifyViteConfig } from \"./modifies/vite-config\";\nimport {\n DEFAULT_LOCALE,\n WUCHALE_LOCALE,\n modifyLayoutServer,\n} from \"./modifies/layout.server\";\nimport { modifyLayoutUniversal } from \"./modifies/layout\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\n/** The locale list from `wuchale.config.js`, or null when it cannot be read. */\nexport function readWuchaleLocales(root: string): string[] | null {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return null;\n const match = fs\n .readFileSync(configPath, \"utf8\")\n .match(/locales:\\s*\\[([^\\]]*)\\]/);\n if (!match) return null;\n const locales = [...match[1].matchAll(/['\"]([^'\"]+)['\"]/g)].map((m) => m[1]);\n return locales.length > 0 ? locales : null;\n}\n\n/**\n * Arguments for the `cms()` Vite plugin.\n *\n * A hosted CMS needs the endpoint and locales at build time so media can be\n * downloaded into the prerendered site. An app hosting the backend itself\n * needs nothing: the media steps are no-ops without an endpoint.\n */\nexport function vitePluginArgs(mode: CmsMode, locales: string[]): string {\n if (mode.local) return \"\";\n const list = locales.map((locale) => `'${locale}'`).join(\", \");\n return `{ endpoint: '${mode.endpoint}', locales: [${list}] }`;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const mode = resolveMode(options);\n const i18n = options.features.i18n;\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config\");\n const viteConfigPath =\n probeFirstExisting(options.root, VITE_CONFIG_CANDIDATES) ??\n path.join(options.root, VITE_CONFIG_CANDIDATES[0]);\n const locales = (i18n && readWuchaleLocales(options.root)) || [\"en\"];\n pushResult(\n modifyOutcomeToFile(\n viteConfigPath,\n modifyViteConfig(viteConfigPath, vitePluginArgs(mode, locales)),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const locale = i18n ? WUCHALE_LOCALE : DEFAULT_LOCALE;\n pushResult(\n modifyOutcomeToFile(\n layoutServerPath,\n modifyLayoutServer(layoutServerPath, locale),\n ),\n );\n\n // A universal root layout has to pass the server load's data along, or\n // `cms` never reaches the page. The static template has one.\n logger.info(\"Modifying src/routes/+layout.ts\");\n const layoutUniversalPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n layoutUniversalPath,\n modifyLayoutUniversal(layoutUniversalPath),\n ),\n );\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutSveltePath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(layoutSveltePath, modifyLayoutSvelte(layoutSveltePath)),\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAMA,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAELC,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAASgB,EAAY,GAAsB;CACzC,OAAOC,EAAK,QAAQ,OAAO,EAAE;AAC/B;AAOA,SAAgBC,EACd,GACA,IAAa,IACE;CACf,IAAMC,IAAO,OAAOC,EAAW;CAC/B,IAAI,CAACR,EAAG,WAAWS,CAAc,GAC/B,OAAO;EAAE,QAAQ;EAAa,SAASrB;CAAe;CAOxD,IAAMsB,IAAa,IAJCC,EAAQ;EAC1B,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAWC,EAAU,OAAO;CACtD,CACmB,CAAA,CAAQ,oBAAoBH,CAAc,GAEzDI,IAAU,IACVC,IAAS;CAMb,AAJkBJ,EACf,sBAAsB,CAAC,CACvB,MAAM,MAAMK,EAAE,wBAAwB,MAAM,qBAE1C,MACHL,EAAW,wBAAwB,GAAG;EACpC,cAAc,CAAC,KAAK;EACpB,iBAAiB;CACnB,CAAC,GACD,IAAU;CAOZ,IAAMM,IAJmBN,EACtB,qBAAqBO,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAOC,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,cAE/B,CAAA,EAAkB,aAAa,CAAC,GAAG,IAC/CC,IACJH,GAAW,QAAQ,MAAMC,EAAW,0BAC/BD,IACD;CAEN,IAAI,CAACG,GACH,IAAS;MACJ;EACL,IAAMC,IAAcD,EAAU,YAAY,SAAS;EACnD,IAAI,CAACC,GAKH,AAJAD,EAAU,sBAAsB;GAC9B,MAAM;GACN,aAAa,IAAIZ,EAAK;EACxB,CAAC,GAC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,CAAO,GAC1BG,IAAOH,EAAQ,SAAS,MAExBI,KAAc,MAAsB;EACxC,AAAInB,KAAMgB,EAAS,KAAKhB,CAAI;CAC9B;CAEA,EAAO,KAAK,uBAAuB;CACnC,IAAMlF,IACJX,EAAmB4G,EAAQ,MAAM3G,CAAsB,KACvDE,EAAK,KAAKyG,EAAQ,MAAM3G,EAAuB,EAAE,GAC7CoG,IAAWU,KAAQd,EAAmBW,EAAQ,IAAI,KAAM,CAAC,IAAI;CAQnE,AAPAI,EACElH,EACEa,GACAH,EAAiBG,GAAgB4F,EAAeC,GAAMH,CAAO,CAAC,CAChE,CACF,GAEAM,EAAO,KAAK,wCAAwC;CACpD,IAAM/B,IAAmBzE,EAAK,KAC5ByG,EAAQ,MACR,OACA,UACA,mBACF;CAWA,AATAI,EACElH,EACE8E,GACAD,EAAmBC,GAJRmC,IAAO9C,IAAiBD,CAIQ,CAC7C,CACF,GAIA2C,EAAO,KAAK,iCAAiC;CAC7C,IAAMM,IAAsB9G,EAAK,KAC/ByG,EAAQ,MACR,OACA,UACA,YACF;CAQA,AAPAI,EACElH,EACEmH,GACA7B,EAAsB6B,CAAmB,CAC3C,CACF,GAEAN,EAAO,KAAK,qCAAqC;CACjD,IAAMO,IAAmB/G,EAAK,KAC5ByG,EAAQ,MACR,OACA,UACA,gBACF;CAKA,OAJAI,EACElH,EAAoBoH,GAAkBtB,EAAmBsB,CAAgB,CAAC,CAC5E,GAEO;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,8 +1,8 @@
1
1
  import { n as e } from "./logger-CQONztPm.js";
2
- import { i as t, n, t as r } from "./pocketbase-B017Cqjq.js";
3
- import { r as i } from "./modify-file-289rStJ2.js";
4
- import { a, i as o, o as s, r as c, t as l } from "./whatsapp-5qJ_xCV1.js";
5
- import { swapAuthPages as u } from "./auth-pages-B52ei-4z.js";
2
+ import { i as t, n, t as r } from "./pocketbase-BtN-wL8f.js";
3
+ import { r as i } from "./modify-file-B4uJzOEj.js";
4
+ import { a, i as o, o as s, r as c, t as l } from "./whatsapp-DbjOxHaZ.js";
5
+ import { swapAuthPages as u } from "./auth-pages-jsyDV1GR.js";
6
6
  import d from "node:fs";
7
7
  import f from "node:path";
8
8
  //#region src/patterns/enable/whatsapp/modifies/modify-test-setup.ts
@@ -65,4 +65,4 @@ async function g(d) {
65
65
  //#endregion
66
66
  export { g as generate };
67
67
 
68
- //# sourceMappingURL=generate.runtime-BxDUtkpT.js.map
68
+ //# sourceMappingURL=generate.runtime-BP31tAcD.js.map