@velastack/patterns 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/chunks/{_layout-Bsx3eNrC.js → _layout-DQhSAhfF.js} +2 -2
- package/dist/chunks/{_layout-Bsx3eNrC.js.map → _layout-DQhSAhfF.js.map} +1 -1
- package/dist/chunks/{collections-DrUG8ngq.js → collections-BYcVyY9O.js} +2 -2
- package/dist/chunks/{collections-DrUG8ngq.js.map → collections-BYcVyY9O.js.map} +1 -1
- package/dist/chunks/constants-Bdx8mp7v.js +6 -0
- package/dist/chunks/constants-Bdx8mp7v.js.map +1 -0
- package/dist/chunks/{env-vars-CdarYsrc.js → env-vars-0hvKe55u.js} +3 -3
- package/dist/chunks/{env-vars-CdarYsrc.js.map → env-vars-0hvKe55u.js.map} +1 -1
- package/dist/chunks/generate-6JS05dWK.js +79 -0
- package/dist/chunks/generate-6JS05dWK.js.map +1 -0
- package/dist/chunks/generate-BZ741GPx.js +177 -0
- package/dist/chunks/generate-BZ741GPx.js.map +1 -0
- package/dist/chunks/{generate-27CjLiGW.js → generate-CNabcEBx.js} +2 -2
- package/dist/chunks/{generate-27CjLiGW.js.map → generate-CNabcEBx.js.map} +1 -1
- package/dist/chunks/{generate-BFcy2wrS.js → generate-Df7t5Nbk.js} +3 -3
- package/dist/chunks/{generate-BFcy2wrS.js.map → generate-Df7t5Nbk.js.map} +1 -1
- package/dist/chunks/{generate-Cqwa8kD9.js → generate-DoHn_xJZ.js} +2 -2
- package/dist/chunks/{generate-Cqwa8kD9.js.map → generate-DoHn_xJZ.js.map} +1 -1
- package/dist/chunks/{generate-D3mSFPdT.js → generate-l2JZTRKb.js} +2 -2
- package/dist/chunks/{generate-D3mSFPdT.js.map → generate-l2JZTRKb.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DIeAeOJg.js → generate.runtime-B53OTMcE.js} +4 -4
- package/dist/chunks/{generate.runtime-DIeAeOJg.js.map → generate.runtime-B53OTMcE.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BJxM7FNA.js → generate.runtime-B84ymwlD.js} +4 -4
- package/dist/chunks/{generate.runtime-BJxM7FNA.js.map → generate.runtime-B84ymwlD.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DMTAocSE.js → generate.runtime-BC6CBKh6.js} +3 -3
- package/dist/chunks/{generate.runtime-DMTAocSE.js.map → generate.runtime-BC6CBKh6.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cxr15Y5H.js → generate.runtime-BDbotRNZ.js} +6 -6
- package/dist/chunks/{generate.runtime-Cxr15Y5H.js.map → generate.runtime-BDbotRNZ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-9KuMcI5r.js → generate.runtime-BOl3LpPB.js} +3 -3
- package/dist/chunks/{generate.runtime-9KuMcI5r.js.map → generate.runtime-BOl3LpPB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-NxuWvkKt.js → generate.runtime-BP31tAcD.js} +4 -4
- package/dist/chunks/{generate.runtime-NxuWvkKt.js.map → generate.runtime-BP31tAcD.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DlLwmjGF.js → generate.runtime-BoYwV0nt.js} +3 -3
- package/dist/chunks/{generate.runtime-DlLwmjGF.js.map → generate.runtime-BoYwV0nt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CIZO2XO9.js → generate.runtime-BqCbJ-No.js} +3 -3
- package/dist/chunks/{generate.runtime-CIZO2XO9.js.map → generate.runtime-BqCbJ-No.js.map} +1 -1
- package/dist/chunks/{generate.runtime-ww3-1FWf.js → generate.runtime-Bvjj3zn0.js} +3 -3
- package/dist/chunks/{generate.runtime-ww3-1FWf.js.map → generate.runtime-Bvjj3zn0.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CK0MTeqc.js → generate.runtime-ByPcr9vJ.js} +3 -3
- package/dist/chunks/{generate.runtime-CK0MTeqc.js.map → generate.runtime-ByPcr9vJ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CMO-Skpk.js → generate.runtime-C4LUUuq7.js} +3 -3
- package/dist/chunks/{generate.runtime-CMO-Skpk.js.map → generate.runtime-C4LUUuq7.js.map} +1 -1
- package/dist/chunks/{generate.runtime-dFTOU_KE.js → generate.runtime-C7tlPKH1.js} +4 -4
- package/dist/chunks/{generate.runtime-dFTOU_KE.js.map → generate.runtime-C7tlPKH1.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BdghkfNp.js → generate.runtime-CHUCMVa2.js} +2 -2
- package/dist/chunks/{generate.runtime-BdghkfNp.js.map → generate.runtime-CHUCMVa2.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DtCaz98N.js → generate.runtime-CVWCUn52.js} +4 -4
- package/dist/chunks/{generate.runtime-DtCaz98N.js.map → generate.runtime-CVWCUn52.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B10-KA87.js → generate.runtime-Cj-5fzbQ.js} +4 -4
- package/dist/chunks/{generate.runtime-B10-KA87.js.map → generate.runtime-Cj-5fzbQ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CbT-EbQT.js → generate.runtime-Cv3unKap.js} +3 -3
- package/dist/chunks/{generate.runtime-CbT-EbQT.js.map → generate.runtime-Cv3unKap.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CVDb-yLt.js → generate.runtime-D677SB4v.js} +2 -2
- package/dist/chunks/{generate.runtime-CVDb-yLt.js.map → generate.runtime-D677SB4v.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B_tWu-Bw.js → generate.runtime-DERcpgc-.js} +4 -4
- package/dist/chunks/{generate.runtime-B_tWu-Bw.js.map → generate.runtime-DERcpgc-.js.map} +1 -1
- package/dist/chunks/{generate.runtime-HSZD935T.js → generate.runtime-DJ5uF6EN.js} +2 -2
- package/dist/chunks/{generate.runtime-HSZD935T.js.map → generate.runtime-DJ5uF6EN.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D6vhkGs8.js → generate.runtime-Dfz53sSK.js} +3 -3
- package/dist/chunks/{generate.runtime-D6vhkGs8.js.map → generate.runtime-Dfz53sSK.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BGuXHl5o.js → generate.runtime-DiqfbDfk.js} +2 -2
- package/dist/chunks/{generate.runtime-BGuXHl5o.js.map → generate.runtime-DiqfbDfk.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B8-GLMkk.js → generate.runtime-Dt3Edp8-.js} +86 -75
- package/dist/chunks/generate.runtime-Dt3Edp8-.js.map +1 -0
- package/dist/chunks/{generate.runtime-CEexT8cJ.js → generate.runtime-Du84quuK.js} +5 -5
- package/dist/chunks/{generate.runtime-CEexT8cJ.js.map → generate.runtime-Du84quuK.js.map} +1 -1
- package/dist/chunks/generate.runtime-KrQk7mqG.js +112 -0
- package/dist/chunks/generate.runtime-KrQk7mqG.js.map +1 -0
- package/dist/chunks/{generate.runtime-tGKorg85.js → generate.runtime-T7JLE4Wc.js} +3 -3
- package/dist/chunks/{generate.runtime-tGKorg85.js.map → generate.runtime-T7JLE4Wc.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CbOMXQSo.js → generate.runtime-WPq7bHRA.js} +2 -2
- package/dist/chunks/{generate.runtime-CbOMXQSo.js.map → generate.runtime-WPq7bHRA.js.map} +1 -1
- package/dist/chunks/{generate.runtime-si5Za61F.js → generate.runtime-e_BkDyP0.js} +2 -2
- package/dist/chunks/{generate.runtime-si5Za61F.js.map → generate.runtime-e_BkDyP0.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Blb6QPZn.js → generate.runtime-gZ4wfYBP.js} +6 -6
- package/dist/chunks/{generate.runtime-Blb6QPZn.js.map → generate.runtime-gZ4wfYBP.js.map} +1 -1
- package/dist/chunks/{generate.runtime-m0m43lkL.js → generate.runtime-oUJUQRdg.js} +6 -6
- package/dist/chunks/{generate.runtime-m0m43lkL.js.map → generate.runtime-oUJUQRdg.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BWRtyQeD.js → generate.runtime-q17D7QUT.js} +3 -3
- package/dist/chunks/{generate.runtime-BWRtyQeD.js.map → generate.runtime-q17D7QUT.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CyTxBcX3.js → generate.runtime-rLlDp4R6.js} +4 -4
- package/dist/chunks/{generate.runtime-CyTxBcX3.js.map → generate.runtime-rLlDp4R6.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Nnk5E8Pi.js → generate.runtime-zr6uIHCd.js} +2 -2
- package/dist/chunks/{generate.runtime-Nnk5E8Pi.js.map → generate.runtime-zr6uIHCd.js.map} +1 -1
- package/dist/chunks/{modify-file-COBp4eCh.js → modify-file-B4uJzOEj.js} +2 -2
- package/dist/chunks/{modify-file-COBp4eCh.js.map → modify-file-B4uJzOEj.js.map} +1 -1
- package/dist/chunks/{package-imports-Dx05A-4S.js → package-imports-B9Asv3ZH.js} +2 -2
- package/dist/chunks/{package-imports-Dx05A-4S.js.map → package-imports-B9Asv3ZH.js.map} +1 -1
- package/dist/chunks/{pocketbase-DL02rq73.js → pocketbase-BtN-wL8f.js} +6 -6
- package/dist/chunks/{pocketbase-DL02rq73.js.map → pocketbase-BtN-wL8f.js.map} +1 -1
- package/dist/chunks/{providers-CAehyySB.js → providers-DRwJnSzb.js} +2 -2
- package/dist/chunks/{providers-CAehyySB.js.map → providers-DRwJnSzb.js.map} +1 -1
- package/dist/chunks/root-layout.svelte-CsJ2QJYi.js +93 -0
- package/dist/chunks/root-layout.svelte-CsJ2QJYi.js.map +1 -0
- package/dist/chunks/{shared-C_Fr8wph.js → shared-BbxLil4g.js} +2 -2
- package/dist/chunks/{shared-C_Fr8wph.js.map → shared-BbxLil4g.js.map} +1 -1
- package/dist/chunks/site-VrqOvuiU.js +149 -0
- package/dist/chunks/site-VrqOvuiU.js.map +1 -0
- package/dist/chunks/{table-core-BPv_RYgD.js → table-core-BHFT-uMX.js} +2 -2
- package/dist/chunks/{table-core-BPv_RYgD.js.map → table-core-BHFT-uMX.js.map} +1 -1
- package/dist/chunks/{test-setup-pYUIfWb2.js → test-setup-BVJwm22s.js} +3 -3
- package/dist/chunks/{test-setup-pYUIfWb2.js.map → test-setup-BVJwm22s.js.map} +1 -1
- package/dist/chunks/{ui-B2yn8c_-.js → ui-gG8i_Mzk.js} +3 -3
- package/dist/chunks/{ui-B2yn8c_-.js.map → ui-gG8i_Mzk.js.map} +1 -1
- package/dist/chunks/{whatsapp-5qJ_xCV1.js → whatsapp-DbjOxHaZ.js} +2 -2
- package/dist/chunks/{whatsapp-5qJ_xCV1.js.map → whatsapp-DbjOxHaZ.js.map} +1 -1
- package/dist/chunks/write-result-DcqMefuP.js +499 -0
- package/dist/chunks/write-result-DcqMefuP.js.map +1 -0
- package/dist/index.d.ts +11 -18
- package/dist/index.js +2144 -2141
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/constants-iej3WkEa.js +0 -6
- package/dist/chunks/constants-iej3WkEa.js.map +0 -1
- package/dist/chunks/generate-BxOzEdc_.js +0 -171
- package/dist/chunks/generate-BxOzEdc_.js.map +0 -1
- package/dist/chunks/generate-DdLwP0E7.js +0 -76
- package/dist/chunks/generate-DdLwP0E7.js.map +0 -1
- package/dist/chunks/generate.runtime-B8-GLMkk.js.map +0 -1
- package/dist/chunks/generate.runtime-D5HxAups.js +0 -109
- package/dist/chunks/generate.runtime-D5HxAups.js.map +0 -1
- package/dist/chunks/site-BoujshKo.js +0 -108
- package/dist/chunks/site-BoujshKo.js.map +0 -1
- package/dist/chunks/write-result-Bn4bnrBI.js +0 -481
- package/dist/chunks/write-result-Bn4bnrBI.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-DMTAocSE.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","FAILURE_HINT","dedent","ensureSiteFile","ensureImports","modifyOutcomeToFile","SvelteFile","modifyConfig","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$2","ensureExtensionsSvx","existing","obj","SyntaxKind","init","arr","el","ensurePreprocessMdsvex","text","modifyViteConfigMdsvex","root","target","_templateObject","PRISM_IMPORT","NOT_FOUND_HINT$1","_taggedTemplateLiteral","FAILURE_HINT$1","modifyRootLayoutSvelte","layoutPath","file","script","appCssMatch","source","insertion","end","BLOG_NAVBAR_ITEM","FAILURE_HINT","NOT_FOUND_HINT","modifyPublicRootLayout","raw","generate","logger","getLogger","options","modifies","pushResult","mdsvex","rootLayoutPath","publicLayoutCandidates","publicLayoutPath","p","siteFile"],"sources":["../../src/patterns/enable/blog/modifies/vite-config.ts","../../src/patterns/enable/blog/modifies/root-layout-svelte.ts","../../src/patterns/enable/blog/modifies/public-root-layout-svelte.ts","../../src/patterns/enable/blog/generate.runtime.ts"],"sourcesContent":["import dedent from \"dedent\";\nimport {\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n} from \"ts-morph\";\nimport {\n modifyConfig,\n type ConfigModifyResult,\n} from \"../../../../runtime/config-target\";\nimport { ensureImports } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Enable mdsvex in your config (the sveltekit() arg in vite.config):\n\n import { mdsvex } from 'mdsvex';\n\n // ...\n extensions: ['.svelte', '.svx'],\n preprocess: [mdsvex()],\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Enable mdsvex by passing config to the sveltekit() plugin in vite.config.ts:\n\n import { sveltekit } from '@sveltejs/kit/vite';\n import { mdsvex } from 'mdsvex';\n import { defineConfig } from 'vite';\n\n export default defineConfig({\n plugins: [\n sveltekit({\n extensions: ['.svelte', '.svx'],\n preprocess: [mdsvex()],\n }),\n ],\n });\n`;\n\nfunction ensureExtensionsSvx(obj: ObjectLiteralExpression): boolean {\n const existing = obj.getProperty(\"extensions\");\n if (!existing) {\n obj.addPropertyAssignment({\n name: \"extensions\",\n initializer: \"['.svelte', '.svx']\",\n });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"['.svelte', '.svx']\",\n );\n return true;\n }\n const arr = init as ArrayLiteralExpression;\n const hasSvx = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \".svx\");\n if (hasSvx) return false;\n arr.addElement(\"'.svx'\");\n return true;\n}\n\nfunction ensurePreprocessMdsvex(obj: ObjectLiteralExpression): boolean {\n const existing = obj.getProperty(\"preprocess\");\n if (!existing) {\n obj.addPropertyAssignment({\n name: \"preprocess\",\n initializer: \"[mdsvex()]\",\n });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init) {\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"[mdsvex()]\",\n );\n return true;\n }\n if (init.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = init as ArrayLiteralExpression;\n const hasMdsvex = arr\n .getElements()\n .some((el) => /\\bmdsvex\\s*\\(/.test(el.getText()));\n if (hasMdsvex) return false;\n arr.addElement(\"mdsvex()\");\n return true;\n }\n const text = init.getText();\n if (/\\bmdsvex\\s*\\(/.test(text)) return false;\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `[${text}, mdsvex()]`,\n );\n return true;\n}\n\n/**\n * Enable mdsvex: ensure `extensions` includes `.svx`, `preprocess` includes\n * `mdsvex()`, and the `mdsvex` import is present, at the top level of the\n * inline sveltekit() arg in vite.config.\n */\nexport function modifyViteConfigMdsvex(root: string): ConfigModifyResult {\n return modifyConfig(\n root,\n { notFound: NOT_FOUND_HINT, failed: FAILURE_HINT },\n (target) => {\n ensureExtensionsSvx(target.configObject);\n ensurePreprocessMdsvex(target.configObject);\n ensureImports(target.sourceFile, [\n { namedImports: [\"mdsvex\"], moduleSpecifier: \"mdsvex\" },\n ]);\n return true;\n },\n );\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst PRISM_IMPORT = `import '../css/prism-vsc-dark-plus.css';`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/routes/+layout.svelte and import the Prism theme for\n code block highlighting in blog posts:\n\n <script lang=\"ts\">\n import '../app.css';\n ${PRISM_IMPORT}\n </script>\n`;\n\nconst FAILURE_HINT = dedent`\n Import the Prism theme in your root +layout.svelte for blog code\n block highlighting:\n\n ${PRISM_IMPORT}\n`;\n\nexport function modifyRootLayoutSvelte(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 const script = file.getScript();\n if (!script) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n if (script.content.includes(\"prism-vsc-dark-plus.css\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const appCssMatch = source.match(\n /^(\\s*)import\\s+['\"][^'\"]*app\\.css['\"];?\\s*$/m,\n );\n if (appCssMatch) {\n const indent = appCssMatch[1] ?? \"\";\n const insertion = `\\n${indent}${PRISM_IMPORT}`;\n const end = (appCssMatch.index ?? 0) + appCssMatch[0].length;\n return source.slice(0, end) + insertion + source.slice(end);\n }\n return source.replace(/^/, `\\n\\t${PRISM_IMPORT}\\n`);\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BLOG_NAVBAR_ITEM = `\n\t\t<Navbar.Item>\n\t\t\t<Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n\t\t\t\tBlog\n\t\t\t</Button>\n\t\t</Navbar.Item>\n\t`;\n\nconst FAILURE_HINT = dedent`\n Add a Blog link inside <Navbar.List> in the public root layout:\n\n <Navbar.Item>\n <Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n Blog\n </Button>\n </Navbar.Item>\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create a public root layout with a Blog link in its Navbar.List:\n\n <Navbar.Item>\n <Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n Blog\n </Button>\n </Navbar.Item>\n`;\n\nexport function modifyPublicRootLayout(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(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const raw = fs.readFileSync(layoutPath, \"utf8\");\n if (/href=[\"']\\/blog[\"']/.test(raw)) {\n return { status: \"success\", changed: false };\n }\n\n file.insertBeforeClosingTag(\"Navbar.List\", BLOG_NAVBAR_ITEM);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifyViteConfigMdsvex } from \"./modifies/vite-config\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout-svelte\";\nimport { modifyPublicRootLayout } from \"./modifies/public-root-layout-svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config for mdsvex\");\n const mdsvex = modifyViteConfigMdsvex(options.root);\n pushResult(modifyOutcomeToFile(mdsvex.filePath, mdsvex.outcome));\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(rootLayoutPath, modifyRootLayoutSvelte(rootLayoutPath)),\n );\n\n logger.info(\"Modifying public root layout\");\n const publicLayoutCandidates = [\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 ];\n const publicLayoutPath =\n publicLayoutCandidates.find((p) => fs.existsSync(p)) ??\n publicLayoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(\n publicLayoutPath,\n modifyPublicRootLayout(publicLayoutPath),\n ),\n );\n\n // The RSS feed is titled and linked from `src/lib/site.ts`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAMA,IAAe,CAAM;;;;;;;;GAUrBC,IAAiB,CAAM;;;;;;;;;;;;;;;;AAiB7B,SAASa,EAAoB,GAAuC;CAClE,IAAMC,IAAWC,EAAI,YAAY,YAAY;CAC7C,IAAI,CAACD,GAKH,OAJAC,EAAI,sBAAsB;EACxB,MAAM;EACN,aAAa;CACf,CAAC,GACM;CAET,IAAID,EAAS,QAAQ,MAAME,EAAW,oBAAoB,OAAO;CACjE,IAAMC,IACJH,EACA,eAAe;CACjB,IAAI,CAACG,KAAQA,EAAK,QAAQ,MAAMD,EAAW,wBAIzC,OAHAF,EAAoD,eAClD,qBACF,GACO;CAET,IAAMI,IAAMD;CAMZ,OAFA,CAHeC,EACZ,YAAY,CAAC,CACb,MAAM,MAAOC,EAAG,QAAQ,CAAC,CAAC,QAAQ,UAAU,EAAE,MAAM,MACnD,MACJD,E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,CAAI;CAC9B;CAEA,EAAO,KAAK,kCAAkC;CAC9C,IAAMiB,IAAS3B,EAAuBwB,EAAQ,IAAI;CAGlD,AAFAE,EAAW1C,EAAoB2C,EAAO,UAAUA,EAAO,OAAO,CAAC,GAE/DL,EAAO,KAAK,qCAAqC;CACjD,IAAMM,IAAiBxC,EAAK,KAC1BoC,EAAQ,MACR,OACA,UACA,gBACF;CAKA,AAJAE,EACE1C,EAAoB4C,GAAgBpB,EAAuBoB,CAAc,CAAC,CAC5E,GAEAN,EAAO,KAAK,8BAA8B;CAC1C,IAAMO,IAAyB;EAC7BzC,EAAK,KAAKoC,EAAQ,MAAM,OAAO,UAAU,YAAY,oBAAoB;EACzEpC,EAAK,KAAKoC,EAAQ,MAAM,OAAO,UAAU,oBAAoB;EAC7DpC,EAAK,KAAKoC,EAAQ,MAAM,OAAO,UAAU,YAAY,gBAAgB;CACvE,GACMM,IACJD,EAAuB,MAAM,MAAM1C,EAAG,WAAW4C,CAAC,CAAC,KACnDF,EAAuB;CACzB,EACE7C,EACE8C,GACAX,EAAuBW,CAAgB,CACzC,CACF;CAGA,IAAME,IAAW,MAAMlD,EAAe0C,CAAO;CAE7C,OAAO;EACL,SAASQ,IAAW,CAACA,CAAQ,IAAI,CAAC;EAClC;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-BC6CBKh6.js","names":["FAILURE_HINT","NOT_FOUND_HINT","NOT_FOUND_HINT","FAILURE_HINT","dedent","ensureSiteFile","ensureImports","modifyOutcomeToFile","SvelteFile","modifyConfig","fs","path","FAILURE_HINT$2","NOT_FOUND_HINT$2","ensureExtensionsSvx","existing","obj","SyntaxKind","init","arr","el","ensurePreprocessMdsvex","text","modifyViteConfigMdsvex","root","target","_templateObject","PRISM_IMPORT","NOT_FOUND_HINT$1","_taggedTemplateLiteral","FAILURE_HINT$1","modifyRootLayoutSvelte","layoutPath","file","script","appCssMatch","source","insertion","end","BLOG_NAVBAR_ITEM","FAILURE_HINT","NOT_FOUND_HINT","modifyPublicRootLayout","raw","generate","logger","getLogger","options","modifies","pushResult","mdsvex","rootLayoutPath","publicLayoutCandidates","publicLayoutPath","p","siteFile"],"sources":["../../src/patterns/enable/blog/modifies/vite-config.ts","../../src/patterns/enable/blog/modifies/root-layout-svelte.ts","../../src/patterns/enable/blog/modifies/public-root-layout-svelte.ts","../../src/patterns/enable/blog/generate.runtime.ts"],"sourcesContent":["import dedent from \"dedent\";\nimport {\n SyntaxKind,\n type ArrayLiteralExpression,\n type ObjectLiteralExpression,\n} from \"ts-morph\";\nimport {\n modifyConfig,\n type ConfigModifyResult,\n} from \"../../../../runtime/config-target\";\nimport { ensureImports } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Enable mdsvex in your config (the sveltekit() arg in vite.config):\n\n import { mdsvex } from 'mdsvex';\n\n // ...\n extensions: ['.svelte', '.svx'],\n preprocess: [mdsvex()],\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Enable mdsvex by passing config to the sveltekit() plugin in vite.config.ts:\n\n import { sveltekit } from '@sveltejs/kit/vite';\n import { mdsvex } from 'mdsvex';\n import { defineConfig } from 'vite';\n\n export default defineConfig({\n plugins: [\n sveltekit({\n extensions: ['.svelte', '.svx'],\n preprocess: [mdsvex()],\n }),\n ],\n });\n`;\n\nfunction ensureExtensionsSvx(obj: ObjectLiteralExpression): boolean {\n const existing = obj.getProperty(\"extensions\");\n if (!existing) {\n obj.addPropertyAssignment({\n name: \"extensions\",\n initializer: \"['.svelte', '.svx']\",\n });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"['.svelte', '.svx']\",\n );\n return true;\n }\n const arr = init as ArrayLiteralExpression;\n const hasSvx = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \".svx\");\n if (hasSvx) return false;\n arr.addElement(\"'.svx'\");\n return true;\n}\n\nfunction ensurePreprocessMdsvex(obj: ObjectLiteralExpression): boolean {\n const existing = obj.getProperty(\"preprocess\");\n if (!existing) {\n obj.addPropertyAssignment({\n name: \"preprocess\",\n initializer: \"[mdsvex()]\",\n });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init) {\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n \"[mdsvex()]\",\n );\n return true;\n }\n if (init.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = init as ArrayLiteralExpression;\n const hasMdsvex = arr\n .getElements()\n .some((el) => /\\bmdsvex\\s*\\(/.test(el.getText()));\n if (hasMdsvex) return false;\n arr.addElement(\"mdsvex()\");\n return true;\n }\n const text = init.getText();\n if (/\\bmdsvex\\s*\\(/.test(text)) return false;\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `[${text}, mdsvex()]`,\n );\n return true;\n}\n\n/**\n * Enable mdsvex: ensure `extensions` includes `.svx`, `preprocess` includes\n * `mdsvex()`, and the `mdsvex` import is present, at the top level of the\n * inline sveltekit() arg in vite.config.\n */\nexport function modifyViteConfigMdsvex(root: string): ConfigModifyResult {\n return modifyConfig(\n root,\n { notFound: NOT_FOUND_HINT, failed: FAILURE_HINT },\n (target) => {\n ensureExtensionsSvx(target.configObject);\n ensurePreprocessMdsvex(target.configObject);\n ensureImports(target.sourceFile, [\n { namedImports: [\"mdsvex\"], moduleSpecifier: \"mdsvex\" },\n ]);\n return true;\n },\n );\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst PRISM_IMPORT = `import '../css/prism-vsc-dark-plus.css';`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/routes/+layout.svelte and import the Prism theme for\n code block highlighting in blog posts:\n\n <script lang=\"ts\">\n import '../app.css';\n ${PRISM_IMPORT}\n </script>\n`;\n\nconst FAILURE_HINT = dedent`\n Import the Prism theme in your root +layout.svelte for blog code\n block highlighting:\n\n ${PRISM_IMPORT}\n`;\n\nexport function modifyRootLayoutSvelte(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 const script = file.getScript();\n if (!script) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n if (script.content.includes(\"prism-vsc-dark-plus.css\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const appCssMatch = source.match(\n /^(\\s*)import\\s+['\"][^'\"]*app\\.css['\"];?\\s*$/m,\n );\n if (appCssMatch) {\n const indent = appCssMatch[1] ?? \"\";\n const insertion = `\\n${indent}${PRISM_IMPORT}`;\n const end = (appCssMatch.index ?? 0) + appCssMatch[0].length;\n return source.slice(0, end) + insertion + source.slice(end);\n }\n return source.replace(/^/, `\\n\\t${PRISM_IMPORT}\\n`);\n });\n\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BLOG_NAVBAR_ITEM = `\n\t\t<Navbar.Item>\n\t\t\t<Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n\t\t\t\tBlog\n\t\t\t</Button>\n\t\t</Navbar.Item>\n\t`;\n\nconst FAILURE_HINT = dedent`\n Add a Blog link inside <Navbar.List> in the public root layout:\n\n <Navbar.Item>\n <Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n Blog\n </Button>\n </Navbar.Item>\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create a public root layout with a Blog link in its Navbar.List:\n\n <Navbar.Item>\n <Button class=\"w-full justify-start md:justify-center md:w-auto\" href=\"/blog\" variant=\"ghost\">\n Blog\n </Button>\n </Navbar.Item>\n`;\n\nexport function modifyPublicRootLayout(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(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const raw = fs.readFileSync(layoutPath, \"utf8\");\n if (/href=[\"']\\/blog[\"']/.test(raw)) {\n return { status: \"success\", changed: false };\n }\n\n file.insertBeforeClosingTag(\"Navbar.List\", BLOG_NAVBAR_ITEM);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifyViteConfigMdsvex } from \"./modifies/vite-config\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout-svelte\";\nimport { modifyPublicRootLayout } from \"./modifies/public-root-layout-svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying vite.config for mdsvex\");\n const mdsvex = modifyViteConfigMdsvex(options.root);\n pushResult(modifyOutcomeToFile(mdsvex.filePath, mdsvex.outcome));\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const rootLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(rootLayoutPath, modifyRootLayoutSvelte(rootLayoutPath)),\n );\n\n logger.info(\"Modifying public root layout\");\n const publicLayoutCandidates = [\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 ];\n const publicLayoutPath =\n publicLayoutCandidates.find((p) => fs.existsSync(p)) ??\n publicLayoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(\n publicLayoutPath,\n modifyPublicRootLayout(publicLayoutPath),\n ),\n );\n\n // The RSS feed is titled and linked from `src/lib/site.ts`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAMA,IAAe,CAAM;;;;;;;;GAUrBC,IAAiB,CAAM;;;;;;;;;;;;;;;;AAiB7B,SAASa,EAAoB,GAAuC;CAClE,IAAMC,IAAWC,EAAI,YAAY,YAAY;CAC7C,IAAI,CAACD,GAKH,OAJAC,EAAI,sBAAsB;EACxB,MAAM;EACN,aAAa;CACf,CAAC,GACM;CAET,IAAID,EAAS,QAAQ,MAAME,EAAW,oBAAoB,OAAO;CACjE,IAAMC,IACJH,EACA,eAAe;CACjB,IAAI,CAACG,KAAQA,EAAK,QAAQ,MAAMD,EAAW,wBAIzC,OAHAF,EAAoD,eAClD,qBACF,GACO;CAET,IAAMI,IAAMD;CAMZ,OAFA,CAHeC,EACZ,YAAY,CAAC,CACb,MAAM,MAAOC,EAAG,QAAQ,CAAC,CAAC,QAAQ,UAAU,EAAE,MAAM,MACnD,MACJD,EAAI,WAAW,QAAQ,GAChB;AACT;AAEA,SAASE,EAAuB,GAAuC;CACrE,IAAMN,IAAWC,EAAI,YAA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I;CAGlD,AAFAE,EAAW1C,EAAoB2C,EAAO,UAAUA,EAAO,OAAO,CAAC,GAE/DL,EAAO,KAAK,qCAAqC;CACjD,IAAMM,IAAiBxC,EAAK,KAC1BoC,EAAQ,MACR,OACA,UACA,gBACF;CAKA,AAJAE,EACE1C,EAAoB4C,GAAgBpB,EAAuBoB,CAAc,CAAC,CAC5E,GAEAN,EAAO,KAAK,8BAA8B;CAC1C,IAAMO,IAAyB;EAC7BzC,EAAK,KAAKoC,EAAQ,MAAM,OAAO,UAAU,YAAY,oBAAoB;EACzEpC,EAAK,KAAKoC,EAAQ,MAAM,OAAO,UAAU,oBAAoB;EAC7DpC,EAAK,KAAKoC,EAAQ,MAAM,OAAO,UAAU,YAAY,gBAAgB;CACvE,GACMM,IACJD,EAAuB,MAAM,MAAM1C,EAAG,WAAW4C,CAAC,CAAC,KACnDF,EAAuB;CACzB,EACE7C,EACE8C,GACAX,EAAuBW,CAAgB,CACzC,CACF;CAGA,IAAME,IAAW,MAAMlD,EAAe0C,CAAO;CAE7C,OAAO;EACL,SAASQ,IAAW,CAACA,CAAQ,IAAI,CAAC;EAClC;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -2,14 +2,14 @@ import { r as e, t } from "./lib-specifier-Cngo1zF_.js";
|
|
|
2
2
|
import { t as n } from "./dedent-Gq6Krl4n.js";
|
|
3
3
|
import { n as r } from "./logger-CQONztPm.js";
|
|
4
4
|
import { t as i } from "./env-vars-mnRA0hOe.js";
|
|
5
|
-
import { n as a } from "./site-
|
|
5
|
+
import { n as a } from "./site-VrqOvuiU.js";
|
|
6
6
|
import { t as o } from "./env-vars-Cr4lbMD_.js";
|
|
7
|
-
import { n as s } from "./shared-
|
|
7
|
+
import { n as s } from "./shared-BbxLil4g.js";
|
|
8
8
|
import { c, m as l, n as u, o as d } from "./ts-morph-helpers-CHI9wAil.js";
|
|
9
|
-
import { a as f, r as p } from "./modify-file-
|
|
10
|
-
import { unmodifyEnvVarsFiles as m } from "./env-vars-
|
|
9
|
+
import { a as f, r as p } from "./modify-file-B4uJzOEj.js";
|
|
10
|
+
import { unmodifyEnvVarsFiles as m } from "./env-vars-0hvKe55u.js";
|
|
11
11
|
import { n as h } from "./compose-handle-BBlamPfx.js";
|
|
12
|
-
import { a as g, l as _, s as v } from "./test-setup-
|
|
12
|
+
import { a as g, l as _, s as v } from "./test-setup-BVJwm22s.js";
|
|
13
13
|
import y from "node:fs";
|
|
14
14
|
import b from "node:path";
|
|
15
15
|
import { Node as x, Project as S, QuoteKind as C } from "ts-morph";
|
|
@@ -152,4 +152,4 @@ async function P(e) {
|
|
|
152
152
|
//#endregion
|
|
153
153
|
export { P as generate };
|
|
154
154
|
|
|
155
|
-
//# sourceMappingURL=generate.runtime-
|
|
155
|
+
//# sourceMappingURL=generate.runtime-BDbotRNZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-Cxr15Y5H.js","names":["libModule","dedent","getLogger","BACKEND_ENV_VARS","ensureSiteFile","WORKFLOWS_ENV_VARS","toDeleteEntry","removeStatementWithComments","ensureBlankLineAfterImports","formatLikeSource","revertOutcomeToFile","modifyOutcomeToFile","removeHandle","unmodifyTestSetup","unmodifySvelteConfig","unmodifyGitignore","fs","path","HANDLE_HINT","INIT_HINT","BACKEND_MODULES","isStartWorkerCall","node","Node","onlyStartsWorker","fn","body","statements","workerInit","sf","decl","target","unmodifyHooksServerBackend","hooksServerPath","original","sourceFile","Project","QuoteKind","init","pruneUnusedImports","FAILURE_HINT","unmodifyLayoutServerMeta","layoutServerPath","updated","withoutParam","isLibSpecifier","m","serverTestFiles","dir","found","entry","full","generate","logger","options","creates","modifies","deletes","revert","svelteConfigFile","hooksServerRevert","hasWorkflows","envVars","unmodifyEnvVarsFiles","spec","gitignorePath","gitignoreFile","layoutServerFile","siteFile","testFile","testSetupPath","testSetupFile"],"sources":["../../src/patterns/disable/backend/modifies/hooks.server.ts","../../src/patterns/disable/backend/modifies/layout-server.ts","../../src/patterns/disable/backend/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport {\n Node,\n Project,\n QuoteKind,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureBlankLineAfterImports,\n pruneUnusedImports,\n removeStatementWithComments,\n formatLikeSource,\n type ModuleMatch,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nconst HANDLE_HINT = dedent`\n Take handlePocketbase(...) out of the exported handle in src/hooks.server.ts,\n and its imports from '@velastack/pocketbase' and '$app/env/private'.\n`;\n\nconst INIT_HINT = dedent`\n The workflows are removed with the backend. Take the startWorker() call out\n of the init hook in src/hooks.server.ts, and its import:\n\n import { startWorker } from '#lib/server/workflows.js';\n`;\n\n/**\n * Modules only the backend's handle and init import from. An import nothing\n * references any more is dropped; a variable other code still reads stays.\n * `$env/dynamic/private` is the `env` object hooks written before SvelteKit 3\n * read the PocketBase variables from.\n */\nconst BACKEND_MODULES: ModuleMatch[] = [\n \"@velastack/pocketbase\",\n \"$app/env/private\",\n \"$env/dynamic/private\",\n libModule(\"server/workflows\"),\n \"@sveltejs/kit\",\n \"@sveltejs/kit/hooks\",\n];\n\n/** `startWorker()`, `await startWorker()` or `return startWorker()`. */\nfunction isStartWorkerCall(node: Node | undefined): boolean {\n if (!node) return false;\n if (Node.isAwaitExpression(node))\n return isStartWorkerCall(node.getExpression());\n if (Node.isExpressionStatement(node) || Node.isReturnStatement(node)) {\n return isStartWorkerCall(node.getExpression());\n }\n return (\n Node.isCallExpression(node) &&\n node.getExpression().getText() === \"startWorker\" &&\n node.getArguments().length === 0\n );\n}\n\n/** A function whose whole body starts the worker. */\nfunction onlyStartsWorker(fn: Node | undefined): boolean {\n if (\n !Node.isArrowFunction(fn) &&\n !Node.isFunctionExpression(fn) &&\n !Node.isFunctionDeclaration(fn)\n ) {\n return false;\n }\n const body = fn.getBody();\n if (!body) return false;\n if (!Node.isBlock(body)) return isStartWorkerCall(body);\n const statements = body.getStatements();\n return statements.length === 1 && isStartWorkerCall(statements[0]);\n}\n\n/**\n * The `init` export when all it does is start the workflow worker, the way\n * the minimal template and enable-workflows write it. `\"custom\"` when an init\n * starts the worker among other things; null when there is nothing to do.\n */\nfunction workerInit(sf: SourceFile): Statement | \"custom\" | null {\n const fn = sf.getFunction(\"init\");\n const decl = sf.getVariableDeclaration(\"init\");\n const target = fn ?? decl?.getVariableStatement();\n if (!target || !target.getText().includes(\"startWorker\")) return null;\n const onlyWorker = fn\n ? onlyStartsWorker(fn)\n : decl?.getVariableStatement()?.getDeclarations().length === 1 &&\n onlyStartsWorker(decl.getInitializer());\n return onlyWorker ? target : \"custom\";\n}\n\n/**\n * Undo what the backend put in `hooks.server.ts`: the PocketBase handle, and\n * the `init` that starts the workflow worker, which is deleted along with the\n * backend. Whatever else the file holds (i18n, content negotiation) stays; a\n * file with nothing else comes out empty, for the caller to delete.\n */\nexport function unmodifyHooksServerBackend(\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 (\n !original.includes(\"handlePocketbase\") &&\n !original.includes(\"startWorker\")\n ) {\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 // Checked before anything changes, so a failure leaves the file as it was.\n if (workerInit(sourceFile) === \"custom\") {\n return { status: \"failed\", message: INIT_HINT };\n }\n\n const removed = removeHandle(sourceFile, \"handlePocketbase\");\n if (removed.status === \"unsupported\") {\n return { status: \"failed\", message: HANDLE_HINT };\n }\n // Looked up again: edits to the file forget the nodes found before them.\n const init = workerInit(sourceFile);\n if (init && init !== \"custom\") removeStatementWithComments(sourceFile, init);\n\n pruneUnusedImports(sourceFile, BACKEND_MODULES);\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 type { ModifyOutcome } from \"../../../../core/types\";\nimport { isLibSpecifier } from \"../../../../runtime/lib-specifier\";\n\nconst FAILURE_HINT = dedent`\n src/routes/+layout.server.ts still reads locals.meta, which only the\n PocketBase hook provides. Read the values from a static module instead:\n\n import { site } from '#lib/site.js';\n\n // locals.meta.appName -> site.name\n // locals.meta.appURL -> site.url\n // meta: locals.meta -> meta: { appName: site.name, appURL: site.url }\n`;\n\n/**\n * Point an older root layout's meta at `#lib/site.js` instead of `locals.meta`.\n * Templates from before `src/lib/site.ts` read the app name and URL off the\n * PocketBase hook; without the backend nothing sets them, and `App.Locals` no\n * longer declares them. Current templates read `#lib/site.js` already, so this\n * leaves them alone.\n */\nexport function unmodifyLayoutServerMeta(\n layoutServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (!original.includes(\"locals.meta\")) {\n return { status: \"success\", changed: false };\n }\n\n let updated = original\n .replace(/\\blocals\\.meta\\.appName\\b/g, \"site.name\")\n .replace(/\\blocals\\.meta\\.appURL\\b/g, \"site.url\")\n .replace(\n /\\bmeta:\\s*locals\\.meta\\b/g,\n \"meta: { appName: site.name, appURL: site.url }\",\n );\n\n if (updated.includes(\"locals.meta\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n // `locals` usually only carried meta; drop it from the destructuring when\n // nothing else reads it.\n const withoutParam = updated\n .replace(/\\(\\{\\s*locals\\s*,\\s*/g, \"({ \")\n .replace(/,\\s*locals\\s*\\}/g, \" }\");\n if (!/\\blocals\\b/.test(withoutParam)) {\n updated = withoutParam;\n }\n\n const importsSite = [...updated.matchAll(/from\\s+['\"]([^'\"]+)['\"]/g)].some(\n (m) => isLibSpecifier(m[1], \"site\"),\n );\n if (!importsSite) {\n updated = \"import { site } from '#lib/site.js';\\n\" + updated;\n }\n\n fs.writeFileSync(layoutServerPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\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 { toDeleteEntry } from \"../../destroy/shared\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { unmodifyHooksServerBackend } from \"./modifies/hooks.server\";\nimport { unmodifyLayoutServerMeta } from \"./modifies/layout-server\";\nimport { unmodifySvelteConfig } from \"../../enable/backend/modifies/svelte-config\";\nimport { unmodifyGitignore } from \"../../enable/backend/modifies/gitignore\";\nimport { unmodifyTestSetup } from \"../../enable/backend/modifies/test-setup\";\nimport { BACKEND_ENV_VARS } from \"../../enable/backend/env-vars\";\nimport { WORKFLOWS_ENV_VARS } from \"../../enable/workflows/env-vars\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\n\n/** Every server test under a directory; they need the PocketBase test context. */\nfunction serverTestFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n const found: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) found.push(...serverTestFiles(full));\n else if (entry.name === \"server.test.ts\") found.push(full);\n }\n return found;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const deletes: File[] = [];\n\n logger.info(\"Reverting adapter config\");\n const revert = unmodifySvelteConfig(options.root);\n const svelteConfigFile = modifyOutcomeToFile(revert.filePath, revert.outcome);\n if (svelteConfigFile) modifies.push(svelteConfigFile);\n\n // Only the backend's handle and worker come out; handles other patterns\n // composed in stay. The file goes when nothing else was in it.\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksServerRevert = revertOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerBackend(hooksServerPath),\n );\n if (hooksServerRevert.modify) modifies.push(hooksServerRevert.modify);\n if (hooksServerRevert.delete) deletes.push(hooksServerRevert.delete);\n\n // The file goes when these were all it declared. The workflow runtime\n // (deleted with the backend) is the only reader of its switches, so they\n // go too, but only from a project that has it: `TEST` is a common name.\n const hasWorkflows = fs.existsSync(\n path.join(options.root, \"src\", \"lib\", \"server\", \"workflows.ts\"),\n );\n logger.info(\n hasWorkflows\n ? \"Removing the PocketBase and workflow variables from src/env.ts\"\n : \"Removing the PocketBase variables from src/env.ts\",\n );\n const envVars = unmodifyEnvVarsFiles(\n options.root,\n (hasWorkflows ? WORKFLOWS_ENV_VARS : BACKEND_ENV_VARS).map(\n (spec) => spec.name,\n ),\n );\n if (envVars.modify) modifies.push(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n logger.info(\"Reverting .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n const gitignoreFile = modifyOutcomeToFile(\n gitignorePath,\n unmodifyGitignore(gitignorePath),\n );\n if (gitignoreFile) modifies.push(gitignoreFile);\n\n logger.info(\"Reverting src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const layoutServerFile = modifyOutcomeToFile(\n layoutServerPath,\n unmodifyLayoutServerMeta(layoutServerPath),\n );\n if (layoutServerFile) modifies.push(layoutServerFile);\n\n // The converted layout reads `src/lib/site.ts`. Every template ships it; a\n // project from before that gets one here, named as PocketBase knew it.\n if (layoutServerFile?.status === \"success\") {\n const siteFile = await ensureSiteFile(options);\n if (siteFile) creates.push(siteFile);\n }\n\n // Server tests run against the PocketBase-backed test context that the\n // backend's test/setup.ts provides; without it they neither type-check nor\n // run.\n for (const testFile of serverTestFiles(path.join(options.root, \"src\"))) {\n logger.info(`Removing ${path.relative(options.root, testFile)}`);\n deletes.push(toDeleteEntry(testFile));\n }\n\n logger.info(\"Reverting test/setup.ts\");\n const testSetupPath = path.join(options.root, \"test\", \"setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetupPath,\n unmodifyTestSetup(testSetupPath),\n );\n if (testSetupFile) modifies.push(testSetupFile);\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":";;;;;;;;;;;;;;;;AAoBA,IAAMkB,IAAc,CAAM;;;GAKpBC,IAAY,CAAM;;;;;GAalBC,IAAiC;CACrC;CACA;CACA;CACApB,EAAU,kBAAkB;CAC5B;CACA;AACF;AAGA,SAASqB,EAAkB,GAAiC;CAO1D,OANKC,IACDC,EAAK,kBAAkBD,CAAI,KAE3BC,EAAK,sBAAsBD,CAAI,KAAKC,EAAK,kBAAkBD,CAAI,IAC1DD,EAAkBC,EAAK,cAAc,CAAC,IAG7CC,EAAK,iBAAiBD,CAAI,KAC1BA,EAAK,cAAc,CAAC,CAAC,QAAQ,MAAM,iBACnCA,EAAK,aAAa,CAAC,CAAC,WAAW,IATf;AAWpB;AAGA,SAASE,EAAiB,GAA+B;CACvD,IACE,CAACD,EAAK,gBAAgBE,CAAE,KACxB,CAACF,EAAK,qBAAqBE,CAAE,KAC7B,CAACF,EAAK,sBAAsBE,CAAE,GAE9B,OAAO;CAET,IAAMC,IAAOD,EAAG,QAAQ;CACxB,IAAI,CAACC,GAAM,OAAO;CAClB,IAAI,CAACH,EAAK,QAAQG,CAAI,GAAG,OAAOL,EAAkBK,CAAI;CACtD,IAAMC,IAAaD,EAAK,cAAc;CACtC,OAAOC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AgB,GAIhDA,GAAkB,WAAW,WAAW;EAC1C,IAAMC,IAAW,MAAMhE,EAAekD,CAAO;EAC7C,AAAIc,KAAUb,EAAQ,KAAKa,CAAQ;CACrC;CAKA,KAAK,IAAMC,KAAYtB,EAAgB9B,EAAK,KAAKqC,EAAQ,MAAM,KAAK,CAAC,GAEnE,AADAD,EAAO,KAAK,YAAYpC,EAAK,SAASqC,EAAQ,MAAMe,CAAQ,GAAG,GAC/DZ,EAAQ,KAAKnD,EAAc+D,CAAQ,CAAC;CAGtC,EAAO,KAAK,yBAAyB;CACrC,IAAMC,IAAgBrD,EAAK,KAAKqC,EAAQ,MAAM,QAAQ,UAAU,GAC1DiB,IAAgB5D,EACpB2D,GACAzD,EAAkByD,CAAa,CACjC;CAGA,OAFIC,KAAef,EAAS,KAAKe,CAAa,GAEvC;EACL;EACA;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
1
|
+
{"version":3,"file":"generate.runtime-BDbotRNZ.js","names":["libModule","dedent","getLogger","BACKEND_ENV_VARS","ensureSiteFile","WORKFLOWS_ENV_VARS","toDeleteEntry","removeStatementWithComments","ensureBlankLineAfterImports","formatLikeSource","revertOutcomeToFile","modifyOutcomeToFile","removeHandle","unmodifyTestSetup","unmodifySvelteConfig","unmodifyGitignore","fs","path","HANDLE_HINT","INIT_HINT","BACKEND_MODULES","isStartWorkerCall","node","Node","onlyStartsWorker","fn","body","statements","workerInit","sf","decl","target","unmodifyHooksServerBackend","hooksServerPath","original","sourceFile","Project","QuoteKind","init","pruneUnusedImports","FAILURE_HINT","unmodifyLayoutServerMeta","layoutServerPath","updated","withoutParam","isLibSpecifier","m","serverTestFiles","dir","found","entry","full","generate","logger","options","creates","modifies","deletes","revert","svelteConfigFile","hooksServerRevert","hasWorkflows","envVars","unmodifyEnvVarsFiles","spec","gitignorePath","gitignoreFile","layoutServerFile","siteFile","testFile","testSetupPath","testSetupFile"],"sources":["../../src/patterns/disable/backend/modifies/hooks.server.ts","../../src/patterns/disable/backend/modifies/layout-server.ts","../../src/patterns/disable/backend/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport {\n Node,\n Project,\n QuoteKind,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeHandle } from \"../../../../runtime/compose-handle\";\nimport {\n ensureBlankLineAfterImports,\n pruneUnusedImports,\n removeStatementWithComments,\n formatLikeSource,\n type ModuleMatch,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\nconst HANDLE_HINT = dedent`\n Take handlePocketbase(...) out of the exported handle in src/hooks.server.ts,\n and its imports from '@velastack/pocketbase' and '$app/env/private'.\n`;\n\nconst INIT_HINT = dedent`\n The workflows are removed with the backend. Take the startWorker() call out\n of the init hook in src/hooks.server.ts, and its import:\n\n import { startWorker } from '#lib/server/workflows.js';\n`;\n\n/**\n * Modules only the backend's handle and init import from. An import nothing\n * references any more is dropped; a variable other code still reads stays.\n * `$env/dynamic/private` is the `env` object hooks written before SvelteKit 3\n * read the PocketBase variables from.\n */\nconst BACKEND_MODULES: ModuleMatch[] = [\n \"@velastack/pocketbase\",\n \"$app/env/private\",\n \"$env/dynamic/private\",\n libModule(\"server/workflows\"),\n \"@sveltejs/kit\",\n \"@sveltejs/kit/hooks\",\n];\n\n/** `startWorker()`, `await startWorker()` or `return startWorker()`. */\nfunction isStartWorkerCall(node: Node | undefined): boolean {\n if (!node) return false;\n if (Node.isAwaitExpression(node))\n return isStartWorkerCall(node.getExpression());\n if (Node.isExpressionStatement(node) || Node.isReturnStatement(node)) {\n return isStartWorkerCall(node.getExpression());\n }\n return (\n Node.isCallExpression(node) &&\n node.getExpression().getText() === \"startWorker\" &&\n node.getArguments().length === 0\n );\n}\n\n/** A function whose whole body starts the worker. */\nfunction onlyStartsWorker(fn: Node | undefined): boolean {\n if (\n !Node.isArrowFunction(fn) &&\n !Node.isFunctionExpression(fn) &&\n !Node.isFunctionDeclaration(fn)\n ) {\n return false;\n }\n const body = fn.getBody();\n if (!body) return false;\n if (!Node.isBlock(body)) return isStartWorkerCall(body);\n const statements = body.getStatements();\n return statements.length === 1 && isStartWorkerCall(statements[0]);\n}\n\n/**\n * The `init` export when all it does is start the workflow worker, the way\n * the minimal template and enable-workflows write it. `\"custom\"` when an init\n * starts the worker among other things; null when there is nothing to do.\n */\nfunction workerInit(sf: SourceFile): Statement | \"custom\" | null {\n const fn = sf.getFunction(\"init\");\n const decl = sf.getVariableDeclaration(\"init\");\n const target = fn ?? decl?.getVariableStatement();\n if (!target || !target.getText().includes(\"startWorker\")) return null;\n const onlyWorker = fn\n ? onlyStartsWorker(fn)\n : decl?.getVariableStatement()?.getDeclarations().length === 1 &&\n onlyStartsWorker(decl.getInitializer());\n return onlyWorker ? target : \"custom\";\n}\n\n/**\n * Undo what the backend put in `hooks.server.ts`: the PocketBase handle, and\n * the `init` that starts the workflow worker, which is deleted along with the\n * backend. Whatever else the file holds (i18n, content negotiation) stays; a\n * file with nothing else comes out empty, for the caller to delete.\n */\nexport function unmodifyHooksServerBackend(\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 (\n !original.includes(\"handlePocketbase\") &&\n !original.includes(\"startWorker\")\n ) {\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 // Checked before anything changes, so a failure leaves the file as it was.\n if (workerInit(sourceFile) === \"custom\") {\n return { status: \"failed\", message: INIT_HINT };\n }\n\n const removed = removeHandle(sourceFile, \"handlePocketbase\");\n if (removed.status === \"unsupported\") {\n return { status: \"failed\", message: HANDLE_HINT };\n }\n // Looked up again: edits to the file forget the nodes found before them.\n const init = workerInit(sourceFile);\n if (init && init !== \"custom\") removeStatementWithComments(sourceFile, init);\n\n pruneUnusedImports(sourceFile, BACKEND_MODULES);\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 type { ModifyOutcome } from \"../../../../core/types\";\nimport { isLibSpecifier } from \"../../../../runtime/lib-specifier\";\n\nconst FAILURE_HINT = dedent`\n src/routes/+layout.server.ts still reads locals.meta, which only the\n PocketBase hook provides. Read the values from a static module instead:\n\n import { site } from '#lib/site.js';\n\n // locals.meta.appName -> site.name\n // locals.meta.appURL -> site.url\n // meta: locals.meta -> meta: { appName: site.name, appURL: site.url }\n`;\n\n/**\n * Point an older root layout's meta at `#lib/site.js` instead of `locals.meta`.\n * Templates from before `src/lib/site.ts` read the app name and URL off the\n * PocketBase hook; without the backend nothing sets them, and `App.Locals` no\n * longer declares them. Current templates read `#lib/site.js` already, so this\n * leaves them alone.\n */\nexport function unmodifyLayoutServerMeta(\n layoutServerPath: string,\n): ModifyOutcome {\n if (!fs.existsSync(layoutServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutServerPath, \"utf8\");\n if (!original.includes(\"locals.meta\")) {\n return { status: \"success\", changed: false };\n }\n\n let updated = original\n .replace(/\\blocals\\.meta\\.appName\\b/g, \"site.name\")\n .replace(/\\blocals\\.meta\\.appURL\\b/g, \"site.url\")\n .replace(\n /\\bmeta:\\s*locals\\.meta\\b/g,\n \"meta: { appName: site.name, appURL: site.url }\",\n );\n\n if (updated.includes(\"locals.meta\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n // `locals` usually only carried meta; drop it from the destructuring when\n // nothing else reads it.\n const withoutParam = updated\n .replace(/\\(\\{\\s*locals\\s*,\\s*/g, \"({ \")\n .replace(/,\\s*locals\\s*\\}/g, \" }\");\n if (!/\\blocals\\b/.test(withoutParam)) {\n updated = withoutParam;\n }\n\n const importsSite = [...updated.matchAll(/from\\s+['\"]([^'\"]+)['\"]/g)].some(\n (m) => isLibSpecifier(m[1], \"site\"),\n );\n if (!importsSite) {\n updated = \"import { site } from '#lib/site.js';\\n\" + updated;\n }\n\n fs.writeFileSync(layoutServerPath, updated, \"utf8\");\n return { status: \"success\", changed: true };\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 { toDeleteEntry } from \"../../destroy/shared\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { unmodifyHooksServerBackend } from \"./modifies/hooks.server\";\nimport { unmodifyLayoutServerMeta } from \"./modifies/layout-server\";\nimport { unmodifySvelteConfig } from \"../../enable/backend/modifies/svelte-config\";\nimport { unmodifyGitignore } from \"../../enable/backend/modifies/gitignore\";\nimport { unmodifyTestSetup } from \"../../enable/backend/modifies/test-setup\";\nimport { BACKEND_ENV_VARS } from \"../../enable/backend/env-vars\";\nimport { WORKFLOWS_ENV_VARS } from \"../../enable/workflows/env-vars\";\nimport { unmodifyEnvVarsFiles } from \"../../../runtime/env-vars\";\n\n/** Every server test under a directory; they need the PocketBase test context. */\nfunction serverTestFiles(dir: string): string[] {\n if (!fs.existsSync(dir)) return [];\n const found: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) found.push(...serverTestFiles(full));\n else if (entry.name === \"server.test.ts\") found.push(full);\n }\n return found;\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const deletes: File[] = [];\n\n logger.info(\"Reverting adapter config\");\n const revert = unmodifySvelteConfig(options.root);\n const svelteConfigFile = modifyOutcomeToFile(revert.filePath, revert.outcome);\n if (svelteConfigFile) modifies.push(svelteConfigFile);\n\n // Only the backend's handle and worker come out; handles other patterns\n // composed in stay. The file goes when nothing else was in it.\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const hooksServerRevert = revertOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServerBackend(hooksServerPath),\n );\n if (hooksServerRevert.modify) modifies.push(hooksServerRevert.modify);\n if (hooksServerRevert.delete) deletes.push(hooksServerRevert.delete);\n\n // The file goes when these were all it declared. The workflow runtime\n // (deleted with the backend) is the only reader of its switches, so they\n // go too, but only from a project that has it: `TEST` is a common name.\n const hasWorkflows = fs.existsSync(\n path.join(options.root, \"src\", \"lib\", \"server\", \"workflows.ts\"),\n );\n logger.info(\n hasWorkflows\n ? \"Removing the PocketBase and workflow variables from src/env.ts\"\n : \"Removing the PocketBase variables from src/env.ts\",\n );\n const envVars = unmodifyEnvVarsFiles(\n options.root,\n (hasWorkflows ? WORKFLOWS_ENV_VARS : BACKEND_ENV_VARS).map(\n (spec) => spec.name,\n ),\n );\n if (envVars.modify) modifies.push(envVars.modify);\n if (envVars.delete) deletes.push(envVars.delete);\n\n logger.info(\"Reverting .gitignore\");\n const gitignorePath = path.join(options.root, \".gitignore\");\n const gitignoreFile = modifyOutcomeToFile(\n gitignorePath,\n unmodifyGitignore(gitignorePath),\n );\n if (gitignoreFile) modifies.push(gitignoreFile);\n\n logger.info(\"Reverting src/routes/+layout.server.ts\");\n const layoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n const layoutServerFile = modifyOutcomeToFile(\n layoutServerPath,\n unmodifyLayoutServerMeta(layoutServerPath),\n );\n if (layoutServerFile) modifies.push(layoutServerFile);\n\n // The converted layout reads `src/lib/site.ts`. Every template ships it; a\n // project from before that gets one here, named as PocketBase knew it.\n if (layoutServerFile?.status === \"success\") {\n const siteFile = await ensureSiteFile(options);\n if (siteFile) creates.push(siteFile);\n }\n\n // Server tests run against the PocketBase-backed test context that the\n // backend's test/setup.ts provides; without it they neither type-check nor\n // run.\n for (const testFile of serverTestFiles(path.join(options.root, \"src\"))) {\n logger.info(`Removing ${path.relative(options.root, testFile)}`);\n deletes.push(toDeleteEntry(testFile));\n }\n\n logger.info(\"Reverting test/setup.ts\");\n const testSetupPath = path.join(options.root, \"test\", \"setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetupPath,\n unmodifyTestSetup(testSetupPath),\n );\n if (testSetupFile) modifies.push(testSetupFile);\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":";;;;;;;;;;;;;;;;AAoBA,IAAMkB,IAAc,CAAM;;;GAKpBC,IAAY,CAAM;;;;;GAalBC,IAAiC;CACrC;CACA;CACA;CACApB,EAAU,kBAAkB;CAC5B;CACA;AACF;AAGA,SAASqB,EAAkB,GAAiC;CAO1D,OANKC,IACDC,EAAK,kBAAkBD,CAAI,KAE3BC,EAAK,sBAAsBD,CAAI,KAAKC,EAAK,kBAAkBD,CAAI,IAC1DD,EAAkBC,EAAK,cAAc,CAAC,IAG7CC,EAAK,iBAAiBD,CAAI,KAC1BA,EAAK,cAAc,CAAC,CAAC,QAAQ,MAAM,iBACnCA,EAAK,aAAa,CAAC,CAAC,WAAW,IATf;AAWpB;AAGA,SAASE,EAAiB,GAA+B;CACvD,IACE,CAACD,EAAK,gBAAgBE,CAAE,KACxB,CAACF,EAAK,qBAAqBE,CAAE,KAC7B,CAACF,EAAK,sBAAsBE,CAAE,GAE9B,OAAO;CAET,IAAMC,IAAOD,EAAG,QAAQ;CACxB,IAAI,CAACC,GAAM,OAAO;CAClB,IAAI,CAACH,EAAK,QAAQG,CAAI,GAAG,OAAOL,EAAkBK,CAAI;CACtD,IAAMC,IAAaD,EAAK,cAAc;CACtC,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KW,CAAgB,GAIhDA,GAAkB,WAAW,WAAW;EAC1C,IAAMC,IAAW,MAAMhE,EAAekD,CAAO;EAC7C,AAAIc,KAAUb,EAAQ,KAAKa,CAAQ;CACrC;CAKA,KAAK,IAAMC,KAAYtB,EAAgB9B,EAAK,KAAKqC,EAAQ,MAAM,KAAK,CAAC,GAEnE,AADAD,EAAO,KAAK,YAAYpC,EAAK,SAASqC,EAAQ,MAAMe,CAAQ,GAAG,GAC/DZ,EAAQ,KAAKnD,EAAc+D,CAAQ,CAAC;CAGtC,EAAO,KAAK,yBAAyB;CACrC,IAAMC,IAAgBrD,EAAK,KAAKqC,EAAQ,MAAM,QAAQ,UAAU,GAC1DiB,IAAgB5D,EACpB2D,GACAzD,EAAkByD,CAAa,CACjC;CAGA,OAFIC,KAAef,EAAS,KAAKe,CAAa,GAEvC;EACL;EACA;EACA;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
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-
|
|
3
|
+
import { n } from "./generate-DoHn_xJZ.js";
|
|
4
4
|
import { _ as r, o as i, r as a } from "./ts-morph-helpers-CHI9wAil.js";
|
|
5
|
-
import { r as o } from "./modify-file-
|
|
5
|
+
import { r as o } from "./modify-file-B4uJzOEj.js";
|
|
6
6
|
import { t as s } from "./svelte-file-Dv5-bl79.js";
|
|
7
7
|
import { a as c, t as l } from "./config-target-BgyFkbFL.js";
|
|
8
8
|
import u from "node:fs";
|
|
@@ -394,4 +394,4 @@ async function q(e) {
|
|
|
394
394
|
//#endregion
|
|
395
395
|
export { q as generate };
|
|
396
396
|
|
|
397
|
-
//# sourceMappingURL=generate.runtime-
|
|
397
|
+
//# sourceMappingURL=generate.runtime-BOl3LpPB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-9KuMcI5r.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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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
|
+
{"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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AEAM,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,7 +1,7 @@
|
|
|
1
1
|
import { n as e } from "./logger-CQONztPm.js";
|
|
2
|
-
import { i as t, n, t as r } from "./pocketbase-
|
|
3
|
-
import { r as i } from "./modify-file-
|
|
4
|
-
import { a, i as o, o as s, r as c, t as l } from "./whatsapp-
|
|
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
5
|
import { swapAuthPages as u } from "./auth-pages-jsyDV1GR.js";
|
|
6
6
|
import d from "node:fs";
|
|
7
7
|
import f from "node:path";
|
|
@@ -65,4 +65,4 @@ async function g(d) {
|
|
|
65
65
|
//#endregion
|
|
66
66
|
export { g as generate };
|
|
67
67
|
|
|
68
|
-
//# sourceMappingURL=generate.runtime-
|
|
68
|
+
//# sourceMappingURL=generate.runtime-BP31tAcD.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-
|
|
1
|
+
{"version":3,"file":"generate.runtime-BP31tAcD.js","names":["getLogger","withPocketbase","getMigrationFile","modifyOutcomeToFile","hasWhatsAppPlugin","writeWhatsAppConfigMigration","enableWhatsAppAuth","MIN_POCKETBASE_SERVER","fs","path","modifyTestSetup","setupPath","original","content","indent","head","tail","bodyIndent","value","fieldIndent","DOCS_URL","migrationCreate","file","generate","logger","options","creates","pb","setupWhatsAppFields","migrationDelay","configMigration","modifies","outcomes","swapAuthPages","filePath","outcome","testSetup","testSetupFile"],"sources":["../../src/patterns/enable/whatsapp/modifies/modify-test-setup.ts","../../src/patterns/enable/whatsapp/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n/**\n * `email` turns optional on `users`, which the generated types follow, so a\n * test setup from before enable-backend handled that no longer type-checks:\n * its `authenticateUser` takes `{ email: string }` and it signs the test\n * user in with `context.user.email`. Brings those two spots up to the\n * current setup; anything else in the file is the project's own.\n */\nexport function modifyTestSetup(setupPath: string): ModifyOutcome {\n if (!fs.existsSync(setupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(setupPath, \"utf8\");\n let content = original;\n\n content = content.replace(\n /^([ \\t]*)(async function authenticateUser\\(agent: Agent, user: \\{ )email: string( \\}\\) \\{\\n)([ \\t]*)/m,\n (_, indent, head, tail, bodyIndent) =>\n `${indent}${head}email?: string${tail}` +\n `${bodyIndent}// Logs in with the password, so it needs the email (made optional by\\n` +\n `${bodyIndent}// enable-whatsapp, for accounts that sign in with a phone number).\\n` +\n `${bodyIndent}if (!user.email) {\\n` +\n `${bodyIndent}${bodyIndent.includes(\"\\t\") ? \"\\t\" : \" \"}throw new Error('authenticateUser needs a user with an email');\\n` +\n `${bodyIndent}}\\n` +\n bodyIndent,\n );\n\n // The user is made with a known email: sign in with that.\n content = content.replace(\n /^([ \\t]*)context\\.user = await context\\.admin\\.collection\\('users'\\)\\.create\\(\\{\\n([ \\t]*)email: (`test-\\$\\{Math\\.random\\(\\)\\.toString\\(36\\)\\.slice\\(2\\)\\}@example\\.com`),/m,\n (_, indent, fieldIndent, value) =>\n `${indent}const email = ${value};\\n` +\n `${indent}context.user = await context.admin.collection('users').create({\\n` +\n `${fieldIndent}email,`,\n );\n if (content.includes(\"const email = `test-\")) {\n content = content.replace(\n \".authWithPassword(context.user.email, testUserPassword)\",\n \".authWithPassword(email, testUserPassword)\",\n );\n }\n\n if (content === original) {\n return { status: \"success\", changed: false };\n }\n fs.writeFileSync(setupPath, content, \"utf8\");\n return { status: \"success\", changed: true };\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 getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport {\n MIN_POCKETBASE_SERVER,\n enableWhatsAppAuth,\n hasWhatsAppPlugin,\n setupWhatsAppFields,\n writeWhatsAppConfigMigration,\n} from \"./runtime/whatsapp\";\nimport { swapAuthPages } from \"./modifies/auth-pages\";\nimport { modifyTestSetup } from \"./modifies/modify-test-setup\";\n\nexport const DOCS_URL = \"https://velastack.dev/docs/enable/whatsapp\";\n\nfunction migrationCreate(file: string): File {\n return {\n path: file,\n language: \"js\",\n content: fs.readFileSync(file, \"utf8\"),\n status: \"success\",\n };\n}\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const creates: File[] = [];\n\n await withPocketbase(options.root, async (pb) => {\n if (!(await hasWhatsAppPlugin(pb))) {\n throw new Error(\n `This PocketBase has no WhatsApp sign-in. It comes with pocketbase-server ${MIN_POCKETBASE_SERVER} and later: run \\`npm install -D pocketbase-server@^${MIN_POCKETBASE_SERVER}\\`, then \\`vela enable whatsapp\\` again.`,\n );\n }\n\n logger.info(\"Adding the phone fields to users and making email optional\");\n if (await setupWhatsAppFields(pb)) {\n await migrationDelay();\n const file = getMigrationFile(\"users\", \"updated\", options);\n if (file) creates.push(migrationCreate(file));\n }\n\n logger.info(\"Turning on WhatsApp sign-in for users\");\n await enableWhatsAppAuth(pb);\n await migrationDelay();\n const configMigration = writeWhatsAppConfigMigration(options, true);\n if (configMigration) creates.push(migrationCreate(configMigration));\n });\n\n logger.info(\"Adding WhatsApp to the login and signup pages\");\n const modifies: File[] = [];\n const outcomes = await swapAuthPages(\n options.root,\n \"enable\",\n (filePath) =>\n `${path.relative(options.root, filePath)} is not the page enable-auth wrote, so it was left as it is. Add the WhatsApp option to it by hand: ${DOCS_URL}`,\n );\n for (const [filePath, outcome] of outcomes) {\n const file = modifyOutcomeToFile(filePath, outcome);\n if (file) modifies.push(file);\n }\n\n logger.info(\"Updating test/setup.ts for an optional email\");\n const testSetup = path.join(options.root, \"test\", \"setup.ts\");\n const testSetupFile = modifyOutcomeToFile(\n testSetup,\n modifyTestSetup(testSetup),\n );\n if (testSetupFile) modifies.push(testSetupFile);\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;AAUA,SAAgBU,EAAgB,GAAkC;CAChE,IAAI,CAACF,EAAG,WAAWG,CAAS,GAC1B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAMC,IAAWJ,EAAG,aAAaG,GAAW,MAAM,GAC9CE,IAAUD;CAiCd,OA/BA,IAAUC,EAAQ,QAChB,0GACC,GAAG,GAAQ,GAAM,GAAM,MACtB,GAAGC,IAASC,EAAK,gBAAgBC,IAC9BC,EAAW,yEACXA,EAAW,uEACXA,EAAW,sBACXA,IAAaA,EAAW,SAAS,GAAI,IAAI,MAAO,KAAK,mEACrDA,EAAW,OACdA,CACJ,GAGA,IAAUJ,EAAQ,QAChB,gLACC,GAAG,G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ACnJ;CACA,KAAK,IAAM,CAACc,GAAUC,MAAYH,GAAU;EAC1C,IAAMV,IAAOnB,EAAoB+B,GAAUC,CAAO;EAClD,AAAIb,KAAMS,EAAS,KAAKT,CAAI;CAC9B;CAEA,EAAO,KAAK,8CAA8C;CAC1D,IAAMc,IAAY3B,EAAK,KAAKgB,EAAQ,MAAM,QAAQ,UAAU,GACtDY,IAAgBlC,EACpBiC,GACA1B,EAAgB0B,CAAS,CAC3B;CAGA,OAFIC,KAAeN,EAAS,KAAKM,CAAa,GAEvC;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -2,11 +2,11 @@ import { t as e } from "./dedent-Gq6Krl4n.js";
|
|
|
2
2
|
import { t } from "./ui-DD4NltyN.js";
|
|
3
3
|
import { n } from "./logger-CQONztPm.js";
|
|
4
4
|
import { _ as r, i, o as a, r as o } from "./ts-morph-helpers-CHI9wAil.js";
|
|
5
|
-
import { r as s } from "./modify-file-
|
|
5
|
+
import { r as s } from "./modify-file-B4uJzOEj.js";
|
|
6
6
|
import { t as c } from "./svelte-file-Dv5-bl79.js";
|
|
7
7
|
import { t as l } from "./compose-handle-BBlamPfx.js";
|
|
8
8
|
import { a as u, t as d } from "./config-target-BgyFkbFL.js";
|
|
9
|
-
import { i as f, n as p } from "./_layout-
|
|
9
|
+
import { i as f, n as p } from "./_layout-DQhSAhfF.js";
|
|
10
10
|
import { r as m, t as h } from "./wuchale-config-c3Q4JVSF.js";
|
|
11
11
|
import g from "node:fs";
|
|
12
12
|
import _ from "node:path";
|
|
@@ -480,4 +480,4 @@ async function ae(e) {
|
|
|
480
480
|
//#endregion
|
|
481
481
|
export { ae as generate, ie as withLibraryTexts };
|
|
482
482
|
|
|
483
|
-
//# sourceMappingURL=generate.runtime-
|
|
483
|
+
//# sourceMappingURL=generate.runtime-BoYwV0nt.js.map
|