@velastack/patterns 0.5.0 → 0.7.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 +11 -0
- package/dist/chunks/{_layout-D-FzWqn0.js → _layout-Bsx3eNrC.js} +3 -3
- package/dist/chunks/{_layout-D-FzWqn0.js.map → _layout-Bsx3eNrC.js.map} +1 -1
- package/dist/chunks/{auth-pages-B52ei-4z.js → auth-pages-jsyDV1GR.js} +7 -10
- package/dist/chunks/{auth-pages-B52ei-4z.js.map → auth-pages-jsyDV1GR.js.map} +1 -1
- package/dist/chunks/collections-BrEA7a62.js +309 -0
- package/dist/chunks/collections-BrEA7a62.js.map +1 -0
- package/dist/chunks/{collections-Cpjo2OiQ.js → collections-DrUG8ngq.js} +39 -35
- package/dist/chunks/collections-DrUG8ngq.js.map +1 -0
- package/dist/chunks/{compose-handle-BDlZ7Pif.js → compose-handle-BBlamPfx.js} +18 -22
- package/dist/chunks/{compose-handle-BDlZ7Pif.js.map → compose-handle-BBlamPfx.js.map} +1 -1
- package/dist/chunks/{config-target-rHgjaA8u.js → config-target-BgyFkbFL.js} +2 -2
- package/dist/chunks/{config-target-rHgjaA8u.js.map → config-target-BgyFkbFL.js.map} +1 -1
- package/dist/chunks/{constants-Rq8SCXwH.js → constants-iej3WkEa.js} +3 -3
- package/dist/chunks/constants-iej3WkEa.js.map +1 -0
- package/dist/chunks/dedent-Gq6Krl4n.js.map +1 -1
- package/dist/chunks/{env-BPfk1VAw.js → env-BugddEjd.js} +5 -9
- package/dist/chunks/{env-BPfk1VAw.js.map → env-BugddEjd.js.map} +1 -1
- package/dist/chunks/{env-vars-Bj41Nccm.js → env-vars-CdarYsrc.js} +6 -11
- package/dist/chunks/{env-vars-Bj41Nccm.js.map → env-vars-CdarYsrc.js.map} +1 -1
- package/dist/chunks/{generate-dNlBII84.js → generate-27CjLiGW.js} +2 -2
- package/dist/chunks/{generate-dNlBII84.js.map → generate-27CjLiGW.js.map} +1 -1
- package/dist/chunks/{generate-yi8AP3xH.js → generate-BFcy2wrS.js} +3 -3
- package/dist/chunks/{generate-yi8AP3xH.js.map → generate-BFcy2wrS.js.map} +1 -1
- package/dist/chunks/generate-BxOzEdc_.js +171 -0
- package/dist/chunks/generate-BxOzEdc_.js.map +1 -0
- package/dist/chunks/{generate-B6Odfk5f.js → generate-Cqwa8kD9.js} +2 -2
- package/dist/chunks/{generate-B6Odfk5f.js.map → generate-Cqwa8kD9.js.map} +1 -1
- package/dist/chunks/{generate-DjBMRzsB.js → generate-D3mSFPdT.js} +2 -2
- package/dist/chunks/{generate-DjBMRzsB.js.map → generate-D3mSFPdT.js.map} +1 -1
- package/dist/chunks/{generate-ZIOVLH6Q.js → generate-DdLwP0E7.js} +51 -47
- package/dist/chunks/generate-DdLwP0E7.js.map +1 -0
- package/dist/chunks/generate-DyV5R8NP.js.map +1 -1
- package/dist/chunks/{generate.runtime-MjWwR2Bd.js → generate.runtime-9KuMcI5r.js} +10 -13
- package/dist/chunks/{generate.runtime-MjWwR2Bd.js.map → generate.runtime-9KuMcI5r.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BKINIJ2c.js → generate.runtime-B10-KA87.js} +69 -69
- package/dist/chunks/{generate.runtime-BKINIJ2c.js.map → generate.runtime-B10-KA87.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DaRVyiSg.js → generate.runtime-B8-GLMkk.js} +131 -197
- package/dist/chunks/generate.runtime-B8-GLMkk.js.map +1 -0
- package/dist/chunks/{generate.runtime-Bdpu4rX0.js → generate.runtime-BGuXHl5o.js} +3 -3
- package/dist/chunks/{generate.runtime-Bdpu4rX0.js.map → generate.runtime-BGuXHl5o.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DjCzW3zU.js → generate.runtime-BJxM7FNA.js} +7 -7
- package/dist/chunks/{generate.runtime-DjCzW3zU.js.map → generate.runtime-BJxM7FNA.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BdmoAVJK.js → generate.runtime-BWRtyQeD.js} +5 -5
- package/dist/chunks/{generate.runtime-BdmoAVJK.js.map → generate.runtime-BWRtyQeD.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CV4soy2n.js → generate.runtime-B_tWu-Bw.js} +47 -47
- package/dist/chunks/{generate.runtime-CV4soy2n.js.map → generate.runtime-B_tWu-Bw.js.map} +1 -1
- package/dist/chunks/{generate.runtime-NaSIZlP5.js → generate.runtime-BdghkfNp.js} +3 -3
- package/dist/chunks/{generate.runtime-NaSIZlP5.js.map → generate.runtime-BdghkfNp.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B4QoBn5v.js → generate.runtime-Blb6QPZn.js} +8 -8
- package/dist/chunks/{generate.runtime-B4QoBn5v.js.map → generate.runtime-Blb6QPZn.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DRRyPa-e.js → generate.runtime-CEexT8cJ.js} +66 -66
- package/dist/chunks/{generate.runtime-DRRyPa-e.js.map → generate.runtime-CEexT8cJ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BKTkVCEm.js → generate.runtime-CIZO2XO9.js} +4 -4
- package/dist/chunks/{generate.runtime-BKTkVCEm.js.map → generate.runtime-CIZO2XO9.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DmsOEsJV.js → generate.runtime-CK0MTeqc.js} +4 -4
- package/dist/chunks/{generate.runtime-DmsOEsJV.js.map → generate.runtime-CK0MTeqc.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BavEh01F.js → generate.runtime-CMO-Skpk.js} +5 -5
- package/dist/chunks/{generate.runtime-BavEh01F.js.map → generate.runtime-CMO-Skpk.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BXZDKLbA.js → generate.runtime-CVDb-yLt.js} +12 -20
- package/dist/chunks/{generate.runtime-BXZDKLbA.js.map → generate.runtime-CVDb-yLt.js.map} +1 -1
- package/dist/chunks/generate.runtime-C_5Ghjri.js +17 -0
- package/dist/chunks/generate.runtime-C_5Ghjri.js.map +1 -0
- package/dist/chunks/{generate.runtime-CWgZhxQt.js → generate.runtime-CbOMXQSo.js} +3 -3
- package/dist/chunks/{generate.runtime-CWgZhxQt.js.map → generate.runtime-CbOMXQSo.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DBBtYTAa.js → generate.runtime-CbT-EbQT.js} +5 -5
- package/dist/chunks/{generate.runtime-DBBtYTAa.js.map → generate.runtime-CbT-EbQT.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CSUnP0l-.js → generate.runtime-Cxr15Y5H.js} +27 -27
- package/dist/chunks/{generate.runtime-CSUnP0l-.js.map → generate.runtime-Cxr15Y5H.js.map} +1 -1
- package/dist/chunks/{generate.runtime-pMpn0Pbf.js → generate.runtime-CyTxBcX3.js} +10 -10
- package/dist/chunks/{generate.runtime-pMpn0Pbf.js.map → generate.runtime-CyTxBcX3.js.map} +1 -1
- package/dist/chunks/{generate.runtime-azOvp6tl.js → generate.runtime-D5HxAups.js} +39 -36
- package/dist/chunks/generate.runtime-D5HxAups.js.map +1 -0
- package/dist/chunks/{generate.runtime-b2RtuPy4.js → generate.runtime-D6vhkGs8.js} +5 -5
- package/dist/chunks/{generate.runtime-b2RtuPy4.js.map → generate.runtime-D6vhkGs8.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DlbG-8Xm.js → generate.runtime-DIeAeOJg.js} +6 -6
- package/dist/chunks/{generate.runtime-DlbG-8Xm.js.map → generate.runtime-DIeAeOJg.js.map} +1 -1
- package/dist/chunks/{generate.runtime-QbmCPT42.js → generate.runtime-DMTAocSE.js} +17 -17
- package/dist/chunks/{generate.runtime-QbmCPT42.js.map → generate.runtime-DMTAocSE.js.map} +1 -1
- package/dist/chunks/{generate.runtime-utFLS6Jz.js → generate.runtime-DlLwmjGF.js} +133 -121
- package/dist/chunks/generate.runtime-DlLwmjGF.js.map +1 -0
- package/dist/chunks/{generate.runtime-BYfyZHhs.js → generate.runtime-DtCaz98N.js} +6 -6
- package/dist/chunks/{generate.runtime-BYfyZHhs.js.map → generate.runtime-DtCaz98N.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BcgjZJug.js → generate.runtime-HSZD935T.js} +4 -4
- package/dist/chunks/{generate.runtime-BcgjZJug.js.map → generate.runtime-HSZD935T.js.map} +1 -1
- package/dist/chunks/{generate.runtime-OEgsdWRP.js → generate.runtime-Nnk5E8Pi.js} +3 -3
- package/dist/chunks/{generate.runtime-OEgsdWRP.js.map → generate.runtime-Nnk5E8Pi.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D-qtaVdq.js → generate.runtime-NxuWvkKt.js} +13 -13
- package/dist/chunks/{generate.runtime-D-qtaVdq.js.map → generate.runtime-NxuWvkKt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CCV4O6_I.js → generate.runtime-dFTOU_KE.js} +71 -71
- package/dist/chunks/{generate.runtime-CCV4O6_I.js.map → generate.runtime-dFTOU_KE.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C7s1Mx5L.js → generate.runtime-m0m43lkL.js} +7 -7
- package/dist/chunks/{generate.runtime-C7s1Mx5L.js.map → generate.runtime-m0m43lkL.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BdHv7Jp1.js → generate.runtime-si5Za61F.js} +3 -3
- package/dist/chunks/{generate.runtime-BdHv7Jp1.js.map → generate.runtime-si5Za61F.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DetYynf4.js → generate.runtime-tGKorg85.js} +10 -14
- package/dist/chunks/{generate.runtime-DetYynf4.js.map → generate.runtime-tGKorg85.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CcPCAEV0.js → generate.runtime-ww3-1FWf.js} +6 -6
- package/dist/chunks/{generate.runtime-CcPCAEV0.js.map → generate.runtime-ww3-1FWf.js.map} +1 -1
- package/dist/chunks/{modify-file-Bbhyfiy_.js → modify-file-COBp4eCh.js} +4 -4
- package/dist/chunks/{modify-file-Bbhyfiy_.js.map → modify-file-COBp4eCh.js.map} +1 -1
- package/dist/chunks/{modify-nav-user-B8h8WTrM.js → modify-nav-user-CJ1LevSU.js} +2 -2
- package/dist/chunks/{modify-nav-user-B8h8WTrM.js.map → modify-nav-user-CJ1LevSU.js.map} +1 -1
- package/dist/chunks/{modify-svelte-config-remote-DhuRX4FI.js → modify-svelte-config-remote-CEyYydL7.js} +2 -2
- package/dist/chunks/{modify-svelte-config-remote-DhuRX4FI.js.map → modify-svelte-config-remote-CEyYydL7.js.map} +1 -1
- package/dist/chunks/{modify-user-signup-BbqTiUuA.js → modify-user-signup-DLtopazD.js} +2 -2
- package/dist/chunks/{modify-user-signup-BbqTiUuA.js.map → modify-user-signup-DLtopazD.js.map} +1 -1
- package/dist/chunks/{package-imports-Bbw3iMPg.js → package-imports-Dx05A-4S.js} +2 -2
- package/dist/chunks/{package-imports-Bbw3iMPg.js.map → package-imports-Dx05A-4S.js.map} +1 -1
- package/dist/chunks/{pocketbase-CgwbH1gI.js → pocketbase-DL02rq73.js} +5 -13
- package/dist/chunks/{pocketbase-CgwbH1gI.js.map → pocketbase-DL02rq73.js.map} +1 -1
- package/dist/chunks/{providers-DwbwccSW.js → providers-CAehyySB.js} +2 -2
- package/dist/chunks/{providers-DwbwccSW.js.map → providers-CAehyySB.js.map} +1 -1
- package/dist/chunks/{rolldown-runtime-DArdT4gl.js → rolldown-runtime-5HNE8Q1r.js} +1 -1
- package/dist/chunks/{shared-D5GOS97l.js → shared-C_Fr8wph.js} +2 -2
- package/dist/chunks/{shared-D5GOS97l.js.map → shared-C_Fr8wph.js.map} +1 -1
- package/dist/chunks/site-BoujshKo.js +108 -0
- package/dist/chunks/site-BoujshKo.js.map +1 -0
- package/dist/chunks/{table-core-DhDqT03G.js → table-core-BPv_RYgD.js} +3 -3
- package/dist/chunks/{table-core-DhDqT03G.js.map → table-core-BPv_RYgD.js.map} +1 -1
- package/dist/chunks/{taggedTemplateLiteral-CswN2AAa.js → taggedTemplateLiteral-KSUnuvOk.js} +1 -1
- package/dist/chunks/{test-setup-DZoyF8Ak.js → test-setup-pYUIfWb2.js} +5 -5
- package/dist/chunks/{test-setup-DZoyF8Ak.js.map → test-setup-pYUIfWb2.js.map} +1 -1
- package/dist/chunks/{ts-morph-helpers-Bepc-Es2.js → ts-morph-helpers-CHI9wAil.js} +7 -11
- package/dist/chunks/{ts-morph-helpers-Bepc-Es2.js.map → ts-morph-helpers-CHI9wAil.js.map} +1 -1
- package/dist/chunks/{ui-BuocThuh.js → ui-B2yn8c_-.js} +3 -3
- package/dist/chunks/{ui-BuocThuh.js.map → ui-B2yn8c_-.js.map} +1 -1
- package/dist/chunks/{unmodify-load-Bl5vXQiL.js → unmodify-load-Buak-r1f.js} +2 -2
- package/dist/chunks/{unmodify-load-Bl5vXQiL.js.map → unmodify-load-Buak-r1f.js.map} +1 -1
- package/dist/chunks/{whatsapp-CguKGTtw.js → whatsapp-5qJ_xCV1.js} +2 -2
- package/dist/chunks/{whatsapp-CguKGTtw.js.map → whatsapp-5qJ_xCV1.js.map} +1 -1
- package/dist/chunks/{write-result-Cq-9A7Zy.js → write-result-Bn4bnrBI.js} +20 -50
- package/dist/chunks/write-result-Bn4bnrBI.js.map +1 -0
- package/dist/chunks/wuchale-config-c3Q4JVSF.js +50 -0
- package/dist/chunks/wuchale-config-c3Q4JVSF.js.map +1 -0
- package/dist/index.d.ts +162 -1
- package/dist/index.js +2193 -2330
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunks/collections-Cpjo2OiQ.js.map +0 -1
- package/dist/chunks/constants-Rq8SCXwH.js.map +0 -1
- package/dist/chunks/generate-BClgUH4J.js +0 -137
- package/dist/chunks/generate-BClgUH4J.js.map +0 -1
- package/dist/chunks/generate-ZIOVLH6Q.js.map +0 -1
- package/dist/chunks/generate.runtime-DaRVyiSg.js.map +0 -1
- package/dist/chunks/generate.runtime-azOvp6tl.js.map +0 -1
- package/dist/chunks/generate.runtime-utFLS6Jz.js.map +0 -1
- package/dist/chunks/shopify-page-D-VFwGxI.js +0 -11
- package/dist/chunks/shopify-page-D-VFwGxI.js.map +0 -1
- package/dist/chunks/site-lj0CDdQ1.js +0 -55
- package/dist/chunks/site-lj0CDdQ1.js.map +0 -1
- package/dist/chunks/write-result-Cq-9A7Zy.js.map +0 -1
|
@@ -15,7 +15,7 @@ async function n(e, t) {
|
|
|
15
15
|
exists: !0,
|
|
16
16
|
rowCount: 0
|
|
17
17
|
}));
|
|
18
|
-
let { withPocketbase: n } = await import("./pocketbase-
|
|
18
|
+
let { withPocketbase: n } = await import("./pocketbase-DL02rq73.js").then((e) => e.r), { planCollectionDrops: r } = await import("./collections-DrUG8ngq.js").then((e) => e.n), i = [];
|
|
19
19
|
return await n(t.root, async (t) => {
|
|
20
20
|
let n = await r(t, e);
|
|
21
21
|
i.push(...n);
|
|
@@ -24,4 +24,4 @@ async function n(e, t) {
|
|
|
24
24
|
//#endregion
|
|
25
25
|
export { t as n, n as t };
|
|
26
26
|
|
|
27
|
-
//# sourceMappingURL=shared-
|
|
27
|
+
//# sourceMappingURL=shared-C_Fr8wph.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-
|
|
1
|
+
{"version":3,"file":"shared-C_Fr8wph.js","names":["languageFromPath","toDeleteEntry","path","planDropsForCollections","collectionNames","options","n","drops","withPocketbase","plans","planCollectionDrops","pb"],"sources":["../../src/patterns/destroy/shared.ts"],"sourcesContent":["import type { CollectionDropSpec, File, Options } from \"../../core/types\";\nimport { languageFromPath } from \"../../core/util\";\n\nexport function toDeleteEntry(path: string): File {\n return {\n path,\n language: languageFromPath(path),\n content: \"\",\n status: \"success\",\n };\n}\n\n/**\n * Build `CollectionDropSpec` entries for each collection name, with live row\n * counts from PocketBase when `env === \"runtime\"`. In preview mode, returns\n * `{ exists: true, rowCount: 0 }` placeholders.\n */\nexport async function planDropsForCollections(\n collectionNames: string[],\n options: Options,\n): Promise<CollectionDropSpec[]> {\n if (collectionNames.length === 0) return [];\n\n if (options.env !== \"runtime\") {\n return collectionNames.map((name) => ({\n name,\n exists: true,\n rowCount: 0,\n }));\n }\n\n const { withPocketbase } = await import(\"../../runtime/pocketbase\");\n const { planCollectionDrops } = await import(\"../../runtime/collections\");\n const drops: CollectionDropSpec[] = [];\n await withPocketbase(options.root, async (pb) => {\n const plans = await planCollectionDrops(pb, collectionNames);\n drops.push(...plans);\n });\n return drops;\n}\n"],"mappings":";;AAGA,SAAgBC,EAAc,GAAoB;CAChD,OAAO;EACL;EACA,UAAUD,EAAiBE,CAAI;EAC/B,SAAS;EACT,QAAQ;CACV;AACF;AAOA,eAAsBC,EACpB,GACA,GAC+B;CAC/B,IAAIC,EAAgB,WAAW,GAAG,OAAO,CAAC;CAE1C,IAAIC,EAAQ,QAAQ,WAClB,OAAOD,EAAgB,KAAK,OAAU;EACpC;EACA,QAAQ;EACR,UAAU;CACZ,EAAE;CAGJ,IAAM,EAAE,sBAAmB,MAAM,OAAO,2BAAA,CAAA,MAAA,MAAAE,EAAA,CAAA,GAClC,EAAE,2BAAwB,MAAM,OAAO,4BAAA,CAAA,MAAA,MAAAA,EAAA,CAAA,GACvCC,IAA8B,CAAC;CAKrC,OAJA,MAAMC,EAAeH,EAAQ,MAAM,OAAO,MAAO;EAC/C,IAAMI,IAAQ,MAAMC,EAAoBC,GAAIP,CAAe;EAC3D,EAAM,KAAK,GAAGK,CAAK;CACrB,CAAC,GACMF;AACT"}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { a as e } from "./util-BLYliuUK.js";
|
|
2
|
+
import { n as t } from "./logger-CQONztPm.js";
|
|
3
|
+
import { i as n } from "./pocketbase-DL02rq73.js";
|
|
4
|
+
import r from "node:fs";
|
|
5
|
+
import i from "node:path";
|
|
6
|
+
//#region src/runtime/site.ts
|
|
7
|
+
function a(e) {
|
|
8
|
+
return i.join(e, "src", "lib", "site.ts");
|
|
9
|
+
}
|
|
10
|
+
function o(e, t = "http://localhost:5173", n) {
|
|
11
|
+
return [
|
|
12
|
+
"/**",
|
|
13
|
+
" * Site-wide metadata, and the one place the app's name and public URL live.",
|
|
14
|
+
" *",
|
|
15
|
+
" * Set `url` to where the site is deployed: canonical links, Open Graph images",
|
|
16
|
+
" * and feeds are built from it, including in prerendered pages. With a backend,",
|
|
17
|
+
" * `vela dev` and `vela deploy` copy `name` into PocketBase's application name",
|
|
18
|
+
" * for the emails it sends, so change it here rather than in the admin panel.",
|
|
19
|
+
" */",
|
|
20
|
+
"export const site = {",
|
|
21
|
+
`\tname: ${f(e)},`,
|
|
22
|
+
n ? [`\turl: ${f(t)},`, ...s(n)].join("\n") : `\turl: ${f(t)}`,
|
|
23
|
+
"};",
|
|
24
|
+
""
|
|
25
|
+
].join("\n");
|
|
26
|
+
}
|
|
27
|
+
function s(e) {
|
|
28
|
+
return [" /** ISO 4217: the currency the business prices in and is paid in. */", `\tcurrency: ${f(e)}`];
|
|
29
|
+
}
|
|
30
|
+
function c(e) {
|
|
31
|
+
if (typeof e != "string") return null;
|
|
32
|
+
let t = e.trim().toUpperCase();
|
|
33
|
+
return /^[A-Z]{3}$/.test(t) && Intl.supportedValuesOf("currency").includes(t) ? t : null;
|
|
34
|
+
}
|
|
35
|
+
var l = /export const site = \{\n([\s\S]*?)\n\};/;
|
|
36
|
+
function u(e, t) {
|
|
37
|
+
let n = l.exec(e);
|
|
38
|
+
if (!n || /^\s*currency\s*:/m.test(n[1])) return null;
|
|
39
|
+
let r = n[1].replace(/,?\s*$/, ",");
|
|
40
|
+
return e.replace(n[0], `export const site = {\n${r}\n${s(t).join("\n")}\n};`);
|
|
41
|
+
}
|
|
42
|
+
function d(e) {
|
|
43
|
+
try {
|
|
44
|
+
let t = r.readFileSync(a(e), "utf8");
|
|
45
|
+
return /^\s*currency\s*:\s*['"]([A-Za-z]{3})['"]/m.exec(t)?.[1] ?? null;
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function f(e) {
|
|
51
|
+
return `'${e.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
52
|
+
}
|
|
53
|
+
async function p(e) {
|
|
54
|
+
if (e.features.backend) try {
|
|
55
|
+
let t;
|
|
56
|
+
if (await n(e.root, async (e) => {
|
|
57
|
+
t = (await e.settings.getAll()).meta?.appName;
|
|
58
|
+
}), typeof t == "string" && t.trim()) return t;
|
|
59
|
+
} catch {}
|
|
60
|
+
try {
|
|
61
|
+
let t = JSON.parse(r.readFileSync(i.join(e.root, "package.json"), "utf8"));
|
|
62
|
+
if (typeof t.name == "string" && t.name.trim()) return t.name;
|
|
63
|
+
} catch {}
|
|
64
|
+
return "My App";
|
|
65
|
+
}
|
|
66
|
+
async function m(n) {
|
|
67
|
+
let i = a(n.root);
|
|
68
|
+
return r.existsSync(i) ? null : (t(n).info("Creating src/lib/site.ts"), {
|
|
69
|
+
path: i,
|
|
70
|
+
language: e(i),
|
|
71
|
+
content: o(await p(n)),
|
|
72
|
+
status: "success"
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
async function h(n, i) {
|
|
76
|
+
let s = a(n.root);
|
|
77
|
+
if (!r.existsSync(s)) return t(n).info("Creating src/lib/site.ts"), {
|
|
78
|
+
file: {
|
|
79
|
+
path: s,
|
|
80
|
+
language: e(s),
|
|
81
|
+
content: o(await p(n), void 0, i),
|
|
82
|
+
status: "success"
|
|
83
|
+
},
|
|
84
|
+
currency: i
|
|
85
|
+
};
|
|
86
|
+
let c = d(n.root);
|
|
87
|
+
if (c) return {
|
|
88
|
+
file: null,
|
|
89
|
+
currency: c
|
|
90
|
+
};
|
|
91
|
+
let l = u(r.readFileSync(s, "utf8"), i);
|
|
92
|
+
return l === null ? {
|
|
93
|
+
file: null,
|
|
94
|
+
currency: i
|
|
95
|
+
} : (t(n).info(`Adding currency ${i} to src/lib/site.ts`), {
|
|
96
|
+
file: {
|
|
97
|
+
path: s,
|
|
98
|
+
language: e(s),
|
|
99
|
+
content: l,
|
|
100
|
+
status: "success"
|
|
101
|
+
},
|
|
102
|
+
currency: i
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
export { o as a, d as i, m as n, a as o, c as r, h as t };
|
|
107
|
+
|
|
108
|
+
//# sourceMappingURL=site-BoujshKo.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"site-BoujshKo.js","names":["intl","languageFromPath","getLogger","withPocketbase","fs","path","sitePath","root","siteModule","quote","name","currency","url","currencyLines","normalizeCurrency","raw","code","SITE_OBJECT","withSiteCurrency","match","source","body","siteCurrency","value","existingName","options","appName","pb","pkg","ensureSiteFile","file","ensureSiteCurrency","existing","next"],"sources":["../../src/runtime/site.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options } from \"../core/types\";\nimport { getLogger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { withPocketbase } from \"./pocketbase\";\n\n/** Where every VelaStack app keeps its name and public URL. */\nexport function sitePath(root: string): string {\n return path.join(root, \"src\", \"lib\", \"site.ts\");\n}\n\n/**\n * `src/lib/site.ts` as the CLI templates ship it (`site.template.ts`), with\n * the placeholders filled in, plus the business's currency when one is given.\n */\nexport function siteModule(\n name: string,\n url = \"http://localhost:5173\",\n currency?: string,\n): string {\n return [\n \"/**\",\n \" * Site-wide metadata, and the one place the app's name and public URL live.\",\n \" *\",\n \" * Set `url` to where the site is deployed: canonical links, Open Graph images\",\n \" * and feeds are built from it, including in prerendered pages. With a backend,\",\n \" * `vela dev` and `vela deploy` copy `name` into PocketBase's application name\",\n \" * for the emails it sends, so change it here rather than in the admin panel.\",\n \" */\",\n \"export const site = {\",\n `\\tname: ${quote(name)},`,\n currency\n ? [`\\turl: ${quote(url)},`, ...currencyLines(currency)].join(\"\\n\")\n : `\\turl: ${quote(url)}`,\n \"};\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** The `currency` property, with what it means; no trailing comma, as the last property. */\nfunction currencyLines(currency: string): string[] {\n return [\n \"\\t/** ISO 4217: the currency the business prices in and is paid in. */\",\n `\\tcurrency: ${quote(currency)}`,\n ];\n}\n\n/** A three-letter code `Intl` knows, upper-cased; anything else is refused. */\nexport function normalizeCurrency(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const code = raw.trim().toUpperCase();\n if (!/^[A-Z]{3}$/.test(code)) return null;\n // Any well-formed code formats, so ask for the list of real ones. Node has\n // had it since 18; the repo's ES2020 lib types just don't declare it.\n const intl = Intl as unknown as {\n supportedValuesOf: (key: \"currency\") => string[];\n };\n return intl.supportedValuesOf(\"currency\").includes(code) ? code : null;\n}\n\nconst SITE_OBJECT = /export const site = \\{\\n([\\s\\S]*?)\\n\\};/;\n\n/**\n * `src/lib/site.ts` with `currency` added as the object's last property,\n * or `null` when it already has one (a project's currency is never changed\n * behind its back) or has no `export const site = { ... };` to add it to.\n */\nexport function withSiteCurrency(\n source: string,\n currency: string,\n): string | null {\n const match = SITE_OBJECT.exec(source);\n if (!match || /^\\s*currency\\s*:/m.test(match[1])) return null;\n const body = match[1].replace(/,?\\s*$/, \",\");\n return source.replace(\n match[0],\n `export const site = {\\n${body}\\n${currencyLines(currency).join(\"\\n\")}\\n};`,\n );\n}\n\n/** The currency `src/lib/site.ts` declares, if any. */\nexport function siteCurrency(root: string): string | null {\n try {\n const source = fs.readFileSync(sitePath(root), \"utf8\");\n return (\n /^\\s*currency\\s*:\\s*['\"]([A-Za-z]{3})['\"]/m.exec(source)?.[1] ?? null\n );\n } catch {\n return null;\n }\n}\n\n/** Single-quoted, as the templates write their strings. */\nfunction quote(value: string): string {\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`;\n}\n\n/**\n * The name a project created before `site.ts` existed already goes by.\n *\n * Those projects kept it in PocketBase's settings, so that is asked first; the\n * package name is the fallback for a project without a backend, or one whose\n * database can't be reached.\n */\nasync function existingName(options: Options): Promise<string> {\n if (options.features.backend) {\n try {\n let appName: unknown;\n await withPocketbase(options.root, async (pb) => {\n const settings = (await pb.settings.getAll()) as {\n meta?: { appName?: unknown };\n };\n appName = settings.meta?.appName;\n });\n if (typeof appName === \"string\" && appName.trim()) return appName;\n } catch {\n // No database to ask; fall through to package.json.\n }\n }\n\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(options.root, \"package.json\"), \"utf8\"),\n ) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name.trim()) return pkg.name;\n } catch {\n // No package.json to name the site after; the placeholder stands.\n }\n return \"My App\";\n}\n\n/**\n * Create `src/lib/site.ts` for a pattern whose files import `#lib/site.js`, when\n * the project doesn't have one yet. Every template ships it; projects created\n * before that read the app name from `locals.meta` instead.\n *\n * Returns null when the file exists, so an existing one is never overwritten.\n */\nexport async function ensureSiteFile(options: Options): Promise<File | null> {\n const file = sitePath(options.root);\n if (fs.existsSync(file)) return null;\n\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options)),\n status: \"success\",\n };\n}\n\n/**\n * Make `src/lib/site.ts` declare the business's currency: create the file\n * with it, or add it to an existing one that has none. An existing currency\n * is kept, whatever `currency` says; the result says which it was.\n */\nexport async function ensureSiteCurrency(\n options: Options,\n currency: string,\n): Promise<{ file: File | null; currency: string }> {\n const file = sitePath(options.root);\n if (!fs.existsSync(file)) {\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options), undefined, currency),\n status: \"success\",\n },\n currency,\n };\n }\n const existing = siteCurrency(options.root);\n if (existing) return { file: null, currency: existing };\n const next = withSiteCurrency(fs.readFileSync(file, \"utf8\"), currency);\n if (next === null) return { file: null, currency };\n getLogger(options).info(`Adding currency ${currency} to src/lib/site.ts`);\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: next,\n status: \"success\",\n },\n currency,\n };\n}\n"],"mappings":";;;;;;AAQA,SAAgBM,EAAS,GAAsB;CAC7C,OAAOD,EAAK,KAAKE,GAAM,OAAO,OAAO,SAAS;AAChD;AAMA,SAAgBC,EACd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nB,CAAQ;CAGrE,OAFIsB,MAAS,OAAa;EAAE,MAAM;EAAM;CAAS,KACjD/B,EAAUuB,CAAO,CAAC,CAAC,KAAK,mBAAmBd,EAAS,oBAAoB,GACjE;EACL,MAAM;GACJ,MAAMmB;GACN,UAAU7B,EAAiB6B,CAAI;GAC/B,SAASG;GACT,QAAQ;EACV;EACA;CACF;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as e } from "./rolldown-runtime-
|
|
1
|
+
import { n as e } from "./rolldown-runtime-5HNE8Q1r.js";
|
|
2
2
|
import { r as t, t as n } from "./errors-DR3gF_7a.js";
|
|
3
3
|
import { n as r } from "./lib-specifier-Cngo1zF_.js";
|
|
4
|
-
import { p as i } from "./constants-
|
|
4
|
+
import { p as i } from "./constants-iej3WkEa.js";
|
|
5
5
|
import { existsSync as a, readFileSync as o } from "node:fs";
|
|
6
6
|
import s from "node:path";
|
|
7
7
|
var c = 1e4;
|
|
@@ -124,4 +124,4 @@ function T(e, t) {
|
|
|
124
124
|
//#endregion
|
|
125
125
|
export { f as a, u as i, v as n, _ as r, T as t };
|
|
126
126
|
|
|
127
|
-
//# sourceMappingURL=table-core-
|
|
127
|
+
//# sourceMappingURL=table-core-BPv_RYgD.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-core-DhDqT03G.js","names":["__exportAll","RegistryUnavailableError","InvalidArgumentError","libAliasPath","TANSTACK_TABLE_CORE","path","REGISTRY_TIMEOUT_MS","optionalString","value","readComponentsConfig","raw","configPath","root","existsSync","parsed","readFileSync","aliases","key","alias","DEFAULT_UI_DIR","resolveUiDir","rel","registryIndexUrl","registry","style","indexCache","parseIndex","body","items","entry","name","type","requestIndex","response","fetchImpl","url","error","reason","fetchRegistryIndex","config","options","cache","pending","table_core_exports","TABLE_CORE_COMPONENTS","assertTableCorePackage","assertTableCoreV9","declaredTableCoreMajor","MIGRATION_GUIDE","packageJsonPath","pkg","major","hasV8DataTable","index","upgradeSteps","outdatedPackage","found","tableComponents","components","component"],"sources":["../../src/runtime/registry.ts","../../src/runtime/table-core.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { RegistryItem, WriteResultRuntime } from \"../core/types\";\nimport { RegistryUnavailableError } from \"../core/errors\";\nimport { libAliasPath } from \"./lib-specifier\";\n\n/**\n * shadcn-svelte's schema defaults. A `components.json` that names no `style`\n * resolves to `nova` (not `vega`, whatever `getRegistryUrl`'s fallback says),\n * which is why the CLI's templates write the key explicitly.\n */\nexport const DEFAULT_STYLE = \"nova\";\nexport const DEFAULT_REGISTRY = \"https://shadcn-svelte.com/registry\";\nexport const DEFAULT_CSS_PATH = \"src/app.css\";\n\nconst REGISTRY_TIMEOUT_MS = 10_000;\n\nexport interface ComponentsConfig {\n style: string;\n registry: string;\n baseColor?: string;\n iconLibrary?: string;\n menuColor?: string;\n menuAccent?: string;\n aliases: Record<string, string>;\n /** `tailwind.css`: the global stylesheet, relative to the root. */\n cssPath: string;\n}\n\ninterface RawComponentsConfig {\n style?: unknown;\n registry?: unknown;\n iconLibrary?: unknown;\n menuColor?: unknown;\n menuAccent?: unknown;\n tailwind?: { css?: unknown; baseColor?: unknown };\n aliases?: Record<string, unknown>;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * The project's `components.json` with the schema defaults filled in. A\n * missing or unreadable file behaves like an empty one, so callers can still\n * compute paths and the existence checks here agree with shadcn's own.\n */\nexport function readComponentsConfig(root: string): ComponentsConfig {\n let raw: RawComponentsConfig = {};\n const configPath = path.join(root, \"components.json\");\n if (existsSync(configPath)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(configPath, \"utf8\"));\n if (parsed && typeof parsed === \"object\") {\n raw = parsed as RawComponentsConfig;\n }\n } catch {\n raw = {};\n }\n }\n\n const aliases: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw.aliases ?? {})) {\n const alias = optionalString(value);\n if (alias) aliases[key] = alias;\n }\n\n return {\n style: optionalString(raw.style) ?? DEFAULT_STYLE,\n registry: optionalString(raw.registry) ?? DEFAULT_REGISTRY,\n baseColor: optionalString(raw.tailwind?.baseColor),\n iconLibrary: optionalString(raw.iconLibrary),\n menuColor: optionalString(raw.menuColor),\n menuAccent: optionalString(raw.menuAccent),\n aliases,\n cssPath: optionalString(raw.tailwind?.css) ?? DEFAULT_CSS_PATH,\n };\n}\n\nconst DEFAULT_UI_DIR = [\"src\", \"lib\", \"components\", \"ui\"];\n\n/**\n * Where shadcn-svelte writes items: `components.json` `aliases.ui`, resolved\n * under `src/lib` for `#lib/...`, or the alias a project from before\n * SvelteKit 3 still has.\n * Anything else (a custom alias, a missing or unreadable config) falls back\n * to the default so the existence check here and shadcn's own target agree\n * for every project the CLI creates.\n */\nexport function resolveUiDir(root: string): string {\n const alias = readComponentsConfig(root).aliases.ui;\n const rel = alias === undefined ? null : libAliasPath(alias);\n if (rel === null) {\n return path.join(root, ...DEFAULT_UI_DIR);\n }\n return path.join(root, \"src\", \"lib\", ...rel.split(\"/\").filter(Boolean));\n}\n\n/** `${registry}/styles/${style}/index.json`: the items one style offers. */\nexport function registryIndexUrl(registry: string, style: string): string {\n return `${registry.replace(/\\/+$/, \"\")}/styles/${encodeURIComponent(style)}/index.json`;\n}\n\n/**\n * One request per registry URL per process, keyed on the fetch implementation\n * so an injected test double never sees another test's answer and the real\n * `fetch` shares its answer across a style switch and the installs it runs.\n */\nconst indexCache = new WeakMap<\n typeof fetch,\n Map<string, Promise<RegistryItem[]>>\n>();\n\nfunction parseIndex(body: unknown): RegistryItem[] {\n if (!Array.isArray(body)) {\n throw new Error(\"the index is not a list\");\n }\n const items: RegistryItem[] = [];\n for (const entry of body) {\n if (!entry || typeof entry !== \"object\") continue;\n const { name, type } = entry as { name?: unknown; type?: unknown };\n if (typeof name === \"string\" && typeof type === \"string\") {\n items.push({ name, type });\n }\n }\n return items;\n}\n\nasync function requestIndex(\n url: string,\n fetchImpl: typeof fetch,\n): Promise<RegistryItem[]> {\n let response: Response;\n try {\n response = await fetchImpl(url, {\n signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),\n });\n } catch (error) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `no answer within ${REGISTRY_TIMEOUT_MS / 1000}s`\n : error instanceof Error\n ? error.message\n : String(error);\n throw new RegistryUnavailableError(url, reason);\n }\n if (!response.ok) {\n throw new RegistryUnavailableError(url, `HTTP ${response.status}`);\n }\n try {\n return parseIndex(await response.json());\n } catch (error) {\n throw new RegistryUnavailableError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\n/**\n * The items the project's registry offers for a style: the configured one by\n * default, or `options.style` to look at the style a project is about to\n * switch to. Throws `RegistryUnavailableError` when the index cannot be read.\n */\nexport async function fetchRegistryIndex(\n root: string,\n options: { style?: string; runtime?: WriteResultRuntime } = {},\n): Promise<RegistryItem[]> {\n const config = readComponentsConfig(root);\n const url = registryIndexUrl(config.registry, options.style ?? config.style);\n const fetchImpl = options.runtime?.fetch ?? globalThis.fetch;\n\n let cache = indexCache.get(fetchImpl);\n if (!cache) {\n cache = new Map();\n indexCache.set(fetchImpl, cache);\n }\n let pending = cache.get(url);\n if (!pending) {\n pending = requestIndex(url, fetchImpl).catch((error: unknown) => {\n // A failed read is not worth remembering: the next command may be online.\n cache.delete(url);\n throw error;\n });\n cache.set(url, pending);\n }\n return pending;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n TANSTACK_TABLE_CORE,\n TANSTACK_TABLE_CORE_MAJOR,\n} from \"../core/constants\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { resolveUiDir } from \"./registry\";\n\n/** The components this package ships that are built on `@tanstack/table-core`. */\nexport const TABLE_CORE_COMPONENTS = [\n \"data-table\",\n \"column-header\",\n \"faceted-filter\",\n \"pagination\",\n];\n\nconst MIGRATION_GUIDE =\n \"https://tanstack.com/table/latest/docs/framework/svelte/guide/migrating\";\n\n/**\n * The major of the `@tanstack/table-core` range `package.json` declares, when\n * it names one (`^8.21.3` is 8; `latest` or `workspace:*` is undefined).\n */\nexport function declaredTableCoreMajor(root: string): number | undefined {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) return undefined;\n const pkg = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const range =\n pkg.dependencies?.[\"@tanstack/table-core\"] ??\n pkg.devDependencies?.[\"@tanstack/table-core\"];\n const major = range?.match(/^[\\^~>=v\\s]*(\\d+)/)?.[1];\n return major === undefined ? undefined : Number(major);\n}\n\n/** Whether the project's `data-table` helper is the v8 one (`createSvelteTable`). */\nfunction hasV8DataTable(root: string): boolean {\n const index = path.join(resolveUiDir(root), \"data-table\", \"index.ts\");\n return (\n existsSync(index) &&\n readFileSync(index, \"utf8\").includes(\"createSvelteTable\")\n );\n}\n\nfunction upgradeSteps(): string {\n return (\n \"Nothing was changed. To upgrade:\\n\" +\n ` 1. Install ${TANSTACK_TABLE_CORE}: npm install ${TANSTACK_TABLE_CORE}\\n` +\n ` 2. Replace the table helpers: vela ui add ${TABLE_CORE_COMPONENTS.join(\" \")} --overwrite\\n` +\n ` 3. Move existing list pages to the v9 API (createTable, tableFeatures): ${MIGRATION_GUIDE}\\n` +\n \"Then run this again.\"\n );\n}\n\n/**\n * Refuses a project still on TanStack Table v8, before anything is written.\n *\n * The scaffold list pages and the table helpers target v9. A project set up\n * before that has `@tanstack/table-core@^8` and v8 helpers; the package is\n * never upgraded by `installPackages` (it is already present) and the helpers\n * are never replaced (they already exist), so a new page would not compile,\n * and upgrading in place would break the list pages already there.\n */\nexport function assertTableCoreV9(root: string): void {\n const major = declaredTableCoreMajor(root);\n const outdatedPackage =\n major !== undefined && major < TANSTACK_TABLE_CORE_MAJOR;\n if (!outdatedPackage && !hasV8DataTable(root)) return;\n\n const found = outdatedPackage\n ? `package.json pins @tanstack/table-core ${major}.x`\n : \"its data-table helper is the v8 one (createSvelteTable)\";\n throw new InvalidArgumentError(\n `This project uses TanStack Table v8 (${found}), and scaffold list pages now need v${TANSTACK_TABLE_CORE_MAJOR}.\\n\\n` +\n upgradeSteps(),\n );\n}\n\n/**\n * Refuses to add v9 table helpers next to a v8 `@tanstack/table-core`, which\n * `installPackages` would leave in place.\n */\nexport function assertTableCorePackage(\n root: string,\n components: string[],\n): void {\n const tableComponents = components.filter((component) =>\n TABLE_CORE_COMPONENTS.includes(component),\n );\n if (tableComponents.length === 0) return;\n const major = declaredTableCoreMajor(root);\n if (major === undefined || major >= TANSTACK_TABLE_CORE_MAJOR) return;\n\n throw new InvalidArgumentError(\n `${tableComponents.join(\", \")} target${tableComponents.length === 1 ? \"s\" : \"\"} TanStack Table v${TANSTACK_TABLE_CORE_MAJOR}, and package.json pins @tanstack/table-core ${major}.x.\\n\\n` +\n `Nothing was changed. Install ${TANSTACK_TABLE_CORE} first (npm install ${TANSTACK_TABLE_CORE}), then run this again.`,\n );\n}\n"],"mappings":";;;;;;AAeA,IAAMM,IAAsB;AAwB5B,SAASC,EAAe,GAAoC;CAC1D,OAAO,OAAOC,KAAU,YAAYA,EAAM,SAAS,IAAIA,IAAQ,KAAA;AACjE;AAOA,SAAgBC,EAAqB,GAAgC;CACnE,IAAIC,IAA2B,CAAC,GAC1BC,IAAaN,EAAK,KAAKO,GAAM,iBAAiB;CACpD,IAAIC,EAAWF,CAAU,GACvB,IAAI;EACF,IAAMG,IAAkB,KAAK,MAAMC,EAAaJ,GAAY,MAAM,CAAC;EACnE,AAAIG,KAAU,OAAOA,KAAW,aAC9B,IAAMA;CAEV,QAAQ;EACN,IAAM,CAAC;CACT;CAGF,IAAME,IAAkC,CAAC;CACzC,KAAK,IAAM,CAACC,GAAKT,MAAU,OAAO,QAAQE,EAAI,WAAW,CAAC,CAAC,GAAG;EAC5D,IAAMQ,IAAQX,EAAeC,CAAK;EAClC,AAAIU,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,KAFJD,EAAI,eAAe,2BACnBA,EAAI,kBAAkB,wBAAA,EACH,MAAM,mBAAmB,CAAC,GAAG;CAClD,OAAOC,MAAU,KAAA,IAAY,KAAA,IAAY,OAAOA,CAAK;AACvD;AAGA,SAASC,EAAe,GAAuB;CAC7C,IAAMC,IAAQhD,EAAK,KAAKe,EAAaR,CAAI,GAAG,cAAc,UAAU;CACpE,OACEC,EAAWwC,CAAK,KAChBtC,EAAasC,GAAO,MAAM,CAAC,CAAC,SAAS,mBAAmB;AAE5D;AAEA,SAASC,IAAuB;CAC9B,OACE;eACgBlD,EAAoB,iBAAiBA,EAAoB,uDACnBwC,EAAsB,KAAK,GAAG,EAAE,0FACTI,EAAgB;AAGjG;AAWA,SAAgBF,EAAkB,GAAoB;CACpD,IAAMK,IAAQJ,EAAuBnC,CAAI,GACnC2C,IACJJ,MAAU,KAAA,KAAaA,IAAA;CACzB,IAAI,CAACI,KAAmB,CAACH,EAAexC,CAAI,GAAG;CAE/C,IAAM4C,IAAQD,IACV,0CAA0CJ,EAAM,MAChD;CACJ,MAAM,IAAIjD,EACR,wCAAwCsD,EAAM,+CAC5CF,EAAa,CACjB;AACF;AAMA,SAAgBT,EACd,GACA,GACM;CACN,IAAMY,IAAkBC,EAAW,QAAQ,MACzCd,EAAsB,SAASe,CAAS,CAC1C;CACA,IAAIF,EAAgB,WAAW,GAAG;CAClC,IAAMN,IAAQJ,EAAuBnC,CAAI;CACzC,IAAI,QAAU,KAAA,KAAauC,KAAA,IAE3B,MAAM,IAAIjD,EACR,GAAGuD,EAAgB,KAAK,IAAI,EAAE,SAASA,EAAgB,WAAW,IAAI,MAAM,GAAG,iEAA4FN,EAAM,sCAC/I/C,EAAoB,sBAAsBA,EAAoB,wBAClG;AACF"}
|
|
1
|
+
{"version":3,"file":"table-core-BPv_RYgD.js","names":["__exportAll","RegistryUnavailableError","InvalidArgumentError","libAliasPath","TANSTACK_TABLE_CORE","path","REGISTRY_TIMEOUT_MS","optionalString","value","readComponentsConfig","raw","configPath","root","existsSync","parsed","readFileSync","aliases","key","alias","DEFAULT_UI_DIR","resolveUiDir","rel","registryIndexUrl","registry","style","indexCache","parseIndex","body","items","entry","name","type","requestIndex","response","fetchImpl","url","error","reason","fetchRegistryIndex","config","options","cache","pending","table_core_exports","TABLE_CORE_COMPONENTS","assertTableCorePackage","assertTableCoreV9","declaredTableCoreMajor","MIGRATION_GUIDE","packageJsonPath","pkg","major","hasV8DataTable","index","upgradeSteps","outdatedPackage","found","tableComponents","components","component"],"sources":["../../src/runtime/registry.ts","../../src/runtime/table-core.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { RegistryItem, WriteResultRuntime } from \"../core/types\";\nimport { RegistryUnavailableError } from \"../core/errors\";\nimport { libAliasPath } from \"./lib-specifier\";\n\n/**\n * shadcn-svelte's schema defaults. A `components.json` that names no `style`\n * resolves to `nova` (not `vega`, whatever `getRegistryUrl`'s fallback says),\n * which is why the CLI's templates write the key explicitly.\n */\nexport const DEFAULT_STYLE = \"nova\";\nexport const DEFAULT_REGISTRY = \"https://shadcn-svelte.com/registry\";\nexport const DEFAULT_CSS_PATH = \"src/app.css\";\n\nconst REGISTRY_TIMEOUT_MS = 10_000;\n\nexport interface ComponentsConfig {\n style: string;\n registry: string;\n baseColor?: string;\n iconLibrary?: string;\n menuColor?: string;\n menuAccent?: string;\n aliases: Record<string, string>;\n /** `tailwind.css`: the global stylesheet, relative to the root. */\n cssPath: string;\n}\n\ninterface RawComponentsConfig {\n style?: unknown;\n registry?: unknown;\n iconLibrary?: unknown;\n menuColor?: unknown;\n menuAccent?: unknown;\n tailwind?: { css?: unknown; baseColor?: unknown };\n aliases?: Record<string, unknown>;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * The project's `components.json` with the schema defaults filled in. A\n * missing or unreadable file behaves like an empty one, so callers can still\n * compute paths and the existence checks here agree with shadcn's own.\n */\nexport function readComponentsConfig(root: string): ComponentsConfig {\n let raw: RawComponentsConfig = {};\n const configPath = path.join(root, \"components.json\");\n if (existsSync(configPath)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(configPath, \"utf8\"));\n if (parsed && typeof parsed === \"object\") {\n raw = parsed as RawComponentsConfig;\n }\n } catch {\n raw = {};\n }\n }\n\n const aliases: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw.aliases ?? {})) {\n const alias = optionalString(value);\n if (alias) aliases[key] = alias;\n }\n\n return {\n style: optionalString(raw.style) ?? DEFAULT_STYLE,\n registry: optionalString(raw.registry) ?? DEFAULT_REGISTRY,\n baseColor: optionalString(raw.tailwind?.baseColor),\n iconLibrary: optionalString(raw.iconLibrary),\n menuColor: optionalString(raw.menuColor),\n menuAccent: optionalString(raw.menuAccent),\n aliases,\n cssPath: optionalString(raw.tailwind?.css) ?? DEFAULT_CSS_PATH,\n };\n}\n\nconst DEFAULT_UI_DIR = [\"src\", \"lib\", \"components\", \"ui\"];\n\n/**\n * Where shadcn-svelte writes items: `components.json` `aliases.ui`, resolved\n * under `src/lib` for `#lib/...`, or the alias a project from before\n * SvelteKit 3 still has.\n * Anything else (a custom alias, a missing or unreadable config) falls back\n * to the default so the existence check here and shadcn's own target agree\n * for every project the CLI creates.\n */\nexport function resolveUiDir(root: string): string {\n const alias = readComponentsConfig(root).aliases.ui;\n const rel = alias === undefined ? null : libAliasPath(alias);\n if (rel === null) {\n return path.join(root, ...DEFAULT_UI_DIR);\n }\n return path.join(root, \"src\", \"lib\", ...rel.split(\"/\").filter(Boolean));\n}\n\n/** `${registry}/styles/${style}/index.json`: the items one style offers. */\nexport function registryIndexUrl(registry: string, style: string): string {\n return `${registry.replace(/\\/+$/, \"\")}/styles/${encodeURIComponent(style)}/index.json`;\n}\n\n/**\n * One request per registry URL per process, keyed on the fetch implementation\n * so an injected test double never sees another test's answer and the real\n * `fetch` shares its answer across a style switch and the installs it runs.\n */\nconst indexCache = new WeakMap<\n typeof fetch,\n Map<string, Promise<RegistryItem[]>>\n>();\n\nfunction parseIndex(body: unknown): RegistryItem[] {\n if (!Array.isArray(body)) {\n throw new Error(\"the index is not a list\");\n }\n const items: RegistryItem[] = [];\n for (const entry of body) {\n if (!entry || typeof entry !== \"object\") continue;\n const { name, type } = entry as { name?: unknown; type?: unknown };\n if (typeof name === \"string\" && typeof type === \"string\") {\n items.push({ name, type });\n }\n }\n return items;\n}\n\nasync function requestIndex(\n url: string,\n fetchImpl: typeof fetch,\n): Promise<RegistryItem[]> {\n let response: Response;\n try {\n response = await fetchImpl(url, {\n signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),\n });\n } catch (error) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `no answer within ${REGISTRY_TIMEOUT_MS / 1000}s`\n : error instanceof Error\n ? error.message\n : String(error);\n throw new RegistryUnavailableError(url, reason);\n }\n if (!response.ok) {\n throw new RegistryUnavailableError(url, `HTTP ${response.status}`);\n }\n try {\n return parseIndex(await response.json());\n } catch (error) {\n throw new RegistryUnavailableError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\n/**\n * The items the project's registry offers for a style: the configured one by\n * default, or `options.style` to look at the style a project is about to\n * switch to. Throws `RegistryUnavailableError` when the index cannot be read.\n */\nexport async function fetchRegistryIndex(\n root: string,\n options: { style?: string; runtime?: WriteResultRuntime } = {},\n): Promise<RegistryItem[]> {\n const config = readComponentsConfig(root);\n const url = registryIndexUrl(config.registry, options.style ?? config.style);\n const fetchImpl = options.runtime?.fetch ?? globalThis.fetch;\n\n let cache = indexCache.get(fetchImpl);\n if (!cache) {\n cache = new Map();\n indexCache.set(fetchImpl, cache);\n }\n let pending = cache.get(url);\n if (!pending) {\n pending = requestIndex(url, fetchImpl).catch((error: unknown) => {\n // A failed read is not worth remembering: the next command may be online.\n cache.delete(url);\n throw error;\n });\n cache.set(url, pending);\n }\n return pending;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n TANSTACK_TABLE_CORE,\n TANSTACK_TABLE_CORE_MAJOR,\n} from \"../core/constants\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { resolveUiDir } from \"./registry\";\n\n/** The components this package ships that are built on `@tanstack/table-core`. */\nexport const TABLE_CORE_COMPONENTS = [\n \"data-table\",\n \"column-header\",\n \"faceted-filter\",\n \"pagination\",\n];\n\nconst MIGRATION_GUIDE =\n \"https://tanstack.com/table/latest/docs/framework/svelte/guide/migrating\";\n\n/**\n * The major of the `@tanstack/table-core` range `package.json` declares, when\n * it names one (`^8.21.3` is 8; `latest` or `workspace:*` is undefined).\n */\nexport function declaredTableCoreMajor(root: string): number | undefined {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) return undefined;\n const pkg = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const range =\n pkg.dependencies?.[\"@tanstack/table-core\"] ??\n pkg.devDependencies?.[\"@tanstack/table-core\"];\n const major = range?.match(/^[\\^~>=v\\s]*(\\d+)/)?.[1];\n return major === undefined ? undefined : Number(major);\n}\n\n/** Whether the project's `data-table` helper is the v8 one (`createSvelteTable`). */\nfunction hasV8DataTable(root: string): boolean {\n const index = path.join(resolveUiDir(root), \"data-table\", \"index.ts\");\n return (\n existsSync(index) &&\n readFileSync(index, \"utf8\").includes(\"createSvelteTable\")\n );\n}\n\nfunction upgradeSteps(): string {\n return (\n \"Nothing was changed. To upgrade:\\n\" +\n ` 1. Install ${TANSTACK_TABLE_CORE}: npm install ${TANSTACK_TABLE_CORE}\\n` +\n ` 2. Replace the table helpers: vela ui add ${TABLE_CORE_COMPONENTS.join(\" \")} --overwrite\\n` +\n ` 3. Move existing list pages to the v9 API (createTable, tableFeatures): ${MIGRATION_GUIDE}\\n` +\n \"Then run this again.\"\n );\n}\n\n/**\n * Refuses a project still on TanStack Table v8, before anything is written.\n *\n * The scaffold list pages and the table helpers target v9. A project set up\n * before that has `@tanstack/table-core@^8` and v8 helpers; the package is\n * never upgraded by `installPackages` (it is already present) and the helpers\n * are never replaced (they already exist), so a new page would not compile,\n * and upgrading in place would break the list pages already there.\n */\nexport function assertTableCoreV9(root: string): void {\n const major = declaredTableCoreMajor(root);\n const outdatedPackage =\n major !== undefined && major < TANSTACK_TABLE_CORE_MAJOR;\n if (!outdatedPackage && !hasV8DataTable(root)) return;\n\n const found = outdatedPackage\n ? `package.json pins @tanstack/table-core ${major}.x`\n : \"its data-table helper is the v8 one (createSvelteTable)\";\n throw new InvalidArgumentError(\n `This project uses TanStack Table v8 (${found}), and scaffold list pages now need v${TANSTACK_TABLE_CORE_MAJOR}.\\n\\n` +\n upgradeSteps(),\n );\n}\n\n/**\n * Refuses to add v9 table helpers next to a v8 `@tanstack/table-core`, which\n * `installPackages` would leave in place.\n */\nexport function assertTableCorePackage(\n root: string,\n components: string[],\n): void {\n const tableComponents = components.filter((component) =>\n TABLE_CORE_COMPONENTS.includes(component),\n );\n if (tableComponents.length === 0) return;\n const major = declaredTableCoreMajor(root);\n if (major === undefined || major >= TANSTACK_TABLE_CORE_MAJOR) return;\n\n throw new InvalidArgumentError(\n `${tableComponents.join(\", \")} target${tableComponents.length === 1 ? \"s\" : \"\"} TanStack Table v${TANSTACK_TABLE_CORE_MAJOR}, and package.json pins @tanstack/table-core ${major}.x.\\n\\n` +\n `Nothing was changed. Install ${TANSTACK_TABLE_CORE} first (npm install ${TANSTACK_TABLE_CORE}), then run this again.`,\n );\n}\n"],"mappings":";;;;;;AAeA,IAAMM,IAAsB;AAwB5B,SAASC,EAAe,GAAoC;CAC1D,OAAO,OAAOC,KAAU,YAAYA,EAAM,SAAS,IAAIA,IAAQ,KAAA;AACjE;AAOA,SAAgBC,EAAqB,GAAgC;CACnE,IAAIC,IAA2B,CAAC,GAC1BC,IAAaN,EAAK,KAAKO,GAAM,iBAAiB;CACpD,IAAIC,EAAWF,CAAU,GACvB,IAAI;EACF,IAA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jD,EACR,GAAGuD,EAAgB,KAAK,IAAI,EAAE,SAASA,EAAgB,WAAW,IAAI,MAAM,GAAG,iEAA4FN,EAAM,sCAC/I/C,EAAoB,sBAAsBA,EAAoB,wBAClG;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region \0@oxc-project+runtime@0.
|
|
1
|
+
//#region \0@oxc-project+runtime@0.154.0/helpers/esm/taggedTemplateLiteral.js
|
|
2
2
|
function e(e, t) {
|
|
3
3
|
return t ||= e.slice(0), Object.freeze(Object.defineProperties(e, { raw: { value: Object.freeze(t) } }));
|
|
4
4
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as e, t } from "./constants-
|
|
1
|
+
import { n as e, t } from "./constants-iej3WkEa.js";
|
|
2
2
|
import { t as n } from "./dedent-Gq6Krl4n.js";
|
|
3
|
-
import { o as r, s as i } from "./config-target-
|
|
4
|
-
import { c as a } from "./write-result-
|
|
3
|
+
import { o as r, s as i } from "./config-target-BgyFkbFL.js";
|
|
4
|
+
import { c as a } from "./write-result-Bn4bnrBI.js";
|
|
5
5
|
import o from "node:fs";
|
|
6
6
|
import s from "node:path";
|
|
7
7
|
import { SyntaxKind as c } from "ts-morph";
|
|
@@ -156,7 +156,7 @@ function E(e) {
|
|
|
156
156
|
});
|
|
157
157
|
}
|
|
158
158
|
function D(e) {
|
|
159
|
-
return !o.existsSync(e) || o.readFileSync(e, "utf8") ===
|
|
159
|
+
return !o.existsSync(e) || o.readFileSync(e, "utf8") === "import { beforeEach, afterEach, beforeAll } from 'vitest';\nimport supertest, { type Agent } from 'supertest';\nimport PocketBase from 'pocketbase-sveltekit';\nimport type { TestContext } from '@velastack/pocketbase/testing';\n\nconst admin = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['admin'];\nconst pb = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['pb'];\n\nconst testUserPassword = 'password';\n\nasync function authenticateUser(agent: Agent, user: { email?: string }) {\n // Logs in with the password, so it needs the email (made optional by\n // enable-whatsapp, for accounts that sign in with a phone number).\n if (!user.email) {\n throw new Error('authenticateUser needs a user with an email');\n }\n await agent.post('/login').type('form').send({\n type: 'password',\n email: user.email,\n password: testUserPassword\n });\n}\n\nbeforeAll(async () => {\n await admin\n // @ts-ignore\n .collection('_superusers')\n .authWithPassword(\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!\n );\n});\n\nbeforeEach(async (context: TestContext) => {\n context.request = supertest(process.env.VITE_TEST_URL!);\n context.agent = supertest.agent(process.env.VITE_TEST_URL!) as TestContext['agent'];\n context.admin = admin;\n context.pb = pb;\n const email = `test-${Math.random().toString(36).slice(2)}@example.com`;\n context.user = await context.admin.collection('users').create({\n email,\n password: testUserPassword,\n passwordConfirm: testUserPassword\n });\n context.agent.authenticateUser = () => authenticateUser(context.agent, context.user);\n await context.pb.collection('users').authWithPassword(email, testUserPassword);\n});\n\nafterEach(async (context: TestContext) => {\n await context.pb.authStore.clear();\n await context.admin.collection('users').delete(context.user.id);\n});\n" ? {
|
|
160
160
|
status: "success",
|
|
161
161
|
changed: !1
|
|
162
162
|
} : (o.writeFileSync(e, S, "utf8"), {
|
|
@@ -176,4 +176,4 @@ function O(e) {
|
|
|
176
176
|
//#endregion
|
|
177
177
|
export { O as a, g as c, D as i, _ as l, S as n, b as o, E as r, x as s, w as t };
|
|
178
178
|
|
|
179
|
-
//# sourceMappingURL=test-setup-
|
|
179
|
+
//# sourceMappingURL=test-setup-pYUIfWb2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-setup-DZoyF8Ak.js","names":["ADAPTER_NODE_SPEC","ADAPTER_STATIC_SPEC","NOT_FOUND_HINT","ADAPTER_STATIC$1","dedent","resolveConfigTarget","saveTarget","packageName","fs","path","ADAPTER_NODE","ADAPTER_NODE$1","ADAPTER_STATIC","ADAPTER_AUTO","FAILURE_HINT","NOT_FOUND_HINT$1","findAdapterImport","sourceFile","decl","adapterCalls","SyntaxKind","ce","modifySvelteConfig","res","root","adapterImport","target","call","args","i","unmodifySvelteConfig","POCKETBASE_BLOCK","NOT_FOUND_HINT","modifyGitignore","gitignorePath","original","next","unmodifyGitignore","cleaned","WITH_BACKEND","WITHOUT_BACKEND","VITEST_CONFIG","VITEST_CONFIG_NAMES","ext","hasVitestConfig","name","viteConfig","modifyTestSetup","testSetupPath","unmodifyTestSetup"],"sources":["../../src/patterns/enable/backend/modifies/svelte-config.ts","../../src/patterns/enable/backend/modifies/gitignore.ts","../../src/patterns/enable/backend/modifies/test-setup.ts"],"sourcesContent":["import dedent from \"dedent\";\nimport { SyntaxKind } from \"ts-morph\";\nimport {\n resolveConfigTarget,\n saveTarget,\n type ConfigModifyResult,\n type ConfigTarget,\n} from \"../../../../runtime/config-target\";\nimport { packageName } from \"../../../../runtime/write-result\";\nimport {\n ADAPTER_NODE as ADAPTER_NODE_SPEC,\n ADAPTER_STATIC as ADAPTER_STATIC_SPEC,\n} from \"../../../../core/constants\";\n\n// Imports name the package, not the versioned spec the constants install.\nconst ADAPTER_NODE = packageName(ADAPTER_NODE_SPEC);\nconst ADAPTER_STATIC = packageName(ADAPTER_STATIC_SPEC);\nconst ADAPTER_AUTO = \"@sveltejs/adapter-auto\";\n\nconst FAILURE_HINT = dedent`\n Switch the SvelteKit adapter to ${ADAPTER_NODE}:\n\n import adapter from '${ADAPTER_NODE}';\n\n // ...\n adapter: adapter()\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Configure ${ADAPTER_NODE} via the sveltekit() plugin in vite.config.ts.\n`;\n\n/**\n * The adapters this pattern moves between. adapter-auto is included because\n * that is what `sv create` ships, and a project that never chose is one the\n * backend is free to decide for.\n */\nfunction findAdapterImport(sourceFile: ConfigTarget[\"sourceFile\"]) {\n return sourceFile\n .getImportDeclarations()\n .find((decl) =>\n [ADAPTER_STATIC, ADAPTER_AUTO, ADAPTER_NODE].includes(\n decl.getModuleSpecifierValue(),\n ),\n );\n}\n\nfunction adapterCalls(sourceFile: ConfigTarget[\"sourceFile\"]) {\n return sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((ce) => ce.getExpression().getText() === \"adapter\");\n}\n\n/**\n * Switch the adapter to `@sveltejs/adapter-node` and drop its arguments in\n * vite.config, which holds the adapter import + `adapter()` call. A project with a\n * backend is served from a Node process, which is what `vela deploy` runs.\n * Operates on the import and call expression directly, so it never needs the\n * config object.\n */\nexport function modifySvelteConfig(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, {\n notFound: NOT_FOUND_HINT,\n failed: FAILURE_HINT,\n });\n if (res.status !== \"resolved\") {\n return {\n filePath: res.filePath,\n outcome: { status: res.status, message: res.message },\n };\n }\n const { target } = res;\n const adapterImport = findAdapterImport(target.sourceFile);\n if (!adapterImport) {\n return {\n filePath: target.filePath,\n outcome: { status: \"failed\", message: FAILURE_HINT },\n };\n }\n\n if (adapterImport.getModuleSpecifierValue() !== ADAPTER_NODE) {\n adapterImport.setModuleSpecifier(ADAPTER_NODE);\n }\n\n for (const call of adapterCalls(target.sourceFile)) {\n const args = call.getArguments();\n for (let i = args.length - 1; i >= 0; i--) {\n call.removeArgument(i);\n }\n }\n\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n\n/**\n * Reverse of {@link modifySvelteConfig}: switch back to\n * `@sveltejs/adapter-static` and restore the `{ fallback: '200.html' }` arg.\n * Lenient when there is no config or no adapter import: a no-op success. A\n * config that can't be edited (a leftover svelte.config) still fails.\n */\nexport function unmodifySvelteConfig(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, {\n notFound: NOT_FOUND_HINT,\n failed: FAILURE_HINT,\n });\n if (res.status === \"not-found\") {\n // Nothing to revert.\n return {\n filePath: res.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n if (res.status === \"failed\") {\n return {\n filePath: res.filePath,\n outcome: { status: \"failed\", message: res.message },\n };\n }\n const { target } = res;\n const adapterImport = findAdapterImport(target.sourceFile);\n if (!adapterImport) {\n return {\n filePath: target.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n\n if (adapterImport.getModuleSpecifierValue() !== ADAPTER_STATIC) {\n adapterImport.setModuleSpecifier(ADAPTER_STATIC);\n }\n\n for (const call of adapterCalls(target.sourceFile)) {\n if (call.getArguments().length === 0) {\n call.addArgument(\"{ fallback: '200.html' }\");\n }\n }\n\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst POCKETBASE_BLOCK = `# PocketBase\n/data/*\n!/data/fixtures\n!/data/seeds\n!/data/hooks\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create a .gitignore at the project root with the PocketBase block:\n\n # PocketBase\n /data/*\n !/data/fixtures\n !/data/seeds\n !/data/hooks\n`;\n\nexport function modifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n\n if (original.includes(\"# PocketBase\") && original.includes(\"/data/*\")) {\n return { status: \"success\", changed: false };\n }\n\n const separator = original.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const next = original + separator + POCKETBASE_BLOCK;\n fs.writeFileSync(gitignorePath, next, \"utf8\");\n\n return { status: \"success\", changed: true };\n}\n\nexport function unmodifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n\n if (!original.includes(\"# PocketBase\")) {\n return { status: \"success\", changed: false };\n }\n\n const withBlockRemoved = original.replace(\n /\\n*# PocketBase\\n\\/data\\/\\*\\n!\\/data\\/fixtures\\n!\\/data\\/seeds\\n!\\/data\\/hooks\\n?/,\n \"\\n\",\n );\n\n const cleaned = withBlockRemoved.replace(/\\n{3,}$/, \"\\n\");\n\n if (cleaned === original) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(gitignorePath, cleaned, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n// Source of truth: velastack-cli/templates/minimal/test/setup.ts\nexport const WITH_BACKEND = `import { beforeEach, afterEach, beforeAll } from 'vitest';\nimport supertest, { type Agent } from 'supertest';\nimport PocketBase from 'pocketbase-sveltekit';\nimport type { TestContext } from '@velastack/pocketbase/testing';\n\nconst admin = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['admin'];\nconst pb = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['pb'];\n\nconst testUserPassword = 'password';\n\nasync function authenticateUser(agent: Agent, user: { email?: string }) {\n\\t// Logs in with the password, so it needs the email (made optional by\n\\t// enable-whatsapp, for accounts that sign in with a phone number).\n\\tif (!user.email) {\n\\t\\tthrow new Error('authenticateUser needs a user with an email');\n\\t}\n\\tawait agent.post('/login').type('form').send({\n\\t\\ttype: 'password',\n\\t\\temail: user.email,\n\\t\\tpassword: testUserPassword\n\\t});\n}\n\nbeforeAll(async () => {\n\\tawait admin\n\\t\\t// @ts-ignore\n\\t\\t.collection('_superusers')\n\\t\\t.authWithPassword(\n\\t\\t\\tprocess.env.POCKETBASE_SUPERUSER_EMAIL!,\n\\t\\t\\tprocess.env.POCKETBASE_SUPERUSER_PASSWORD!\n\\t\\t);\n});\n\nbeforeEach(async (context: TestContext) => {\n\\tcontext.request = supertest(process.env.VITE_TEST_URL!);\n\\tcontext.agent = supertest.agent(process.env.VITE_TEST_URL!) as TestContext['agent'];\n\\tcontext.admin = admin;\n\\tcontext.pb = pb;\n\\tconst email = \\`test-\\${Math.random().toString(36).slice(2)}@example.com\\`;\n\\tcontext.user = await context.admin.collection('users').create({\n\\t\\temail,\n\\t\\tpassword: testUserPassword,\n\\t\\tpasswordConfirm: testUserPassword\n\\t});\n\\tcontext.agent.authenticateUser = () => authenticateUser(context.agent, context.user);\n\\tawait context.pb.collection('users').authWithPassword(email, testUserPassword);\n});\n\nafterEach(async (context: TestContext) => {\n\\tawait context.pb.authStore.clear();\n\\tawait context.admin.collection('users').delete(context.user.id);\n});\n`;\n\n// The static template ships no test setup at all; this is the backend-free\n// subset of the minimal one, kept so existing tests keep their agents.\nconst WITHOUT_BACKEND = `import { beforeEach } from 'vitest';\nimport supertest from 'supertest';\n\nbeforeEach(async (context: any) => {\n\\tcontext.request = supertest(process.env.VITE_TEST_URL!);\n\\tcontext.agent = supertest.agent(process.env.VITE_TEST_URL!);\n});\n`;\n\n// Source of truth: velastack-cli/templates/minimal/vitest.config.ts\nexport const VITEST_CONFIG = `import { defineConfig, mergeConfig } from 'vitest/config';\nimport viteConfig from './vite.config';\n\nexport default mergeConfig(\n\\tviteConfig,\n\\tdefineConfig({\n\\t\\ttest: {\n\\t\\t\\texpect: {\n\\t\\t\\t\\trequireAssertions: true\n\\t\\t\\t},\n\\t\\t\\tname: 'server',\n\\t\\t\\tenvironment: 'node',\n\\t\\t\\tinclude: ['src/**/*.{test,spec}.{js,ts}'],\n\\t\\t\\texclude: ['src/**/*.svelte.{test,spec}.{js,ts}'],\n\\t\\t\\tsetupFiles: ['test/setup.ts']\n\\t\\t}\n\\t})\n);\n`;\n\nconst VITEST_CONFIG_NAMES = [\"ts\", \"mts\", \"js\", \"mjs\"].flatMap((ext) => [\n `vitest.config.${ext}`,\n `vitest.workspace.${ext}`,\n]);\n\n/**\n * Whether the project already configures vitest, in a file of its own or a\n * `test` block in its vite config. Without either, `test/setup.ts` is never\n * loaded and every generated `server.test.ts` fails on its missing context.\n */\nexport function hasVitestConfig(root: string): boolean {\n if (\n VITEST_CONFIG_NAMES.some((name) => fs.existsSync(path.join(root, name)))\n ) {\n return true;\n }\n return [\"ts\", \"mts\", \"js\", \"mjs\"].some((ext) => {\n const viteConfig = path.join(root, `vite.config.${ext}`);\n return (\n fs.existsSync(viteConfig) &&\n /\\btest\\s*:/.test(fs.readFileSync(viteConfig, \"utf8\"))\n );\n });\n}\n\n/**\n * Brings an existing `test/setup.ts` up to the backend one. A project without\n * the file gets it as a create instead (see `generate.runtime.ts`), so it is\n * reported as created rather than modified.\n */\nexport function modifyTestSetup(testSetupPath: string): ModifyOutcome {\n if (!fs.existsSync(testSetupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(testSetupPath, \"utf8\");\n if (original === WITH_BACKEND) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(testSetupPath, WITH_BACKEND, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\nexport function unmodifyTestSetup(testSetupPath: string): ModifyOutcome {\n if (!fs.existsSync(testSetupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(testSetupPath, \"utf8\");\n if (original === WITHOUT_BACKEND) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(testSetupPath, WITHOUT_BACKEND, \"utf8\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;;;;;;;AAeA,IAAMU,IAAeH,EAAYP,CAAiB,GAC5CY,IAAiBL,EAAYN,CAAmB,GAChDY,IAAe,0BAEfC,IAAe,CAAM;oCACSJ,EAAa;;yBAExBA,EAAa;;;;GAMhCR,IAAiB,CAAM;cACfQ,EAAa;;AAQ3B,SAASM,EAAkB,GAAwC;CACjE,OAAOC,EACJ,sBAAsB,CAAC,CACvB,MAAM,MACL;EAACL;EAAgBC;EAAcH;CAAY,CAAC,CAAC,SAC3CQ,EAAK,wBAAwB,CAC/B,CACF;AACJ;AAEA,SAASC,EAAa,GAAwC;CAC5D,OAAOF,EACJ,qBAAqBG,EAAW,cAAc,CAAC,CAC/C,QAAQ,MAAOC,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,SAAS;AAC9D;AASA,SAAgBC,EAAmB,GAAkC;CACnE,IAAMC,IAAMlB,EAAoBmB,GAAM;EACpC,UAAUtB;EACV,QAAQY;CACV,CAAC;C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uB;CAMrD,OAJEF,EAAoB,MAAM,MAASlC,EAAG,WAAWC,EAAK,KAAKe,GAAMqB,CAAI,CAAC,CAAC,IAEhE,KAEF;EAAC;EAAM;EAAO;EAAM;CAAK,CAAC,CAAC,MAAM,MAAQ;EAC9C,IAAMC,IAAarC,EAAK,KAAKe,GAAM,eAAemB,GAAK;EACvD,OACEnC,EAAG,WAAWsC,CAAU,KACxB,aAAa,KAAKtC,EAAG,aAAasC,GAAY,MAAM,CAAC;CAEzD,CAAC;AACH;AAOA,SAAgBC,EAAgB,GAAsC;CAWpE,OAVI,CAACvC,EAAG,WAAWwC,CAAa,KAIfxC,EAAG,aAAawC,GAAe,MAC5C,MAAaT,IACR;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7C/B,EAAG,cAAcwC,GAAeT,GAAc,MAAM,GAC7C;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;AAEA,SAAgBU,EAAkB,GAAsC;CAWtE,OAVI,CAACzC,EAAG,WAAWwC,CAAa,KAIfxC,EAAG,aAAawC,GAAe,MAC5C,MAAaR,IACR;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7ChC,EAAG,cAAcwC,GAAeR,GAAiB,MAAM,GAChD;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
|
|
1
|
+
{"version":3,"file":"test-setup-pYUIfWb2.js","names":["ADAPTER_NODE_SPEC","ADAPTER_STATIC_SPEC","NOT_FOUND_HINT","ADAPTER_STATIC$1","dedent","resolveConfigTarget","saveTarget","packageName","fs","path","ADAPTER_NODE","ADAPTER_NODE$1","ADAPTER_STATIC","ADAPTER_AUTO","FAILURE_HINT","NOT_FOUND_HINT$1","findAdapterImport","sourceFile","decl","adapterCalls","SyntaxKind","ce","modifySvelteConfig","res","root","adapterImport","target","call","args","i","unmodifySvelteConfig","POCKETBASE_BLOCK","NOT_FOUND_HINT","modifyGitignore","gitignorePath","original","next","unmodifyGitignore","cleaned","WITH_BACKEND","WITHOUT_BACKEND","VITEST_CONFIG","VITEST_CONFIG_NAMES","ext","hasVitestConfig","name","viteConfig","modifyTestSetup","testSetupPath","unmodifyTestSetup"],"sources":["../../src/patterns/enable/backend/modifies/svelte-config.ts","../../src/patterns/enable/backend/modifies/gitignore.ts","../../src/patterns/enable/backend/modifies/test-setup.ts"],"sourcesContent":["import dedent from \"dedent\";\nimport { SyntaxKind } from \"ts-morph\";\nimport {\n resolveConfigTarget,\n saveTarget,\n type ConfigModifyResult,\n type ConfigTarget,\n} from \"../../../../runtime/config-target\";\nimport { packageName } from \"../../../../runtime/write-result\";\nimport {\n ADAPTER_NODE as ADAPTER_NODE_SPEC,\n ADAPTER_STATIC as ADAPTER_STATIC_SPEC,\n} from \"../../../../core/constants\";\n\n// Imports name the package, not the versioned spec the constants install.\nconst ADAPTER_NODE = packageName(ADAPTER_NODE_SPEC);\nconst ADAPTER_STATIC = packageName(ADAPTER_STATIC_SPEC);\nconst ADAPTER_AUTO = \"@sveltejs/adapter-auto\";\n\nconst FAILURE_HINT = dedent`\n Switch the SvelteKit adapter to ${ADAPTER_NODE}:\n\n import adapter from '${ADAPTER_NODE}';\n\n // ...\n adapter: adapter()\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Configure ${ADAPTER_NODE} via the sveltekit() plugin in vite.config.ts.\n`;\n\n/**\n * The adapters this pattern moves between. adapter-auto is included because\n * that is what `sv create` ships, and a project that never chose is one the\n * backend is free to decide for.\n */\nfunction findAdapterImport(sourceFile: ConfigTarget[\"sourceFile\"]) {\n return sourceFile\n .getImportDeclarations()\n .find((decl) =>\n [ADAPTER_STATIC, ADAPTER_AUTO, ADAPTER_NODE].includes(\n decl.getModuleSpecifierValue(),\n ),\n );\n}\n\nfunction adapterCalls(sourceFile: ConfigTarget[\"sourceFile\"]) {\n return sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((ce) => ce.getExpression().getText() === \"adapter\");\n}\n\n/**\n * Switch the adapter to `@sveltejs/adapter-node` and drop its arguments in\n * vite.config, which holds the adapter import + `adapter()` call. A project with a\n * backend is served from a Node process, which is what `vela deploy` runs.\n * Operates on the import and call expression directly, so it never needs the\n * config object.\n */\nexport function modifySvelteConfig(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, {\n notFound: NOT_FOUND_HINT,\n failed: FAILURE_HINT,\n });\n if (res.status !== \"resolved\") {\n return {\n filePath: res.filePath,\n outcome: { status: res.status, message: res.message },\n };\n }\n const { target } = res;\n const adapterImport = findAdapterImport(target.sourceFile);\n if (!adapterImport) {\n return {\n filePath: target.filePath,\n outcome: { status: \"failed\", message: FAILURE_HINT },\n };\n }\n\n if (adapterImport.getModuleSpecifierValue() !== ADAPTER_NODE) {\n adapterImport.setModuleSpecifier(ADAPTER_NODE);\n }\n\n for (const call of adapterCalls(target.sourceFile)) {\n const args = call.getArguments();\n for (let i = args.length - 1; i >= 0; i--) {\n call.removeArgument(i);\n }\n }\n\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n\n/**\n * Reverse of {@link modifySvelteConfig}: switch back to\n * `@sveltejs/adapter-static` and restore the `{ fallback: '200.html' }` arg.\n * Lenient when there is no config or no adapter import: a no-op success. A\n * config that can't be edited (a leftover svelte.config) still fails.\n */\nexport function unmodifySvelteConfig(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, {\n notFound: NOT_FOUND_HINT,\n failed: FAILURE_HINT,\n });\n if (res.status === \"not-found\") {\n // Nothing to revert.\n return {\n filePath: res.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n if (res.status === \"failed\") {\n return {\n filePath: res.filePath,\n outcome: { status: \"failed\", message: res.message },\n };\n }\n const { target } = res;\n const adapterImport = findAdapterImport(target.sourceFile);\n if (!adapterImport) {\n return {\n filePath: target.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n\n if (adapterImport.getModuleSpecifierValue() !== ADAPTER_STATIC) {\n adapterImport.setModuleSpecifier(ADAPTER_STATIC);\n }\n\n for (const call of adapterCalls(target.sourceFile)) {\n if (call.getArguments().length === 0) {\n call.addArgument(\"{ fallback: '200.html' }\");\n }\n }\n\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst POCKETBASE_BLOCK = `# PocketBase\n/data/*\n!/data/fixtures\n!/data/seeds\n!/data/hooks\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create a .gitignore at the project root with the PocketBase block:\n\n # PocketBase\n /data/*\n !/data/fixtures\n !/data/seeds\n !/data/hooks\n`;\n\nexport function modifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n\n if (original.includes(\"# PocketBase\") && original.includes(\"/data/*\")) {\n return { status: \"success\", changed: false };\n }\n\n const separator = original.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const next = original + separator + POCKETBASE_BLOCK;\n fs.writeFileSync(gitignorePath, next, \"utf8\");\n\n return { status: \"success\", changed: true };\n}\n\nexport function unmodifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n\n if (!original.includes(\"# PocketBase\")) {\n return { status: \"success\", changed: false };\n }\n\n const withBlockRemoved = original.replace(\n /\\n*# PocketBase\\n\\/data\\/\\*\\n!\\/data\\/fixtures\\n!\\/data\\/seeds\\n!\\/data\\/hooks\\n?/,\n \"\\n\",\n );\n\n const cleaned = withBlockRemoved.replace(/\\n{3,}$/, \"\\n\");\n\n if (cleaned === original) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(gitignorePath, cleaned, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n// Source of truth: velastack-cli/templates/minimal/test/setup.ts\nexport const WITH_BACKEND = `import { beforeEach, afterEach, beforeAll } from 'vitest';\nimport supertest, { type Agent } from 'supertest';\nimport PocketBase from 'pocketbase-sveltekit';\nimport type { TestContext } from '@velastack/pocketbase/testing';\n\nconst admin = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['admin'];\nconst pb = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['pb'];\n\nconst testUserPassword = 'password';\n\nasync function authenticateUser(agent: Agent, user: { email?: string }) {\n\\t// Logs in with the password, so it needs the email (made optional by\n\\t// enable-whatsapp, for accounts that sign in with a phone number).\n\\tif (!user.email) {\n\\t\\tthrow new Error('authenticateUser needs a user with an email');\n\\t}\n\\tawait agent.post('/login').type('form').send({\n\\t\\ttype: 'password',\n\\t\\temail: user.email,\n\\t\\tpassword: testUserPassword\n\\t});\n}\n\nbeforeAll(async () => {\n\\tawait admin\n\\t\\t// @ts-ignore\n\\t\\t.collection('_superusers')\n\\t\\t.authWithPassword(\n\\t\\t\\tprocess.env.POCKETBASE_SUPERUSER_EMAIL!,\n\\t\\t\\tprocess.env.POCKETBASE_SUPERUSER_PASSWORD!\n\\t\\t);\n});\n\nbeforeEach(async (context: TestContext) => {\n\\tcontext.request = supertest(process.env.VITE_TEST_URL!);\n\\tcontext.agent = supertest.agent(process.env.VITE_TEST_URL!) as TestContext['agent'];\n\\tcontext.admin = admin;\n\\tcontext.pb = pb;\n\\tconst email = \\`test-\\${Math.random().toString(36).slice(2)}@example.com\\`;\n\\tcontext.user = await context.admin.collection('users').create({\n\\t\\temail,\n\\t\\tpassword: testUserPassword,\n\\t\\tpasswordConfirm: testUserPassword\n\\t});\n\\tcontext.agent.authenticateUser = () => authenticateUser(context.agent, context.user);\n\\tawait context.pb.collection('users').authWithPassword(email, testUserPassword);\n});\n\nafterEach(async (context: TestContext) => {\n\\tawait context.pb.authStore.clear();\n\\tawait context.admin.collection('users').delete(context.user.id);\n});\n`;\n\n// The static template ships no test setup at all; this is the backend-free\n// subset of the minimal one, kept so existing tests keep their agents.\nconst WITHOUT_BACKEND = `import { beforeEach } from 'vitest';\nimport supertest from 'supertest';\n\nbeforeEach(async (context: any) => {\n\\tcontext.request = supertest(process.env.VITE_TEST_URL!);\n\\tcontext.agent = supertest.agent(process.env.VITE_TEST_URL!);\n});\n`;\n\n// Source of truth: velastack-cli/templates/minimal/vitest.config.ts\nexport const VITEST_CONFIG = `import { defineConfig, mergeConfig } from 'vitest/config';\nimport viteConfig from './vite.config';\n\nexport default mergeConfig(\n\\tviteConfig,\n\\tdefineConfig({\n\\t\\ttest: {\n\\t\\t\\texpect: {\n\\t\\t\\t\\trequireAssertions: true\n\\t\\t\\t},\n\\t\\t\\tname: 'server',\n\\t\\t\\tenvironment: 'node',\n\\t\\t\\tinclude: ['src/**/*.{test,spec}.{js,ts}'],\n\\t\\t\\texclude: ['src/**/*.svelte.{test,spec}.{js,ts}'],\n\\t\\t\\tsetupFiles: ['test/setup.ts']\n\\t\\t}\n\\t})\n);\n`;\n\nconst VITEST_CONFIG_NAMES = [\"ts\", \"mts\", \"js\", \"mjs\"].flatMap((ext) => [\n `vitest.config.${ext}`,\n `vitest.workspace.${ext}`,\n]);\n\n/**\n * Whether the project already configures vitest, in a file of its own or a\n * `test` block in its vite config. Without either, `test/setup.ts` is never\n * loaded and every generated `server.test.ts` fails on its missing context.\n */\nexport function hasVitestConfig(root: string): boolean {\n if (\n VITEST_CONFIG_NAMES.some((name) => fs.existsSync(path.join(root, name)))\n ) {\n return true;\n }\n return [\"ts\", \"mts\", \"js\", \"mjs\"].some((ext) => {\n const viteConfig = path.join(root, `vite.config.${ext}`);\n return (\n fs.existsSync(viteConfig) &&\n /\\btest\\s*:/.test(fs.readFileSync(viteConfig, \"utf8\"))\n );\n });\n}\n\n/**\n * Brings an existing `test/setup.ts` up to the backend one. A project without\n * the file gets it as a create instead (see `generate.runtime.ts`), so it is\n * reported as created rather than modified.\n */\nexport function modifyTestSetup(testSetupPath: string): ModifyOutcome {\n if (!fs.existsSync(testSetupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(testSetupPath, \"utf8\");\n if (original === WITH_BACKEND) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(testSetupPath, WITH_BACKEND, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\nexport function unmodifyTestSetup(testSetupPath: string): ModifyOutcome {\n if (!fs.existsSync(testSetupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(testSetupPath, \"utf8\");\n if (original === WITHOUT_BACKEND) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(testSetupPath, WITHOUT_BACKEND, \"utf8\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;;;;;;;AAeA,IAAMU,IAAeH,EAAYP,CAAiB,GAC5CY,IAAiBL,EAAYN,CAAmB,GAChDY,IAAe,0BAEfC,IAAe,CAAM;oCACSJ,EAAa;;yBAExBA,EAAa;;;;GAMhCR,IAAiB,CAAM;cACfQ,EAAa;;AAQ3B,SAASM,EAAkB,GAAwC;CACjE,OAAOC,EACJ,sBAAsB,CAAC,CACvB,MAAM,MACL;EAACL;EAAgBC;EAAcH;CAAY,CAAC,CAAC,SAC3CQ,EAAK,wBAAwB,CAC/B,CACF;AACJ;AAEA,SAASC,EAAa,GAAwC;CAC5D,OAAOF,EACJ,qBAAqBG,EAAW,cAAc,CAAC,CAC/C,QAAQ,MAAOC,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,SAAS;AAC9D;AASA,SAAgBC,EAAmB,GAAkC;CACnE,IAAMC,IAAMlB,EAAoBmB,GAAM;EACpC,UAAUtB;EACV,QAAQY;CACV,CAAC;CACD,IAAIS,EAAI,WAAW,YACjB,OAAO;EACL,UAAUA,EAAI;EACd,SAAS;GAAE,QAAQA,EAAI;GAAQ,SAASA,EAAI;EAAQ;CACtD;CAEF,IAAM,EAAE,cAAWA,GACbE,IAAgBT,EAAkBU,EAAO,UAAU;CACzD,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EAAK,KAAKe,GAAM,eAAemB,GAAK;EACvD,OACEnC,EAAG,WAAWsC,CAAU,KACxB,aAAa,KAAKtC,EAAG,aAAasC,GAAY,MAAM,CAAC;CAEzD,CAAC;AACH;AAOA,SAAgBC,EAAgB,GAAsC;CAWpE,OAVI,CAACvC,EAAG,WAAWwC,CAAa,KAIfxC,EAAG,aAAawC,GAAe,MAC5C,MAAA,41DACK;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7CxC,EAAG,cAAcwC,GAAeT,GAAc,MAAM,GAC7C;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;AAEA,SAAgBU,EAAkB,GAAsC;CAWtE,OAVI,CAACzC,EAAG,WAAWwC,CAAa,KAIfxC,EAAG,aAAawC,GAAe,MAC5C,MAAaR,IACR;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7ChC,EAAG,cAAcwC,GAAeR,GAAiB,MAAM,GAChD;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
|
|
@@ -107,18 +107,14 @@ function p(e, t) {
|
|
|
107
107
|
}
|
|
108
108
|
function m(e, t, n, r = !1) {
|
|
109
109
|
let i = e.getImportDeclarations().find((e) => e.getModuleSpecifierValue() === t && !e.getNamespaceImport() && (r || !e.isTypeOnly()));
|
|
110
|
-
|
|
111
|
-
e.addImportDeclaration({
|
|
112
|
-
isTypeOnly: r,
|
|
113
|
-
namedImports: [n],
|
|
114
|
-
moduleSpecifier: t
|
|
115
|
-
});
|
|
116
|
-
return;
|
|
117
|
-
}
|
|
118
|
-
i.getNamedImports().some((e) => e.getName() === n) || i.addNamedImport(r && !i.isTypeOnly() ? {
|
|
110
|
+
i ? i.getNamedImports().some((e) => e.getName() === n) || i.addNamedImport(r && !i.isTypeOnly() ? {
|
|
119
111
|
name: n,
|
|
120
112
|
isTypeOnly: !0
|
|
121
|
-
} : n)
|
|
113
|
+
} : n) : e.addImportDeclaration({
|
|
114
|
+
isTypeOnly: r,
|
|
115
|
+
namedImports: [n],
|
|
116
|
+
moduleSpecifier: t
|
|
117
|
+
});
|
|
122
118
|
}
|
|
123
119
|
function h(e) {
|
|
124
120
|
let t = e.getKind();
|
|
@@ -268,4 +264,4 @@ function j(e, t, n) {
|
|
|
268
264
|
//#endregion
|
|
269
265
|
export { c as _, E as a, p as c, f as d, j as f, O as g, k as h, m as i, y as l, b as m, C as n, o, D as p, l as r, S as s, A as t, u };
|
|
270
266
|
|
|
271
|
-
//# sourceMappingURL=ts-morph-helpers-
|
|
267
|
+
//# sourceMappingURL=ts-morph-helpers-CHI9wAil.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ts-morph-helpers-Bepc-Es2.js","names":["importsModule","specifier","decl","match","detectIndent","spaces","line","source","width","formatLikeSource","indent","sf","size","commonIndent","common","lead","i","withInMemoryScript","project","Project","QuoteKind","dedented","result","fn","out","lines","ensureImports","spec","imports","d","structure","removeImportByModuleSpecifier","moduleSpecifier","isReferenced","SyntaxKind","id","local","kind","removeNamedImportIfUnused","ni","name","named","rest","pruneUnusedImports","removed","moduleSpecifiers","m","defaultImport","namespaceImport","ensureNamedImport","existing","typeOnly","isCommentNode","node","newlines","text","siblingsOf","parent","statement","Node","commentsAbove","siblings","comments","cursor","removeAttachedComments","spacing","spacingAround","doc","comment","removeStatementWithComments","next","first","prev","setOff","isEffectivelyEmpty","s","ensureBlankLineAfterImports","last","propsDeclaration","propsBinding","ensurePropsBinding","binding","elements","texts","removePropsBindingIfUnused","reads","markup","expression","element","kept","removeUnusedBindingElement","nameNode","pattern","owner","removeTopLevelStatementByIdentifier","addNavItemToScript","newNavItemSnippet","title","url","icon","scriptSource","dataInit","navProp","init","arr","el","titleProp","value","iconImportPath","removeNavItemFromScript","index","importDecl","importName"],"sources":["../../src/runtime/ts-morph-helpers.ts"],"sourcesContent":["import {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type ImportDeclarationStructure,\n type OptionalKind,\n type SourceFile,\n type Statement,\n type StringLiteral,\n} from \"ts-morph\";\n\n/**\n * A module specifier, or a test for one. Disable modifiers pass\n * `libModule(\"negotiate\")` so `#lib/negotiate.js` and the alias a project\n * from before SvelteKit 3 imports it by both match.\n */\nexport type ModuleMatch = string | ((specifier: string) => boolean);\n\nfunction importsModule(\n decl: { getModuleSpecifierValue(): string },\n match: ModuleMatch,\n): boolean {\n const specifier = decl.getModuleSpecifierValue();\n return typeof match === \"string\" ? specifier === match : match(specifier);\n}\n\nexport interface ImportSpec {\n defaultImport?: string;\n namespaceImport?: string;\n namedImports?: string[];\n moduleSpecifier: string;\n}\n\n/**\n * The indentation unit a source uses: a tab, or that many spaces. Read from\n * the shallowest indented line; a lone leading space is a comment\n * continuation, not an indent. Tabs when nothing is indented, which is what\n * `sv create` and vela's templates use.\n */\nexport function detectIndent(source: string): string {\n let spaces = 0;\n for (const line of source.split(\"\\n\")) {\n if (line.startsWith(\"\\t\")) return \"\\t\";\n const width = line.match(/^ +(?=\\S)/)?.[0].length ?? 0;\n if (width >= 2 && (spaces === 0 || width < spaces)) spaces = width;\n }\n return spaces === 0 ? \"\\t\" : \" \".repeat(spaces);\n}\n\n/**\n * `formatText()` in the file's own indentation. ts-morph's default is four\n * spaces, which rewrote every line of a tab-indented config to change one; a\n * project without prettier has nothing to put that back.\n */\nexport function formatLikeSource(sf: SourceFile): void {\n const indent = detectIndent(sf.getFullText());\n const size = indent === \"\\t\" ? 4 : indent.length;\n sf.formatText({\n convertTabsToSpaces: indent !== \"\\t\",\n indentSize: size,\n tabSize: size,\n });\n}\n\n/** The whitespace every non-blank line starts with. */\nfunction commonIndent(source: string): string {\n let common: string | null = null;\n for (const line of source.split(\"\\n\")) {\n if (line.trim() === \"\") continue;\n const lead = line.match(/^[\\t ]*/)![0];\n if (common === null) {\n common = lead;\n continue;\n }\n let i = 0;\n while (i < common.length && i < lead.length && common[i] === lead[i]) i++;\n common = common.slice(0, i);\n }\n return common ?? \"\";\n}\n\n/**\n * Run a function with an in-memory ts-morph SourceFile and return the resulting\n * source plus whatever the callback returned.\n *\n * A `<script>` body is indented one level as a whole, which ts-morph knows\n * nothing about: a statement it adds lands at column zero beside indented\n * neighbours. The shared indent is taken off first and put back afterwards,\n * so additions come out level with what was there.\n */\nexport function withInMemoryScript<T>(\n source: string,\n fn: (sf: SourceFile) => T,\n): { source: string; result: T } {\n const project = new Project({\n useInMemoryFileSystem: true,\n skipFileDependencyResolution: true,\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const indent = commonIndent(source);\n const dedented = indent\n ? source\n .split(\"\\n\")\n .map((line) =>\n line.startsWith(indent) ? line.slice(indent.length) : line,\n )\n .join(\"\\n\")\n : source;\n const sf = project.createSourceFile(\"script.ts\", dedented, {\n overwrite: true,\n });\n const result = fn(sf);\n const out = sf.getFullText();\n if (!indent) return { source: out, result };\n if (out === dedented) return { source, result };\n const lines = out.split(\"\\n\");\n const reindented = lines\n .map((line, i) =>\n // The last line is the whitespace before `</script>`, never a statement.\n line.trim() === \"\" || i === lines.length - 1 ? line : indent + line,\n )\n .join(\"\\n\");\n return { source: reindented, result };\n}\n\n/** Add the given imports to the source file, skipping any whose module specifier already exists. */\nexport function ensureImports(sf: SourceFile, imports: ImportSpec[]): void {\n for (const spec of imports) {\n const existing = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) continue;\n\n const structure: OptionalKind<ImportDeclarationStructure> = {\n moduleSpecifier: spec.moduleSpecifier,\n };\n if (spec.defaultImport) structure.defaultImport = spec.defaultImport;\n if (spec.namespaceImport) structure.namespaceImport = spec.namespaceImport;\n if (spec.namedImports) structure.namedImports = spec.namedImports;\n sf.addImportDeclaration(structure);\n }\n}\n\n/** Remove the import declaration for the given module specifier, if present. */\nexport function removeImportByModuleSpecifier(\n sf: SourceFile,\n moduleSpecifier: ModuleMatch,\n): { wasRemoved: boolean } {\n const decl = sf\n .getImportDeclarations()\n .find((d) => importsModule(d, moduleSpecifier));\n if (!decl) return { wasRemoved: false };\n decl.remove();\n return { wasRemoved: true };\n}\n\n/**\n * Whether `local` is used anywhere other than the import that binds it.\n * Conservative: a same-named property counts, which only ever keeps an import.\n */\nexport function isReferenced(sf: SourceFile, local: string): boolean {\n return sf.getDescendantsOfKind(SyntaxKind.Identifier).some((id) => {\n if (id.getText() !== local) return false;\n const kind = id.getParent()?.getKind();\n return (\n kind !== SyntaxKind.ImportSpecifier &&\n kind !== SyntaxKind.ImportClause &&\n kind !== SyntaxKind.NamespaceImport\n );\n });\n}\n\n/**\n * Drop `name` from the import of `moduleSpecifier` once nothing else in the\n * file references it; the whole declaration goes when `name` was its only\n * import. For unwrapping `sequence(...)` and the like after a revert. An\n * aliased import (`sequence as seq`) is checked by its local name.\n */\nexport function removeNamedImportIfUnused(\n sf: SourceFile,\n moduleSpecifier: ModuleMatch,\n name: string,\n): { wasRemoved: boolean } {\n const decl = sf\n .getImportDeclarations()\n .find(\n (d) =>\n importsModule(d, moduleSpecifier) &&\n d.getNamedImports().some((ni) => ni.getName() === name),\n );\n if (!decl) return { wasRemoved: false };\n\n const named = decl.getNamedImports().find((ni) => ni.getName() === name);\n if (!named) return { wasRemoved: false };\n\n const local = named.getAliasNode()?.getText() ?? name;\n if (isReferenced(sf, local)) return { wasRemoved: false };\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n // `import { sequence, type Handle }` less `sequence` reads as\n // `import type { Handle }`, the way it was before `sequence` joined it.\n const rest = decl.getNamedImports();\n if (!decl.getDefaultImport() && rest.every((ni) => ni.isTypeOnly())) {\n for (const ni of rest) ni.setIsTypeOnly(false);\n decl.setIsTypeOnly(true);\n }\n }\n return { wasRemoved: true };\n}\n\n/**\n * Drop every binding imported from `moduleSpecifiers` that nothing references\n * any more, and the declaration once it binds nothing. Side-effect imports\n * (`import 'x'`) bind nothing to begin with and are left alone.\n */\nexport function pruneUnusedImports(\n sf: SourceFile,\n moduleSpecifiers: ModuleMatch[],\n): { removed: string[] } {\n const removed: string[] = [];\n for (const decl of sf.getImportDeclarations()) {\n if (!moduleSpecifiers.some((m) => importsModule(decl, m))) continue;\n if (!decl.getImportClause()) continue;\n\n for (const named of decl.getNamedImports()) {\n const local = named.getAliasNode()?.getText() ?? named.getName();\n if (isReferenced(sf, local)) continue;\n named.remove();\n removed.push(local);\n }\n const defaultImport = decl.getDefaultImport();\n if (defaultImport && !isReferenced(sf, defaultImport.getText())) {\n removed.push(defaultImport.getText());\n decl.removeDefaultImport();\n }\n const namespaceImport = decl.getNamespaceImport();\n if (namespaceImport && !isReferenced(sf, namespaceImport.getText())) {\n removed.push(namespaceImport.getText());\n decl.removeNamespaceImport();\n }\n\n if (\n decl.getNamedImports().length === 0 &&\n !decl.getDefaultImport() &&\n !decl.getNamespaceImport()\n ) {\n decl.remove();\n }\n }\n return { removed };\n}\n\n/**\n * Import `name` from `moduleSpecifier`, joining an existing import of that\n * module. A type-only name joins a value import as an inline `type`\n * specifier; an `import type` declaration already covers it.\n */\nexport function ensureNamedImport(\n sf: SourceFile,\n moduleSpecifier: string,\n name: string,\n typeOnly = false,\n): void {\n const existing = sf\n .getImportDeclarations()\n .find(\n (d) =>\n d.getModuleSpecifierValue() === moduleSpecifier &&\n !d.getNamespaceImport() &&\n (typeOnly || !d.isTypeOnly()),\n );\n if (!existing) {\n sf.addImportDeclaration({\n isTypeOnly: typeOnly,\n namedImports: [name],\n moduleSpecifier,\n });\n return;\n }\n if (existing.getNamedImports().some((ni) => ni.getName() === name)) return;\n existing.addNamedImport(\n typeOnly && !existing.isTypeOnly() ? { name, isTypeOnly: true } : name,\n );\n}\n\nfunction isCommentNode(node: Node): boolean {\n const kind = node.getKind();\n return (\n kind === SyntaxKind.SingleLineCommentTrivia ||\n kind === SyntaxKind.MultiLineCommentTrivia\n );\n}\n\nfunction newlines(text: string): number {\n return (text.match(/\\n/g) ?? []).length;\n}\n\n/**\n * The statements and comment lines beside `statement`: the file's for a\n * top-level one, the block's for one inside a function body.\n */\nfunction siblingsOf(statement: Statement): Statement[] {\n const parent = statement.getParent();\n return Node.isStatemented(parent) ? parent.getStatementsWithComments() : [];\n}\n\n/**\n * The comment lines directly above a statement, up to the first blank line.\n * ts-morph parses them as statements of their own; the JSDoc is not among\n * them, it belongs to the statement.\n */\nfunction commentsAbove(sf: SourceFile, statement: Statement): Statement[] {\n const siblings = siblingsOf(statement);\n const text = sf.getFullText();\n const comments: Statement[] = [];\n let cursor = statement.getStart(true);\n for (let i = siblings.indexOf(statement) - 1; i >= 0; i--) {\n const node = siblings[i];\n if (!isCommentNode(node)) break;\n if (newlines(text.slice(node.getEnd(), cursor)) > 1) break;\n comments.unshift(node);\n cursor = node.getStart();\n }\n return comments;\n}\n\n/**\n * Remove the JSDoc and comment lines directly above a statement, leaving the\n * statement. For a statement whose comment describes something that has just\n * been swapped out.\n */\nexport function removeAttachedComments(\n sf: SourceFile,\n statement: Statement,\n): void {\n const comments = commentsAbove(sf, statement);\n const spacing = spacingAround(sf, comments[0] ?? statement);\n if (Node.isJSDocable(statement)) {\n for (const doc of statement.getJsDocs()) doc.remove();\n }\n for (const comment of comments.reverse()) comment.remove();\n spacing.restore(statement);\n}\n\n/**\n * Remove a statement, top-level or in a function body, together with its\n * JSDoc, the comment lines directly above it and a comment trailing its last\n * line. ts-morph's own `remove()` leaves the comment lines behind as orphans.\n */\nexport function removeStatementWithComments(\n sf: SourceFile,\n statement: Statement,\n): void {\n const comments = commentsAbove(sf, statement);\n const siblings = siblingsOf(statement);\n const next = siblings[siblings.indexOf(statement) + 1];\n const spacing = spacingAround(sf, comments[0] ?? statement);\n statement.remove();\n for (const comment of comments.reverse()) comment.remove();\n if (next) spacing.restore(next);\n}\n\n/**\n * ts-morph takes the blank line before a removed statement or comment with\n * it. Note whether `first` (the start of what is about to go) was set off by\n * one, so `restore` can put it back before whatever follows.\n */\nfunction spacingAround(sf: SourceFile, first: Statement) {\n const siblings = siblingsOf(first);\n const prev = siblings[siblings.indexOf(first) - 1];\n const setOff =\n prev !== undefined &&\n newlines(sf.getFullText().slice(prev.getEnd(), first.getStart(true))) > 1;\n return {\n restore(next: Statement) {\n if (!setOff || !prev) return;\n const gap = sf.getFullText().slice(prev.getEnd(), next.getStart(true));\n if (newlines(gap) < 2) sf.insertText(prev.getEnd(), \"\\n\");\n },\n };\n}\n\n/**\n * True when the file has no statements left: only comments and whitespace,\n * or nothing at all. A revert that empties a file it once created reports\n * the file as a delete instead.\n */\nexport function isEffectivelyEmpty(sf: SourceFile): boolean {\n return sf.compilerNode.statements.every(\n (s) => s.kind === SyntaxKind.EmptyStatement,\n );\n}\n\n/**\n * Keep one blank line between the import block and what follows. Removing\n * statements right after the imports takes the separating blank line with\n * them, and prettier preserves whichever spacing it finds.\n */\nexport function ensureBlankLineAfterImports(sf: SourceFile): void {\n const imports = sf.getImportDeclarations();\n const last = imports[imports.length - 1];\n const next = last?.getNextSibling();\n if (!last || !next) return;\n // Up to the next statement's JSDoc, whose own newlines are no blank line.\n const between = sf.getFullText().slice(last.getEnd(), next.getStart(true));\n if ((between.match(/\\n/g) ?? []).length >= 2) return;\n sf.insertText(last.getEnd(), \"\\n\");\n}\n\n/** A component's `let { ... } = $props()` declaration, if it destructures. */\nfunction propsDeclaration(sf: SourceFile) {\n return sf\n .getVariableDeclarations()\n .find(\n (decl) =>\n decl.getInitializer()?.getText() === \"$props()\" &&\n Node.isObjectBindingPattern(decl.getNameNode()),\n );\n}\n\n/** The `{ ... }` of a component's `let { ... } = $props()`, if it has one. */\nfunction propsBinding(sf: SourceFile) {\n return propsDeclaration(sf)\n ?.getNameNode()\n .asKind(SyntaxKind.ObjectBindingPattern);\n}\n\n/**\n * Make sure a Svelte component's `$props()` destructures `name`, for markup a\n * modifier inserts that reads it. Adds a `$props()` declaration when the\n * component has none.\n */\nexport function ensurePropsBinding(sf: SourceFile, name: string): void {\n const binding = propsBinding(sf);\n if (!binding) {\n sf.addStatements(`let { ${name} } = $props();`);\n return;\n }\n const elements = binding.getElements();\n if (elements.some((e) => e.getName() === name)) return;\n const texts = elements.map((e) => e.getText());\n const rest = elements.findIndex((e) => e.getDotDotDotToken());\n texts.splice(rest === -1 ? texts.length : rest, 0, name);\n binding.replaceWithText(`{ ${texts.join(\", \")} }`);\n}\n\n/**\n * Drop `name` from a Svelte component's `$props()` once neither the script\n * nor `markup` reads it, undoing `ensurePropsBinding`. The declaration stays\n * even when it empties, as `let {} = $props()` is harmless.\n */\nexport function removePropsBindingIfUnused(\n sf: SourceFile,\n name: string,\n markup: string,\n): void {\n // Only expressions read it: `{data.user}`, `{data}`, `x={data.y}`. A bare\n // word match would also catch `data-role` attributes and body text.\n const reads = new RegExp(`(?<![\\\\w$.])${name}(?![\\\\w$])`);\n const expressions =\n markup.replace(/<style[\\s\\S]*?<\\/style>/g, \"\").match(/\\{[^{}]*\\}/g) ?? [];\n if (expressions.some((expression) => reads.test(expression))) return;\n const decl = propsDeclaration(sf);\n const binding = propsBinding(sf);\n const element = binding\n ?.getElements()\n .find((e) => e.getName() === name && !e.getPropertyNameNode());\n if (!decl || !binding || !element) return;\n // Outside the declaration itself, whose type may name the prop too.\n const usedInScript = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === name && !decl.containsRange(id.getPos(), id.getEnd()),\n );\n if (usedInScript) return;\n const kept = binding\n .getElements()\n .filter((e) => e !== element)\n .map((e) => e.getText());\n binding.replaceWithText(`{ ${kept.join(\", \")} }`);\n}\n\n/**\n * Drop a destructured `name` (as in `({ locals, url })`) that nothing in the\n * file reads any more, for reverting an edit that was its last use. A\n * parameter left as a bare `{}` goes, as does a `const {} = ...` statement.\n * Conservative: any other identifier spelled `name` keeps it.\n */\nexport function removeUnusedBindingElement(sf: SourceFile, name: string): void {\n const element = sf\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .find(\n (e) =>\n e.getName() === name &&\n !e.getPropertyNameNode() &&\n !e.getDotDotDotToken(),\n );\n if (!element) return;\n const nameNode = element.getNameNode();\n const referenced = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === name && id !== nameNode);\n if (referenced) return;\n\n const pattern = element.getParentIfKindOrThrow(\n SyntaxKind.ObjectBindingPattern,\n );\n const kept = pattern\n .getElements()\n .filter((e) => e !== element)\n .map((e) => e.getText());\n const owner = pattern.getParent();\n if (kept.length === 0 && Node.isParameterDeclaration(owner)) {\n owner.remove();\n } else if (kept.length === 0 && Node.isVariableDeclaration(owner)) {\n owner.getVariableStatement()?.remove();\n } else {\n pattern.replaceWithText(`{ ${kept.join(\", \")} }`);\n }\n}\n\n/**\n * Remove a top-level function or variable declaration by name, if present.\n * In a statement that declares several variables only `name`'s declarator\n * goes; the statement goes with its last one.\n */\nexport function removeTopLevelStatementByIdentifier(\n sf: SourceFile,\n name: string,\n): { wasRemoved: boolean } {\n const fn = sf.getFunction(name);\n if (fn) {\n fn.remove();\n return { wasRemoved: true };\n }\n const decl = sf\n .getVariableStatements()\n .flatMap((s) => s.getDeclarations())\n .find((d) => d.getName() === name);\n if (decl) {\n decl.remove();\n return { wasRemoved: true };\n }\n return { wasRemoved: false };\n}\n\n/**\n * Add an item to the `data.navUser` array in a Svelte component's script body.\n * Idempotent: if an entry with the same `title` already exists, no-op.\n */\nexport function addNavItemToScript(\n scriptSource: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { source: string; wasAdded: boolean } {\n const newNavItemSnippet = `\n {\n title: '${title}',\n url: '${url}',\n icon: ${icon}\n }\n `.trim();\n\n const { source, result } = withInMemoryScript(scriptSource, (sf) => {\n const dataDecl = sf\n .getVariableDeclarations()\n .find((d) => d.getName() === \"data\");\n const dataInit = dataDecl?.getInitializer();\n if (\n !dataInit ||\n dataInit.getKind() !== SyntaxKind.ObjectLiteralExpression\n ) {\n return { wasAdded: false };\n }\n\n const obj = dataInit.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const navProp = obj.getProperty(\"navUser\");\n if (!navProp || navProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return { wasAdded: false };\n }\n\n const init = navProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n return { wasAdded: false };\n }\n\n const arr = init.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n const exists = arr.getElements().some((el) => {\n if (el.getKind() !== SyntaxKind.ObjectLiteralExpression) return false;\n const o = el.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const titleProp = o.getProperty(\"title\");\n if (!titleProp || titleProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return false;\n }\n const value = titleProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n return (\n value?.getKind() === SyntaxKind.StringLiteral &&\n (value as StringLiteral).getLiteralText() === title\n );\n });\n\n if (exists) return { wasAdded: false };\n\n ensureImports(sf, [\n { defaultImport: icon, moduleSpecifier: iconImportPath },\n ]);\n arr.addElement(newNavItemSnippet);\n formatLikeSource(sf);\n return { wasAdded: true };\n });\n\n return { source, wasAdded: result.wasAdded };\n}\n\n/**\n * Remove the entry with the given `title` from the `data.navUser` array in a\n * Svelte component's script body. Also removes the icon import if supplied and\n * no other navUser entry references it. Idempotent: no-op if the entry or\n * navUser structure is missing.\n */\nexport function removeNavItemFromScript(\n scriptSource: string,\n title: string,\n iconImportPath?: string,\n): { source: string; wasRemoved: boolean } {\n const { source, result } = withInMemoryScript(scriptSource, (sf) => {\n const dataDecl = sf\n .getVariableDeclarations()\n .find((d) => d.getName() === \"data\");\n const dataInit = dataDecl?.getInitializer();\n if (\n !dataInit ||\n dataInit.getKind() !== SyntaxKind.ObjectLiteralExpression\n ) {\n return { wasRemoved: false };\n }\n\n const obj = dataInit.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const navProp = obj.getProperty(\"navUser\");\n if (!navProp || navProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return { wasRemoved: false };\n }\n\n const init = navProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n return { wasRemoved: false };\n }\n\n const arr = init.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n const elements = arr.getElements();\n const index = elements.findIndex((el) => {\n if (el.getKind() !== SyntaxKind.ObjectLiteralExpression) return false;\n const o = el.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const titleProp = o.getProperty(\"title\");\n if (!titleProp || titleProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return false;\n }\n const value = titleProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n return (\n value?.getKind() === SyntaxKind.StringLiteral &&\n (value as StringLiteral).getLiteralText() === title\n );\n });\n\n if (index === -1) return { wasRemoved: false };\n\n arr.removeElement(index);\n\n if (iconImportPath) {\n const importDecl = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === iconImportPath);\n if (importDecl) {\n const importName = importDecl.getDefaultImport()?.getText();\n const stillUsed =\n importName &&\n sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === importName &&\n id.getParent()?.getKind() !== SyntaxKind.ImportClause &&\n id.getParent()?.getKind() !== SyntaxKind.ImportSpecifier,\n );\n if (!stillUsed) {\n importDecl.remove();\n }\n }\n }\n\n formatLikeSource(sf);\n return { wasRemoved: true };\n });\n\n return { source, wasRemoved: result.wasRemoved };\n}\n"],"mappings":";;AAmBA,SAASA,EACP,GACA,GACS;CACT,IAAMC,IAAYC,EAAK,wBAAwB;CAC/C,OAAO,OAAOC,KAAU,WAAWF,MAAcE,IAAQA,EAAMF,CAAS;AAC1E;AAeA,SAAgBG,EAAa,GAAwB;CACnD,IAAIC,IAAS;CACb,KAAK,IAAMC,KAAQC,EAAO,MAAM,IAAI,GAAG;EACrC,IAAID,EAAK,WAAW,GAAI,GAAG,OAAO;EAClC,IAAME,IAAQF,EAAK,MAAM,WAAW,CAAC,GAAG,EAAE,CAAC,UAAU;EACrD,A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G,QAAQ,MAAM6E,KACjB7E,EAAG,UAAU,CAAC,EAAE,QAAQ,MAAMD,EAAW,gBACzCC,EAAG,UAAU,CAAC,EAAE,QAAQ,MAAMD,EAAW,eAC7C,KAEF6E,EAAW,OAAO;GAEtB;EACF;EAGA,OADAtG,EAAiBE,CAAE,GACZ,EAAE,YAAY,GAAK;CAC5B,CAAC;CAED,OAAO;EAAE;EAAQ,YAAYW,EAAO;CAAW;AACjD"}
|
|
1
|
+
{"version":3,"file":"ts-morph-helpers-CHI9wAil.js","names":["importsModule","specifier","decl","match","detectIndent","spaces","line","source","width","formatLikeSource","indent","sf","size","commonIndent","common","lead","i","withInMemoryScript","project","Project","QuoteKind","dedented","result","fn","out","lines","ensureImports","spec","imports","d","structure","removeImportByModuleSpecifier","moduleSpecifier","isReferenced","SyntaxKind","id","local","kind","removeNamedImportIfUnused","ni","name","named","rest","pruneUnusedImports","removed","moduleSpecifiers","m","defaultImport","namespaceImport","ensureNamedImport","existing","typeOnly","isCommentNode","node","newlines","text","siblingsOf","parent","statement","Node","commentsAbove","siblings","comments","cursor","removeAttachedComments","spacing","spacingAround","doc","comment","removeStatementWithComments","next","first","prev","setOff","isEffectivelyEmpty","s","ensureBlankLineAfterImports","last","propsDeclaration","propsBinding","ensurePropsBinding","binding","elements","texts","removePropsBindingIfUnused","reads","markup","expression","element","kept","removeUnusedBindingElement","nameNode","pattern","owner","removeTopLevelStatementByIdentifier","addNavItemToScript","newNavItemSnippet","title","url","icon","scriptSource","dataInit","navProp","init","arr","el","titleProp","value","iconImportPath","removeNavItemFromScript","index","importDecl","importName"],"sources":["../../src/runtime/ts-morph-helpers.ts"],"sourcesContent":["import {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type ImportDeclarationStructure,\n type OptionalKind,\n type SourceFile,\n type Statement,\n type StringLiteral,\n} from \"ts-morph\";\n\n/**\n * A module specifier, or a test for one. Disable modifiers pass\n * `libModule(\"negotiate\")` so `#lib/negotiate.js` and the alias a project\n * from before SvelteKit 3 imports it by both match.\n */\nexport type ModuleMatch = string | ((specifier: string) => boolean);\n\nfunction importsModule(\n decl: { getModuleSpecifierValue(): string },\n match: ModuleMatch,\n): boolean {\n const specifier = decl.getModuleSpecifierValue();\n return typeof match === \"string\" ? specifier === match : match(specifier);\n}\n\nexport interface ImportSpec {\n defaultImport?: string;\n namespaceImport?: string;\n namedImports?: string[];\n moduleSpecifier: string;\n}\n\n/**\n * The indentation unit a source uses: a tab, or that many spaces. Read from\n * the shallowest indented line; a lone leading space is a comment\n * continuation, not an indent. Tabs when nothing is indented, which is what\n * `sv create` and vela's templates use.\n */\nexport function detectIndent(source: string): string {\n let spaces = 0;\n for (const line of source.split(\"\\n\")) {\n if (line.startsWith(\"\\t\")) return \"\\t\";\n const width = line.match(/^ +(?=\\S)/)?.[0].length ?? 0;\n if (width >= 2 && (spaces === 0 || width < spaces)) spaces = width;\n }\n return spaces === 0 ? \"\\t\" : \" \".repeat(spaces);\n}\n\n/**\n * `formatText()` in the file's own indentation. ts-morph's default is four\n * spaces, which rewrote every line of a tab-indented config to change one; a\n * project without prettier has nothing to put that back.\n */\nexport function formatLikeSource(sf: SourceFile): void {\n const indent = detectIndent(sf.getFullText());\n const size = indent === \"\\t\" ? 4 : indent.length;\n sf.formatText({\n convertTabsToSpaces: indent !== \"\\t\",\n indentSize: size,\n tabSize: size,\n });\n}\n\n/** The whitespace every non-blank line starts with. */\nfunction commonIndent(source: string): string {\n let common: string | null = null;\n for (const line of source.split(\"\\n\")) {\n if (line.trim() === \"\") continue;\n const lead = line.match(/^[\\t ]*/)![0];\n if (common === null) {\n common = lead;\n continue;\n }\n let i = 0;\n while (i < common.length && i < lead.length && common[i] === lead[i]) i++;\n common = common.slice(0, i);\n }\n return common ?? \"\";\n}\n\n/**\n * Run a function with an in-memory ts-morph SourceFile and return the resulting\n * source plus whatever the callback returned.\n *\n * A `<script>` body is indented one level as a whole, which ts-morph knows\n * nothing about: a statement it adds lands at column zero beside indented\n * neighbours. The shared indent is taken off first and put back afterwards,\n * so additions come out level with what was there.\n */\nexport function withInMemoryScript<T>(\n source: string,\n fn: (sf: SourceFile) => T,\n): { source: string; result: T } {\n const project = new Project({\n useInMemoryFileSystem: true,\n skipFileDependencyResolution: true,\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const indent = commonIndent(source);\n const dedented = indent\n ? source\n .split(\"\\n\")\n .map((line) =>\n line.startsWith(indent) ? line.slice(indent.length) : line,\n )\n .join(\"\\n\")\n : source;\n const sf = project.createSourceFile(\"script.ts\", dedented, {\n overwrite: true,\n });\n const result = fn(sf);\n const out = sf.getFullText();\n if (!indent) return { source: out, result };\n if (out === dedented) return { source, result };\n const lines = out.split(\"\\n\");\n const reindented = lines\n .map((line, i) =>\n // The last line is the whitespace before `</script>`, never a statement.\n line.trim() === \"\" || i === lines.length - 1 ? line : indent + line,\n )\n .join(\"\\n\");\n return { source: reindented, result };\n}\n\n/** Add the given imports to the source file, skipping any whose module specifier already exists. */\nexport function ensureImports(sf: SourceFile, imports: ImportSpec[]): void {\n for (const spec of imports) {\n const existing = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === spec.moduleSpecifier);\n if (existing) continue;\n\n const structure: OptionalKind<ImportDeclarationStructure> = {\n moduleSpecifier: spec.moduleSpecifier,\n };\n if (spec.defaultImport) structure.defaultImport = spec.defaultImport;\n if (spec.namespaceImport) structure.namespaceImport = spec.namespaceImport;\n if (spec.namedImports) structure.namedImports = spec.namedImports;\n sf.addImportDeclaration(structure);\n }\n}\n\n/** Remove the import declaration for the given module specifier, if present. */\nexport function removeImportByModuleSpecifier(\n sf: SourceFile,\n moduleSpecifier: ModuleMatch,\n): { wasRemoved: boolean } {\n const decl = sf\n .getImportDeclarations()\n .find((d) => importsModule(d, moduleSpecifier));\n if (!decl) return { wasRemoved: false };\n decl.remove();\n return { wasRemoved: true };\n}\n\n/**\n * Whether `local` is used anywhere other than the import that binds it.\n * Conservative: a same-named property counts, which only ever keeps an import.\n */\nexport function isReferenced(sf: SourceFile, local: string): boolean {\n return sf.getDescendantsOfKind(SyntaxKind.Identifier).some((id) => {\n if (id.getText() !== local) return false;\n const kind = id.getParent()?.getKind();\n return (\n kind !== SyntaxKind.ImportSpecifier &&\n kind !== SyntaxKind.ImportClause &&\n kind !== SyntaxKind.NamespaceImport\n );\n });\n}\n\n/**\n * Drop `name` from the import of `moduleSpecifier` once nothing else in the\n * file references it; the whole declaration goes when `name` was its only\n * import. For unwrapping `sequence(...)` and the like after a revert. An\n * aliased import (`sequence as seq`) is checked by its local name.\n */\nexport function removeNamedImportIfUnused(\n sf: SourceFile,\n moduleSpecifier: ModuleMatch,\n name: string,\n): { wasRemoved: boolean } {\n const decl = sf\n .getImportDeclarations()\n .find(\n (d) =>\n importsModule(d, moduleSpecifier) &&\n d.getNamedImports().some((ni) => ni.getName() === name),\n );\n if (!decl) return { wasRemoved: false };\n\n const named = decl.getNamedImports().find((ni) => ni.getName() === name);\n if (!named) return { wasRemoved: false };\n\n const local = named.getAliasNode()?.getText() ?? name;\n if (isReferenced(sf, local)) return { wasRemoved: false };\n\n if (decl.getNamedImports().length === 1 && !decl.getDefaultImport()) {\n decl.remove();\n } else {\n named.remove();\n // `import { sequence, type Handle }` less `sequence` reads as\n // `import type { Handle }`, the way it was before `sequence` joined it.\n const rest = decl.getNamedImports();\n if (!decl.getDefaultImport() && rest.every((ni) => ni.isTypeOnly())) {\n for (const ni of rest) ni.setIsTypeOnly(false);\n decl.setIsTypeOnly(true);\n }\n }\n return { wasRemoved: true };\n}\n\n/**\n * Drop every binding imported from `moduleSpecifiers` that nothing references\n * any more, and the declaration once it binds nothing. Side-effect imports\n * (`import 'x'`) bind nothing to begin with and are left alone.\n */\nexport function pruneUnusedImports(\n sf: SourceFile,\n moduleSpecifiers: ModuleMatch[],\n): { removed: string[] } {\n const removed: string[] = [];\n for (const decl of sf.getImportDeclarations()) {\n if (!moduleSpecifiers.some((m) => importsModule(decl, m))) continue;\n if (!decl.getImportClause()) continue;\n\n for (const named of decl.getNamedImports()) {\n const local = named.getAliasNode()?.getText() ?? named.getName();\n if (isReferenced(sf, local)) continue;\n named.remove();\n removed.push(local);\n }\n const defaultImport = decl.getDefaultImport();\n if (defaultImport && !isReferenced(sf, defaultImport.getText())) {\n removed.push(defaultImport.getText());\n decl.removeDefaultImport();\n }\n const namespaceImport = decl.getNamespaceImport();\n if (namespaceImport && !isReferenced(sf, namespaceImport.getText())) {\n removed.push(namespaceImport.getText());\n decl.removeNamespaceImport();\n }\n\n if (\n decl.getNamedImports().length === 0 &&\n !decl.getDefaultImport() &&\n !decl.getNamespaceImport()\n ) {\n decl.remove();\n }\n }\n return { removed };\n}\n\n/**\n * Import `name` from `moduleSpecifier`, joining an existing import of that\n * module. A type-only name joins a value import as an inline `type`\n * specifier; an `import type` declaration already covers it.\n */\nexport function ensureNamedImport(\n sf: SourceFile,\n moduleSpecifier: string,\n name: string,\n typeOnly = false,\n): void {\n const existing = sf\n .getImportDeclarations()\n .find(\n (d) =>\n d.getModuleSpecifierValue() === moduleSpecifier &&\n !d.getNamespaceImport() &&\n (typeOnly || !d.isTypeOnly()),\n );\n if (!existing) {\n sf.addImportDeclaration({\n isTypeOnly: typeOnly,\n namedImports: [name],\n moduleSpecifier,\n });\n return;\n }\n if (existing.getNamedImports().some((ni) => ni.getName() === name)) return;\n existing.addNamedImport(\n typeOnly && !existing.isTypeOnly() ? { name, isTypeOnly: true } : name,\n );\n}\n\nfunction isCommentNode(node: Node): boolean {\n const kind = node.getKind();\n return (\n kind === SyntaxKind.SingleLineCommentTrivia ||\n kind === SyntaxKind.MultiLineCommentTrivia\n );\n}\n\nfunction newlines(text: string): number {\n return (text.match(/\\n/g) ?? []).length;\n}\n\n/**\n * The statements and comment lines beside `statement`: the file's for a\n * top-level one, the block's for one inside a function body.\n */\nfunction siblingsOf(statement: Statement): Statement[] {\n const parent = statement.getParent();\n return Node.isStatemented(parent) ? parent.getStatementsWithComments() : [];\n}\n\n/**\n * The comment lines directly above a statement, up to the first blank line.\n * ts-morph parses them as statements of their own; the JSDoc is not among\n * them, it belongs to the statement.\n */\nfunction commentsAbove(sf: SourceFile, statement: Statement): Statement[] {\n const siblings = siblingsOf(statement);\n const text = sf.getFullText();\n const comments: Statement[] = [];\n let cursor = statement.getStart(true);\n for (let i = siblings.indexOf(statement) - 1; i >= 0; i--) {\n const node = siblings[i];\n if (!isCommentNode(node)) break;\n if (newlines(text.slice(node.getEnd(), cursor)) > 1) break;\n comments.unshift(node);\n cursor = node.getStart();\n }\n return comments;\n}\n\n/**\n * Remove the JSDoc and comment lines directly above a statement, leaving the\n * statement. For a statement whose comment describes something that has just\n * been swapped out.\n */\nexport function removeAttachedComments(\n sf: SourceFile,\n statement: Statement,\n): void {\n const comments = commentsAbove(sf, statement);\n const spacing = spacingAround(sf, comments[0] ?? statement);\n if (Node.isJSDocable(statement)) {\n for (const doc of statement.getJsDocs()) doc.remove();\n }\n for (const comment of comments.reverse()) comment.remove();\n spacing.restore(statement);\n}\n\n/**\n * Remove a statement, top-level or in a function body, together with its\n * JSDoc, the comment lines directly above it and a comment trailing its last\n * line. ts-morph's own `remove()` leaves the comment lines behind as orphans.\n */\nexport function removeStatementWithComments(\n sf: SourceFile,\n statement: Statement,\n): void {\n const comments = commentsAbove(sf, statement);\n const siblings = siblingsOf(statement);\n const next = siblings[siblings.indexOf(statement) + 1];\n const spacing = spacingAround(sf, comments[0] ?? statement);\n statement.remove();\n for (const comment of comments.reverse()) comment.remove();\n if (next) spacing.restore(next);\n}\n\n/**\n * ts-morph takes the blank line before a removed statement or comment with\n * it. Note whether `first` (the start of what is about to go) was set off by\n * one, so `restore` can put it back before whatever follows.\n */\nfunction spacingAround(sf: SourceFile, first: Statement) {\n const siblings = siblingsOf(first);\n const prev = siblings[siblings.indexOf(first) - 1];\n const setOff =\n prev !== undefined &&\n newlines(sf.getFullText().slice(prev.getEnd(), first.getStart(true))) > 1;\n return {\n restore(next: Statement) {\n if (!setOff || !prev) return;\n const gap = sf.getFullText().slice(prev.getEnd(), next.getStart(true));\n if (newlines(gap) < 2) sf.insertText(prev.getEnd(), \"\\n\");\n },\n };\n}\n\n/**\n * True when the file has no statements left: only comments and whitespace,\n * or nothing at all. A revert that empties a file it once created reports\n * the file as a delete instead.\n */\nexport function isEffectivelyEmpty(sf: SourceFile): boolean {\n return sf.compilerNode.statements.every(\n (s) => s.kind === SyntaxKind.EmptyStatement,\n );\n}\n\n/**\n * Keep one blank line between the import block and what follows. Removing\n * statements right after the imports takes the separating blank line with\n * them, and prettier preserves whichever spacing it finds.\n */\nexport function ensureBlankLineAfterImports(sf: SourceFile): void {\n const imports = sf.getImportDeclarations();\n const last = imports[imports.length - 1];\n const next = last?.getNextSibling();\n if (!last || !next) return;\n // Up to the next statement's JSDoc, whose own newlines are no blank line.\n const between = sf.getFullText().slice(last.getEnd(), next.getStart(true));\n if ((between.match(/\\n/g) ?? []).length >= 2) return;\n sf.insertText(last.getEnd(), \"\\n\");\n}\n\n/** A component's `let { ... } = $props()` declaration, if it destructures. */\nfunction propsDeclaration(sf: SourceFile) {\n return sf\n .getVariableDeclarations()\n .find(\n (decl) =>\n decl.getInitializer()?.getText() === \"$props()\" &&\n Node.isObjectBindingPattern(decl.getNameNode()),\n );\n}\n\n/** The `{ ... }` of a component's `let { ... } = $props()`, if it has one. */\nfunction propsBinding(sf: SourceFile) {\n return propsDeclaration(sf)\n ?.getNameNode()\n .asKind(SyntaxKind.ObjectBindingPattern);\n}\n\n/**\n * Make sure a Svelte component's `$props()` destructures `name`, for markup a\n * modifier inserts that reads it. Adds a `$props()` declaration when the\n * component has none.\n */\nexport function ensurePropsBinding(sf: SourceFile, name: string): void {\n const binding = propsBinding(sf);\n if (!binding) {\n sf.addStatements(`let { ${name} } = $props();`);\n return;\n }\n const elements = binding.getElements();\n if (elements.some((e) => e.getName() === name)) return;\n const texts = elements.map((e) => e.getText());\n const rest = elements.findIndex((e) => e.getDotDotDotToken());\n texts.splice(rest === -1 ? texts.length : rest, 0, name);\n binding.replaceWithText(`{ ${texts.join(\", \")} }`);\n}\n\n/**\n * Drop `name` from a Svelte component's `$props()` once neither the script\n * nor `markup` reads it, undoing `ensurePropsBinding`. The declaration stays\n * even when it empties, as `let {} = $props()` is harmless.\n */\nexport function removePropsBindingIfUnused(\n sf: SourceFile,\n name: string,\n markup: string,\n): void {\n // Only expressions read it: `{data.user}`, `{data}`, `x={data.y}`. A bare\n // word match would also catch `data-role` attributes and body text.\n const reads = new RegExp(`(?<![\\\\w$.])${name}(?![\\\\w$])`);\n const expressions =\n markup.replace(/<style[\\s\\S]*?<\\/style>/g, \"\").match(/\\{[^{}]*\\}/g) ?? [];\n if (expressions.some((expression) => reads.test(expression))) return;\n const decl = propsDeclaration(sf);\n const binding = propsBinding(sf);\n const element = binding\n ?.getElements()\n .find((e) => e.getName() === name && !e.getPropertyNameNode());\n if (!decl || !binding || !element) return;\n // Outside the declaration itself, whose type may name the prop too.\n const usedInScript = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === name && !decl.containsRange(id.getPos(), id.getEnd()),\n );\n if (usedInScript) return;\n const kept = binding\n .getElements()\n .filter((e) => e !== element)\n .map((e) => e.getText());\n binding.replaceWithText(`{ ${kept.join(\", \")} }`);\n}\n\n/**\n * Drop a destructured `name` (as in `({ locals, url })`) that nothing in the\n * file reads any more, for reverting an edit that was its last use. A\n * parameter left as a bare `{}` goes, as does a `const {} = ...` statement.\n * Conservative: any other identifier spelled `name` keeps it.\n */\nexport function removeUnusedBindingElement(sf: SourceFile, name: string): void {\n const element = sf\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .find(\n (e) =>\n e.getName() === name &&\n !e.getPropertyNameNode() &&\n !e.getDotDotDotToken(),\n );\n if (!element) return;\n const nameNode = element.getNameNode();\n const referenced = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === name && id !== nameNode);\n if (referenced) return;\n\n const pattern = element.getParentIfKindOrThrow(\n SyntaxKind.ObjectBindingPattern,\n );\n const kept = pattern\n .getElements()\n .filter((e) => e !== element)\n .map((e) => e.getText());\n const owner = pattern.getParent();\n if (kept.length === 0 && Node.isParameterDeclaration(owner)) {\n owner.remove();\n } else if (kept.length === 0 && Node.isVariableDeclaration(owner)) {\n owner.getVariableStatement()?.remove();\n } else {\n pattern.replaceWithText(`{ ${kept.join(\", \")} }`);\n }\n}\n\n/**\n * Remove a top-level function or variable declaration by name, if present.\n * In a statement that declares several variables only `name`'s declarator\n * goes; the statement goes with its last one.\n */\nexport function removeTopLevelStatementByIdentifier(\n sf: SourceFile,\n name: string,\n): { wasRemoved: boolean } {\n const fn = sf.getFunction(name);\n if (fn) {\n fn.remove();\n return { wasRemoved: true };\n }\n const decl = sf\n .getVariableStatements()\n .flatMap((s) => s.getDeclarations())\n .find((d) => d.getName() === name);\n if (decl) {\n decl.remove();\n return { wasRemoved: true };\n }\n return { wasRemoved: false };\n}\n\n/**\n * Add an item to the `data.navUser` array in a Svelte component's script body.\n * Idempotent: if an entry with the same `title` already exists, no-op.\n */\nexport function addNavItemToScript(\n scriptSource: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { source: string; wasAdded: boolean } {\n const newNavItemSnippet = `\n {\n title: '${title}',\n url: '${url}',\n icon: ${icon}\n }\n `.trim();\n\n const { source, result } = withInMemoryScript(scriptSource, (sf) => {\n const dataDecl = sf\n .getVariableDeclarations()\n .find((d) => d.getName() === \"data\");\n const dataInit = dataDecl?.getInitializer();\n if (\n !dataInit ||\n dataInit.getKind() !== SyntaxKind.ObjectLiteralExpression\n ) {\n return { wasAdded: false };\n }\n\n const obj = dataInit.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const navProp = obj.getProperty(\"navUser\");\n if (!navProp || navProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return { wasAdded: false };\n }\n\n const init = navProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n return { wasAdded: false };\n }\n\n const arr = init.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n const exists = arr.getElements().some((el) => {\n if (el.getKind() !== SyntaxKind.ObjectLiteralExpression) return false;\n const o = el.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const titleProp = o.getProperty(\"title\");\n if (!titleProp || titleProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return false;\n }\n const value = titleProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n return (\n value?.getKind() === SyntaxKind.StringLiteral &&\n (value as StringLiteral).getLiteralText() === title\n );\n });\n\n if (exists) return { wasAdded: false };\n\n ensureImports(sf, [\n { defaultImport: icon, moduleSpecifier: iconImportPath },\n ]);\n arr.addElement(newNavItemSnippet);\n formatLikeSource(sf);\n return { wasAdded: true };\n });\n\n return { source, wasAdded: result.wasAdded };\n}\n\n/**\n * Remove the entry with the given `title` from the `data.navUser` array in a\n * Svelte component's script body. Also removes the icon import if supplied and\n * no other navUser entry references it. Idempotent: no-op if the entry or\n * navUser structure is missing.\n */\nexport function removeNavItemFromScript(\n scriptSource: string,\n title: string,\n iconImportPath?: string,\n): { source: string; wasRemoved: boolean } {\n const { source, result } = withInMemoryScript(scriptSource, (sf) => {\n const dataDecl = sf\n .getVariableDeclarations()\n .find((d) => d.getName() === \"data\");\n const dataInit = dataDecl?.getInitializer();\n if (\n !dataInit ||\n dataInit.getKind() !== SyntaxKind.ObjectLiteralExpression\n ) {\n return { wasRemoved: false };\n }\n\n const obj = dataInit.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const navProp = obj.getProperty(\"navUser\");\n if (!navProp || navProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return { wasRemoved: false };\n }\n\n const init = navProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ArrayLiteralExpression) {\n return { wasRemoved: false };\n }\n\n const arr = init.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n const elements = arr.getElements();\n const index = elements.findIndex((el) => {\n if (el.getKind() !== SyntaxKind.ObjectLiteralExpression) return false;\n const o = el.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const titleProp = o.getProperty(\"title\");\n if (!titleProp || titleProp.getKind() !== SyntaxKind.PropertyAssignment) {\n return false;\n }\n const value = titleProp\n .asKindOrThrow(SyntaxKind.PropertyAssignment)\n .getInitializer();\n return (\n value?.getKind() === SyntaxKind.StringLiteral &&\n (value as StringLiteral).getLiteralText() === title\n );\n });\n\n if (index === -1) return { wasRemoved: false };\n\n arr.removeElement(index);\n\n if (iconImportPath) {\n const importDecl = sf\n .getImportDeclarations()\n .find((d) => d.getModuleSpecifierValue() === iconImportPath);\n if (importDecl) {\n const importName = importDecl.getDefaultImport()?.getText();\n const stillUsed =\n importName &&\n sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === importName &&\n id.getParent()?.getKind() !== SyntaxKind.ImportClause &&\n id.getParent()?.getKind() !== SyntaxKind.ImportSpecifier,\n );\n if (!stillUsed) {\n importDecl.remove();\n }\n }\n }\n\n formatLikeSource(sf);\n return { wasRemoved: true };\n });\n\n return { source, wasRemoved: result.wasRemoved };\n}\n"],"mappings":";;AAmBA,SAASA,EACP,GACA,GACS;CACT,IAAMC,IAAYC,EAAK,wBAAwB;CAC/C,OAAO,OAAOC,KAAU,WAAWF,MAAcE,IAAQA,EAAMF,CAAS;AAC1E;AAeA,SAAgBG,EAAa,GAAwB;CACnD,IAAIC,IAAS;CACb,KAAK,IAAMC,KAAQC,EAAO,MAAM,IAAI,GAAG;EACrC,IAAID,EAAK,WAAW,GAAI,GAAG,OAAO;EAClC,IAAME,IAAQF,EAAK,MAAM,WAAW,CAAC,GAAG,EAAE,CAAC,UAAU;EACrD,AAAIE,KAAS,MAAMH,MAAW,KAAKG,IAAQH,OAAS,IAASG;CAC/D;CACA,OAAOH,MAAW,IAAI,MAAO,IAA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