@velastack/patterns 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{_layout-kkgN0IF7.js → _layout-D-FzWqn0.js} +2 -2
- package/dist/chunks/_layout-D-FzWqn0.js.map +1 -0
- package/dist/chunks/_page-C7kGoW7_.js +6 -0
- package/dist/chunks/_page-C7kGoW7_.js.map +1 -0
- package/dist/chunks/_page-e_I-fdSR.js +6 -0
- package/dist/chunks/_page-e_I-fdSR.js.map +1 -0
- package/dist/chunks/auth-pages-B52ei-4z.js +291 -0
- package/dist/chunks/auth-pages-B52ei-4z.js.map +1 -0
- package/dist/chunks/{collections-Dz2fvKnz.js → collections-zzZ_HQxB.js} +2 -2
- package/dist/chunks/collections-zzZ_HQxB.js.map +1 -0
- package/dist/chunks/{compose-handle-D_Rz3Fzo.js → compose-handle-BDlZ7Pif.js} +2 -2
- package/dist/chunks/compose-handle-BDlZ7Pif.js.map +1 -0
- package/dist/chunks/{config-target-Dx3w6WSk.js → config-target-rHgjaA8u.js} +2 -2
- package/dist/chunks/config-target-rHgjaA8u.js.map +1 -0
- package/dist/chunks/{constants-BjyMU5s8.js → constants-Rq8SCXwH.js} +2 -2
- package/dist/chunks/constants-Rq8SCXwH.js.map +1 -0
- package/dist/chunks/dedent-Gq6Krl4n.js.map +1 -1
- package/dist/chunks/dispatch-D4TN9pdW.js +6 -0
- package/dist/chunks/dispatch-D4TN9pdW.js.map +1 -0
- package/dist/chunks/env-BPfk1VAw.js.map +1 -1
- package/dist/chunks/{env-vars-C1NUX-bf.js → env-vars-CcE6ODqC.js} +4 -4
- package/dist/chunks/env-vars-CcE6ODqC.js.map +1 -0
- package/dist/chunks/env-vars-Cr4lbMD_.js.map +1 -1
- package/dist/chunks/env-vars-De0Xs0L2.js.map +1 -1
- package/dist/chunks/env-vars-file-B_6esJW3.js.map +1 -1
- package/dist/chunks/env-vars-mnRA0hOe.js.map +1 -1
- package/dist/chunks/env.preview-uMRKT5Pc.js.map +1 -1
- package/dist/chunks/errors-DR3gF_7a.js.map +1 -1
- package/dist/chunks/{format-result-DZ8De8KY.js → format-result-BVoLVknk.js} +2 -2
- package/dist/chunks/format-result-BVoLVknk.js.map +1 -0
- package/dist/chunks/{generate-DeaBlnK6.js → generate-B6Odfk5f.js} +2 -2
- package/dist/chunks/generate-B6Odfk5f.js.map +1 -0
- package/dist/chunks/{generate-WMJo3QGZ.js → generate-Bg0E3eWm.js} +2 -2
- package/dist/chunks/generate-Bg0E3eWm.js.map +1 -0
- package/dist/chunks/{generate-Gcc8iRkZ.js → generate-CFqpRi9D.js} +3 -3
- package/dist/chunks/generate-CFqpRi9D.js.map +1 -0
- package/dist/chunks/{generate-BW3l5Fxw.js → generate-CZGHByV3.js} +2 -2
- package/dist/chunks/generate-CZGHByV3.js.map +1 -0
- package/dist/chunks/generate-DetW_gbr.js.map +1 -1
- package/dist/chunks/{generate.runtime-IlBCcXvv.js → generate.runtime-5rIc-RNL.js} +7 -7
- package/dist/chunks/generate.runtime-5rIc-RNL.js.map +1 -0
- package/dist/chunks/{generate.runtime-CA7Ofjlx.js → generate.runtime-BK3mR0Rj.js} +93 -141
- package/dist/chunks/generate.runtime-BK3mR0Rj.js.map +1 -0
- package/dist/chunks/{generate.runtime-cwvAoKoH.js → generate.runtime-BpMN5Uq-.js} +3 -3
- package/dist/chunks/generate.runtime-BpMN5Uq-.js.map +1 -0
- package/dist/chunks/{generate.runtime-DD51OSuL.js → generate.runtime-CAn1qIQ_.js} +4 -4
- package/dist/chunks/generate.runtime-CAn1qIQ_.js.map +1 -0
- package/dist/chunks/{generate.runtime-CuNhY5hn.js → generate.runtime-CEqLgLT9.js} +16 -11
- package/dist/chunks/generate.runtime-CEqLgLT9.js.map +1 -0
- package/dist/chunks/{generate.runtime-B1jVAnDI.js → generate.runtime-CK10Mum5.js} +8 -8
- package/dist/chunks/generate.runtime-CK10Mum5.js.map +1 -0
- package/dist/chunks/{generate.runtime-DqD3PW-W.js → generate.runtime-CZ46nkSL.js} +3 -3
- package/dist/chunks/generate.runtime-CZ46nkSL.js.map +1 -0
- package/dist/chunks/{generate.runtime-CslAvllQ.js → generate.runtime-CbE9RHcf.js} +5 -5
- package/dist/chunks/generate.runtime-CbE9RHcf.js.map +1 -0
- package/dist/chunks/{generate.runtime-CCr1lvo4.js → generate.runtime-CpMKXBkn.js} +7 -7
- package/dist/chunks/generate.runtime-CpMKXBkn.js.map +1 -0
- package/dist/chunks/{generate.runtime-6FXJM8hT.js → generate.runtime-CqncBFNg.js} +5 -5
- package/dist/chunks/generate.runtime-CqncBFNg.js.map +1 -0
- package/dist/chunks/generate.runtime-DG2z6kqH.js +68 -0
- package/dist/chunks/generate.runtime-DG2z6kqH.js.map +1 -0
- package/dist/chunks/{generate.runtime-C6bSvGMb.js → generate.runtime-DHHlYfTD.js} +6 -6
- package/dist/chunks/generate.runtime-DHHlYfTD.js.map +1 -0
- package/dist/chunks/generate.runtime-DJ9MVVPC.js +325 -0
- package/dist/chunks/generate.runtime-DJ9MVVPC.js.map +1 -0
- package/dist/chunks/{generate.runtime-CnPraLKv.js → generate.runtime-DVB7uuht.js} +4 -4
- package/dist/chunks/generate.runtime-DVB7uuht.js.map +1 -0
- package/dist/chunks/{generate.runtime-kvxmTlQb.js → generate.runtime-Db0HZyj3.js} +3 -3
- package/dist/chunks/{generate.runtime-kvxmTlQb.js.map → generate.runtime-Db0HZyj3.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D_sQOeQa.js → generate.runtime-Djas9UNy.js} +6 -6
- package/dist/chunks/generate.runtime-Djas9UNy.js.map +1 -0
- package/dist/chunks/{generate.runtime-Ce_rwzNa.js → generate.runtime-Dl6OQ7pe.js} +4 -4
- package/dist/chunks/generate.runtime-Dl6OQ7pe.js.map +1 -0
- package/dist/chunks/{generate.runtime-1-91UmM8.js → generate.runtime-DoZJHtZh.js} +4 -4
- package/dist/chunks/generate.runtime-DoZJHtZh.js.map +1 -0
- package/dist/chunks/generate.runtime-Dp7SsCQG.js +42 -0
- package/dist/chunks/generate.runtime-Dp7SsCQG.js.map +1 -0
- package/dist/chunks/{generate.runtime-C8zJRNYG.js → generate.runtime-E-zoeSKW.js} +5 -5
- package/dist/chunks/generate.runtime-E-zoeSKW.js.map +1 -0
- package/dist/chunks/{generate.runtime-pVLzzpUM.js → generate.runtime-EQnytCFL.js} +40 -40
- package/dist/chunks/generate.runtime-EQnytCFL.js.map +1 -0
- package/dist/chunks/generate.runtime-IWEhGhWY.js +218 -0
- package/dist/chunks/generate.runtime-IWEhGhWY.js.map +1 -0
- package/dist/chunks/{generate.runtime-CYagyR5c.js → generate.runtime-a3R4hqFy.js} +6 -6
- package/dist/chunks/generate.runtime-a3R4hqFy.js.map +1 -0
- package/dist/chunks/{generate.runtime-zJpEufTc.js → generate.runtime-aQnBmH8D.js} +9 -9
- package/dist/chunks/generate.runtime-aQnBmH8D.js.map +1 -0
- package/dist/chunks/{generate.runtime-Dtgw9IQO.js → generate.runtime-axm9wcQv.js} +5 -5
- package/dist/chunks/generate.runtime-axm9wcQv.js.map +1 -0
- package/dist/chunks/{generate.runtime-DHBRyMAq.js → generate.runtime-hTKzxH2M.js} +5 -5
- package/dist/chunks/generate.runtime-hTKzxH2M.js.map +1 -0
- package/dist/chunks/{generate.runtime-BA3tDKnn.js → generate.runtime-kciwaXxh.js} +5 -5
- package/dist/chunks/generate.runtime-kciwaXxh.js.map +1 -0
- package/dist/chunks/{generate.runtime-B_UVGa3q.js → generate.runtime-koQxLywh.js} +5 -5
- package/dist/chunks/generate.runtime-koQxLywh.js.map +1 -0
- package/dist/chunks/{generate.runtime-BXkZob1O.js → generate.runtime-rs1ZOIET.js} +6 -6
- package/dist/chunks/{generate.runtime-BXkZob1O.js.map → generate.runtime-rs1ZOIET.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DV3WmZtb.js → generate.runtime-uLUiPgqx.js} +6 -6
- package/dist/chunks/generate.runtime-uLUiPgqx.js.map +1 -0
- package/dist/chunks/lib-specifier-Cngo1zF_.js.map +1 -1
- package/dist/chunks/logger-CQONztPm.js.map +1 -1
- package/dist/chunks/{modify-file-BlDeeurK.js → modify-file-DK-tCH9k.js} +3 -3
- package/dist/chunks/modify-file-DK-tCH9k.js.map +1 -0
- package/dist/chunks/modify-nav-user-BLyrW2sK.js +71 -0
- package/dist/chunks/modify-nav-user-BLyrW2sK.js.map +1 -0
- package/dist/chunks/{modify-svelte-config-remote-p0TfVzxm.js → modify-svelte-config-remote-DhuRX4FI.js} +2 -2
- package/dist/chunks/modify-svelte-config-remote-DhuRX4FI.js.map +1 -0
- package/dist/chunks/modify-user-signup-BbqTiUuA.js +54 -0
- package/dist/chunks/modify-user-signup-BbqTiUuA.js.map +1 -0
- package/dist/chunks/modify-utils-Cw-on_cL.js.map +1 -1
- package/dist/chunks/package-imports-Bbw3iMPg.js.map +1 -1
- package/dist/chunks/pocketbase-C5GS-Dh5.js.map +1 -1
- package/dist/chunks/{pocketbase-Dry6ry17.js → pocketbase-CgwbH1gI.js} +2 -2
- package/dist/chunks/pocketbase-CgwbH1gI.js.map +1 -0
- package/dist/chunks/pocketbase-DpudAAmd.js.map +1 -1
- package/dist/chunks/providers-BHR6-XZ7.js.map +1 -1
- package/dist/chunks/{shared-CZC4d7Uj.js → shared-Cc_ns5-y.js} +2 -2
- package/dist/chunks/shared-Cc_ns5-y.js.map +1 -0
- package/dist/chunks/{site-BwCA18Sv.js → site-lj0CDdQ1.js} +2 -2
- package/dist/chunks/site-lj0CDdQ1.js.map +1 -0
- package/dist/chunks/svelte-file-B3RfgVdt.js.map +1 -1
- package/dist/chunks/{table-core-AjBpYi-y.js → table-core-DhDqT03G.js} +2 -2
- package/dist/chunks/table-core-DhDqT03G.js.map +1 -0
- package/dist/chunks/{taggedTemplateLiteral-Dx0fjWiw.js → taggedTemplateLiteral-CswN2AAa.js} +1 -1
- package/dist/chunks/{test-setup-DEmWd9Ul.js → test-setup-B9fQ5L_-.js} +5 -5
- package/dist/chunks/test-setup-B9fQ5L_-.js.map +1 -0
- package/dist/chunks/{ts-morph-helpers-CDW4lhox.js → ts-morph-helpers-Bepc-Es2.js} +27 -23
- package/dist/chunks/ts-morph-helpers-Bepc-Es2.js.map +1 -0
- package/dist/chunks/{ui-X698F10c.js → ui-CuCsupFq.js} +3 -3
- package/dist/chunks/ui-CuCsupFq.js.map +1 -0
- package/dist/chunks/ui-DD4NltyN.js.map +1 -1
- package/dist/chunks/{unmodify-load-CyGzC1Hu.js → unmodify-load-Bl5vXQiL.js} +2 -2
- package/dist/chunks/unmodify-load-Bl5vXQiL.js.map +1 -0
- package/dist/chunks/util-BLYliuUK.js.map +1 -1
- package/dist/chunks/whatsapp-CguKGTtw.js +105 -0
- package/dist/chunks/whatsapp-CguKGTtw.js.map +1 -0
- package/dist/chunks/{write-result-B68lvI57.js → write-result-DiZsCS_y.js} +5 -5
- package/dist/chunks/write-result-DiZsCS_y.js.map +1 -0
- package/dist/index.d.ts +133 -1
- package/dist/index.js +2240 -2005
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunks/_layout-kkgN0IF7.js.map +0 -1
- package/dist/chunks/collections-Dz2fvKnz.js.map +0 -1
- package/dist/chunks/compose-handle-D_Rz3Fzo.js.map +0 -1
- package/dist/chunks/config-target-Dx3w6WSk.js.map +0 -1
- package/dist/chunks/constants-BjyMU5s8.js.map +0 -1
- package/dist/chunks/dispatch-CXOXPLFk.js +0 -6
- package/dist/chunks/dispatch-CXOXPLFk.js.map +0 -1
- package/dist/chunks/env-vars-C1NUX-bf.js.map +0 -1
- package/dist/chunks/format-result-DZ8De8KY.js.map +0 -1
- package/dist/chunks/generate-BW3l5Fxw.js.map +0 -1
- package/dist/chunks/generate-DeaBlnK6.js.map +0 -1
- package/dist/chunks/generate-Gcc8iRkZ.js.map +0 -1
- package/dist/chunks/generate-WMJo3QGZ.js.map +0 -1
- package/dist/chunks/generate.runtime-1-91UmM8.js.map +0 -1
- package/dist/chunks/generate.runtime-6FXJM8hT.js.map +0 -1
- package/dist/chunks/generate.runtime-B1jVAnDI.js.map +0 -1
- package/dist/chunks/generate.runtime-BA3tDKnn.js.map +0 -1
- package/dist/chunks/generate.runtime-BO778G0r.js +0 -188
- package/dist/chunks/generate.runtime-BO778G0r.js.map +0 -1
- package/dist/chunks/generate.runtime-B_UVGa3q.js.map +0 -1
- package/dist/chunks/generate.runtime-C6bSvGMb.js.map +0 -1
- package/dist/chunks/generate.runtime-C8zJRNYG.js.map +0 -1
- package/dist/chunks/generate.runtime-CA7Ofjlx.js.map +0 -1
- package/dist/chunks/generate.runtime-CCr1lvo4.js.map +0 -1
- package/dist/chunks/generate.runtime-CYagyR5c.js.map +0 -1
- package/dist/chunks/generate.runtime-Ce_rwzNa.js.map +0 -1
- package/dist/chunks/generate.runtime-CexC1Oky.js +0 -269
- package/dist/chunks/generate.runtime-CexC1Oky.js.map +0 -1
- package/dist/chunks/generate.runtime-CnPraLKv.js.map +0 -1
- package/dist/chunks/generate.runtime-CslAvllQ.js.map +0 -1
- package/dist/chunks/generate.runtime-CuNhY5hn.js.map +0 -1
- package/dist/chunks/generate.runtime-DD51OSuL.js.map +0 -1
- package/dist/chunks/generate.runtime-DHBRyMAq.js.map +0 -1
- package/dist/chunks/generate.runtime-DV3WmZtb.js.map +0 -1
- package/dist/chunks/generate.runtime-D_sQOeQa.js.map +0 -1
- package/dist/chunks/generate.runtime-DqD3PW-W.js.map +0 -1
- package/dist/chunks/generate.runtime-Dtgw9IQO.js.map +0 -1
- package/dist/chunks/generate.runtime-IlBCcXvv.js.map +0 -1
- package/dist/chunks/generate.runtime-cwvAoKoH.js.map +0 -1
- package/dist/chunks/generate.runtime-pVLzzpUM.js.map +0 -1
- package/dist/chunks/generate.runtime-zJpEufTc.js.map +0 -1
- package/dist/chunks/modify-file-BlDeeurK.js.map +0 -1
- package/dist/chunks/modify-svelte-config-remote-p0TfVzxm.js.map +0 -1
- package/dist/chunks/nav-user-BRIHOOpG.js +0 -6
- package/dist/chunks/nav-user-BRIHOOpG.js.map +0 -1
- package/dist/chunks/pocketbase-Dry6ry17.js.map +0 -1
- package/dist/chunks/shared-CZC4d7Uj.js.map +0 -1
- package/dist/chunks/site-BwCA18Sv.js.map +0 -1
- package/dist/chunks/table-core-AjBpYi-y.js.map +0 -1
- package/dist/chunks/test-setup-DEmWd9Ul.js.map +0 -1
- package/dist/chunks/ts-morph-helpers-CDW4lhox.js.map +0 -1
- package/dist/chunks/ui-X698F10c.js.map +0 -1
- package/dist/chunks/unmodify-load-CyGzC1Hu.js.map +0 -1
- package/dist/chunks/write-result-B68lvI57.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@velastack/patterns",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.2",
|
|
4
4
|
"description": "Registry of VelaStack patterns: generators and modifications applied to SvelteKit projects by the VelaStack CLI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
|
@@ -98,7 +98,7 @@
|
|
|
98
98
|
"@types/node": "^26.5.1",
|
|
99
99
|
"@types/pluralize": "^0.0.33",
|
|
100
100
|
"@velastack/kit": "^0.4.0",
|
|
101
|
-
"@velastack/pocketbase": "^0.4.
|
|
101
|
+
"@velastack/pocketbase": "^0.4.2",
|
|
102
102
|
"@velastack/pocketbase-codegen": "^0.1.0",
|
|
103
103
|
"change-case": "^5.4.4",
|
|
104
104
|
"cross-spawn": "^7.0.6",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"_layout-kkgN0IF7.js","names":[],"sources":["../../src/patterns/enable/i18n/modifies/package-imports.ts","../../src/patterns/enable/i18n/modifies/+layout.ts"],"sourcesContent":["import {\n ensurePackageImports,\n type PackageJsonEditResult,\n} from \"../../../../runtime/package-imports\";\n\n/**\n * The package.json `imports` entry the app's `#locales/*.js` specifiers\n * resolve through. wuchale writes its loaders and data to `src/locales`;\n * SvelteKit 3 deprecates `alias`, so the directory is mapped the way `#lib`\n * is. wuchale's own generated imports are relative and never go through it.\n */\nexport const LOCALES_IMPORTS = { \"#locales/*\": \"./src/locales/*\" };\n\n/** Add `#locales/*` to package.json `imports`; a different value already there is reported. */\nexport function modifyPackageImportsI18n(root: string): PackageJsonEditResult {\n return ensurePackageImports(root, LOCALES_IMPORTS);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport {\n ensureImports,\n ensureNamedImport,\n formatLikeSource,\n} from \"../../../../runtime/ts-morph-helpers\";\n\nconst IMPORT_SNIPPET = dedent`\n import { browser } from '$app/env';\n import { loadLocale } from 'wuchale/load-utils';\n\n import { getLocale } from '#locales/main.url.js';\n import '#locales/main.loader.svelte.js';\n import '#locales/js.loader.js';\n`;\n\n/** The load `disable-i18n` looks for to take it out again. */\nexport const LOAD_STATEMENT = dedent`\n export const load = async ({ url, data }) => {\n const locale = getLocale(url);\n\n if (browser) {\n await loadLocale(locale);\n }\n\n return data;\n };\n`;\n\n/** The whole file, for a project that had no root `+layout.ts`. */\nexport const LOAD_SNIPPET = `${IMPORT_SNIPPET}\\n\\n${LOAD_STATEMENT}`;\n\nconst FAILURE_HINT = [\n \"Merge the wuchale loader into your existing load function in +layout.ts:\",\n \"\",\n LOAD_SNIPPET,\n].join(\"\\n\");\n\nexport function ensureRootLayoutI18n(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n fs.mkdirSync(path.dirname(layoutPath), { recursive: true });\n fs.writeFileSync(layoutPath, LOAD_SNIPPET + \"\\n\");\n return { status: \"success\", changed: true };\n }\n\n const existing = fs.readFileSync(layoutPath, \"utf8\");\n if (existing.includes(\"loadLocale\") || existing.includes(\"translateUrl\")) {\n return { status: \"success\", changed: false };\n }\n\n if (/\\bexport\\s+(const|function)\\s+load\\b/.test(existing)) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n // No load to merge with, but the file may hold other route options\n // (`export const prerender = true`, say), so the load is added to it\n // rather than written over it.\n const project = new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n ensureNamedImport(sourceFile, \"$app/env\", \"browser\");\n ensureNamedImport(sourceFile, \"wuchale/load-utils\", \"loadLocale\");\n ensureNamedImport(sourceFile, \"#locales/main.url.js\", \"getLocale\");\n ensureImports(sourceFile, [\n { moduleSpecifier: \"#locales/main.loader.svelte.js\" },\n { moduleSpecifier: \"#locales/js.loader.js\" },\n ]);\n\n sourceFile.addStatements(`\\n${LOAD_STATEMENT}\\n`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;;;;;;AAWA,IAAa,IAAkB,EAAE,cAAc,kBAAkB;AAGjE,SAAgB,EAAyB,GAAqC;CAC5E,OAAO,EAAqB,GAAM,CAAe;AACnD;;;ACLA,IAAM,IAAiB,CAAM;;;;;;;GAUhB,IAAiB,CAAM;;;;;;;;;;GAavB,IAAe,GAAG,EAAe,MAAM,KAE9C,IAAe;CACnB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgB,EAAqB,GAAmC;CACtE,IAAI,CAAC,EAAG,WAAW,CAAU,GAG3B,OAFA,EAAG,UAAU,EAAK,QAAQ,CAAU,GAAG,EAAE,WAAW,GAAK,CAAC,GAC1D,EAAG,cAAc,GAAY,IAAe,IAAI,GACzC;EAAE,QAAQ;EAAW,SAAS;CAAK;CAG5C,IAAM,IAAW,EAAG,aAAa,GAAY,MAAM;CACnD,IAAI,EAAS,SAAS,YAAY,KAAK,EAAS,SAAS,cAAc,GACrE,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAI,uCAAuC,KAAK,CAAQ,GACtD,OAAO;EAAE,QAAQ;EAAU,SAAS;CAAa;CAUnD,IAAM,IAAa,IAJC,EAAQ;EAC1B,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAW,EAAU,OAAO;CACtD,CACmB,CAAA,CAAQ,oBAAoB,CAAU;CAazD,OAXA,EAAkB,GAAY,YAAY,SAAS,GACnD,EAAkB,GAAY,sBAAsB,YAAY,GAChE,EAAkB,GAAY,wBAAwB,WAAW,GACjE,EAAc,GAAY,CACxB,EAAE,iBAAiB,iCAAiC,GACpD,EAAE,iBAAiB,wBAAwB,CAC7C,CAAC,GAED,EAAW,cAAc,KAAK,EAAe,GAAG,GAChD,EAAiB,CAAU,GAC3B,EAAW,SAAS,GACb;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"collections-Dz2fvKnz.js","names":[],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\ninterface RelationFieldLike {\n type?: string;\n collectionId?: string;\n}\n\n/**\n * A spec may name the collection a relation points at (`stripe_customers`)\n * where PocketBase wants its id; specs read better by name, and the id is\n * only known once the target exists. Names are swapped for ids here, and a\n * value that already is an id (`_pb_users_auth_`) is left alone.\n */\nasync function resolveRelationTargets(\n pb: PocketBase,\n spec: CollectionCreateInput,\n): Promise<CollectionCreateInput> {\n const fields = (spec as { fields?: RelationFieldLike[] }).fields;\n const relations = (fields ?? []).filter(\n (field) => field.type === \"relation\" && field.collectionId,\n );\n if (relations.length === 0) return spec;\n\n const existing = await pb.collections.getFullList();\n const ids = new Set(existing.map((c) => c.id));\n const byName = new Map(existing.map((c) => [c.name, c.id]));\n if (relations.every((field) => ids.has(field.collectionId!))) return spec;\n\n return {\n ...spec,\n fields: fields!.map((field) => {\n if (field.type !== \"relation\" || !field.collectionId) return field;\n const id = byName.get(field.collectionId);\n return id && !ids.has(field.collectionId)\n ? { ...field, collectionId: id }\n : field;\n }),\n } as CollectionCreateInput;\n}\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(\n await resolveRelationTargets(pb, spec),\n );\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\nexport interface DropCollectionResult {\n dropped: boolean;\n existed: boolean;\n}\n\n/**\n * Idempotent collection drop. Returns `{ existed: false, dropped: false }` if\n * the collection is already gone, matching the idempotency contract of\n * `createCollectionIdempotent`.\n */\nexport async function dropCollectionIdempotent(\n pb: PocketBase,\n name: string,\n logger: Logger = NOOP_LOGGER,\n): Promise<DropCollectionResult> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n logger.info(`Collection \"${name}\" does not exist, skipping drop`);\n return { dropped: false, existed: false };\n }\n throw error;\n }\n await pb.collections.delete(name);\n return { dropped: true, existed: true };\n}\n\nexport interface CollectionStats {\n exists: boolean;\n rowCount: number;\n}\n\nexport async function getCollectionStats(\n pb: PocketBase,\n name: string,\n): Promise<CollectionStats> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n return { exists: false, rowCount: 0 };\n }\n throw error;\n }\n\n try {\n const result = await pb\n .collection(name)\n .getList(1, 1, { skipTotal: false });\n return { exists: true, rowCount: result.totalItems };\n } catch {\n return { exists: true, rowCount: 0 };\n }\n}\n\n/**\n * Resolve the set of collections to drop, with current row counts. Missing\n * collections are included with `exists: false, rowCount: 0` so callers can\n * display the full reversal plan even when some collections were already gone.\n */\nexport async function planCollectionDrops(\n pb: PocketBase,\n names: string[],\n): Promise<CollectionDropSpec[]> {\n const plans: CollectionDropSpec[] = [];\n for (const name of names) {\n const stats = await getCollectionStats(pb, name);\n plans.push({ name, exists: stats.exists, rowCount: stats.rowCount });\n }\n return plans;\n}\n\n/**\n * Drop each of the given collections (skipping those that are already gone)\n * and collect the `_deleted_<name>.js` migration file PocketBase emits for\n * each successful drop. Symmetric to `createCollections`.\n */\nexport async function dropCollections(\n specs: CollectionDropSpec[],\n options: Options,\n): Promise<File[]> {\n if (specs.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const spec of specs) {\n logger.info(`Dropping collection \"${spec.name}\"`);\n const { dropped } = await dropCollectionIdempotent(pb, spec.name, logger);\n if (!dropped) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(spec.name, \"deleted\", options);\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n\nexport async function createCollections(\n collections: CollectionSpec[],\n options: Options,\n): Promise<File[]> {\n if (collections.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const collection of collections) {\n logger.info(`Creating collection \"${collection.name}\"`);\n const { created } = await createCollectionIdempotent(\n pb,\n collection,\n logger,\n );\n if (!created) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n collection.name,\n \"created\",\n options,\n );\n if (!migrationFile) {\n continue;\n }\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;AA4BA,SAAS,EACP,GACS;CACT,IACE,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAGT,IAAM,IAAU,EAAM,SAAS,YAAY,KAAK;CAChD,OACE,EAAQ,SAAS,gBAAgB,KAAK,EAAQ,SAAS,gBAAgB;AAE3E;AAeA,eAAe,EACb,GACA,GACgC;CAChC,IAAM,IAAU,EAA0C,QACpD,KAAa,KAAU,CAAC,EAAA,CAAG,QAC9B,MAAU,EAAM,SAAS,cAAc,EAAM,YAChD;CACA,IAAI,EAAU,WAAW,GAAG,OAAO;CAEnC,IAAM,IAAW,MAAM,EAAG,YAAY,YAAY,GAC5C,IAAM,IAAI,IAAI,EAAS,KAAK,MAAM,EAAE,EAAE,CAAC,GACvC,IAAS,IAAI,IAAI,EAAS,KAAK,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;CAG1D,OAFI,EAAU,OAAO,MAAU,EAAI,IAAI,EAAM,YAAa,CAAC,IAAU,IAE9D;EACL,GAAG;EACH,QAAQ,EAAQ,KAAK,MAAU;GAC7B,IAAI,EAAM,SAAS,cAAc,CAAC,EAAM,cAAc,OAAO;GAC7D,IAAM,IAAK,EAAO,IAAI,EAAM,YAAY;GACxC,OAAO,KAAM,CAAC,EAAI,IAAI,EAAM,YAAY,IACpC;IAAE,GAAG;IAAO,cAAc;GAAG,IAC7B;EACN,CAAC;CACH;AACF;AAaA,eAAsB,EACpB,GACA,GACA,IAAiB,GACgB;CACjC,IAAM,IAAQ,EAA0B;CACxC,IAAI;EAIF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KAAQ,GAAO;GACxB,EAAO,KAAK,wBAAwB,EAAK,KAAK,EAAE;GAChD,IAAM,EAAE,eAAY,MAAM,EAAyB,GAAI,EAAK,MAAM,CAAM;GACxE,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EAAiB,EAAK,MAAM,WAAW,CAAO;GAC/D,KAEL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT;AAEA,eAAsB,EACpB,GACA,GACiB;CACjB,IAAI,EAAY,WAAW,GACzB,OAAO,CAAC;CAGV,IAAM,IAAqB,CAAC,GACtB,IAAS,EAAU,CAAO;CA+BhC,OA7BA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAM,KAAc,GAAa;GACpC,EAAO,KAAK,wBAAwB,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAM,EACxB,GACA,GACA,CACF;GACA,IAAI,CAAC,GAAS;GACd,MAAM,EAAe;GAErB,IAAM,IAAgB,EACpB,EAAW,MACX,WACA,CACF;GACK,KAIL,EAAW,KAAK;IACd,MAAM;IACN,UAAU,EAAiB,CAAa;IACxC,SAAS,EAAa,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEM;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"compose-handle-D_Rz3Fzo.js","names":[],"sources":["../../src/runtime/compose-handle.ts"],"sourcesContent":["import {\n Node,\n SyntaxKind,\n ts,\n type CallExpression,\n type Expression,\n type FunctionDeclaration,\n type SourceFile,\n type Statement,\n type VariableDeclaration,\n type VariableStatement,\n} from \"ts-morph\";\nimport {\n ensureBlankLineAfterImports,\n removeAttachedComments,\n removeNamedImportIfUnused,\n removeStatementWithComments,\n} from \"./ts-morph-helpers\";\n\n/**\n * Composes the server `handle` hook in `hooks.server.ts`.\n *\n * Patterns add and subtract handles in the exported `handle` without caring\n * what shape it is in: a lone expression becomes `sequence(new, old)`, a\n * `sequence(...)` gains or loses an argument, and a handle that is a function\n * is moved to a local `handleApp` so it can take part. Subtracting back to one\n * handle unwraps the `sequence` again, and puts a `handleApp` back the way it\n * was written, so enabling then disabling a pattern round-trips.\n *\n * Nothing here formats or saves: callers do, as they always have. A result of\n * `unsupported` means the file was left exactly as it was found.\n */\n\nconst KIT_HOOKS = \"@sveltejs/kit/hooks\";\nconst EXTRACTED = \"handleApp\";\n\nexport interface HandleSpec {\n /** Source text of the sequence argument: `handleWuchale`, `handlePocketbase({ ... })`. */\n expression: string;\n /** Identifier, or callee identifier, that marks this handle. Defaults to `expression`. */\n name?: string;\n /** Where it goes in the chain. */\n position?: \"first\" | \"last\";\n}\n\nexport type Unsupported =\n /** `export { handle } from '…'`, `export { x as handle }`, or `export *` with no local handle. */\n | \"re-export\"\n /** A local `handle` SvelteKit cannot see. */\n | \"not-exported\"\n /** `export const { handle } = …` */\n | \"destructured\"\n /** `export default function handle` */\n | \"default-export\"\n /** `export let handle;` */\n | \"no-initializer\"\n /** A `sequence` in scope that is not `@sveltejs/kit/hooks`'. */\n | \"foreign-sequence\"\n /** The handle has to move to `handleApp`, and the name is taken. */\n | \"name-collision\"\n /** The handle has to move to `handleApp`, and shares its statement with other declarations. */\n | \"multi-declarator\"\n /** The handle is referenced outside the composition (`dev ? a : handleX`, or inside a function handle). */\n | \"ambiguous-reference\";\n\nexport type ComposeResult =\n /** `statement` is the `handle` declaration, when there still is one. */\n | { status: \"changed\"; statement?: Statement }\n | { status: \"unchanged\"; statement?: Statement }\n | { status: \"unsupported\"; reason: Unsupported };\n\ntype Site =\n | {\n kind: \"variable\";\n decl: VariableDeclaration;\n statement: VariableStatement;\n inlineExport: boolean;\n }\n | { kind: \"function\"; fn: FunctionDeclaration; inlineExport: boolean };\n\ntype Located =\n { site: Site | null; starExport: boolean } | { unsupported: Unsupported };\n\n/** A `sequence(...)` argument with the comments that belong to it. */\ninterface Piece {\n leading: string[];\n text: string;\n trailing: string[];\n}\n\n/** How `sequence` from `@sveltejs/kit/hooks` is bound in this file, if at all. */\ninterface KitSequence {\n local: string | null;\n namespace: string | null;\n}\n\n/** Find the exported `handle`, or say why it cannot be composed. */\nfunction locate(sf: SourceFile): Located {\n let exportedBySpecifier = false;\n let starExport = false;\n\n for (const ed of sf.getExportDeclarations()) {\n const fromModule = ed.getModuleSpecifier() !== undefined;\n if (ed.isNamespaceExport()) {\n if (ed.getNamespaceExport()?.getName() === \"handle\") {\n return { unsupported: \"re-export\" };\n }\n if (fromModule) starExport = true;\n continue;\n }\n for (const spec of ed.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== \"handle\") continue;\n if (fromModule || spec.getName() !== \"handle\") {\n return { unsupported: \"re-export\" };\n }\n exportedBySpecifier = true;\n }\n }\n\n const fn = sf.getFunctions().find((f) => f.getName() === \"handle\");\n if (fn) {\n if (fn.isDefaultExport()) return { unsupported: \"default-export\" };\n if (!fn.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n return {\n site: { kind: \"function\", fn, inlineExport: fn.hasExportKeyword() },\n starExport,\n };\n }\n\n for (const statement of sf.getVariableStatements()) {\n for (const decl of statement.getDeclarations()) {\n const nameNode = decl.getNameNode();\n if (!Node.isIdentifier(nameNode)) {\n const bindsHandle = nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === \"handle\");\n if (bindsHandle) return { unsupported: \"destructured\" };\n continue;\n }\n if (nameNode.getText() !== \"handle\") continue;\n if (!statement.hasExportKeyword() && !exportedBySpecifier) {\n return { unsupported: \"not-exported\" };\n }\n if (!decl.getInitializer()) return { unsupported: \"no-initializer\" };\n return {\n site: {\n kind: \"variable\",\n decl,\n statement,\n inlineExport: statement.hasExportKeyword(),\n },\n starExport,\n };\n }\n }\n\n // `export { handle }` naming something that is not a local variable or\n // function: an import passed straight through, or a class.\n if (exportedBySpecifier) return { unsupported: \"re-export\" };\n return { site: null, starExport };\n}\n\nfunction kitSequence(sf: SourceFile): KitSequence {\n const found: KitSequence = { local: null, namespace: null };\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getModuleSpecifierValue() !== KIT_HOOKS || decl.isTypeOnly()) {\n continue;\n }\n const namespace = decl.getNamespaceImport();\n if (namespace) found.namespace = namespace.getText();\n for (const named of decl.getNamedImports()) {\n if (named.getName() !== \"sequence\" || named.isTypeOnly()) continue;\n found.local = named.getAliasNode()?.getText() ?? \"sequence\";\n }\n }\n return found;\n}\n\n/** Whether `name` is declared at the top level or imported. */\nfunction isBound(sf: SourceFile, name: string): boolean {\n for (const decl of sf.getImportDeclarations()) {\n if (decl.getDefaultImport()?.getText() === name) return true;\n if (decl.getNamespaceImport()?.getText() === name) return true;\n for (const named of decl.getNamedImports()) {\n if ((named.getAliasNode()?.getText() ?? named.getName()) === name) {\n return true;\n }\n }\n }\n if (sf.getFunction(name) || sf.getClass(name) || sf.getEnum(name)) {\n return true;\n }\n return sf.getVariableDeclarations().some((d) => {\n const nameNode = d.getNameNode();\n if (Node.isIdentifier(nameNode)) return nameNode.getText() === name;\n return nameNode\n .getDescendantsOfKind(SyntaxKind.BindingElement)\n .some((el) => el.getNameNode().getText() === name);\n });\n}\n\n/** The callee to write for a new `sequence(...)`, or null when none can be had. */\nfunction sequenceCallee(sf: SourceFile, kit: KitSequence): string | null {\n if (kit.local) return kit.local;\n if (kit.namespace) return `${kit.namespace}.sequence`;\n return isBound(sf, \"sequence\") ? null : \"sequence\";\n}\n\nfunction ensureSequenceImport(sf: SourceFile, kit: KitSequence): void {\n if (kit.local || kit.namespace) return;\n const decl = sf\n .getImportDeclarations()\n .find(\n (d) =>\n d.getModuleSpecifierValue() === KIT_HOOKS &&\n !d.isTypeOnly() &&\n !d.getNamespaceImport(),\n );\n // `import type { Handle } from '@sveltejs/kit/hooks'` takes `sequence` in:\n // `import { sequence, type Handle }`.\n const typeOnly = decl\n ? undefined\n : sf\n .getImportDeclarations()\n .find(\n (d) =>\n d.getModuleSpecifierValue() === KIT_HOOKS &&\n d.isTypeOnly() &&\n !d.getDefaultImport() &&\n !d.getNamespaceImport(),\n );\n if (decl) decl.addNamedImport(\"sequence\");\n else if (typeOnly) {\n const names = typeOnly.getNamedImports();\n typeOnly.setIsTypeOnly(false);\n for (const named of names) named.setIsTypeOnly(true);\n typeOnly.insertNamedImport(0, \"sequence\");\n } else {\n sf.addImportDeclaration({\n namedImports: [\"sequence\"],\n moduleSpecifier: KIT_HOOKS,\n });\n }\n}\n\nfunction pruneSequenceImport(sf: SourceFile): void {\n // ts-morph takes the blank line after the imports with a removed import.\n const { wasRemoved } = removeNamedImportIfUnused(sf, KIT_HOOKS, \"sequence\");\n if (wasRemoved) ensureBlankLineAfterImports(sf);\n}\n\nfunction isSequenceCall(node: Node, kit: KitSequence): node is CallExpression {\n if (!Node.isCallExpression(node)) return false;\n const callee = node.getExpression();\n if (Node.isIdentifier(callee)) return callee.getText() === kit.local;\n if (Node.isPropertyAccessExpression(callee)) {\n return (\n kit.namespace !== null &&\n callee.getExpression().getText() === kit.namespace &&\n callee.getName() === \"sequence\"\n );\n }\n return false;\n}\n\n/** Strip `( )`, `satisfies T`, `as T`, `<T>` and `!` down to the composition. */\nfunction unwrap(node: Expression): Expression {\n for (;;) {\n if (\n Node.isParenthesizedExpression(node) ||\n Node.isSatisfiesExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isTypeAssertion(node) ||\n Node.isNonNullExpression(node)\n ) {\n node = node.getExpression();\n } else {\n return node;\n }\n }\n}\n\n/** `name`, or a call of `name`: `handleWuchale`, `handlePocketbase({ ... })`. */\nfunction isHandle(node: Node, name: string): boolean {\n if (Node.isIdentifier(node)) return node.getText() === name;\n if (Node.isCallExpression(node)) {\n const callee = node.getExpression();\n return Node.isIdentifier(callee) && callee.getText() === name;\n }\n return false;\n}\n\n/** The chain of `sequence` calls down to the argument that is `name`. */\nfunction findInSequence(\n node: Node,\n name: string,\n kit: KitSequence,\n): { calls: CallExpression[]; index: number } | null {\n if (!isSequenceCall(node, kit)) return null;\n const args = node.getArguments();\n const index = args.findIndex((arg) => isHandle(arg, name));\n if (index >= 0) return { calls: [node], index };\n for (const arg of args) {\n const inner = findInSequence(arg, name, kit);\n if (inner) return { calls: [node, ...inner.calls], index: inner.index };\n }\n return null;\n}\n\nfunction references(node: Node, name: string): boolean {\n if (Node.isIdentifier(node) && node.getText() === name) return true;\n return node\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === name);\n}\n\nfunction commentTexts(text: string, ranges: ts.CommentRange[]): string[] {\n return ranges.map((r) => text.slice(r.pos, r.end));\n}\n\n/**\n * The arguments of a `sequence(...)` call, each with its comments. A comment\n * after an argument's comma on the same line is that argument's; comments on\n * the lines above an argument are its own too.\n */\nfunction pieces(call: CallExpression): Piece[] {\n const text = call.getSourceFile().getFullText();\n const args = call.getArguments();\n const openParen = call.getFirstChildByKindOrThrow(SyntaxKind.OpenParenToken);\n const closeParen = call.getLastChildByKindOrThrow(SyntaxKind.CloseParenToken);\n\n const result = args.map((arg, i): Piece => {\n let leadingFrom = openParen.getEnd();\n if (i > 0) {\n const prevComma = args[i - 1].getNextSiblingIfKind(SyntaxKind.CommaToken);\n leadingFrom = prevComma?.getEnd() ?? args[i - 1].getEnd();\n const prevTrailing = ts.getTrailingCommentRanges(text, leadingFrom);\n if (prevTrailing?.length) {\n leadingFrom = prevTrailing[prevTrailing.length - 1].end;\n }\n }\n const leading = (\n ts.getLeadingCommentRanges(text, leadingFrom) ?? []\n ).filter((r) => r.end <= arg.getStart());\n const comma = arg.getNextSiblingIfKind(SyntaxKind.CommaToken);\n const trailing =\n ts.getTrailingCommentRanges(text, comma?.getEnd() ?? arg.getEnd()) ?? [];\n return {\n leading: commentTexts(text, leading),\n text: arg.getText(),\n trailing: commentTexts(text, trailing),\n };\n });\n\n // Comments on their own lines just before `)` go with the last argument.\n const last = result[result.length - 1];\n if (last) {\n const lastArg = args[args.length - 1];\n let from =\n lastArg.getNextSiblingIfKind(SyntaxKind.CommaToken)?.getEnd() ??\n lastArg.getEnd();\n const sameLine = ts.getTrailingCommentRanges(text, from);\n if (sameLine?.length) from = sameLine[sameLine.length - 1].end;\n const dangling = (ts.getLeadingCommentRanges(text, from) ?? []).filter(\n (r) => r.end <= closeParen.getStart(),\n );\n last.trailing.push(...commentTexts(text, dangling));\n }\n return result;\n}\n\nfunction hasComments(list: Piece[]): boolean {\n return list.some((p) => p.leading.length > 0 || p.trailing.length > 0);\n}\n\nfunction renderCall(callee: string, list: Piece[], multiline: boolean): string {\n if (!multiline && !hasComments(list)) {\n return `${callee}(${list.map((p) => p.text).join(\", \")})`;\n }\n const lines = list.map((p) => {\n const leading = p.leading.map((c) => `${c}\\n`).join(\"\");\n const trailing = p.trailing.length ? ` ${p.trailing.join(\" \")}` : \"\";\n return `${leading}${p.text},${trailing}`;\n });\n return `${callee}(\\n${lines.join(\"\\n\")}\\n)`;\n}\n\n/** A lone argument taken out of a nested `sequence`: its comments go above it. */\nfunction renderAlone(piece: Piece): string {\n const comments = [...piece.leading, ...piece.trailing];\n return comments.map((c) => `${c}\\n`).join(\"\") + piece.text;\n}\n\nfunction isMultiline(call: CallExpression): boolean {\n return call\n .getArguments()\n .some((arg, i, args) =>\n i === 0\n ? false\n : arg.getStartLineNumber() !== args[i - 1].getEndLineNumber(),\n );\n}\n\nfunction rewriteSequence(call: CallExpression, list: Piece[]): Node {\n const multiline = isMultiline(call);\n return call.replaceWithText(\n renderCall(call.getExpression().getText(), list, multiline),\n );\n}\n\nfunction handleStatement(site: Site): Statement {\n return site.kind === \"function\" ? site.fn : site.statement;\n}\n\n/** The `handle` statement as it stands now; nodes go stale on every edit. */\nfunction currentStatement(sf: SourceFile): Statement | undefined {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return undefined;\n return handleStatement(located.site);\n}\n\nfunction changed(sf: SourceFile): ComposeResult {\n return { status: \"changed\", statement: currentStatement(sf) };\n}\n\nfunction unchanged(site: Site | null): ComposeResult {\n return {\n status: \"unchanged\",\n statement: site ? handleStatement(site) : undefined,\n };\n}\n\nfunction unsupported(reason: Unsupported): ComposeResult {\n return { status: \"unsupported\", reason };\n}\n\n/**\n * Take the whole `handle` out: its declarator, or its statement with the\n * comments above it, and an `export { handle }` naming it.\n */\nfunction removeWholeHandle(sf: SourceFile, site: Site): void {\n const viaSpecifier = !site.inlineExport;\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n site.decl.remove();\n } else {\n removeStatementWithComments(sf, handleStatement(site));\n }\n if (!viaSpecifier) return;\n for (const ed of sf.getExportDeclarations()) {\n if (ed.getModuleSpecifier() !== undefined) continue;\n const spec = ed.getNamedExports().find((s) => s.getName() === \"handle\");\n if (!spec) continue;\n if (ed.getNamedExports().length === 1) ed.remove();\n else spec.remove();\n }\n}\n\n/**\n * Move a handle that is a function out of the way: rename it `handleApp`,\n * un-export it, and export `sequence(...)` of it right after, so `handleApp`\n * is declared before anything reads it.\n */\nfunction extract(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n callee: string,\n kit: KitSequence,\n): ComposeResult {\n const position = spec.position ?? \"first\";\n const args =\n position === \"first\"\n ? [spec.expression, EXTRACTED]\n : [EXTRACTED, spec.expression];\n const exportKeyword = site.inlineExport ? \"export \" : \"\";\n const composed = `${exportKeyword}const handle = ${callee}(${args.join(\", \")});`;\n\n if (site.kind === \"function\") {\n if (site.inlineExport) site.fn.setIsExported(false);\n sf.getFunctionOrThrow(\"handle\").getNameNode()!.replaceWithText(EXTRACTED);\n const fn = sf.getFunctionOrThrow(EXTRACTED);\n sf.insertText(fn.getEnd(), `\\n\\n${composed}`);\n } else {\n if (site.inlineExport) site.statement.setIsExported(false);\n sf.getVariableDeclarationOrThrow(\"handle\")\n .getNameNode()\n .replaceWithText(EXTRACTED);\n const statement = sf.getVariableStatementOrThrow(EXTRACTED);\n sf.insertText(statement.getEnd(), `\\n\\n${composed}`);\n }\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\n/**\n * After a `sequence` unwraps to `handleApp` alone, put the function back the\n * way `extract` found it: `handleApp` renamed to `handle` and exported, and\n * the `handle = handleApp` statement gone.\n */\nfunction restoreExtracted(sf: SourceFile): void {\n const located = locate(sf);\n if (\"unsupported\" in located || located.site?.kind !== \"variable\") return;\n const { decl, statement, inlineExport } = located.site;\n const init = decl.getInitializer();\n if (\n !init ||\n !Node.isIdentifier(init) ||\n init.getText() !== EXTRACTED ||\n decl.getTypeNode() ||\n statement.getDeclarations().length > 1\n ) {\n return;\n }\n\n const uses = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .filter((id) => id.getText() === EXTRACTED);\n // Its declaration and the one use in `handle`.\n if (uses.length !== 2) return;\n\n const fn = sf.getFunction(EXTRACTED);\n const variable = sf.getVariableStatements().find((s) => {\n const decls = s.getDeclarations();\n return decls.length === 1 && decls[0].getName() === EXTRACTED;\n });\n const target = fn ?? variable;\n if (!target || target.hasExportKeyword()) return;\n\n statement.remove();\n if (fn) {\n const restored = sf.getFunctionOrThrow(EXTRACTED);\n restored.getNameNode()!.replaceWithText(\"handle\");\n if (inlineExport) sf.getFunctionOrThrow(\"handle\").setIsExported(true);\n } else {\n const restored = sf.getVariableDeclarationOrThrow(EXTRACTED);\n restored.getNameNode().replaceWithText(\"handle\");\n if (inlineExport) {\n sf.getVariableStatementOrThrow(\"handle\").setIsExported(true);\n }\n }\n}\n\n/**\n * Add a handle to the exported `handle`. Already present anywhere in the\n * composition: unchanged. No `handle` yet: `export const handle = <expression>`.\n */\nexport function addHandle(sf: SourceFile, spec: HandleSpec): ComposeResult {\n const name = spec.name ?? spec.expression;\n const position = spec.position ?? \"first\";\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n const kit = kitSequence(sf);\n\n if (!site) {\n if (located.starExport) return unsupported(\"re-export\");\n const blank = sf.getStatementsWithComments().length > 0 ? \"\\n\" : \"\";\n sf.addStatements(`${blank}export const handle = ${spec.expression};`);\n return changed(sf);\n }\n\n if (site.kind === \"function\") {\n if (references(site.fn, name)) return unsupported(\"ambiguous-reference\");\n return extractChecked(sf, site, spec, kit);\n }\n\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name) || findInSequence(core, name, kit)) {\n return unchanged(site);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n\n if (isSequenceCall(core, kit)) {\n const list = pieces(core);\n const piece: Piece = { leading: [], text: spec.expression, trailing: [] };\n if (position === \"first\") list.unshift(piece);\n else list.push(piece);\n rewriteSequence(core, list);\n return changed(sf);\n }\n\n if (Node.isArrowFunction(core) || Node.isFunctionExpression(core)) {\n return extractChecked(sf, site, spec, kit);\n }\n\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const existing = core.getText();\n const args =\n position === \"first\"\n ? [spec.expression, existing]\n : [existing, spec.expression];\n const multiline = args.some((a) => a.includes(\"\\n\"));\n core.replaceWithText(\n renderCall(\n callee,\n args.map((text) => ({ leading: [], text, trailing: [] })),\n multiline,\n ),\n );\n ensureSequenceImport(sf, kit);\n return changed(sf);\n}\n\nfunction extractChecked(\n sf: SourceFile,\n site: Site,\n spec: HandleSpec,\n kit: KitSequence,\n): ComposeResult {\n const callee = sequenceCallee(sf, kit);\n if (!callee) return unsupported(\"foreign-sequence\");\n const taken = sf\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some((id) => id.getText() === EXTRACTED);\n if (taken) return unsupported(\"name-collision\");\n if (site.kind === \"variable\" && site.statement.getDeclarations().length > 1) {\n return unsupported(\"multi-declarator\");\n }\n return extract(sf, site, spec, callee, kit);\n}\n\n/**\n * Take a handle out of the exported `handle`. A `sequence` left with one\n * argument unwraps to it; the last handle takes the `handle` export with it.\n */\nexport function removeHandle(sf: SourceFile, name: string): ComposeResult {\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site) return unchanged(null);\n\n if (site.kind === \"function\") {\n return references(site.fn, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, name)) {\n removeWholeHandle(sf, site);\n pruneSequenceImport(sf);\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (!found) {\n return references(core, name)\n ? unsupported(\"ambiguous-reference\")\n : unchanged(site);\n }\n\n // Innermost call first; a nested `sequence` emptied by the removal is in\n // turn removed from the one around it.\n const calls = [...found.calls];\n let index = found.index;\n for (;;) {\n const call = calls.pop()!;\n const list = pieces(call);\n list.splice(index, 1);\n const outer = calls[calls.length - 1];\n\n if (list.length === 0) {\n if (!outer) {\n removeWholeHandle(sf, site);\n break;\n }\n index = outer.getArguments().indexOf(call);\n continue;\n }\n if (list.length === 1 && outer) {\n call.replaceWithText(renderAlone(list[0]));\n break;\n }\n if (list.length === 1) {\n // `handle = sequence(x)` unwraps to `handle = x`, and x's comments move\n // above the statement rather than dangle after the `=`.\n const [kept] = list;\n const comments = [...kept.leading, ...kept.trailing];\n call.replaceWithText(kept.text);\n if (comments.length === 0) restoreExtracted(sf);\n else {\n const statement = currentStatement(sf)!;\n sf.insertText(\n statement.getStart(true),\n comments.map((c) => `${c}\\n`).join(\"\"),\n );\n }\n break;\n }\n rewriteSequence(call, list);\n break;\n }\n\n pruneSequenceImport(sf);\n return changed(sf);\n}\n\n/**\n * Swap handle `name` for `spec` in the same place in the chain. When `name`\n * was the whole `handle`, the comments above the statement go too: they\n * described the old handle. With `name` absent this is `addHandle`.\n */\nexport function replaceHandle(\n sf: SourceFile,\n name: string,\n spec: HandleSpec,\n): ComposeResult {\n const newName = spec.name ?? spec.expression;\n const located = locate(sf);\n if (\"unsupported\" in located) return unsupported(located.unsupported);\n const { site } = located;\n if (!site || site.kind === \"function\") return addHandle(sf, spec);\n\n const kit = kitSequence(sf);\n const core = unwrap(site.decl.getInitializerOrThrow());\n if (isHandle(core, newName) || findInSequence(core, newName, kit)) {\n const stale = isHandle(core, name) || findInSequence(core, name, kit);\n return stale ? removeHandle(sf, name) : unchanged(site);\n }\n\n if (isHandle(core, name)) {\n core.replaceWithText(spec.expression);\n removeAttachedComments(sf, sf.getVariableStatementOrThrow(\"handle\"));\n return changed(sf);\n }\n\n const found = findInSequence(core, name, kit);\n if (found) {\n const call = found.calls[found.calls.length - 1];\n const list = pieces(call);\n list[found.index] = { ...list[found.index], text: spec.expression };\n rewriteSequence(call, list);\n return changed(sf);\n }\n if (references(core, name)) return unsupported(\"ambiguous-reference\");\n return addHandle(sf, spec);\n}\n\n/**\n * The handles in the exported `handle`, in order: each argument's identifier,\n * or its callee's, or its source text. A function handle is `handle` itself.\n * `null` when there is no `handle` to compose.\n */\nexport function listHandles(sf: SourceFile): string[] | null {\n const located = locate(sf);\n if (\"unsupported\" in located || !located.site) return null;\n if (located.site.kind === \"function\") return [\"handle\"];\n const kit = kitSequence(sf);\n\n const names = (node: Node): string[] => {\n if (isSequenceCall(node, kit)) return node.getArguments().flatMap(names);\n if (Node.isIdentifier(node)) return [node.getText()];\n if (\n Node.isCallExpression(node) &&\n Node.isIdentifier(node.getExpression())\n ) {\n return [node.getExpression().getText()];\n }\n return [node.getText()];\n };\n return names(unwrap(located.site.decl.getInitializerOrThrow()));\n}\n"],"mappings":";;;AAiCA,IAAM,IAAY,uBACZ,IAAY;AA+DlB,SAAS,EAAO,GAAyB;CACvC,IAAI,IAAsB,IACtB,IAAa;CAEjB,KAAK,IAAM,KAAM,EAAG,sBAAsB,GAAG;EAC3C,IAAM,IAAa,EAAG,mBAAmB,MAAM,KAAA;EAC/C,IAAI,EAAG,kBAAkB,GAAG;GAC1B,IAAI,EAAG,mBAAmB,CAAC,EAAE,QAAQ,MAAM,UACzC,OAAO,EAAE,aAAa,YAAY;GAEpC,AAAI,MAAY,IAAa;GAC7B;EACF;EACA,KAAK,IAAM,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xC,IAAO,EAAO,CAAI;EAGxB,OAFA,EAAK,EAAM,SAAS;GAAE,GAAG,EAAK,EAAM;GAAQ,MAAM,EAAK;EAAW,GAClE,EAAgB,GAAM,CAAI,GACnB,EAAQ,CAAE;CACnB;CAEA,OADI,EAAW,GAAM,CAAI,IAAU,EAAY,qBAAqB,IAC7D,EAAU,GAAI,CAAI;AAC3B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"config-target-Dx3w6WSk.js","names":[],"sources":["../../src/runtime/config-target.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Project,\n QuoteKind,\n SyntaxKind,\n type CallExpression,\n type ObjectLiteralExpression,\n type SourceFile,\n} from \"ts-morph\";\nimport type { ModifyOutcome } from \"../core/types\";\nimport { formatLikeSource } from \"./ts-morph-helpers\";\n\nexport const VITE_CONFIG_CANDIDATES = [\n \"vite.config.ts\",\n \"vite.config.js\",\n \"vite.config.mjs\",\n \"vite.config.cjs\",\n];\n\n/** SvelteKit 2's config files; SvelteKit 3 refuses to start with any of them. */\nexport const SVELTE_CONFIG_CANDIDATES = [\n \"svelte.config.ts\",\n \"svelte.config.js\",\n \"svelte.config.mjs\",\n \"svelte.config.cjs\",\n];\n\n/**\n * The message every pattern prints for a project still on SvelteKit 2's\n * `svelte.config.*`. SvelteKit 3 refuses to start with one, so editing it\n * would be pointless; the migration moves it into `vite.config.ts`.\n */\nexport const SVELTE_CONFIG_MESSAGE =\n \"SvelteKit 3 no longer reads svelte.config.* — run `npx vela@^0.15 migrate sveltekit-3` to move it into vite.config.ts.\";\n\n/** SvelteKit 3 fails on a leftover `kit: {...}` inside the `sveltekit()` arg. */\nexport const KIT_NESTING_MESSAGE =\n \"SvelteKit 3 reads its options at the top level of sveltekit({...}), not under `kit:` — run `npx vela@^0.15 migrate sveltekit-3` to move them.\";\n\n/**\n * Where SvelteKit 3 reads its configuration: the inline argument object of the\n * `sveltekit()` call in `vite.config.*`. The former `kit.*` options (adapter,\n * alias, experimental, paths, ...) sit at its top level, beside\n * `compilerOptions`, `preprocess` and `extensions`.\n */\nexport interface ConfigTarget {\n /** The file to add imports to and save. */\n sourceFile: SourceFile;\n /** Absolute path of the resolved file. */\n filePath: string;\n /** The `sveltekit()` arg object. */\n configObject: ObjectLiteralExpression;\n /** Full text captured before any mutation, for change detection. */\n originalText: string;\n /**\n * The `sveltekit()` call when resolving it added the `{}` arg; saving drops\n * that arg again while it is still empty.\n */\n addedArgTo?: CallExpression;\n}\n\n/** Why a config could not be resolved for editing. */\nexport type ConfigFailure =\n /** A `svelte.config.*` exists: a SvelteKit 2 project that needs migrating. */\n | \"svelte-config\"\n /** The `sveltekit()` arg still nests options under `kit:`. */\n | \"kit-nesting\"\n /** The `sveltekit()` arg is not an object literal (`sveltekit(config)`). */\n | \"non-object-arg\";\n\nexport type ResolveResult =\n | { status: \"resolved\"; target: ConfigTarget }\n | { status: \"not-found\"; message: string; filePath: string }\n | {\n status: \"failed\";\n reason: ConfigFailure;\n message: string;\n filePath: string;\n };\n\n/** Result shape returned by every config modifier so call sites can build a File. */\nexport interface ConfigModifyResult {\n filePath: string;\n outcome: ModifyOutcome;\n}\n\n/** First candidate that exists under `root`, or null. */\nexport function probeFirstExisting(\n root: string,\n candidates: string[],\n): string | null {\n for (const rel of candidates) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/**\n * Get the object-literal value of property `name` on `obj`, creating it as an\n * empty object if missing (or replacing a non-object initializer). Returns null\n * if the property can't be coerced to an object literal.\n */\nexport function getOrCreateObjectLiteralProperty(\n obj: ObjectLiteralExpression,\n name: string,\n initializer: string,\n): ObjectLiteralExpression | null {\n const prop = obj.getProperty(name);\n if (!prop) {\n obj.addPropertyAssignment({ name, initializer });\n const added = obj.getProperty(name);\n if (!added || added.getKind() !== SyntaxKind.PropertyAssignment)\n return null;\n const init = (\n added as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (!init || init.getKind() !== SyntaxKind.ObjectLiteralExpression)\n return null;\n return init as ObjectLiteralExpression;\n }\n\n if (prop.getKind() !== SyntaxKind.PropertyAssignment) return null;\n const init = (prop as import(\"ts-morph\").PropertyAssignment).getInitializer();\n if (!init) return null;\n if (init.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n (prop as import(\"ts-morph\").PropertyAssignment).setInitializer(initializer);\n const init2 = (\n prop as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n return init2 && init2.getKind() === SyntaxKind.ObjectLiteralExpression\n ? (init2 as ObjectLiteralExpression)\n : null;\n }\n\n return init as ObjectLiteralExpression;\n}\n\n/** Ensure `obj[name] === true`. Returns whether a change was made. */\nexport function ensureBooleanTrue(\n obj: ObjectLiteralExpression,\n name: string,\n): boolean {\n const existing = obj.getProperty(name);\n if (!existing) {\n obj.addPropertyAssignment({ name, initializer: \"true\" });\n return true;\n }\n if (existing.getKind() !== SyntaxKind.PropertyAssignment) return false;\n const init = (\n existing as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (init?.getText() === \"true\") return false;\n (existing as import(\"ts-morph\").PropertyAssignment).setInitializer(\"true\");\n return true;\n}\n\nfunction findSveltekitCall(sourceFile: SourceFile): CallExpression | null {\n return (\n sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"sveltekit\") ?? null\n );\n}\n\n/**\n * Resolve the `sveltekit()` arg in `vite.config.*` for editing:\n * - any `svelte.config.*` → failed (`svelte-config`), even when the inline\n * arg exists too: SvelteKit 3 refuses to start until it is gone;\n * - an object arg with a `kit:` property → failed (`kit-nesting`);\n * - an object arg → resolved;\n * - a bare `sveltekit()` → `{}` is added and resolved;\n * - any other arg → failed (`non-object-arg`);\n * - no vite config, or no `sveltekit()` call in it → not-found.\n *\n * `hints.failed` is the message for a shape that can't be edited; the\n * `svelte-config` and `kit-nesting` failures always carry the migrate message.\n */\nexport function resolveConfigTarget(\n root: string,\n hints?: { notFound?: string; failed?: string },\n): ResolveResult {\n const notFound = hints?.notFound ?? \"Could not find a Vite config to modify.\";\n const failed = hints?.failed ?? \"Could not modify the Vite config.\";\n\n const sveltePath = probeFirstExisting(root, SVELTE_CONFIG_CANDIDATES);\n if (sveltePath) {\n return {\n status: \"failed\",\n reason: \"svelte-config\",\n message: SVELTE_CONFIG_MESSAGE,\n filePath: sveltePath,\n };\n }\n\n const vitePath = probeFirstExisting(root, VITE_CONFIG_CANDIDATES);\n if (!vitePath) {\n return {\n status: \"not-found\",\n message: notFound,\n filePath: path.join(root, VITE_CONFIG_CANDIDATES[0]),\n };\n }\n\n const sourceFile = newProject().addSourceFileAtPath(vitePath);\n const originalText = sourceFile.getFullText();\n const call = findSveltekitCall(sourceFile);\n if (!call) {\n return { status: \"not-found\", message: notFound, filePath: vitePath };\n }\n\n const arg = call.getArguments()[0];\n if (!arg) {\n const created = call\n .addArgument(\"{}\")\n .asKind(SyntaxKind.ObjectLiteralExpression);\n if (!created) {\n return {\n status: \"failed\",\n reason: \"non-object-arg\",\n message: failed,\n filePath: vitePath,\n };\n }\n return {\n status: \"resolved\",\n target: {\n sourceFile,\n filePath: vitePath,\n configObject: created,\n originalText,\n addedArgTo: call,\n },\n };\n }\n\n const configObject = arg.asKind(SyntaxKind.ObjectLiteralExpression);\n if (!configObject) {\n return {\n status: \"failed\",\n reason: \"non-object-arg\",\n message: failed,\n filePath: vitePath,\n };\n }\n if (configObject.getProperty(\"kit\")) {\n return {\n status: \"failed\",\n reason: \"kit-nesting\",\n message: KIT_NESTING_MESSAGE,\n filePath: vitePath,\n };\n }\n return {\n status: \"resolved\",\n target: { sourceFile, filePath: vitePath, configObject, originalText },\n };\n}\n\n/**\n * Format, compare against the captured original, and save only if changed.\n * A `{}` that resolving added to a bare `sveltekit()` is taken out again when\n * nothing went into it, so a no-op edit reports unchanged.\n */\nexport function saveTarget(target: ConfigTarget): ModifyOutcome {\n if (target.addedArgTo && target.configObject.getProperties().length === 0) {\n target.addedArgTo.removeArgument(0);\n }\n formatLikeSource(target.sourceFile);\n const newText = target.sourceFile.getFullText();\n if (newText === target.originalText) {\n return { status: \"success\", changed: false };\n }\n target.sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n\n/**\n * Resolve a config target and run `mutate` against it. Handles the\n * not-found/failed branches and change detection uniformly. `mutate` returns\n * `false` when the config shape can't be safely edited (→ failed).\n */\nexport function modifyConfig(\n root: string,\n hints: { notFound: string; failed: string },\n mutate: (target: ConfigTarget) => boolean,\n): ConfigModifyResult {\n const res = resolveConfigTarget(root, hints);\n if (res.status !== \"resolved\") {\n return {\n filePath: res.filePath,\n outcome: { status: res.status, message: res.message },\n };\n }\n const ok = mutate(res.target);\n if (!ok) {\n return {\n filePath: res.target.filePath,\n outcome: { status: \"failed\", message: hints.failed },\n };\n }\n return { filePath: res.target.filePath, outcome: saveTarget(res.target) };\n}\n"],"mappings":";;;;;AAaA,IAAa,IAAyB;CACpC;CACA;CACA;CACA;AACF,GAGa,IAA2B;CACtC;CACA;CACA;CACA;AACF,GAOa,IACX,0HAGW,IACX;AAkDF,SAAgB,EACd,GACA,GACe;CACf,KAAK,IAAM,KAAO,GAAY;EAC5B,IAAM,IAAM,EAAK,KAAK,GAAM,CAAG;EAC/B,IAAI,EAAG,WAAW,CAAG,GAAG,OAAO;CACjC;CACA,OAAO;AACT;AAEA,SAAS,IAAsB;CAC7B,OAAO,IAAI,EAAQ;EACjB,iBAAiB,EAAE,SAAS,GAAK;EACjC,sBAAsB,EAAE,WAAW,EAAU,OAAO;CACtD,CAAC;AACH;AAOA,SAAgB,EACd,GACA,GACA,GACgC;CAChC,IAAM,IAAO,EAAI,YAAY,CAAI;CACjC,IAAI,CAAC,GAAM;EACT,EAAI,sBAAsB;GAAE;GAAM;EAAY,CAAC;EAC/C,IAAM,IAAQ,EAAI,YAAY,CAAI;EAClC,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AAO;CACrD,IAVO;EACL,UAAU,EAAI;EACd,SAAS;GAAE,QAAQ,EAAI;GAAQ,SAAS,EAAI;EAAQ;CACtD;AAUJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants-BjyMU5s8.js","names":[],"sources":["../../src/core/constants.ts"],"sourcesContent":["export const DATA_DIR = \"data\";\nexport const MIGRATIONS_DIR = \"migrations\";\nexport const FIXTURE_PREFIX = \"vela\";\nexport const PUBLIC_DIR = \"(public)\";\nexport const APP_DIR = \"(app)\";\nexport const AUTHED_REDIRECT_PATH = \"/dashboard\";\nexport const API_URL = \"http://localhost:5173\";\n\n/**\n * The table helpers this repo ships (`data-table`, `column-header`,\n * `faceted-filter`, `pagination`) and the pages the scaffold generators emit\n * target TanStack Table v9, whose API and types are incompatible with v8; see\n * `assertTableCoreV9` for projects that still have the v8 helpers.\n */\nexport const TANSTACK_TABLE_CORE = \"@tanstack/table-core@^9.2.4\";\n\n/** The major `TANSTACK_TABLE_CORE` pins. */\nexport const TANSTACK_TABLE_CORE_MAJOR = 9;\n\n/** `file-form` and `multiselect` build on formsnap's field context. */\nexport const FORMSNAP = \"formsnap@^2.0.1\";\n\n/**\n * The superforms release that supports SvelteKit 3 (its `latest` accepts\n * only Kit 1 and 2). Installed exactly, not with a caret: a caret on a\n * prerelease would follow later `next` builds.\n */\nexport const SUPERFORMS_VERSION = \"3.0.0-next.1\";\n\n/**\n * What a generated superforms page needs. Vela's templates already carry\n * both; a project vela did not create may have neither.\n */\nexport const SUPERFORMS = `sveltekit-superforms@${SUPERFORMS_VERSION}`;\n\n/**\n * formsnap 2 peers `sveltekit-superforms ^2`, so every project that installs\n * it needs this npm override, or `npm install` fails with ERESOLVE. The value\n * is the literal version: `$sveltekit-superforms` breaks on npm 10.\n * `writeResult` adds it before any install that brings formsnap in.\n */\nexport const FORMSNAP_OVERRIDES = {\n formsnap: { \"sveltekit-superforms\": SUPERFORMS_VERSION },\n};\n\n/** The flash-message release that supports SvelteKit 3; installed exactly, like superforms. */\nexport const FLASH = \"sveltekit-flash-message@3.0.0-next.0\";\n\n/** The adapter `vela enable backend` moves a project to. */\nexport const ADAPTER_NODE = \"@sveltejs/adapter-node@^6.0.0\";\n\n/** The adapter a static project builds with (`vela disable backend`). */\nexport const ADAPTER_STATIC = \"@sveltejs/adapter-static@^4.0.0\";\n\n/** The VelaStack libraries' SvelteKit 3 releases. */\nexport const VELASTACK_KIT = \"@velastack/kit@^0.4.0\";\nexport const VELASTACK_POCKETBASE = \"@velastack/pocketbase@^0.4.0\";\nexport const VELASTACK_CMS = \"@velastack/cms@^0.6.0\";\nexport const NEGOTIATE = \"sveltekit-negotiate@^0.3.0\";\nexport const ZOD = \"zod@^4.1.11\";\n\n/** What `vela enable i18n` installs: wuchale and its Svelte adapter. */\nexport const WUCHALE = \"wuchale@^0.26.3\";\nexport const WUCHALE_SVELTE = \"@wuchale/svelte@^0.21.1\";\n"],"mappings":";AAAA,IAAa,IAAW,QACX,IAAiB,cAEjB,IAAa,YACb,IAAU,SAUV,IAAsB,+BAMtB,IAAW,mBAOX,IAAqB,gBAMrB,IAAa,wBAAwB,KAQrC,IAAqB,EAChC,UAAU,EAAE,wBAAwB,EAAmB,EACzD,GAGa,IAAQ,wCAGR,IAAe,iCAGf,IAAiB,mCAGjB,IAAgB,yBAChB,IAAuB,gCACvB,IAAgB,yBAChB,IAAY,8BACZ,IAAM,eAGN,IAAU,mBACV,IAAiB"}
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
//#region src/patterns/enable/subscriptions/preview-modifies/src/lib/components/app-sidebar.svelte?raw
|
|
2
|
-
var e = "<script lang=\"ts\" module>\n import HomeIcon from '@lucide/svelte/icons/home';\n\n let data = {\n navMain: [\n {\n title: 'Dashboard',\n url: '/dashboard',\n icon: HomeIcon\n }\n ]\n };\n<\/script>\n\n<script lang=\"ts\">\n import favicon from '#lib/assets/favicon.svg';\n import { site } from '#lib/site.js';\n\n import NavMain from './nav-main.svelte';\n import NavUser from './nav-user.svelte';\n import * as Sidebar from '#lib/components/ui/sidebar/index.js';\n import type { ComponentProps } from 'svelte';\n\n let {\n user,\n // [!code highlight:1]\n subscription = null,\n ref = $bindable(null),\n ...restProps\n }: ComponentProps<typeof Sidebar.Root> & {\n user: any;\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n<\/script>\n\n<Sidebar.Root bind:ref variant=\"inset\" {...restProps}>\n <Sidebar.Header>\n <Sidebar.Menu>\n <Sidebar.MenuItem>\n <Sidebar.MenuButton size=\"lg\">\n {#snippet child({ props })}\n <a href=\"/dashboard\" {...props}>\n <div\n class=\"bg-sidebar-accent text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg\"\n >\n <img src={favicon} alt=\"logo\" class=\"size-6\" />\n </div>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">{site.name}</span>\n </div>\n </a>\n {/snippet}\n </Sidebar.MenuButton>\n </Sidebar.MenuItem>\n </Sidebar.Menu>\n </Sidebar.Header>\n <Sidebar.Content>\n <NavMain items={data.navMain} />\n </Sidebar.Content>\n <Sidebar.Footer>\n <NavUser {user} {subscription} />\n </Sidebar.Footer>\n</Sidebar.Root>\n", t = "<script lang=\"ts\">\n import { toggleMode, mode } from \"mode-watcher\";\n import ChevronsUpDownIcon from \"@lucide/svelte/icons/chevrons-up-down\";\n import Settings2Icon from \"@lucide/svelte/icons/settings-2\";\n import CreditCardIcon from \"@lucide/svelte/icons/credit-card\";\n import LogOutIcon from \"@lucide/svelte/icons/log-out\";\n import MoonIcon from \"@lucide/svelte/icons/moon\";\n import SunIcon from \"@lucide/svelte/icons/sun\";\n import * as Avatar from \"#lib/components/ui/avatar/index.js\";\n import * as DropdownMenu from \"#lib/components/ui/dropdown-menu/index.js\";\n import * as Sidebar from \"#lib/components/ui/sidebar/index.js\";\n\n let data = {\n navUser: [\n {\n title: \"Settings\",\n url: \"/settings\",\n icon: Settings2Icon,\n },\n {\n title: \"Billing\",\n url: \"/billing\",\n icon: CreditCardIcon,\n },\n ],\n };\n\n let {\n user,\n // [!code highlight:1]\n subscription = null,\n }: {\n user: {\n id: string;\n name: string;\n email: string;\n avatar: string;\n };\n // [!code highlight:1]\n subscription?: { id: string; productName: string | null } | null;\n } = $props();\n\n // [!code highlight:1]\n const planLabel = $derived(subscription?.productName ?? \"Free\");\n\n const sidebar = Sidebar.useSidebar();\n<\/script>\n\n<Sidebar.Menu>\n <Sidebar.MenuItem>\n <DropdownMenu.Root>\n <DropdownMenu.Trigger>\n {#snippet child({ props })}\n <Sidebar.MenuButton\n size=\"lg\"\n class=\"data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground\"\n {...props}\n >\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image\n src=\"/api/files/users/{user.id}/{user.avatar}\"\n alt={user.name}\n />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() ||\n user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">\n {user.name || user.email}\n </span>\n <!-- [!code highlight:3] -->\n <span class=\"truncate text-xs text-muted-foreground\">\n {planLabel}\n </span>\n </div>\n <ChevronsUpDownIcon class=\"ml-auto size-4\" />\n </Sidebar.MenuButton>\n {/snippet}\n </DropdownMenu.Trigger>\n <DropdownMenu.Content\n class=\"w-(--bits-dropdown-menu-anchor-width) min-w-56 rounded-lg\"\n side={sidebar.isMobile ? \"bottom\" : \"right\"}\n align=\"end\"\n sideOffset={4}\n >\n <DropdownMenu.Label class=\"p-0 font-normal\">\n <div class=\"flex items-center gap-2 px-1 py-1.5 text-left text-sm\">\n <Avatar.Root class=\"size-8 rounded-lg\">\n {#if user.avatar}\n <Avatar.Image\n src=\"/api/files/users/{user.id}/{user.avatar}\"\n alt={user.name}\n />\n {/if}\n <Avatar.Fallback class=\"rounded-lg\">\n {user.name?.charAt(0).toUpperCase() ||\n user.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n <div class=\"grid flex-1 text-left text-sm leading-tight\">\n <span class=\"truncate font-medium\">\n {user.name || user.email}\n </span>\n <!-- [!code highlight:3] -->\n <span class=\"truncate text-xs\">\n {planLabel}\n </span>\n </div>\n </div>\n </DropdownMenu.Label>\n <DropdownMenu.Separator />\n <DropdownMenu.Group>\n <DropdownMenu.Item onclick={toggleMode}>\n {#if mode.current === \"dark\"}\n <SunIcon />\n Light mode\n {:else}\n <MoonIcon />\n Dark mode\n {/if}\n </DropdownMenu.Item>\n {#each data.navUser as item}\n <DropdownMenu.Item class=\"p-0\">\n <a\n href={item.url}\n class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\"\n >\n <item.icon />\n {item.title}\n </a>\n </DropdownMenu.Item>\n {/each}\n </DropdownMenu.Group>\n <DropdownMenu.Separator />\n <DropdownMenu.Item class=\"p-0\">\n <form action=\"/logout\" method=\"post\" class=\"w-full\">\n <button\n type=\"submit\"\n class=\"flex cursor-default items-center gap-2 px-2 py-1.5 w-full\"\n >\n <LogOutIcon />\n Log out\n </button>\n </form>\n </DropdownMenu.Item>\n </DropdownMenu.Content>\n </DropdownMenu.Root>\n </Sidebar.MenuItem>\n</Sidebar.Menu>\n", n = "// [!code highlight:33]\nasync function loadActiveSubscription(locals: App.Locals, userId: string) {\n const subscriptions = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\n 'user = {:user} && (status = \"active\" || status = \"trialing\")',\n { user: userId },\n ),\n expand: \"price\",\n sort: \"-created\",\n })\n .catch(() => []);\n\n const sub = subscriptions[0];\n if (!sub) return null;\n\n const price = sub.expand?.price;\n let productName: string | null = null;\n if (price?.product) {\n const product = await locals.admin\n .collection(\"stripe_products\")\n .getOne(price.product)\n .catch(() => null);\n productName = product?.name ?? null;\n }\n\n return {\n id: sub.id,\n status: sub.status as string,\n productName,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n };\n}\n\nexport const load = async ({ locals }) => {\n const user = locals.pb.authStore.record!;\n const breadcrumbs = [{ title: \"Home\", url: \"/dashboard\" }];\n // [!code highlight:1]\n const subscription = await loadActiveSubscription(locals, user.id);\n\n // [!code highlight:1]\n return { user, breadcrumbs, subscription };\n};\n", r = "<script lang=\"ts\">\n import * as Sidebar from \"#lib/components/ui/sidebar/index.js\";\n import { Separator } from \"#lib/components/ui/separator/index.js\";\n import AppSidebar from \"#lib/components/app-sidebar.svelte\";\n import * as Breadcrumb from \"#lib/components/ui/breadcrumb/index.js\";\n import { page } from \"$app/state\";\n\n let breadcrumbs = $derived(page.data.breadcrumbs || []) as {\n title: string;\n url: string;\n }[];\n let { data, children } = $props();\n<\/script>\n\n<div class=\"min-h-dvh dashboard\">\n <Sidebar.Provider>\n <!-- [!code highlight:5] -->\n <AppSidebar\n user={data.user}\n \n subscription={data.subscription}\n />\n <Sidebar.Inset>\n <header class=\"flex h-16 shrink-0 items-center gap-2\">\n <div class=\"flex items-center gap-2 px-4\">\n <Sidebar.Trigger class=\"-ml-1\" />\n <Separator\n orientation=\"vertical\"\n class=\"mr-2 data-[orientation=vertical]:h-4\"\n />\n {#if breadcrumbs.length > 0}\n <Breadcrumb.Root>\n <Breadcrumb.List>\n {#if breadcrumbs.length > 1}\n {#each breadcrumbs.slice(0, -1) as breadcrumb}\n <Breadcrumb.Item>\n <Breadcrumb.Link href={breadcrumb.url}\n >{breadcrumb.title}</Breadcrumb.Link\n >\n </Breadcrumb.Item>\n <Breadcrumb.Separator />\n {/each}\n {/if}\n <Breadcrumb.Page>\n {breadcrumbs[breadcrumbs.length - 1].title}\n </Breadcrumb.Page>\n </Breadcrumb.List>\n </Breadcrumb.Root>\n {/if}\n </div>\n </header>\n <div class=\"flex flex-1 flex-col p-4 pt-0\">\n {@render children?.()}\n </div>\n </Sidebar.Inset>\n </Sidebar.Provider>\n</div>\n\n<style>\n :global(body:has(div.dashboard)) {\n background-color: var(--color-sidebar);\n }\n</style>\n", i = "import { error } from \"@sveltejs/kit\";\nimport stripe from \"#lib/stripe.js\";\n\ntype RecurringInfo = {\n interval: string;\n interval_count: number;\n trial_period_days?: number | null;\n};\n\nfunction parseRecurring(value: unknown): RecurringInfo | null {\n if (!value) return null;\n if (typeof value === \"object\") return value as RecurringInfo;\n try {\n return JSON.parse(value as string) as RecurringInfo;\n } catch {\n return null;\n }\n}\n\nconst ACTIVE_SUBSCRIPTION_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n];\n\nexport const load = async ({ locals, depends, parent }) => {\n const { user } = await parent();\n depends(\"app:billing\");\n\n let customer;\n try {\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n locals.admin.filter(\"user = {:user}\", { user: user.id }),\n );\n } catch {\n // The link-stripe-customer workflow started at signup has not finished.\n return {\n paymentMethods: [],\n user,\n billingReady: false,\n hasDefaultPaymentMethod: false,\n activeSubscription: null,\n availablePlans: [],\n };\n }\n\n const stripeCustomer = await stripe.customers.retrieve(customer.id);\n if (stripeCustomer.deleted) {\n return error(400, \"Customer not found\");\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n {\n type: \"card\",\n allow_redisplay: \"always\",\n },\n );\n\n const subscriptionRecords = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(\"user = {:user}\", { user: user.id }),\n expand: \"price\",\n sort: \"-created\",\n });\n\n const recurringPrices = await locals.admin\n .collection(\"stripe_prices\")\n .getFullList({\n filter: locals.admin.filter(\"type = {:type} && active = true\", {\n type: \"recurring\",\n }),\n });\n\n const productIds: string[] = Array.from(\n new Set(\n recurringPrices\n .map((p) => p.product)\n .filter((id): id is string => Boolean(id)),\n ),\n );\n const productMap = new Map<string, string>();\n if (productIds.length > 0) {\n const products = await locals.admin\n .collection(\"stripe_products\")\n .getFullList({\n filter: productIds.map((id) => `id = \"${id}\"`).join(\" || \"),\n });\n for (const product of products) {\n productMap.set(product.id, product.name ?? product.id);\n }\n }\n\n const availablePlans = recurringPrices.map((price) => ({\n id: price.id,\n productName:\n (price.product && productMap.get(price.product)) ?? price.product ?? \"\",\n unitAmount: (price.unit_amount ?? 0) as number,\n currency: (price.currency ?? \"\") as string,\n recurring: parseRecurring(price.recurring),\n }));\n\n const subscriptions = subscriptionRecords.map((sub) => {\n const expanded = sub.expand?.price;\n return {\n id: sub.id,\n status: sub.status as string,\n currentPeriodStart: (sub.current_period_start as string | null) ?? null,\n currentPeriodEnd: (sub.current_period_end as string | null) ?? null,\n cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),\n canceledAt: (sub.canceled_at as string | null) || null,\n priceId: sub.price as string,\n productName: expanded\n ? ((expanded.product && productMap.get(expanded.product)) ??\n expanded.product ??\n null)\n : null,\n unitAmount: expanded ? ((expanded.unit_amount ?? null) as number | null) : null,\n currency: expanded ? ((expanded.currency ?? null) as string | null) : null,\n recurring: expanded ? parseRecurring(expanded.recurring) : null,\n };\n });\n\n const activeSubscription =\n subscriptions.find((s) => ACTIVE_SUBSCRIPTION_STATUSES.includes(s.status)) ||\n null;\n\n // If the active plan isn't in the list (e.g., price was deactivated), include\n // it so it can still be shown as the current plan.\n if (\n activeSubscription &&\n !availablePlans.some((p) => p.id === activeSubscription.priceId)\n ) {\n availablePlans.push({\n id: activeSubscription.priceId,\n productName: activeSubscription.productName ?? \"\",\n unitAmount: activeSubscription.unitAmount ?? 0,\n currency: activeSubscription.currency ?? \"\",\n recurring: activeSubscription.recurring,\n });\n }\n\n availablePlans.sort((a, b) => a.unitAmount - b.unitAmount);\n\n return {\n billingReady: true,\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card!.brand,\n last4: pm.card!.last4,\n expMonth: pm.card!.exp_month,\n expYear: pm.card!.exp_year,\n isDefault: pm.id === customer.default_payment_method,\n })),\n user,\n hasDefaultPaymentMethod: Boolean(customer.default_payment_method),\n activeSubscription,\n availablePlans,\n };\n};\n\nasync function getUserCustomer(locals: App.Locals) {\n const userId = locals.pb.authStore.record?.id;\n if (!userId) {\n return error(401, \"Unauthorized\");\n }\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${userId}\"`);\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n return customer;\n}\n\n// A subscription can be updated in-place unless it has fully terminated.\nconst UPDATABLE_STATUSES = [\n \"active\",\n \"trialing\",\n \"past_due\",\n \"incomplete\",\n \"paused\",\n];\n\nasync function findUpdatableSubscription(\n locals: App.Locals,\n userId: string,\n) {\n const filterClause = UPDATABLE_STATUSES.map(\n (s) => `status = \"${s}\"`,\n ).join(\" || \");\n const subs = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getFullList({\n filter: locals.admin.filter(`user = {:user} && (${filterClause})`, {\n user: userId,\n }),\n sort: \"-created\",\n });\n return subs[0] ?? null;\n}\n\nexport const actions = {\n setDefaultPaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n if (!customer || !customer.id) {\n return error(400, \"Customer not found\");\n }\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: paymentMethodId,\n });\n },\n deletePaymentMethod: async ({ locals, request }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\") as string;\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(`user.id = \"${locals.pb.authStore.record?.id}\"`);\n\n const defaultPaymentMethod = customer.default_payment_method;\n\n await stripe.paymentMethods.detach(paymentMethodId);\n\n // If default payment method was deleted, update default payment method\n if (defaultPaymentMethod === paymentMethodId) {\n const paymentMethods = await stripe.paymentMethods.list({\n customer: customer.id,\n });\n\n if (paymentMethods.data.length > 0) {\n const defaultPaymentMethod = paymentMethods.data[0];\n\n await stripe.customers.update(customer.id, {\n invoice_settings: {\n default_payment_method: defaultPaymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: defaultPaymentMethod.id,\n });\n } else {\n await locals.admin.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method: null,\n });\n }\n }\n },\n selectPlan: async ({ locals, request }) => {\n const formData = await request.formData();\n const priceId = formData.get(\"priceId\") as string;\n if (!priceId) return error(400, \"Price ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // If an updatable subscription already exists, change its price in place\n // rather than creating a duplicate. Covers switch, resume-to-different-plan,\n // and races where the webhook hasn't delivered the existing sub yet.\n const existing = await findUpdatableSubscription(locals, userId);\n if (existing) {\n const stripeSub = await stripe.subscriptions.retrieve(existing.id);\n const item = stripeSub.items.data[0];\n if (!item) return error(500, \"Subscription has no items\");\n\n await stripe.subscriptions.update(existing.id, {\n items: [{ id: item.id, price: priceId }],\n proration_behavior: \"create_prorations\",\n cancel_at_period_end: false,\n });\n return;\n }\n\n const customer = await getUserCustomer(locals);\n if (!customer.default_payment_method) {\n return error(400, \"Add a default payment method before subscribing\");\n }\n\n await stripe.subscriptions.create({\n customer: customer.id,\n items: [{ price: priceId }],\n default_payment_method: customer.default_payment_method,\n payment_behavior: \"error_if_incomplete\",\n off_session: true,\n });\n },\n cancelSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n // Verify the subscription belongs to this user before touching Stripe.\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: true,\n });\n },\n resumeSubscription: async ({ locals, request }) => {\n const formData = await request.formData();\n const subscriptionId = formData.get(\"subscriptionId\") as string;\n if (!subscriptionId) return error(400, \"Subscription ID is required\");\n\n const userId = locals.pb.authStore.record?.id;\n if (!userId) return error(401, \"Unauthorized\");\n\n try {\n const record = await locals.admin\n .collection(\"stripe_subscriptions\")\n .getOne(subscriptionId);\n if (record.user !== userId) {\n return error(403, \"Forbidden\");\n }\n } catch {\n return error(404, \"Subscription not found\");\n }\n\n await stripe.subscriptions.update(subscriptionId, {\n cancel_at_period_end: false,\n });\n },\n};\n", a = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import * as Card from '#lib/components/ui/card/index.js';\n import { Badge } from '#lib/components/ui/badge/index.js';\n import * as AlertDialog from '#lib/components/ui/alert-dialog/index.js';\n import SetupButton from '#lib/components/payments/setup-button.svelte';\n import { CreditCard, Trash2, Check, Package } from '@lucide/svelte';\n import { toast } from 'svelte-sonner';\n import { invalidate, refreshAll } from '$app/navigation';\n import { untrack } from 'svelte';\n\n let { data } = $props();\n let paymentMethods = $derived(data.paymentMethods);\n let availablePlans = $derived(data.availablePlans);\n let hasDefaultPaymentMethod = $derived(data.hasDefaultPaymentMethod);\n\n // Local, mutable mirror of the server-side subscription. We optimistically\n // update it on user actions so the UI reflects the change immediately; the\n // $effect re-syncs from the server after the webhook has had a chance to\n // fire (refreshAll runs on a short delay below).\n let activeSubscription = $state(untrack(() => data.activeSubscription));\n $effect(() => {\n activeSubscription = data.activeSubscription;\n });\n let showDeleteDialog = $state(false);\n let selectedPaymentMethodId = $state<string | null>(null);\n let isProcessing = $state(false);\n let showCancelDialog = $state(false);\n let isSubscribing = $state<string | null>(null);\n let isCanceling = $state(false);\n\n function openDeleteDialog(paymentMethodId: string) {\n selectedPaymentMethodId = paymentMethodId;\n showDeleteDialog = true;\n }\n\n function closeDeleteDialog() {\n showDeleteDialog = false;\n selectedPaymentMethodId = null;\n }\n\n async function handleDeletePaymentMethod() {\n if (!selectedPaymentMethodId) return;\n isProcessing = true;\n\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', selectedPaymentMethodId);\n\n await fetch('?/deletePaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Payment method removed successfully');\n closeDeleteDialog();\n } catch (err) {\n console.error('Error deleting payment method:', err);\n toast.error('Failed to remove payment method');\n } finally {\n isProcessing = false;\n }\n }\n\n async function setDefaultPaymentMethod(paymentMethodId: string) {\n try {\n const formData = new FormData();\n formData.append('paymentMethodId', paymentMethodId);\n\n await fetch('?/setDefaultPaymentMethod', {\n method: 'POST',\n body: formData\n });\n\n await invalidate('app:billing');\n toast.success('Default payment method updated');\n } catch (err) {\n console.error('Error setting default payment method:', err);\n toast.error('Failed to update default payment method');\n }\n }\n\n function getCardBrandIcon(brand: string) {\n // You can customize these icons or use actual card brand icons\n const brands: Record<string, string> = {\n visa: '💳',\n mastercard: '💳',\n amex: '💳',\n discover: '💳',\n unknown: '💳'\n };\n return brands[brand.toLowerCase()] || brands.unknown;\n }\n\n function formatCardBrand(brand: string) {\n return brand.charAt(0).toUpperCase() + brand.slice(1);\n }\n\n function formatAmount(amount: number | null, currency: string | null) {\n if (amount === null || !currency) return '—';\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: currency.toUpperCase()\n }).format(amount / 100);\n }\n\n function formatInterval(recurring: { interval: string; interval_count: number } | null) {\n if (!recurring) return '';\n if (recurring.interval_count === 1) return `/ ${recurring.interval}`;\n return `every ${recurring.interval_count} ${recurring.interval}s`;\n }\n\n function formatDate(iso: string | null) {\n if (!iso) return '—';\n return new Date(iso).toLocaleDateString(undefined, {\n year: 'numeric',\n month: 'short',\n day: 'numeric'\n });\n }\n\n async function selectPlan(priceId: string, successMessage: string) {\n if (!hasDefaultPaymentMethod) {\n toast.error('Add a default payment method first');\n return;\n }\n const previous = activeSubscription;\n const plan = availablePlans.find((p) => p.id === priceId);\n if (plan) {\n activeSubscription = previous\n ? {\n ...previous,\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false\n }\n : {\n id: 'pending',\n status: 'active',\n priceId,\n productName: plan.productName,\n unitAmount: plan.unitAmount,\n currency: plan.currency,\n recurring: plan.recurring,\n cancelAtPeriodEnd: false,\n currentPeriodStart: null,\n currentPeriodEnd: null,\n canceledAt: null\n };\n }\n\n isSubscribing = priceId;\n try {\n const formData = new FormData();\n formData.append('priceId', priceId);\n\n const res = await fetch('?/selectPlan', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`selectPlan failed: ${res.status}`);\n }\n\n toast.success(successMessage);\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error selecting plan:', err);\n toast.error('Failed to update plan');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function subscribe(priceId: string) {\n await selectPlan(priceId, 'Subscription started');\n }\n\n async function switchPlan(priceId: string) {\n await selectPlan(priceId, 'Subscription updated');\n }\n\n async function resumeSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isSubscribing = activeSubscription.priceId;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: false };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/resumeSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Resume failed: ${res.status}`);\n }\n\n toast.success('Subscription resumed');\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error resuming subscription:', err);\n toast.error('Failed to resume subscription');\n activeSubscription = previous;\n } finally {\n isSubscribing = null;\n }\n }\n\n async function handleCancelSubscription() {\n if (!activeSubscription) return;\n const previous = activeSubscription;\n isCanceling = true;\n activeSubscription = { ...activeSubscription, cancelAtPeriodEnd: true };\n try {\n const formData = new FormData();\n formData.append('subscriptionId', previous.id);\n\n const res = await fetch('?/cancelSubscription', {\n method: 'POST',\n body: formData\n });\n\n if (!res.ok) {\n throw new Error(`Cancel failed: ${res.status}`);\n }\n\n toast.success('Subscription will cancel at period end');\n showCancelDialog = false;\n setTimeout(() => {\n refreshAll();\n }, 2000);\n } catch (err) {\n console.error('Error canceling subscription:', err);\n toast.error('Failed to cancel subscription');\n activeSubscription = previous;\n } finally {\n isCanceling = false;\n }\n }\n<\/script>\n\n<div class=\"divide-y divide-gray-900/10 dark:divide-white/10\">\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Payment Methods</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">\n Manage your payment methods for subscriptions and purchases.\n </p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if !data.billingReady}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">Setting up billing</p>\n <p class=\"text-sm\">This takes a moment after signing up. Refresh to check again.</p>\n </div>\n {:else if paymentMethods.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <CreditCard class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No payment methods</p>\n <p class=\"text-sm\">Add a payment method to get started</p>\n </div>\n {:else}\n <div class=\"space-y-4\">\n {#each paymentMethods as method (method.id)}\n <div\n class=\"border-border hover:bg-accent/50 flex items-center justify-between rounded-lg border p-4 transition-colors\"\n >\n <div class=\"flex items-center gap-4\">\n <div\n class=\"bg-muted flex size-12 items-center justify-center rounded-lg text-2xl\"\n >\n {getCardBrandIcon(method.brand)}\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">\n {formatCardBrand(method.brand)} •••• {method.last4}\n </p>\n {#if method.isDefault}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Default\n </Badge>\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n Expires {method.expMonth.toString().padStart(2, '0')}/{method.expYear}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if !method.isDefault}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => setDefaultPaymentMethod(method.id)}\n >\n Set as Default\n </Button>\n {/if}\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n onclick={() => openDeleteDialog(method.id)}\n disabled={method.isDefault && paymentMethods.length === 1}\n >\n <Trash2 class=\"size-4\" />\n </Button>\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n {#if data.billingReady}\n <Card.Footer class=\"border-t justify-end\">\n <SetupButton\n label=\"Add Payment Method\"\n processingLabel=\"Adding...\"\n onsuccess={() => invalidate('app:billing')}\n />\n </Card.Footer>\n {/if}\n </Card.Root>\n </div>\n </div>\n\n <div class=\"grid grid-cols-1 gap-x-8 gap-y-8 py-10 md:grid-cols-3\">\n <div class=\"px-4 sm:px-0\">\n <h2 class=\"text-base/7 font-semibold text-gray-900 dark:text-white\">Plan</h2>\n <p class=\"mt-1 text-sm/6 text-gray-600 dark:text-gray-400\">Manage your subscription.</p>\n </div>\n\n <div class=\"md:col-span-2\">\n <Card.Root>\n <Card.Content>\n {#if availablePlans.length === 0}\n <div\n class=\"text-muted-foreground flex flex-col items-center justify-center py-12 text-center\"\n >\n <Package class=\"mb-4 size-12 opacity-50\" />\n <p class=\"mb-2 text-lg font-medium\">No plans available</p>\n <p class=\"text-sm\">Check back soon.</p>\n </div>\n {:else}\n {#if !hasDefaultPaymentMethod}\n <p class=\"text-muted-foreground mb-4 rounded-md border border-dashed p-3 text-sm\">\n Add a default payment method above to subscribe.\n </p>\n {/if}\n <div class=\"space-y-4\">\n {#each availablePlans as plan (plan.id)}\n {@const isCurrent = activeSubscription?.priceId === plan.id}\n <div\n class=\"flex items-center justify-between rounded-lg border p-4 transition-colors {isCurrent\n ? 'border-primary ring-primary ring-1'\n : 'border-border hover:bg-accent/50'}\"\n >\n <div class=\"flex items-center gap-4\">\n <div class=\"bg-muted flex size-12 items-center justify-center rounded-lg\">\n <Package class=\"size-5\" />\n </div>\n <div>\n <div class=\"flex items-center gap-2\">\n <p class=\"font-medium\">{plan.productName}</p>\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Badge variant=\"outline\">Pending cancellation</Badge>\n {:else if activeSubscription.status === 'trialing'}\n <Badge variant=\"secondary\">Trial</Badge>\n {:else if activeSubscription.status === 'past_due'}\n <Badge variant=\"destructive\">Past due</Badge>\n {:else}\n <Badge variant=\"secondary\">\n <Check class=\"mr-1 size-3\" />\n Current\n </Badge>\n {/if}\n {/if}\n </div>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(plan.unitAmount, plan.currency)}\n {formatInterval(plan.recurring)}\n {#if isCurrent && activeSubscription?.currentPeriodEnd}\n <span>\n •\n {activeSubscription.cancelAtPeriodEnd ? 'Cancels on' : 'Renews on'}\n {formatDate(activeSubscription.currentPeriodEnd)}\n </span>\n {/if}\n </p>\n </div>\n </div>\n <div class=\"flex items-center gap-2\">\n {#if isCurrent && activeSubscription}\n {#if activeSubscription.cancelAtPeriodEnd}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={isSubscribing === plan.id}\n onclick={resumeSubscription}\n >\n {isSubscribing === plan.id ? 'Resuming...' : 'Resume'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onclick={() => (showCancelDialog = true)}\n >\n Cancel subscription\n </Button>\n {/if}\n {:else if activeSubscription}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => switchPlan(plan.id)}\n >\n {isSubscribing === plan.id ? 'Switching...' : 'Switch'}\n </Button>\n {:else}\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={!hasDefaultPaymentMethod || isSubscribing === plan.id}\n onclick={() => subscribe(plan.id)}\n >\n {isSubscribing === plan.id ? 'Subscribing...' : 'Subscribe'}\n </Button>\n {/if}\n </div>\n </div>\n {/each}\n </div>\n {/if}\n </Card.Content>\n </Card.Root>\n </div>\n </div>\n</div>\n\n<!-- Cancel Subscription Dialog -->\n<AlertDialog.Root bind:open={showCancelDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Cancel Subscription</AlertDialog.Title>\n <AlertDialog.Description>\n Your subscription will remain active until the end of the current billing period, then\n cancel automatically.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={() => (showCancelDialog = false)}>\n Keep Subscription\n </AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleCancelSubscription} disabled={isCanceling}>\n {isCanceling ? 'Canceling...' : 'Cancel at Period End'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n\n<!-- Delete Confirmation Dialog -->\n<AlertDialog.Root bind:open={showDeleteDialog}>\n <AlertDialog.Content>\n <AlertDialog.Header>\n <AlertDialog.Title>Remove Payment Method</AlertDialog.Title>\n <AlertDialog.Description>\n Are you sure you want to remove this payment method? This action cannot be undone.\n </AlertDialog.Description>\n </AlertDialog.Header>\n <AlertDialog.Footer>\n <AlertDialog.Cancel onclick={closeDeleteDialog}>Cancel</AlertDialog.Cancel>\n <AlertDialog.Action onclick={handleDeletePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Removing...' : 'Remove'}\n </AlertDialog.Action>\n </AlertDialog.Footer>\n </AlertDialog.Content>\n</AlertDialog.Root>\n", o = "import type Stripe from 'stripe';\nimport { handlePaymentIntentSucceeded } from './payment-intent/succeeded';\nimport { handlePaymentMethodAttached } from './payment-method/attached';\nimport { handleSubscriptionCreated } from './subscription/created';\nimport { handleSubscriptionUpdated } from './subscription/updated';\nimport { handleSubscriptionDeleted } from './subscription/deleted';\n\n/**\n * Routes a verified Stripe event to its handler. Runs inside the stripe-event\n * workflow, so a handler that throws is retried with backoff rather than lost.\n */\nexport async function dispatchStripeEvent(event: Stripe.Event, locals: App.Locals) {\n switch (event.type) {\n case 'payment_intent.succeeded':\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n case 'payment_method.attached':\n await handlePaymentMethodAttached(event.data.object, locals);\n break;\n\n case 'customer.subscription.created':\n await handleSubscriptionCreated(event.data.object, locals);\n break;\n\n case 'customer.subscription.updated':\n await handleSubscriptionUpdated(event.data.object, locals);\n break;\n\n case 'customer.subscription.deleted':\n await handleSubscriptionDeleted(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n}\n";
|
|
3
|
-
//#endregion
|
|
4
|
-
export { n as a, r as i, a as n, t as o, i as r, e as s, o as t };
|
|
5
|
-
|
|
6
|
-
//# sourceMappingURL=dispatch-CXOXPLFk.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dispatch-CXOXPLFk.js","names":[],"sources":[],"mappings":""}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"env-vars-C1NUX-bf.js","names":[],"sources":["../../src/runtime/env-vars.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type Expression,\n type ObjectLiteralElementLike,\n type ObjectLiteralExpression,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\nimport { toDeleteEntry } from \"../patterns/destroy/shared\";\nimport { modifyOutcomeToFile } from \"./modify-file\";\nimport {\n ENV_DECL_CANDIDATES,\n envVarEntry,\n envVarsFile,\n ENV_MODULE,\n type EnvVarSpec,\n} from \"./env-vars-file\";\nimport { ensureNamedImport, formatLikeSource } from \"./ts-morph-helpers\";\n\nexport { ENV_DECL_CANDIDATES, envVarEntry, envVarsFile, type EnvVarSpec };\n\n/**\n * Declares environment variables in `src/env.ts`, where SvelteKit 3 reads\n * them: a variable it finds no declaration for is not exposed through\n * `$app/env/private` or `$app/env/public` at all.\n *\n * Three shapes of `variables` are edited:\n *\n * - `export const variables = defineEnvVars({ ... })`\n * - `const variables = defineEnvVars({ ... }); export { variables }`\n * - either of the above with a plain object literal in place of the call\n *\n * Entries are matched by property name, quoted or not, and an entry that is\n * already there is never touched: a project that declared `STRIPE_SECRET_KEY`\n * as required keeps it required.\n */\n\nconst VARIABLES = \"variables\";\nconst DEFINE = \"defineEnvVars\";\n\nexport type EnvVarsUnsupported =\n /** `variables` is exported some other way: a function, `export let variables;`, a re-export. */\n | \"not-variable\"\n /** `variables` is not an object literal or `defineEnvVars({ ... })`. */\n | \"not-object\"\n /** The object spreads another one in, which may already declare the names. */\n | \"spread\"\n /** A computed key (`[name]: ...`) whose name can't be read. */\n | \"computed-key\";\n\nexport type EnvVarsEditResult =\n | { status: \"changed\" | \"unchanged\" }\n | { status: \"unsupported\"; reason: EnvVarsUnsupported };\n\ntype Located =\n | { kind: \"object\"; object: ObjectLiteralExpression }\n | { kind: \"missing\" }\n | { kind: \"unsupported\"; reason: EnvVarsUnsupported };\n\nfunction unwrap(expr: Expression): Expression {\n let current = expr;\n for (;;) {\n if (\n Node.isParenthesizedExpression(current) ||\n Node.isAsExpression(current) ||\n Node.isSatisfiesExpression(current)\n ) {\n current = current.getExpression();\n continue;\n }\n return current;\n }\n}\n\n/** The local name exported as `variables`: itself, or `x` in `export { x as variables }`. */\nfunction exportedLocalName(sf: SourceFile): string | null | \"re-export\" {\n for (const decl of sf.getExportDeclarations()) {\n for (const spec of decl.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== VARIABLES) continue;\n if (decl.getModuleSpecifier()) return \"re-export\";\n return spec.getName();\n }\n }\n return null;\n}\n\n/** A top-level import or destructuring pattern that binds `name`. */\nfunction bindsName(sf: SourceFile, name: string): boolean {\n const imported = sf\n .getImportDeclarations()\n .some(\n (decl) =>\n decl.getDefaultImport()?.getText() === name ||\n decl.getNamespaceImport()?.getText() === name ||\n decl\n .getNamedImports()\n .some(\n (ni) => (ni.getAliasNode()?.getText() ?? ni.getName()) === name,\n ),\n );\n if (imported) return true;\n return sf.getVariableStatements().some((statement) =>\n statement.getDeclarations().some((decl) => {\n const nameNode = decl.getNameNode();\n return (\n !Node.isIdentifier(nameNode) &&\n nameNode\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === name &&\n (Node.isBindingElement(id.getParent()) ||\n Node.isShorthandPropertyAssignment(id.getParent())),\n )\n );\n }),\n );\n}\n\nfunction locateVariables(sf: SourceFile): Located {\n const reExported = exportedLocalName(sf);\n if (reExported === \"re-export\") {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const local = reExported ?? VARIABLES;\n\n const decl = sf.getVariableDeclaration(local);\n if (!decl) {\n // A function, class, import or destructured binding of that name,\n // exported or not, is not ours to replace.\n const taken =\n sf.getFunction(local) ?? sf.getClass(local) ?? sf.getEnum(local);\n if (taken || reExported || bindsName(sf, local)) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n return { kind: \"missing\" };\n }\n if (!reExported && !decl.isExported()) {\n // `const variables = ...` that SvelteKit can't see; exporting it is the\n // developer's call, not ours.\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n if (!Node.isIdentifier(decl.getNameNode())) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const init = decl.getInitializer();\n if (!init) return { kind: \"unsupported\", reason: \"not-variable\" };\n\n const value = unwrap(init);\n if (Node.isObjectLiteralExpression(value)) {\n return { kind: \"object\", object: value };\n }\n if (\n Node.isCallExpression(value) &&\n value.getExpression().getText() === DEFINE\n ) {\n const arg = value.getArguments()[0];\n const object = arg && unwrap(arg as Expression);\n if (object && Node.isObjectLiteralExpression(object)) {\n return { kind: \"object\", object };\n }\n }\n return { kind: \"unsupported\", reason: \"not-object\" };\n}\n\n/** A property's name as SvelteKit sees it, `null` for a spread or computed key. */\nfunction propertyName(prop: ObjectLiteralElementLike): string | null {\n if (Node.isSpreadAssignment(prop)) return null;\n const nameNode = prop.getNameNode();\n if (Node.isComputedPropertyName(nameNode)) {\n const inner = nameNode.getExpression();\n return Node.isStringLiteral(inner) ||\n Node.isNoSubstitutionTemplateLiteral(inner)\n ? inner.getLiteralText()\n : null;\n }\n if (\n Node.isStringLiteral(nameNode) ||\n Node.isNoSubstitutionTemplateLiteral(nameNode)\n ) {\n return nameNode.getLiteralText();\n }\n return nameNode.getText();\n}\n\nfunction declaredNames(\n object: ObjectLiteralExpression,\n): Set<string> | EnvVarsUnsupported {\n const names = new Set<string>();\n for (const prop of object.getProperties()) {\n if (Node.isSpreadAssignment(prop)) return \"spread\";\n const name = propertyName(prop);\n if (name === null) return \"computed-key\";\n names.add(name);\n }\n return names;\n}\n\n/** The quote the file already writes its strings with. */\nfunction quoteOf(sf: SourceFile): \"'\" | '\"' {\n const first = sf.getFirstDescendantByKind(SyntaxKind.StringLiteral);\n return first?.getText().startsWith('\"') ? '\"' : \"'\";\n}\n\n/**\n * Add a declaration for every spec `sf` doesn't declare yet. Creates\n * `export const variables = defineEnvVars({ ... })`, and its import, when the\n * file has no `variables` at all. Neither formats nor saves.\n */\nexport function addEnvVars(\n sf: SourceFile,\n specs: EnvVarSpec[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const quote = quoteOf(sf);\n\n if (located.kind === \"missing\") {\n const unique = dedupe(specs);\n if (unique.length === 0) return { status: \"unchanged\" };\n ensureNamedImport(sf, ENV_MODULE, DEFINE);\n const entries = unique\n .map((spec) => `\\t${envVarEntry(spec, { quote })}`)\n .join(\",\\n\");\n sf.addStatements(\n `\\nexport const ${VARIABLES} = ${DEFINE}({\\n${entries}\\n});`,\n );\n return { status: \"changed\" };\n }\n\n const declared = declaredNames(located.object);\n if (typeof declared === \"string\") {\n return { status: \"unsupported\", reason: declared };\n }\n const missing = dedupe(specs).filter((spec) => !declared.has(spec.name));\n if (missing.length === 0) return { status: \"unchanged\" };\n for (const spec of missing) {\n located.object.addProperty(envVarEntry(spec, { quote }));\n }\n return { status: \"changed\" };\n}\n\n/**\n * Remove the declarations of `names` from `sf`. A file with no `variables`,\n * or none of the names, is unchanged. Neither formats nor saves.\n */\nexport function removeEnvVars(\n sf: SourceFile,\n names: string[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"missing\") return { status: \"unchanged\" };\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const wanted = new Set(names);\n const doomed = located.object.getProperties().filter((prop) => {\n const name = propertyName(prop);\n return name !== null && wanted.has(name);\n });\n if (doomed.length === 0) return { status: \"unchanged\" };\n for (const prop of doomed.reverse()) prop.remove();\n if (located.object.getProperties().length === 0) {\n located.object.replaceWithText(\"{}\");\n }\n return { status: \"changed\" };\n}\n\nfunction dedupe(specs: EnvVarSpec[]): EnvVarSpec[] {\n const seen = new Set<string>();\n return specs.filter((spec) => {\n if (seen.has(spec.name)) return false;\n seen.add(spec.name);\n return true;\n });\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n skipFileDependencyResolution: true,\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/** The project's declaration file: `src/env.ts` or `src/env.js`, if either exists. */\nexport function findEnvDecl(root: string): string | null {\n for (const rel of ENV_DECL_CANDIDATES) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\nfunction relative(root: string, filePath: string): string {\n return path.relative(root, filePath).split(path.sep).join(\"/\");\n}\n\nconst REASONS: Record<EnvVarsUnsupported, string> = {\n \"not-variable\": \"its `variables` export is not a variable this can edit\",\n \"not-object\":\n \"`variables` is not an object literal or a `defineEnvVars({ ... })` call\",\n spread: \"`variables` spreads in another object\",\n \"computed-key\": \"`variables` has a computed key\",\n};\n\nfunction addHint(\n file: string,\n reason: EnvVarsUnsupported,\n specs: EnvVarSpec[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n \"Declare these in the object passed to defineEnvVars() (or exported as `variables`), skipping any already there:\",\n \"\",\n ...dedupe(specs).map((spec) => `${envVarEntry(spec)},`),\n ].join(\"\\n\");\n}\n\nfunction removeHint(\n file: string,\n reason: EnvVarsUnsupported,\n names: string[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n `Remove these declarations from \\`variables\\` by hand: ${names.join(\", \")}`,\n ].join(\"\\n\");\n}\n\nexport interface ModifyEnvVarsResult {\n /** `src/env.ts` to create, when the project has no declaration file. */\n create?: File;\n /** The existing declaration file, already saved when `outcome` changed it. */\n modify?: { filePath: string; outcome: ModifyOutcome };\n}\n\n/**\n * Declare `specs` in the project's `src/env.ts` (or `src/env.js`). Existing\n * entries are never touched.\n *\n * - No declaration file: `create` holds a new `src/env.ts` (always `.ts`,\n * written like the CLI templates' one); nothing is written yet.\n * - An existing file is edited and saved in place, and `modify` reports it\n * like every other runtime modifier: turn it into a File with\n * `modifyOutcomeToFile` (or use {@link modifyEnvVarsFiles}).\n * - A file whose `variables` can't be edited safely is left alone, and the\n * `failed` outcome's message lists the exact entries to paste.\n */\nexport function modifyEnvVars(\n root: string,\n specs: EnvVarSpec[],\n): ModifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n if (dedupe(specs).length === 0) return {};\n const filePath = path.join(root, ENV_DECL_CANDIDATES[0]);\n return {\n create: {\n path: filePath,\n language: languageFromPath(filePath),\n content: envVarsFile(specs),\n status: \"success\",\n },\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = addEnvVars(sf, specs);\n if (result.status === \"unsupported\") {\n return {\n modify: {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: addHint(relative(root, existing), result.reason, specs),\n },\n },\n };\n }\n if (result.status === \"unchanged\") {\n return {\n modify: {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n },\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n modify: { filePath: existing, outcome: { status: \"success\", changed } },\n };\n}\n\n/** {@link modifyEnvVars} as the File entries a pattern's Result carries. */\nexport function modifyEnvVarsFiles(\n root: string,\n specs: EnvVarSpec[],\n): { create: File | null; modify: File | null } {\n const { create, modify } = modifyEnvVars(root, specs);\n return {\n create: create ?? null,\n modify: modify\n ? modifyOutcomeToFile(modify.filePath, modify.outcome)\n : null,\n };\n}\n\nexport interface UnmodifyEnvVarsResult {\n filePath: string;\n outcome: ModifyOutcome;\n /**\n * The revert left nothing but the `defineEnvVars` import and an empty\n * `variables`. The emptied file has been saved; the caller reports it as a\n * delete (`toDeleteEntry(filePath)`) instead of a modify, as\n * {@link unmodifyEnvVarsFiles} does.\n */\n deleted: boolean;\n}\n\n/**\n * Remove the declarations of `names` from `src/env.ts` (or `.js`). A project\n * without the file, or without the names, is a no-op success.\n */\nexport function unmodifyEnvVars(\n root: string,\n names: string[],\n): UnmodifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n return {\n filePath: path.join(root, ENV_DECL_CANDIDATES[0]),\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = removeEnvVars(sf, names);\n if (result.status === \"unsupported\") {\n return {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: removeHint(relative(root, existing), result.reason, names),\n },\n deleted: false,\n };\n }\n if (result.status === \"unchanged\") {\n return {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n filePath: existing,\n outcome: { status: \"success\", changed },\n deleted: changed && holdsNothing(sf),\n };\n}\n\n/** {@link unmodifyEnvVars} as the File entries a pattern's Result carries. */\nexport function unmodifyEnvVarsFiles(\n root: string,\n names: string[],\n): { modify: File | null; delete: File | null } {\n const { filePath, outcome, deleted } = unmodifyEnvVars(root, names);\n if (deleted) return { modify: null, delete: toDeleteEntry(filePath) };\n return { modify: modifyOutcomeToFile(filePath, outcome), delete: null };\n}\n\n/**\n * Only the `defineEnvVars` import, an empty `variables` and its\n * `export { variables }` are left. Comments don't count.\n */\nfunction holdsNothing(sf: SourceFile): boolean {\n const located = locateVariables(sf);\n if (located.kind !== \"object\") return false;\n if (located.object.getProperties().length > 0) return false;\n const decl = located.object.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n return sf.getStatements().every((statement: Statement) => {\n if (statement === decl) return true;\n if (Node.isEmptyStatement(statement)) return true;\n if (Node.isImportDeclaration(statement)) {\n return (\n statement.getModuleSpecifierValue() === ENV_MODULE &&\n !statement.getDefaultImport() &&\n !statement.getNamespaceImport() &&\n statement.getNamedImports().every((ni) => ni.getName() === DEFINE)\n );\n }\n if (Node.isExportDeclaration(statement)) {\n return (\n !statement.getModuleSpecifier() &&\n statement\n .getNamedExports()\n .every(\n (spec) =>\n (spec.getAliasNode()?.getText() ?? spec.getName()) === VARIABLES,\n )\n );\n }\n return false;\n });\n}\n"],"mappings":";;;;;;;;;AA4CA,IAAM,IAAY,aACZ,IAAS;AAqBf,SAAS,EAAO,GAA8B;CAC5C,IAAI,IAAU;CACd,SAAS;EACP,IACE,EAAK,0BAA0B,CAAO,KACtC,EAAK,eAAe,CAAO,KAC3B,EAAK,sBAAsB,CAAO,GAClC;GACA,IAAU,EAAQ,cAAc;GAChC;EACF;EACA,OAAO;CACT;AACF;AAGA,SAAS,EAAkB,GAA6C;CACtE,KAAK,IAAM,KAAQ,EAA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IAElC,EAAU,wBAAwB,MAAA,uBAClC,CAAC,EAAU,iBAAiB,KAC5B,CAAC,EAAU,mBAAmB,KAC9B,EAAU,gBAAgB,CAAC,CAAC,OAAO,MAAO,EAAG,QAAQ,MAAM,CAAM,IAGjE,EAAK,oBAAoB,CAAS,IAElC,CAAC,EAAU,mBAAmB,KAC9B,EACG,gBAAgB,CAAC,CACjB,OACE,OACE,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAK,EAAK,QAAQ,OAAO,CAC3D,IAGC,EACR;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"format-result-DZ8De8KY.js","names":[],"sources":["../../src/core/format-result.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport prettier from \"prettier\";\nimport type { File, Options, Result } from \"./types\";\nimport sveltePlugin from \"prettier-plugin-svelte\";\n\n/** What the formatter needs to know about the run: where the project is, and whether it exists at all. */\nexport type FormatContext = Pick<Options, \"env\" | \"root\">;\n\nfunction canFormatFile(file: File): boolean {\n return (\n file.language === \"ts\" ||\n file.language === \"js\" ||\n file.language === \"svelte\" ||\n file.path.endsWith(\".json\")\n );\n}\n\nfunction dependsOnPrettier(root: string): boolean {\n try {\n const pkg = JSON.parse(\n readFileSync(path.join(root, \"package.json\"), \"utf8\"),\n ) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return Boolean(pkg.dependencies?.prettier || pkg.devDependencies?.prettier);\n } catch {\n return false;\n }\n}\n\n/**\n * Whether the project formats with prettier: it depends on it, or prettier\n * finds a config file for the target (a monorepo may keep one at its root).\n * A project with neither, like a bare `sv create`, has a style of its own\n * that prettier's defaults would rewrite in every file a pattern edits.\n */\nasync function usesPrettier(root: string, target: string): Promise<boolean> {\n if (dependsOnPrettier(root)) return true;\n return (await prettier.resolveConfigFile(target)) !== null;\n}\n\n/**\n * The target project's own prettier settings (`.prettierrc`, `.editorconfig`,\n * `package.json#prettier`), so pattern output matches what `npm run lint`\n * expects there; `null` when the project does not use prettier. Preview runs\n * have no project and use prettier's defaults.\n *\n * The svelte plugin is always supplied as a module: a project's config names\n * it by string, which would resolve relative to this package instead.\n */\nasync function projectOptions(\n file: Pick<File, \"path\">,\n context?: FormatContext,\n): Promise<prettier.Options | null> {\n if (context?.env !== \"runtime\" || !context.root) return {};\n const target = path.isAbsolute(file.path)\n ? file.path\n : path.join(context.root, file.path);\n if (!(await usesPrettier(context.root, target))) return null;\n const resolved = await prettier.resolveConfig(target, { editorconfig: true });\n if (!resolved) return {};\n const plugins = (resolved.plugins ?? []).filter(\n (plugin) => plugin !== \"prettier-plugin-svelte\",\n );\n return { ...resolved, plugins };\n}\n\nconst MAX_FORMAT_PASSES = 3;\n\n/**\n * Formats one source text the way pattern output is formatted; the content\n * comes back unchanged when prettier cannot parse it, or when the project\n * does not use prettier and the file is not `created`. A file a generator\n * created is formatted either way, with prettier's defaults if need be: it\n * relies on formatting for its indentation and has no style of its own to\n * keep. Also used for component files that arrive on disk from\n * `shadcn-svelte add` or the bundled components, so `npm run lint` in the\n * project stays clean after an install.\n */\nexport async function formatSource(\n content: string,\n filePath: string,\n context?: FormatContext,\n { created = false }: { created?: boolean } = {},\n): Promise<string> {\n try {\n const options =\n (await projectOptions({ path: filePath }, context)) ??\n (created ? {} : null);\n if (!options) return content;\n const format = (source: string) =>\n prettier.format(source, {\n ...options,\n filepath: filePath,\n plugins: [...(options.plugins ?? []), sveltePlugin],\n });\n // Prettier is not always idempotent: a long one-line member chain\n // (`await context.admin.collection(\"x\").create({ ... })`) comes out broken\n // across lines on the first pass and joined on the second, which the\n // project's `prettier --check` would flag. Format until it settles.\n let formatted = await format(content);\n for (let pass = 1; pass < MAX_FORMAT_PASSES; pass++) {\n const again = await format(formatted);\n if (again === formatted) break;\n formatted = again;\n }\n return formatted;\n } catch {\n return content;\n }\n}\n\nasync function formatFile(\n file: File,\n context: FormatContext | undefined,\n created: boolean,\n): Promise<File> {\n if (file.status !== \"success\" || !canFormatFile(file)) {\n return file;\n }\n return {\n ...file,\n content: await formatSource(file.content, file.path, context, { created }),\n };\n}\n\nasync function formatFiles(\n files: File[],\n context: FormatContext | undefined,\n created: boolean,\n): Promise<File[]> {\n return Promise.all(files.map((file) => formatFile(file, context, created)));\n}\n\nexport async function formatResult(\n result: Result,\n context?: FormatContext,\n): Promise<Result> {\n const [creates, modifies] = await Promise.all([\n formatFiles(result.creates, context, true),\n formatFiles(result.modifies, context, false),\n ]);\n\n return {\n ...result,\n creates,\n modifies,\n };\n}\n"],"mappings":";;;;;AASA,SAAS,EAAc,GAAqB;CAC1C,OACE,EAAK,aAAa,QAClB,EAAK,aAAa,QAClB,EAAK,aAAa,YAClB,EAAK,KAAK,SAAS,OAAO;AAE9B;AAEA,SAAS,EAAkB,GAAuB;CAChD,IAAI;EACF,IAAM,IAAM,KAAK,MACf,EAAa,EAAK,KAAK,GAAM,cAAc,GAAG,MAAM,CACtD;EAIA,OAAO,GAAQ,EAAI,cAAc,YAAY,EAAI,iBAAiB;CACpE,QAAQ;EACN,OAAO;CACT;AACF;AAQA,eAAe,EAAa,GAAc,GAAkC;CAE1E,OADI,EAAkB,CAAI,IAAU,KAC5B,MAAM,EAAS,kBAAkB,CAAM,MAAO;AACxD;AAWA,eAAe,EACb,GACA,GACkC;CAClC,IAAI,GAAS,QAAQ,aAAa,CAAC,EAAQ,MAAM,OAAO,CAAC;CACzD,IAAM,IAAS,EAAK,WAAW,EAAK,IAAI,IACpC,EAAK,OACL,EAAK,KAAK,EAAQ,MAAM,EAAK,IAAI;CACrC,IAAI,CAAE,MAAM,EAAa,EAAQ,MAAM,CAAM,GAAI,OAAO;CACxD,IAAM,IAAW,MAAM,EAAS,cAAc,GAAQ,EAAE,cAAc,GAAK,CAAC;CAC5E,IAAI,CAAC,GAAU,OAAO,CAAC;CACvB,IAAM,KAAW,EAAS,WAAW,CAAC,EAAA,CAAG,QACtC,MAAW,MAAW,wBACzB;CACA,OAAO;EAAE,GAAG;EAAU;CAAQ;AAChC;AAEA,IAAM,IAAoB;AAY1B,eAAsB,EACpB,GACA,GACA,GACA,EAAE,aAAU,OAAiC,CAAC,GAC7B;CACjB,IAAI;EACF,IAAM,IACH,MAAM,EAAe,EAAE,MAAM,EAAS,GAAG,CAAO,MAChD,IAAU,CAAC,IAAI;EAClB,IAAI,CAAC,GAAS,OAAO;EACrB,IAAM,KAAU,MACd,EAAS,OAAO,GAAQ;GACtB,GAAG;GACH,UAAU;GACV,SAAS,CAAC,GAAI,EAAQ,WAAW,CAAC,GAAI,CAAY;EACpD,CAAC,GAKC,IAAY,MAAM,EAAO,CAAO;EACpC,KAAK,IAAI,IAAO,GAAG,IAAO,GAAmB,KAAQ;GACnD,IAAM,IAAQ,MAAM,EAAO,CAAS;GACpC,IAAI,MAAU,GAAW;GACzB,IAAY;EACd;EACA,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,EACb,GACA,GACA,GACe;CAIf,OAHI,EAAK,WAAW,aAAa,CAAC,EAAc,CAAI,IAC3C,IAEF;EACL,GAAG;EACH,SAAS,MAAM,EAAa,EAAK,SAAS,EAAK,MAAM,GAAS,EAAE,WAAQ,CAAC;CAC3E;AACF;AAEA,eAAe,EACb,GACA,GACA,GACiB;CACjB,OAAO,QAAQ,IAAI,EAAM,KAAK,MAAS,EAAW,GAAM,GAAS,CAAO,CAAC,CAAC;AAC5E;AAEA,eAAsB,EACpB,GACA,GACiB;CACjB,IAAM,CAAC,GAAS,KAAY,MAAM,QAAQ,IAAI,CAC5C,EAAY,EAAO,SAAS,GAAS,EAAI,GACzC,EAAY,EAAO,UAAU,GAAS,EAAK,CAC7C,CAAC;CAED,OAAO;EACL,GAAG;EACH;EACA;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate-BW3l5Fxw.js","names":[],"sources":["../../node_modules/change-case/dist/index.js","../../src/parse/route.ts","../../src/patterns/enable/ai/generate.ts"],"sourcesContent":["// Regexps involved with splitting words in various case formats.\nconst SPLIT_LOWER_UPPER_RE = /([\\p{Ll}\\d])(\\p{Lu})/gu;\nconst SPLIT_UPPER_UPPER_RE = /(\\p{Lu})([\\p{Lu}][\\p{Ll}])/gu;\n// Used to iterate over the initial split result and separate numbers.\nconst SPLIT_SEPARATE_NUMBER_RE = /(\\d)\\p{Ll}|(\\p{L})\\d/u;\n// Regexp involved with stripping non-word characters from the result.\nconst DEFAULT_STRIP_REGEXP = /[^\\p{L}\\d]+/giu;\n// The replacement value for splits.\nconst SPLIT_REPLACE_VALUE = \"$1\\0$2\";\n// The default characters to keep after transforming case.\nconst DEFAULT_PREFIX_SUFFIX_CHARACTERS = \"\";\n/**\n * Split any cased input strings into an array of words.\n */\nexport function split(value) {\n let result = value.trim();\n result = result\n .replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE)\n .replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);\n result = result.replace(DEFAULT_STRIP_REGEXP, \"\\0\");\n let start = 0;\n let end = result.length;\n // Trim the delimiter from around the output string.\n while (result.charAt(start) === \"\\0\")\n start++;\n if (start === end)\n return [];\n while (result.charAt(end - 1) === \"\\0\")\n end--;\n return result.slice(start, end).split(/\\0/g);\n}\n/**\n * Split the input string into an array of words, separating numbers.\n */\nexport function splitSeparateNumbers(value) {\n const words = split(value);\n for (let i = 0; i < words.length; i++) {\n const word = words[i];\n const match = SPLIT_SEPARATE_NUMBER_RE.exec(word);\n if (match) {\n const offset = match.index + (match[1] ?? match[2]).length;\n words.splice(i, 1, word.slice(0, offset), word.slice(offset));\n }\n }\n return words;\n}\n/**\n * Convert a string to space separated lower case (`foo bar`).\n */\nexport function noCase(input, options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (prefix +\n words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? \" \") +\n suffix);\n}\n/**\n * Convert a string to camel case (`fooBar`).\n */\nexport function camelCase(input, options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return (prefix +\n words\n .map((word, index) => {\n if (index === 0)\n return lower(word);\n return transform(word, index);\n })\n .join(options?.delimiter ?? \"\") +\n suffix);\n}\n/**\n * Convert a string to pascal case (`FooBar`).\n */\nexport function pascalCase(input, options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = options?.mergeAmbiguousCharacters\n ? capitalCaseTransformFactory(lower, upper)\n : pascalCaseTransformFactory(lower, upper);\n return prefix + words.map(transform).join(options?.delimiter ?? \"\") + suffix;\n}\n/**\n * Convert a string to pascal snake case (`Foo_Bar`).\n */\nexport function pascalSnakeCase(input, options) {\n return capitalCase(input, { delimiter: \"_\", ...options });\n}\n/**\n * Convert a string to capital case (`Foo Bar`).\n */\nexport function capitalCase(input, options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n return (prefix +\n words\n .map(capitalCaseTransformFactory(lower, upper))\n .join(options?.delimiter ?? \" \") +\n suffix);\n}\n/**\n * Convert a string to constant case (`FOO_BAR`).\n */\nexport function constantCase(input, options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n return (prefix +\n words.map(upperFactory(options?.locale)).join(options?.delimiter ?? \"_\") +\n suffix);\n}\n/**\n * Convert a string to dot case (`foo.bar`).\n */\nexport function dotCase(input, options) {\n return noCase(input, { delimiter: \".\", ...options });\n}\n/**\n * Convert a string to kebab case (`foo-bar`).\n */\nexport function kebabCase(input, options) {\n return noCase(input, { delimiter: \"-\", ...options });\n}\n/**\n * Convert a string to path case (`foo/bar`).\n */\nexport function pathCase(input, options) {\n return noCase(input, { delimiter: \"/\", ...options });\n}\n/**\n * Convert a string to path case (`Foo bar`).\n */\nexport function sentenceCase(input, options) {\n const [prefix, words, suffix] = splitPrefixSuffix(input, options);\n const lower = lowerFactory(options?.locale);\n const upper = upperFactory(options?.locale);\n const transform = capitalCaseTransformFactory(lower, upper);\n return (prefix +\n words\n .map((word, index) => {\n if (index === 0)\n return transform(word);\n return lower(word);\n })\n .join(options?.delimiter ?? \" \") +\n suffix);\n}\n/**\n * Convert a string to snake case (`foo_bar`).\n */\nexport function snakeCase(input, options) {\n return noCase(input, { delimiter: \"_\", ...options });\n}\n/**\n * Convert a string to header case (`Foo-Bar`).\n */\nexport function trainCase(input, options) {\n return capitalCase(input, { delimiter: \"-\", ...options });\n}\nfunction lowerFactory(locale) {\n return locale === false\n ? (input) => input.toLowerCase()\n : (input) => input.toLocaleLowerCase(locale);\n}\nfunction upperFactory(locale) {\n return locale === false\n ? (input) => input.toUpperCase()\n : (input) => input.toLocaleUpperCase(locale);\n}\nfunction capitalCaseTransformFactory(lower, upper) {\n return (word) => `${upper(word[0])}${lower(word.slice(1))}`;\n}\nfunction pascalCaseTransformFactory(lower, upper) {\n return (word, index) => {\n const char0 = word[0];\n const initial = index > 0 && char0 >= \"0\" && char0 <= \"9\" ? \"_\" + char0 : upper(char0);\n return initial + lower(word.slice(1));\n };\n}\nfunction splitPrefixSuffix(input, options = {}) {\n const splitFn = options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);\n const prefixCharacters = options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n const suffixCharacters = options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;\n let prefixIndex = 0;\n let suffixIndex = input.length;\n while (prefixIndex < input.length) {\n const char = input.charAt(prefixIndex);\n if (!prefixCharacters.includes(char))\n break;\n prefixIndex++;\n }\n while (suffixIndex > prefixIndex) {\n const index = suffixIndex - 1;\n const char = input.charAt(index);\n if (!suffixCharacters.includes(char))\n break;\n suffixIndex = index;\n }\n return [\n input.slice(0, prefixIndex),\n splitFn(input.slice(prefixIndex, suffixIndex)),\n input.slice(suffixIndex),\n ];\n}\n//# sourceMappingURL=index.js.map","import * as changeCase from \"change-case\";\nimport { APP_DIR, PUBLIC_DIR } from \"../core/constants\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport type { Options } from \"../core/types\";\nimport type {\n Model,\n RouteInfo,\n RouteKind,\n ScaffoldFilePaths,\n ScaffoldUrls,\n} from \"./types\";\n\nconst ROUTES_ROOT = \"src/routes\";\nconst DYNAMIC_PARAM_RE = /\\[([^\\]]+)\\]/g;\nconst VALID_SEGMENT_RE = /^[a-zA-Z0-9_\\-[\\]()]+$/;\n\ntype RouteOptions = Pick<Options, \"features\" | \"routeGroups\">;\n\n/**\n * The group a route lands in when none is given, or null for a project that\n * has no such group. Without `routeGroups` this is the vela layout.\n */\nexport function defaultGroup({\n features,\n routeGroups,\n}: RouteOptions): string | null {\n const groups = routeGroups ?? { public: PUBLIC_DIR, app: APP_DIR };\n return features.auth ? (groups.app ?? groups.public) : groups.public;\n}\n\nfunction routeFileBase(group: string | null, route: string): string {\n return [ROUTES_ROOT, group, route].filter(Boolean).join(\"/\");\n}\n\nfunction defaultRouteSegment(model: Model, kind: RouteKind): string {\n return kind === \"scaffold\"\n ? changeCase.kebabCase(model.pluralDisplayName)\n : changeCase.kebabCase(model.displayName);\n}\n\nfunction stripRouteGroups(filePath: string): string {\n const withoutRoot = filePath.startsWith(`${ROUTES_ROOT}/`)\n ? filePath.slice(ROUTES_ROOT.length + 1)\n : filePath;\n const segments = withoutRoot.split(\"/\").filter((segment) => {\n return !(segment.startsWith(\"(\") && segment.endsWith(\")\"));\n });\n return `/${segments.join(\"/\")}`;\n}\n\nfunction extractDynamicParams(filePath: string): string[] {\n const params: string[] = [];\n for (const match of filePath.matchAll(DYNAMIC_PARAM_RE)) {\n params.push(match[1]);\n }\n return params;\n}\n\nfunction validateRouteInput(input: string): void {\n if (input.startsWith(\"/\")) {\n throw new InvalidArgumentError(\n `Route must not start with \"/\". Got: \"${input}\"`,\n );\n }\n if (input.startsWith(`${ROUTES_ROOT}/`) || input === ROUTES_ROOT) {\n throw new InvalidArgumentError(\n `Route must not start with \"${ROUTES_ROOT}/\" — paths are rooted there automatically. Got: \"${input}\"`,\n );\n }\n const segments = input.split(\"/\");\n for (const segment of segments) {\n if (segment.length === 0) {\n throw new InvalidArgumentError(\n `Route must not contain empty segments. Got: \"${input}\"`,\n );\n }\n if (segment === \".\" || segment === \"..\") {\n throw new InvalidArgumentError(\n `Route must not contain \".\" or \"..\" segments. Got: \"${input}\"`,\n );\n }\n if (segment.startsWith(\"_\")) {\n throw new InvalidArgumentError(\n `Route segments must not start with underscore. Got: \"${segment}\"`,\n );\n }\n if (!VALID_SEGMENT_RE.test(segment)) {\n throw new InvalidArgumentError(\n `Route segment \"${segment}\" contains invalid characters. Allowed: letters, digits, underscore, dash, brackets, parentheses.`,\n );\n }\n }\n}\n\nfunction hasRouteGroup(input: string): boolean {\n return input\n .split(\"/\")\n .some((segment) => segment.startsWith(\"(\") && segment.endsWith(\")\"));\n}\n\nexport function parseRoute(\n routeInput: string | undefined,\n model: Model,\n options: RouteOptions,\n kind: RouteKind,\n): RouteInfo {\n if (routeInput === undefined || routeInput === \"\") {\n const segment = defaultRouteSegment(model, kind);\n const fileBase = routeFileBase(defaultGroup(options), segment);\n return {\n fileBase,\n urlBase: stripRouteGroups(fileBase),\n dynamicParams: extractDynamicParams(fileBase),\n };\n }\n\n validateRouteInput(routeInput);\n\n const fileBase = routeFileBase(\n hasRouteGroup(routeInput) ? null : defaultGroup(options),\n routeInput,\n );\n\n return {\n fileBase,\n urlBase: stripRouteGroups(fileBase),\n dynamicParams: extractDynamicParams(fileBase),\n };\n}\n\nexport function scaffoldFilePaths(route: RouteInfo): ScaffoldFilePaths {\n return {\n list: route.fileBase,\n new: `${route.fileBase}/new`,\n show: `${route.fileBase}/[id]`,\n edit: `${route.fileBase}/[id]/edit`,\n };\n}\n\nexport function scaffoldUrls(route: RouteInfo): ScaffoldUrls {\n return {\n list: route.urlBase,\n new: `${route.urlBase}/new`,\n show: `${route.urlBase}/[id]`,\n edit: `${route.urlBase}/[id]/edit`,\n };\n}\n","import type {\n File,\n Options,\n Package,\n Provider,\n Result,\n} from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { ZOD } from \"../../../core/constants\";\nimport { resolveUi } from \"../../../core/field/ui\";\nimport {\n providerCreates,\n providerEnvEdits,\n resolveProvider,\n} from \"../../../core/providers\";\nimport { composeCreates, filesFromGlob } from \"../../../core/util\";\nimport { defaultGroup } from \"../../../parse/route\";\n\n/**\n * The providers in prompt order. Each one's `env` key is what the CLI asks\n * for (without echo), what `generate.runtime.ts` writes to `.env` and\n * declares in `src/env.ts`; the generated `src/lib/server/ai.ts` imports it\n * from `$app/env/private`, and `/api/chat` answers 503 while it is blank.\n */\nexport const PROVIDERS: Provider[] = [\n {\n id: \"gateway\",\n label: \"Vercel AI Gateway\",\n env: [\n {\n key: \"AI_GATEWAY_API_KEY\",\n label: \"Vercel AI Gateway API key\",\n secret: true,\n },\n ],\n },\n {\n id: \"openai\",\n label: \"OpenAI\",\n env: [\n {\n key: \"OPENAI_API_KEY\",\n label: \"OpenAI API key\",\n placeholder: \"sk-...\",\n secret: true,\n },\n ],\n },\n {\n id: \"anthropic\",\n label: \"Anthropic\",\n env: [\n {\n key: \"ANTHROPIC_API_KEY\",\n label: \"Anthropic API key\",\n placeholder: \"sk-ant-...\",\n secret: true,\n },\n ],\n },\n];\n\n/**\n * `ai` carries the gateway provider itself; the others are a package each.\n * zod, a peer of `ai`, is installed alongside but is not listed here: it is\n * not the pattern's to uninstall.\n */\nexport const PACKAGES: Package[] = [\"ai@^7.0.107\", \"@ai-sdk/svelte@^5.0.107\"];\nexport const PROVIDER_PACKAGES: Record<string, Package[]> = {\n openai: [\"@ai-sdk/openai@^4.0.71\"],\n anthropic: [\"@ai-sdk/anthropic@^4.0.58\"],\n};\n\n/** What `resolveProvider` needs; `index.ts` spreads the rest of the metadata. */\nexport const META = { slug: \"enable-ai\", providers: PROVIDERS };\n\n/** Where the demo page is stored; `generate` moves it to the project's default group. */\nexport const DEMO_DIR = \"src/routes/(public)/ai/\";\n\n/**\n * The demo page's directory: `(public)/ai`, `(app)/ai` behind sign-in when\n * auth is on, or `ai` straight under `src/routes` in a project without groups.\n */\nexport function demoDir(\n options: Pick<Options, \"features\" | \"routeGroups\">,\n): string {\n return [\"src/routes\", defaultGroup(options), \"ai\"].filter(Boolean).join(\"/\");\n}\n\n/** The `.env` lines for a provider, under a `# AI SDK (<Label>)` heading. */\nexport function envEditsFor(\n provider: Provider,\n supplied: Record<string, string> = {},\n): EnvEdit[] {\n return providerEnvEdits(provider, `AI SDK (${provider.label})`, supplied);\n}\n\nconst createsRaw = import.meta.glob<string>(\"./creates/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\n// With auth, the endpoint answers only signed-in users: every reply is\n// billed to the project's API key.\nconst createsAppModeRaw = import.meta.glob<string>(\"./creates-app-mode/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\n// A plain project gets the demo page in native elements, at the same path.\nconst variantsRaw = import.meta.glob<string>(\"./variants/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst providersRaw = import.meta.glob<string>(\"./providers/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nexport async function generate(options: Options) {\n const provider = resolveProvider(META, options);\n const ui = resolveUi(options);\n const serverTests = options.input.serverTests ?? true;\n\n const files: Record<string, File> = {};\n const add = (list: File[]) => {\n for (const file of list) files[file.path] = file;\n };\n add(\n composeCreates(\n createsRaw,\n \"./creates/\",\n variantsRaw,\n ui === \"plain\" ? \"plain\" : undefined,\n ),\n );\n if (options.features.auth) {\n add(Object.values(filesFromGlob(createsAppModeRaw, \"./creates-app-mode/\")));\n }\n add(providerCreates(providersRaw, provider.id));\n\n const target = `${demoDir(options)}/`;\n const creates = Object.values(files)\n .filter((file) => serverTests || !file.path.endsWith(\"server.test.ts\"))\n .map((file) =>\n file.path.startsWith(DEMO_DIR)\n ? { ...file, path: target + file.path.slice(DEMO_DIR.length) }\n : file,\n )\n .sort((a, b) => a.path.localeCompare(b.path));\n\n return {\n creates,\n modifies: [],\n deletes: [],\n components: ui === \"plain\" ? [] : [\"button\", \"textarea\"],\n // vela's templates already have zod; a project vela did not create may not.\n packages: [...PACKAGES, ZOD, ...(PROVIDER_PACKAGES[provider.id] ?? [])],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"x_google_ignoreList":[0],"mappings":";;;;;;AACA,IAAM,IAAuB,0BACvB,IAAuB,gCAEvB,IAA2B,yBAE3B,IAAuB,kBAEvB,IAAsB,UAEtB,IAAmC;AAIzC,SAAgB,EAAM,GAAO;CACzB,IAAI,IAAS,EAAM,KAAK;CAIxB,AAHA,IAAS,EACJ,QAAQ,GAAsB,CAAmB,CAAC,CAClD,QAAQ,GAAsB,CAAmB,GACtD,IAAS,EAAO,QAAQ,GAAsB,IAAI;CAClD,IAAI,IAAQ,GACR,IAAM,EAAO;CAEjB,OAAO,EAAO,OAAO,CAAK,MAAM,OAC5B;CACJ,IAAI,MAAU,GACV,OAAO,CAAC;CACZ,OAAO,EAAO,OAAO,IAAM,CAAC,MAAM,OAC9B;CACJ,OAAO,EAAO,MAAM,GAAO,CAAG,CAAC,CAAC,MAAM,KAAK;AAC/C;AAIA,SAAgB,EAAqB,GAAO;CACxC,IAAM,IAAQ,EAAM,CAAK;CACzB,KAAK,IAAI,IAAI,GAAG,IAAI,EAAM,QAAQ,KAAK;EACnC,IAAM,IAAO,EAAM,IACb,IAAQ,EAAyB,KAAK,CAAI;EAChD,IAAI,GAAO;GACP,IAAM,IAAS,EAAM,SAAS,EAAM,MAAM,EAAM,GAAA,CAAI;GACpD,EAAM,OAAO,GAAG,GAAG,EAAK,MAAM,GAAG,CAAM,GAAG,EAAK,MAAM,CAAM,CAAC;EAChE;CACJ;CACA,OAAO;AACX;AAI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OAAO;EACL,SAVc,OAAO,OAAO,CAAK,CAAC,CACjC,QAAQ,MAAS,KAAe,CAAC,EAAK,KAAK,SAAS,gBAAgB,CAAC,CAAC,CACtE,KAAK,MACJ,EAAK,KAAK,WAAA,yBAAmB,IACzB;GAAE,GAAG;GAAM,MAAM,IAAS,EAAK,KAAK,MAAM,EAAe;EAAE,IAC3D,CACN,CAAC,CACA,MAAM,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAG3C;EACA,UAAU,CAAC;EACX,SAAS,CAAC;EACV,YAAY,MAAO,UAAU,CAAC,IAAI,CAAC,UAAU,UAAU;EAEvD,UAAU;GAAC,GAAG;GAAU;GAAK,GAAI,EAAkB,EAAS,OAAO,CAAC;EAAE;EACtE,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate-DeaBlnK6.js","names":[],"sources":["../../src/patterns/enable/cms/generate.ts"],"sourcesContent":["import type { File, Options, Result } from \"../../../core/types\";\nimport { VELASTACK_CMS, VELASTACK_KIT } from \"../../../core/constants\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\nimport { filesFromGlob } from \"../../../core/util\";\n\n// The backend, for an app that hosts the CMS itself: the SQLite-backed HTTP\n// API and the two routes that mount it and serve uploads.\nconst backendRaw = import.meta.glob<string>(\"./creates-backend/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst BACKEND_PREFIX = \"./creates-backend/\";\n\n/** Where an app that hosts the backend itself mounts it. Also the admin bar's default. */\nexport const LOCAL_ENDPOINT = \"/api/cms\";\n\nexport const ENDPOINT_EXAMPLE =\n \"https://velastack.dev/v1/projects/<project>/cms\";\n\nexport interface CmsMode {\n /** What the read path and the admin bar talk to. */\n endpoint: string;\n /** Whether this app hosts the backend at `endpoint` itself. */\n local: boolean;\n}\n\n/** `--endpoint <url>` or `--endpoint=<url>`, for callers that hand flags through in argv. */\nfunction endpointFromArgv(argv: string[]): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--endpoint\") return argv[i + 1];\n if (arg.startsWith(\"--endpoint=\")) return arg.slice(\"--endpoint=\".length);\n }\n return undefined;\n}\n\n/**\n * Which of the two shapes to produce.\n *\n * An explicit `--endpoint` means a hosted CMS: the app only reads from it and\n * the admin bar signs in there, so no backend is installed. Without one, an\n * app with a server hosts the backend itself at `/api/cms`. A static site has\n * no server to host it, so there the endpoint is required.\n */\nexport function resolveMode(options: Options): CmsMode {\n const raw =\n typeof options.input.endpoint === \"string\"\n ? options.input.endpoint\n : endpointFromArgv(options.argv);\n const endpoint = raw?.trim().replace(/\\/+$/, \"\");\n\n if (endpoint) {\n if (!/^https?:\\/\\/\\S+$/.test(endpoint)) {\n throw new InvalidArgumentError(\n `--endpoint must be the absolute URL of a hosted CMS, like ${ENDPOINT_EXAMPLE}; got ${endpoint}`,\n );\n }\n return { endpoint, local: false };\n }\n\n // A PocketBase backend implies a Node server, but it is not the only way to\n // have one: a project on adapter-node alone can host the SQLite backend too.\n // The caller detects that and says so with `input.server`.\n if (!(options.input.server ?? options.features.backend)) {\n throw new InvalidArgumentError(\n \"This site has no server to host the CMS backend. \" +\n `Point it at a hosted CMS instead: vela enable cms --endpoint ${ENDPOINT_EXAMPLE}`,\n );\n }\n\n return { endpoint: LOCAL_ENDPOINT, local: true };\n}\n\n/** `src/lib/cms.ts`: the read path, with the endpoint and locales bound. */\nfunction cmsLibSource(mode: CmsMode, i18n: boolean): string {\n const imports = [\n \"import { apiAdapter, createCms } from '@velastack/cms/server';\",\n ];\n if (i18n) imports.push(\"import { locales } from '#locales/data.js';\");\n\n const where = mode.local\n ? [\n \" * `/api/cms` is where `src/routes/api/cms/[...path]/+server.ts` mounts the\",\n \" * backend. It is also the admin bar's default, so the endpoint is named here\",\n \" * and nowhere else.\",\n ]\n : [\n \" * The CMS is hosted at this endpoint: the app reads published content from\",\n \" * it and the admin bar signs in there. The same URL is given to the `cms()`\",\n \" * plugin in vite.config.ts, which downloads media into the build.\",\n ];\n\n const which = i18n\n ? [\n \" * The locales are the site's own, from wuchale, so the CMS supports exactly\",\n \" * the languages the UI does; the first is the default that a missing\",\n \" * translation falls back to.\",\n ]\n : [\n \" * `locales` lists every locale the site supports; the first is the default\",\n \" * that a missing translation falls back to.\",\n ];\n\n return [\n ...imports,\n \"\",\n \"/**\",\n \" * The CMS read path, called from the root `+layout.server.ts`.\",\n \" *\",\n ...where,\n \" *\",\n ...which,\n \" */\",\n \"export const { load: loadCms, generateEntries } = createCms({\",\n `\\tadapter: apiAdapter({ endpoint: '${mode.endpoint}' }),`,\n `\\tlocales: ${i18n ? \"[...locales]\" : \"['en']\"}`,\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n\nexport async function generate(options: Options) {\n const mode = resolveMode(options);\n const creates: Record<string, File> = {};\n\n if (mode.local) {\n Object.assign(creates, filesFromGlob(backendRaw, BACKEND_PREFIX));\n }\n\n creates[\"src/lib/cms.ts\"] = {\n path: \"src/lib/cms.ts\",\n language: \"ts\",\n content: cmsLibSource(mode, options.features.i18n),\n status: \"success\",\n };\n\n const sortedCreates = Object.values(creates).sort((a, b) =>\n a.path.localeCompare(b.path),\n );\n\n // better-sqlite3 and marked are the package's optional peers, which npm\n // skips on install precisely because they are optional — so they have to be\n // named here. The backend needs the first; the root entry imports the\n // second statically, so <AdminBar /> cannot render without it.\n // @velastack/cms 0.6 is the SvelteKit 3 line; 0.5 and older peer on Kit 2.\n // The backend's cms.ts resolves its database with `dataPath` from\n // @velastack/kit, which a backend template has and a project on adapter-node\n // alone does not.\n const packages = mode.local\n ? [VELASTACK_CMS, VELASTACK_KIT, \"better-sqlite3\", \"marked\"]\n : [VELASTACK_CMS, \"marked\"];\n\n return {\n creates: sortedCreates,\n modifies: [],\n deletes: [],\n components: [],\n packages,\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;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,EAAS,GAAkB;CAC/C,IAAM,IAAO,EAAY,CAAO,GAC1B,IAAgC,CAAC;CA6BvC,OA3BI,EAAK,SACP,OAAO,OAAO,GAAS,EAAc,GAAY,CAAc,CAAC,GAGlE,EAAQ,oBAAoB;EAC1B,MAAM;EACN,UAAU;EACV,SAAS,EAAa,GAAM,EAAQ,SAAS,IAAI;EACjD,QAAQ;CACV,GAkBO;EACL,SAjBoB,OAAO,OAAO,CAAO,CAAC,CAAC,MAAM,GAAG,MACpD,EAAE,KAAK,cAAc,EAAE,IAAI,CAgBlB;EACT,UAAU,CAAC;EACX,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UATe,EAAK,QAClB;GAAC;GAAe;GAAe;GAAkB;EAAQ,IACzD,CAAC,GAAe,QAAQ;EAQ1B,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate-Gcc8iRkZ.js","names":[],"sources":["../../src/patterns/disable/ai/generate.ts"],"sourcesContent":["import type { Options, Result } from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { appRelativePath } from \"../../../core/util\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport {\n DEMO_DIR,\n demoDir,\n envEditsFor,\n PACKAGES,\n PROVIDER_PACKAGES,\n PROVIDERS,\n} from \"../../enable/ai/generate\";\n\nconst createsRaw = import.meta.glob<string>(\"../../enable/ai/creates/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst createsAppModeRaw = import.meta.glob<string>(\n \"../../enable/ai/creates-app-mode/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\nconst providersRaw = import.meta.glob<string>(\"../../enable/ai/providers/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\ntype DemoOptions = Pick<Options, \"features\" | \"routeGroups\">;\n\n/**\n * Where enable-ai may have put the demo page in this project: the group it\n * picks with auth on and with it off. Auth enabled after AI leaves the page\n * in the public group, so both are candidates.\n */\nexport function demoDirs(options: DemoOptions): string[] {\n const dirs = [false, true].map((auth) =>\n demoDir({ ...options, features: { ...options.features, auth } }),\n );\n return [...new Set(dirs)];\n}\n\n/** A path enable-ai writes, with the stored demo directory moved to `dir`. */\nfunction atDemoDir(path: string, dir: string): string {\n return path.startsWith(DEMO_DIR)\n ? `${dir}/${path.slice(DEMO_DIR.length)}`\n : path;\n}\n\n/**\n * Every path enable-ai writes for this project: the model module, the\n * endpoint and its test, and the demo page in its current default group.\n * `generate.runtime.ts` adds the page in the other group when it exists.\n */\nexport function aiPaths(options: DemoOptions): string[] {\n const dir = demoDir(options);\n const paths = new Set<string>(allProviderPaths(providersRaw));\n for (const [raw, prefix] of [\n [createsRaw, \"../../enable/ai/creates/\"],\n [createsAppModeRaw, \"../../enable/ai/creates-app-mode/\"],\n ] as const) {\n for (const key of Object.keys(raw)) {\n paths.add(atDemoDir(appRelativePath(key, prefix), dir));\n }\n }\n return [...paths].sort();\n}\n\n/**\n * The `.env` lines every provider writes. Which provider was chosen is not\n * recorded, so all are removed; keys that are not there are skipped.\n */\nexport function allEnvEdits(): EnvEdit[] {\n return PROVIDERS.flatMap((provider) => envEditsFor(provider));\n}\n\n/** Every provider's env var names, as `src/env.ts` declares them. */\nexport function allEnvNames(): string[] {\n return PROVIDERS.flatMap((provider) =>\n (provider.env ?? []).map((variable) => variable.key),\n );\n}\n\nexport async function generate(options: Options) {\n return {\n creates: [],\n modifies: [],\n // Missing ones are skipped, and emptied directories (api/chat, ai) go too.\n deletes: aiPaths(options).map(toDeleteEntry),\n components: [],\n packages: [],\n // zod and the shadcn button/textarea stay: other code uses them.\n uninstalls: [...PACKAGES, ...Object.values(PROVIDER_PACKAGES).flat()],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;AAcA,IAAM,IAAa,uBAAA,OAAA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,CAAC;EACb,UAAU,CAAC;EAEX,YAAY,CAAC,GAAG,GAAU,GAAG,OAAO,OAAO,CAAiB,CAAC,CAAC,KAAK,CAAC;EACpE,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate-WMJo3QGZ.js","names":[],"sources":["../../src/patterns/disable/analytics/generate.ts"],"sourcesContent":["import type { Options, Result } from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { envEditsFor, PROVIDERS } from \"../../enable/analytics/generate\";\n\nconst providersRaw = import.meta.glob<string>(\n \"../../enable/analytics/providers/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\n/**\n * The `.env` lines every provider writes. The project only has one set, but\n * which one is not recorded anywhere, so all are removed; keys that are not\n * there are skipped.\n */\nexport function allEnvEdits(): EnvEdit[] {\n return PROVIDERS.flatMap((provider) => envEditsFor(provider));\n}\n\n/** Every provider's env var names, as `src/env.ts` declares them. */\nexport function allEnvNames(): string[] {\n return PROVIDERS.flatMap((provider) =>\n (provider.env ?? []).map((variable) => variable.key),\n );\n}\n\nexport async function generate(_options: Options) {\n return {\n creates: [],\n modifies: [],\n // Every provider's files: missing ones are skipped, and the emptied\n // components/analytics directory goes with them.\n deletes: allProviderPaths(providersRaw).map(toDeleteEntry),\n components: [],\n packages: [],\n // PostHog's SDK; the other providers load a script and install nothing.\n uninstalls: [\"posthog-js\"],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;AAMA,IAAM,IAAe,uBAAA,OAAA;CAAA,yFAAA;CAAA,gFAAA;CAAA,4FAAA;CAAA,0FAAA;AAGrB,CAAA;AAOA,SAAgB,IAAyB;CACvC,OAAO,EAAU,SAAS,MAAa,EAAY,CAAQ,CAAC;AAC9D;AAGA,SAAgB,IAAwB;CACtC,OAAO,EAAU,SAAS,OACvB,EAAS,OAAO,CAAC,EAAA,CAAG,KAAK,MAAa,EAAS,GAAG,CACrD;AACF;AAEA,eAAsB,EAAS,GAAmB;CAChD,OAAO;EACL,SAAS,CAAC;EACV,UAAU,CAAC;EAGX,SAAS,EAAiB,CAAY,CAAC,CAAC,IAAI,CAAa;EACzD,YAAY,CAAC;EACb,UAAU,CAAC;EAEX,YAAY,CAAC,YAAY;EACzB,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-1-91UmM8.js","names":[],"sources":["../../src/patterns/enable/analytics/modifies/layout.svelte.ts","../../src/patterns/enable/analytics/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst MODULE_SPECIFIER = \"#lib/components/analytics/analytics.svelte\";\n\nconst IMPORT_SNIPPET = dedent`\n import Analytics from '${MODULE_SPECIFIER}';\n`;\n\nconst MARKUP_SNIPPET = \"\\n<Analytics />\\n\";\n\nconst NOT_FOUND_HINT = [\n \"Create the root src/routes/+layout.svelte and mount <Analytics /> inside it.\",\n \"\",\n \"Import for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Mount <Analytics /> in the root src/routes/+layout.svelte.\",\n \"\",\n 'Import for a <script lang=\"ts\"> tag:',\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add at the top level of the layout, above {@render children()}:\",\n MARKUP_SNIPPET.trim(),\n].join(\"\\n\");\n\n/**\n * Mounts `<Analytics />` at the top level of the root layout, ahead of\n * `{@render children()}`. The component is the same path for every provider,\n * so this modifier is provider-agnostic and a re-run with another provider\n * leaves the layout alone.\n */\nexport function modifyLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (file.hasElement(\"Analytics\")) {\n return { status: \"success\", changed: false };\n }\n if (!file.getScript()) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n { defaultImport: \"Analytics\", moduleSpecifier: MODULE_SPECIFIER },\n ]);\n });\n return out;\n });\n\n if (!file.insertBeforeChildren(MARKUP_SNIPPET)) {\n file.appendMarkup(MARKUP_SNIPPET);\n }\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n providerEnvVars,\n resolveProvider,\n suppliedProviderEnv,\n} from \"../../../core/providers\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnv } from \"../../../runtime/env\";\nimport { envEditsFor, META } from \"./generate\";\nimport { modifyLayoutSvelte } from \"./modifies/layout.svelte\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const provider = resolveProvider(META, options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying src/routes/+layout.svelte\");\n const layoutPath = path.join(options.root, \"src\", \"routes\", \"+layout.svelte\");\n pushResult(modifyOutcomeToFile(layoutPath, modifyLayoutSvelte(layoutPath)));\n\n // SvelteKit 3 exposes only declared variables, and only `public: true`\n // ones through `$app/env/public`, where the component imports them.\n logger.info(\"Declaring the analytics variables in src/env.ts\");\n const envVars = modifyEnvVarsFiles(options.root, providerEnvVars(provider));\n if (envVars.create) creates.push(envVars.create);\n pushResult(envVars.modify);\n\n logger.info(\"Updating .env\");\n const envPath = path.join(options.root, \".env\");\n pushResult(\n modifyOutcomeToFile(\n envPath,\n modifyEnv(envPath, envEditsFor(provider, suppliedProviderEnv(options))),\n ),\n );\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AASA,IAAM,IAAmB,8CAEnB,IAAiB,CAAM;2BACF,EAAiB;GAGtC,IAAiB,qBAEjB,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA,EAAe,KAAK;AACtB,CAAC,CAAC,KAAK,IAAI,GAEL,IAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA,EAAe,KAAK;AACtB,CAAC,CAAC,KAAK,IAAI;AAQX,SAAgB,EAAmB,GAAmC;CACpE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAa,SAAS;CAAe;CAGxD,IAAM,IAAO,EAAW,SAAS,CAAU;CAqB3C,OApBI,EAAK,WAAW,WAAW,IACtB;EAAE,QAAQ;EAAW,SAAS;CAAM,IAExC,EAAK,UAAU,KAIpB,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQ,MAAQ,EAAmB,IAAS,MAAO;GACzD,EAAc,GAAI,CAChB;IAAE,eAAe;IAAa,iBAAiB;GAAiB,CAClE,CAAC;EACH,CAAC;EACD,OAAO;CACT,CAAC,GAEI,EAAK,qBAAqB,CAAc,KAC3C,EAAK,aAAa,CAAc,GAElC,EAAK,QAAQ,CAAU,GAChB;EAAE,QAAQ;EAAW,SAAS,EAAK,WAAW;CAAE,KAhB9C;EAAE,QAAQ;EAAU,SAAS;CAAa;AAiBrD;;;AC1DA,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,CAAO,GAC1B,IAAW,EAAgB,GAAM,CAAO,GACxC,IAAkB,CAAC,GACnB,IAAmB,CAAC,GAEpB,KAAc,MAAsB;EACxC,AAAI,KAAM,EAAS,KAAK,CAAI;CAC9B;CAEA,EAAO,KAAK,qCAAqC;CACjD,IAAM,IAAa,EAAK,KAAK,EAAQ,MAAM,OAAO,UAAU,gBAAgB;CAK5E,AAJA,EAAW,EAAoB,GAAY,EAAmB,CAAU,CAAC,CAAC,GAI1E,EAAO,KAAK,iDAAiD;CAC7D,IAAM,IAAU,EAAmB,EAAQ,MAAM,EAAgB,CAAQ,CAAC;CAI1E,AAHI,EAAQ,UAAQ,EAAQ,KAAK,EAAQ,MAAM,GAC/C,EAAW,EAAQ,MAAM,GAEzB,EAAO,KAAK,eAAe;CAC3B,IAAM,IAAU,EAAK,KAAK,EAAQ,MAAM,MAAM;CAQ9C,OAPA,EACE,EACE,GACA,EAAU,GAAS,EAAY,GAAU,EAAoB,CAAO,CAAC,CAAC,CACxE,CACF,GAEO;EACL;EACA;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"generate.runtime-6FXJM8hT.js","names":[],"sources":["../../src/patterns/disable/notifications/modifies/modify-app-layout.ts","../../src/patterns/disable/notifications/modifies/+layout.server.ts","../../src/patterns/disable/notifications/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureBlankLineAfterImports,\n removeImportByModuleSpecifier,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { libModule } from \"../../../../runtime/lib-specifier\";\n\n/** Take the bell (and the wrapper enable-notifications put it in) out of the header. */\nexport function unmodifyAppLayout(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(layoutPath, \"utf8\");\n if (!original.includes(\"NotificationsBell\")) {\n return { status: \"success\", changed: false };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n removeImportByModuleSpecifier(\n sf,\n libModule(\"components/notifications-bell.svelte\"),\n );\n ensureBlankLineAfterImports(sf);\n });\n return out;\n });\n\n let updated = file.toString();\n updated = updated.replace(\n /\\n*[ \\t]*<div class=\"ml-auto px-4\">\\s*<NotificationsBell\\s*\\/>\\s*<\\/div>[ \\t]*/g,\n \"\",\n );\n updated = updated.replace(/[ \\t]*<NotificationsBell\\s*\\/>[ \\t]*\\r?\\n?/g, \"\");\n\n fs.writeFileSync(layoutPath, updated, \"utf8\");\n return { status: \"success\", changed: updated !== original };\n}\n","import type { ModifyOutcome } from \"../../../../core/types\";\nimport { removeFromLoad } from \"../../../../runtime/unmodify-load\";\n\n/** Take the unread-notifications query back out of the (app) layout's load. */\nexport function unmodifyLayoutServer(layoutServerPath: string): ModifyOutcome {\n return removeFromLoad(layoutServerPath, {\n variables: [\"notificationsList\", \"notifications\"],\n dependsKeys: [\"app:notifications\"],\n returnProps: [\"notifications\"],\n });\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { planDropsForCollections } from \"../../destroy/shared\";\nimport { unmodifyAppLayout } from \"./modifies/modify-app-layout\";\nimport { unmodifyLayoutServer } from \"./modifies/+layout.server\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Reverting (app) +layout.svelte\");\n const appLayoutPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.svelte\",\n );\n pushResult(\n modifyOutcomeToFile(appLayoutPath, unmodifyAppLayout(appLayoutPath)),\n );\n\n logger.info(\"Reverting (app) +layout.server.ts\");\n const appLayoutServerPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(app)\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(\n appLayoutServerPath,\n unmodifyLayoutServer(appLayoutServerPath),\n ),\n );\n\n // The timeAgo helper enable-notifications added to #lib/utils.js stays: it is\n // generic, and other code may have started using it.\n\n const collectionDrops = await planDropsForCollections(\n [\"notifications\"],\n options,\n );\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops,\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;AAWA,SAAgB,EAAkB,GAAmC;CACnE,IAAI,CAAC,EAAG,WAAW,CAAU,GAC3B,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAW,EAAG,aAAa,GAAY,MAAM;CACnD,IAAI,CAAC,EAAS,SAAS,mBAAmB,GACxC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAO,EAAW,SAAS,CAAU;CAC3C,EAAK,cAAc,MAAW;EAC5B,IAAM,EAAE,QAAQ,MAAQ,EAAmB,IAAS,MAAO;GAKzD,AAJA,EACE,GACA,EAAU,sCAAsC,CAClD,GACA,EAA4B,CAAE;EAChC,CAAC;EACD,OAAO;CACT,CAAC;CAED,IAAI,IAAU,EAAK,SAAS;CAQ5B,OAPA,IAAU,EAAQ,QAChB,mFACA,EACF,GACA,IAAU,EAAQ,QAAQ,+CAA+C,EAAE,GAE3E,EAAG,cAAc,GAAY,GAAS,MAAM,GACrC;EAAE,QAAQ;EAAW,SAAS,MAAY;CAAS;AAC5D;;;ACtCA,SAAgB,EAAqB,GAAyC;CAC5E,OAAO,EAAe,GAA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