@velastack/patterns 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -3
- package/dist/chunks/_layout-B7ujvjnA.js +55 -0
- package/dist/chunks/_layout-B7ujvjnA.js.map +1 -0
- package/dist/chunks/{collections-CgdvZXmh.js → collections-CrOvS2E7.js} +3 -3
- package/dist/chunks/{collections-CgdvZXmh.js.map → collections-CrOvS2E7.js.map} +1 -1
- package/dist/chunks/{compose-handle-Cg9jnCsS.js → compose-handle-B-CkDcQD.js} +23 -23
- package/dist/chunks/{compose-handle-Cg9jnCsS.js.map → compose-handle-B-CkDcQD.js.map} +1 -1
- package/dist/chunks/config-target-Bln26FJe.js +164 -0
- package/dist/chunks/config-target-Bln26FJe.js.map +1 -0
- package/dist/chunks/{constants-DSFKQwtP.js → constants-BYkd9jeJ.js} +2 -2
- package/dist/chunks/constants-BYkd9jeJ.js.map +1 -0
- package/dist/chunks/errors-DR3gF_7a.js +18 -0
- package/dist/chunks/errors-DR3gF_7a.js.map +1 -0
- package/dist/chunks/{format-result-Cb2hWsb8.js → format-result-DZ8De8KY.js} +19 -11
- package/dist/chunks/format-result-DZ8De8KY.js.map +1 -0
- package/dist/chunks/{generate-DRA63W0r.js → generate-6snrlnpA.js} +2 -2
- package/dist/chunks/{generate-DRA63W0r.js.map → generate-6snrlnpA.js.map} +1 -1
- package/dist/chunks/{generate-iQP31-m1.js → generate-Ca_6FlPi.js} +5 -5
- package/dist/chunks/{generate-iQP31-m1.js.map → generate-Ca_6FlPi.js.map} +1 -1
- package/dist/chunks/{generate-tOkjJFUf.js → generate-CyuY2Ci7.js} +4 -3
- package/dist/chunks/generate-CyuY2Ci7.js.map +1 -0
- package/dist/chunks/{generate-BkQ1xMDp.js → generate-DQeWOEPY.js} +4 -4
- package/dist/chunks/{generate-BkQ1xMDp.js.map → generate-DQeWOEPY.js.map} +1 -1
- package/dist/chunks/{generate-_LvrYK6i.js → generate-DwADTUob.js} +4 -4
- package/dist/chunks/{generate-_LvrYK6i.js.map → generate-DwADTUob.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BbIN0tUZ.js → generate.runtime-4FDxnvCl.js} +67 -66
- package/dist/chunks/generate.runtime-4FDxnvCl.js.map +1 -0
- package/dist/chunks/{generate.runtime-B0hhtyAL.js → generate.runtime-AYQVW1S-.js} +27 -26
- package/dist/chunks/generate.runtime-AYQVW1S-.js.map +1 -0
- package/dist/chunks/{generate.runtime-wA1G3tQ4.js → generate.runtime-B2aFFaac.js} +38 -37
- package/dist/chunks/generate.runtime-B2aFFaac.js.map +1 -0
- package/dist/chunks/{generate.runtime-DhkaXTq3.js → generate.runtime-B45MvtYm.js} +61 -59
- package/dist/chunks/generate.runtime-B45MvtYm.js.map +1 -0
- package/dist/chunks/{generate.runtime-S5RIgbQx.js → generate.runtime-BFOXm2DD.js} +98 -92
- package/dist/chunks/generate.runtime-BFOXm2DD.js.map +1 -0
- package/dist/chunks/{generate.runtime-BnWE4qsu.js → generate.runtime-BHkFmI2Y.js} +55 -54
- package/dist/chunks/generate.runtime-BHkFmI2Y.js.map +1 -0
- package/dist/chunks/{generate.runtime-DNaQxed-.js → generate.runtime-BKiJvE8I.js} +84 -83
- package/dist/chunks/generate.runtime-BKiJvE8I.js.map +1 -0
- package/dist/chunks/{generate.runtime-DoZdSh9W.js → generate.runtime-BSRFv4cJ.js} +58 -57
- package/dist/chunks/generate.runtime-BSRFv4cJ.js.map +1 -0
- package/dist/chunks/{generate.runtime-B49wetSx.js → generate.runtime-BUqsF3AF.js} +43 -42
- package/dist/chunks/generate.runtime-BUqsF3AF.js.map +1 -0
- package/dist/chunks/{generate.runtime-acRmiU7e.js → generate.runtime-BsaSyTnU.js} +9 -8
- package/dist/chunks/{generate.runtime-acRmiU7e.js.map → generate.runtime-BsaSyTnU.js.map} +1 -1
- package/dist/chunks/generate.runtime-CMnvmeVt.js +111 -0
- package/dist/chunks/generate.runtime-CMnvmeVt.js.map +1 -0
- package/dist/chunks/{generate.runtime-BORbegw_.js → generate.runtime-CN5c2xH8.js} +123 -122
- package/dist/chunks/generate.runtime-CN5c2xH8.js.map +1 -0
- package/dist/chunks/{generate.runtime-flFRYzpi.js → generate.runtime-CgoSrP55.js} +62 -61
- package/dist/chunks/generate.runtime-CgoSrP55.js.map +1 -0
- package/dist/chunks/{generate.runtime-D0icLb5j.js → generate.runtime-D1DNAY6k.js} +12 -11
- package/dist/chunks/{generate.runtime-D0icLb5j.js.map → generate.runtime-D1DNAY6k.js.map} +1 -1
- package/dist/chunks/generate.runtime-DG-3G00z.js +87 -0
- package/dist/chunks/generate.runtime-DG-3G00z.js.map +1 -0
- package/dist/chunks/{generate.runtime-BKo-Nidn.js → generate.runtime-DQwSY6Nc.js} +6 -6
- package/dist/chunks/{generate.runtime-BKo-Nidn.js.map → generate.runtime-DQwSY6Nc.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DSqkXvps.js → generate.runtime-D_yqWLcI.js} +15 -14
- package/dist/chunks/{generate.runtime-DSqkXvps.js.map → generate.runtime-D_yqWLcI.js.map} +1 -1
- package/dist/chunks/generate.runtime-Drmahmdl.js +313 -0
- package/dist/chunks/generate.runtime-Drmahmdl.js.map +1 -0
- package/dist/chunks/{generate.runtime-D8vgh5MH.js → generate.runtime-FdZw277n.js} +156 -76
- package/dist/chunks/generate.runtime-FdZw277n.js.map +1 -0
- package/dist/chunks/generate.runtime-Lh1cW9Tz.js +94 -0
- package/dist/chunks/generate.runtime-Lh1cW9Tz.js.map +1 -0
- package/dist/chunks/{generate.runtime-DAmYsIvF.js → generate.runtime-QGHToXRY.js} +5 -5
- package/dist/chunks/{generate.runtime-DAmYsIvF.js.map → generate.runtime-QGHToXRY.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CRYjWJRe.js → generate.runtime-Um77JfwC.js} +89 -88
- package/dist/chunks/generate.runtime-Um77JfwC.js.map +1 -0
- package/dist/chunks/{generate.runtime-BwhGDnGu.js → generate.runtime-VgVwRiiN.js} +151 -150
- package/dist/chunks/generate.runtime-VgVwRiiN.js.map +1 -0
- package/dist/chunks/{generate.runtime-CcuAXuV2.js → generate.runtime-YyIVd4oy.js} +15 -14
- package/dist/chunks/{generate.runtime-CcuAXuV2.js.map → generate.runtime-YyIVd4oy.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DOuufRLr.js → generate.runtime-cQGLxuZM.js} +82 -81
- package/dist/chunks/generate.runtime-cQGLxuZM.js.map +1 -0
- package/dist/chunks/generate.runtime-n9AFWtPp.js +94 -0
- package/dist/chunks/generate.runtime-n9AFWtPp.js.map +1 -0
- package/dist/chunks/generate.runtime-ofdnLtxS.js +57 -0
- package/dist/chunks/generate.runtime-ofdnLtxS.js.map +1 -0
- package/dist/chunks/generate.runtime-onBnOiS7.js +328 -0
- package/dist/chunks/generate.runtime-onBnOiS7.js.map +1 -0
- package/dist/chunks/modify-file-Dwfv0dCI.js +46 -0
- package/dist/chunks/modify-file-Dwfv0dCI.js.map +1 -0
- package/dist/chunks/{modify-svelte-config-remote-CDKs_Qi0.js → modify-svelte-config-remote-BUU_EaDf.js} +2 -2
- package/dist/chunks/{modify-svelte-config-remote-CDKs_Qi0.js.map → modify-svelte-config-remote-BUU_EaDf.js.map} +1 -1
- package/dist/chunks/{pocketbase-CeG5BMN2.js → pocketbase-BkhUywtb.js} +2 -2
- package/dist/chunks/{pocketbase-CeG5BMN2.js.map → pocketbase-BkhUywtb.js.map} +1 -1
- package/dist/chunks/{providers-DO9kMyzB.js → providers-BL9vJP_9.js} +2 -2
- package/dist/chunks/{providers-DO9kMyzB.js.map → providers-BL9vJP_9.js.map} +1 -1
- package/dist/chunks/{shared-BwHQM-a9.js → shared-C8GtNxpm.js} +2 -2
- package/dist/chunks/{shared-BwHQM-a9.js.map → shared-C8GtNxpm.js.map} +1 -1
- package/dist/chunks/{site-D027dpBm.js → site-BdMX8qrH.js} +2 -2
- package/dist/chunks/{site-D027dpBm.js.map → site-BdMX8qrH.js.map} +1 -1
- package/dist/chunks/table-core-G9Shld4F.js +126 -0
- package/dist/chunks/table-core-G9Shld4F.js.map +1 -0
- package/dist/chunks/{test-setup-B2hd8I-s.js → test-setup-DHEFKEHE.js} +23 -10
- package/dist/chunks/test-setup-DHEFKEHE.js.map +1 -0
- package/dist/chunks/ts-morph-helpers-CeduA--o.js +253 -0
- package/dist/chunks/ts-morph-helpers-CeduA--o.js.map +1 -0
- package/dist/chunks/{ui-jhXrsw4T.js → ui-DD4NltyN.js} +2 -2
- package/dist/chunks/{ui-jhXrsw4T.js.map → ui-DD4NltyN.js.map} +1 -1
- package/dist/chunks/{ui-B4Tuit-7.js → ui-TlEuI2Sz.js} +50 -49
- package/dist/chunks/{ui-B4Tuit-7.js.map → ui-TlEuI2Sz.js.map} +1 -1
- package/dist/chunks/unmodify-load-jfdcVZ_a.js +81 -0
- package/dist/chunks/unmodify-load-jfdcVZ_a.js.map +1 -0
- package/dist/chunks/write-result-Djy0SZXX.js +376 -0
- package/dist/chunks/write-result-Djy0SZXX.js.map +1 -0
- package/dist/index.d.ts +33 -1
- package/dist/index.js +2240 -2020
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunks/_layout-DqH4lA_r.js +0 -47
- package/dist/chunks/_layout-DqH4lA_r.js.map +0 -1
- package/dist/chunks/config-target-Co-ij8p3.js +0 -163
- package/dist/chunks/config-target-Co-ij8p3.js.map +0 -1
- package/dist/chunks/constants-DSFKQwtP.js.map +0 -1
- package/dist/chunks/errors-D6gyegUK.js +0 -14
- package/dist/chunks/errors-D6gyegUK.js.map +0 -1
- package/dist/chunks/format-result-Cb2hWsb8.js.map +0 -1
- package/dist/chunks/generate-tOkjJFUf.js.map +0 -1
- package/dist/chunks/generate.runtime-B0hhtyAL.js.map +0 -1
- package/dist/chunks/generate.runtime-B49wetSx.js.map +0 -1
- package/dist/chunks/generate.runtime-B7LRx-BU.js +0 -86
- package/dist/chunks/generate.runtime-B7LRx-BU.js.map +0 -1
- package/dist/chunks/generate.runtime-BORbegw_.js.map +0 -1
- package/dist/chunks/generate.runtime-BbIN0tUZ.js.map +0 -1
- package/dist/chunks/generate.runtime-BnWE4qsu.js.map +0 -1
- package/dist/chunks/generate.runtime-BwhGDnGu.js.map +0 -1
- package/dist/chunks/generate.runtime-CCg2Pjcv.js +0 -257
- package/dist/chunks/generate.runtime-CCg2Pjcv.js.map +0 -1
- package/dist/chunks/generate.runtime-CRYjWJRe.js.map +0 -1
- package/dist/chunks/generate.runtime-D2e_KRj0.js +0 -56
- package/dist/chunks/generate.runtime-D2e_KRj0.js.map +0 -1
- package/dist/chunks/generate.runtime-D44gjxRA.js +0 -332
- package/dist/chunks/generate.runtime-D44gjxRA.js.map +0 -1
- package/dist/chunks/generate.runtime-D8vgh5MH.js.map +0 -1
- package/dist/chunks/generate.runtime-DNaQxed-.js.map +0 -1
- package/dist/chunks/generate.runtime-DOuufRLr.js.map +0 -1
- package/dist/chunks/generate.runtime-DhkaXTq3.js.map +0 -1
- package/dist/chunks/generate.runtime-DoZdSh9W.js.map +0 -1
- package/dist/chunks/generate.runtime-S5RIgbQx.js.map +0 -1
- package/dist/chunks/generate.runtime-WmSMWL15.js +0 -82
- package/dist/chunks/generate.runtime-WmSMWL15.js.map +0 -1
- package/dist/chunks/generate.runtime-flFRYzpi.js.map +0 -1
- package/dist/chunks/generate.runtime-gtpOuLNO.js +0 -110
- package/dist/chunks/generate.runtime-gtpOuLNO.js.map +0 -1
- package/dist/chunks/generate.runtime-kLxeDGnS.js +0 -93
- package/dist/chunks/generate.runtime-kLxeDGnS.js.map +0 -1
- package/dist/chunks/generate.runtime-wA1G3tQ4.js.map +0 -1
- package/dist/chunks/modify-file-GQD6uNgI.js +0 -254
- package/dist/chunks/modify-file-GQD6uNgI.js.map +0 -1
- package/dist/chunks/test-setup-B2hd8I-s.js.map +0 -1
- package/dist/chunks/unmodify-load-W1ePZQHr.js +0 -80
- package/dist/chunks/unmodify-load-W1ePZQHr.js.map +0 -1
- package/dist/chunks/write-result-DewHCNhM.js +0 -451
- package/dist/chunks/write-result-DewHCNhM.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate.runtime-ofdnLtxS.js","names":[],"sources":["../../src/patterns/disable/api/modifies/hooks.server.ts","../../src/patterns/disable/api/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function unmodifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"success\", changed: false };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"success\", changed: false };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n return { status: \"success\", changed: false };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n return { status: \"success\", changed: false };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n const apiProp = optionsObj.getProperty(\"api\");\n if (!apiProp) {\n return { status: \"success\", changed: false };\n }\n\n apiProp.remove();\n\n if (optionsObj.getProperties().length === 0) {\n callExpr.removeArgument(0);\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { unmodifyHooksServer } from \"./modifies/hooks.server\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const modifies: File[] = [];\n\n logger.info(\"Reverting hooks.server.ts\");\n const hooksServerPath = path.join(options.root, \"src\", \"hooks.server.ts\");\n const file = modifyOutcomeToFile(\n hooksServerPath,\n unmodifyHooksServer(hooksServerPath),\n );\n if (file) modifies.push(file);\n\n return {\n creates: [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;AAKA,SAAgB,EAAoB,GAAwC;CAC1E,IAAI,CAAC,EAAG,WAAW,CAAe,GAChC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAiB,EAAG,aAAa,GAAiB,MAAM,GAExD,IAAa,IADC,EACD,CAAA,CAAQ,oBAAoB,CAAe,GAExD,IAAW,EACd,qBAAqB,EAAW,cAAc,CAAC,CAC/C,MAAM,MAAO,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,kBAAkB;CAEnE,IAAI,CAAC,GACH,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAO,EAAS,aAAa;CACnC,IAAI,EAAK,WAAW,GAClB,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAW,EAAK;CACtB,IAAI,EAAS,QAAQ,MAAM,EAAW,yBACpC,OAAO;EAAE,QAAQ;EAAW,SAAS;CAAM;CAG7C,IAAM,IAAa,EAAS,cAAc,EAAW,uBAAuB,GACtE,IAAU,EAAW,YAAY,KAAK;CAc5C,OAbK,KAIL,EAAQ,OAAO,GAEX,EAAW,cAAc,CAAC,CAAC,WAAW,KACxC,EAAS,eAAe,CAAC,GAG3B,EAAiB,CAAU,GAC3B,EAAW,SAAS,GAEb;EACL,QAAQ;EACR,SAAS,EAAW,YAAY,MAAM;CACxC,KAfS;EAAE,QAAQ;EAAW,SAAS;CAAM;AAgB/C;;;AC7CA,eAAsB,EAAS,GAAkB;CAC/C,IAAM,IAAS,EAAU,CAAO,GAC1B,IAAmB,CAAC;CAE1B,EAAO,KAAK,2BAA2B;CACvC,IAAM,IAAkB,EAAK,KAAK,EAAQ,MAAM,OAAO,iBAAiB,GAClE,IAAO,EACX,GACA,EAAoB,CAAe,CACrC;CAGA,OAFI,KAAM,EAAS,KAAK,CAAI,GAErB;EACL,SAAS,CAAC;EACV;EACA,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { t as e } from "./dedent-Gq6Krl4n.js";
|
|
2
|
+
import { n as t } from "./logger-CQONztPm.js";
|
|
3
|
+
import { _ as n, a as r, o as i, r as a } from "./ts-morph-helpers-CeduA--o.js";
|
|
4
|
+
import { modifyOutcomeToFile as o } from "./modify-file-Dwfv0dCI.js";
|
|
5
|
+
import { t as s } from "./svelte-file-B3RfgVdt.js";
|
|
6
|
+
import { i as c, n as l, t as u } from "./pocketbase-BkhUywtb.js";
|
|
7
|
+
import { t as d } from "./site-BdMX8qrH.js";
|
|
8
|
+
import { modifySvelteConfigRemote as f } from "./modify-svelte-config-remote-BUU_EaDf.js";
|
|
9
|
+
import p from "node:fs";
|
|
10
|
+
import m from "node:path";
|
|
11
|
+
import { Project as h, SyntaxKind as g } from "ts-morph";
|
|
12
|
+
//#region src/patterns/enable/auth-remote/modifies/+layout.server.ts
|
|
13
|
+
function _(t) {
|
|
14
|
+
if (!p.existsSync(t)) {
|
|
15
|
+
let n = e`
|
|
16
|
+
export const load = async ({ locals }) => {
|
|
17
|
+
return { user: locals.pb.authStore.record };
|
|
18
|
+
};
|
|
19
|
+
`;
|
|
20
|
+
return p.writeFileSync(t, n), {
|
|
21
|
+
status: "success",
|
|
22
|
+
changed: !0
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
let n = p.readFileSync(t, "utf8"), r = new h().addSourceFileAtPath(t), a = (e) => {
|
|
26
|
+
e.getProperty("user") || e.addPropertyAssignment({
|
|
27
|
+
name: "user",
|
|
28
|
+
initializer: "locals.pb.authStore.record"
|
|
29
|
+
});
|
|
30
|
+
}, o, s, c = r.getVariableDeclaration("load");
|
|
31
|
+
if (c && c.getFirstAncestorByKind(g.VariableStatement)?.hasExportKeyword()) {
|
|
32
|
+
let e = c.getInitializerIfKind(g.ArrowFunction);
|
|
33
|
+
if (e) o = e;
|
|
34
|
+
else {
|
|
35
|
+
let e = c.getInitializer();
|
|
36
|
+
if (e) {
|
|
37
|
+
let t = e.getFirstDescendantByKind(g.ArrowFunction);
|
|
38
|
+
if (t) o = t;
|
|
39
|
+
else {
|
|
40
|
+
let t = e.getFirstDescendantByKind(g.FunctionExpression);
|
|
41
|
+
t && (s = t);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (!o) {
|
|
47
|
+
let e = r.getFunction("load");
|
|
48
|
+
e && e.isExported() && (s = e);
|
|
49
|
+
}
|
|
50
|
+
if (!o && !s) return r.addFunction({
|
|
51
|
+
isExported: !0,
|
|
52
|
+
isAsync: !0,
|
|
53
|
+
name: "load",
|
|
54
|
+
parameters: [{ name: "{ locals }" }],
|
|
55
|
+
statements: "return { user: locals.pb.authStore.record };"
|
|
56
|
+
}), i(r), r.saveSync(), {
|
|
57
|
+
status: "success",
|
|
58
|
+
changed: !0
|
|
59
|
+
};
|
|
60
|
+
let l = o ?? s, u = l.getParameters();
|
|
61
|
+
if (u.length === 0) l.insertParameter(0, { name: "{ locals }" });
|
|
62
|
+
else {
|
|
63
|
+
let e = u[0], t = e.getStructure(), n = e.getNameNode();
|
|
64
|
+
if (n.getKind() === g.ObjectBindingPattern) {
|
|
65
|
+
let r = n;
|
|
66
|
+
if (!r.getElements().some((e) => e.getName() === "locals")) {
|
|
67
|
+
let n = r.getElements().map((e) => e.getText()).filter(Boolean), i = n.length > 0 ? ", " + n.join(", ") : "";
|
|
68
|
+
e.set({
|
|
69
|
+
name: `{ locals${i} }`,
|
|
70
|
+
type: t.type,
|
|
71
|
+
initializer: t.initializer
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
} else {
|
|
75
|
+
let n = e.getName();
|
|
76
|
+
n !== "locals" && e.set({
|
|
77
|
+
name: `{ locals, ...${n} }`,
|
|
78
|
+
type: t.type,
|
|
79
|
+
initializer: t.initializer
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (o) {
|
|
84
|
+
let e = o.getBody();
|
|
85
|
+
if (e.getKind() === g.Block) e.getDescendantsOfKind(g.ReturnStatement).forEach((e) => {
|
|
86
|
+
let t = e.getExpression();
|
|
87
|
+
if (t) {
|
|
88
|
+
if (t.getKind() === g.ObjectLiteralExpression) a(t);
|
|
89
|
+
else if (t.getKind() === g.ParenthesizedExpression) {
|
|
90
|
+
let e = t.getExpression();
|
|
91
|
+
e.getKind() === g.ObjectLiteralExpression && a(e);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
else {
|
|
96
|
+
let t = e;
|
|
97
|
+
if (t.getKind() === g.ParenthesizedExpression) {
|
|
98
|
+
let e = t.getExpression();
|
|
99
|
+
e.getKind() === g.ObjectLiteralExpression && a(e);
|
|
100
|
+
} else t.getKind() === g.ObjectLiteralExpression && a(t);
|
|
101
|
+
}
|
|
102
|
+
} else if (s) {
|
|
103
|
+
let e = s.getBody();
|
|
104
|
+
e && e.getDescendantsOfKind(g.ReturnStatement).forEach((e) => {
|
|
105
|
+
let t = e.getExpression();
|
|
106
|
+
if (t) {
|
|
107
|
+
if (t.getKind() === g.ObjectLiteralExpression) a(t);
|
|
108
|
+
else if (t.getKind() === g.ParenthesizedExpression) {
|
|
109
|
+
let e = t.getExpression();
|
|
110
|
+
e.getKind() === g.ObjectLiteralExpression && a(e);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return i(r), r.saveSync(), {
|
|
116
|
+
status: "success",
|
|
117
|
+
changed: r.getFullText() !== n
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
//#region src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts
|
|
122
|
+
var v = "\n <Navbar.Item\n class=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n >\n <AuthMenu.Root>\n {#snippet user()}\n <AuthMenu.Trigger>\n <Avatar.Root>\n {#if data.user?.avatar}\n <Avatar.Image\n src=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n alt={data.user?.email}\n />\n {/if}\n <Avatar.Fallback>\n {data.user?.email?.charAt(0).toUpperCase()}\n </Avatar.Fallback>\n </Avatar.Root>\n </AuthMenu.Trigger>\n\n <AuthMenu.Content align=\"end\">\n <AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n <AuthMenu.Group>\n <AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n <AuthMenu.Item>\n <form action=\"/logout\" method=\"post\">\n <button type=\"submit\" class=\"contents\">Logout</button>\n </form>\n </AuthMenu.Item>\n </AuthMenu.Group>\n </AuthMenu.Content>\n {/snippet}\n\n {#snippet guest()}\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n variant=\"ghost\"\n href=\"/login\">Login</Button\n >\n <Button\n class=\"w-full justify-start md:justify-center md:w-auto\"\n variant=\"outline\"\n href=\"/signup\">Sign up</Button\n >\n {/snippet}\n </AuthMenu.Root>\n </Navbar.Item>\n ", y = e`
|
|
123
|
+
import * as AuthMenu from '$lib/components/ui/auth-menu';
|
|
124
|
+
import * as Avatar from '$lib/components/ui/avatar';
|
|
125
|
+
`, b = [
|
|
126
|
+
"Add the auth menu inside your <Navbar.List> in the root layout.",
|
|
127
|
+
"",
|
|
128
|
+
"Imports to add to the <script> tag:",
|
|
129
|
+
"",
|
|
130
|
+
y,
|
|
131
|
+
"",
|
|
132
|
+
"Markup to add inside <Navbar.List>:",
|
|
133
|
+
v
|
|
134
|
+
].join("\n"), x = [
|
|
135
|
+
"Create a root layout that includes an auth menu inside <Navbar.List>.",
|
|
136
|
+
"",
|
|
137
|
+
"Imports for the <script> tag:",
|
|
138
|
+
"",
|
|
139
|
+
y,
|
|
140
|
+
"",
|
|
141
|
+
"Markup inside <Navbar.List>:",
|
|
142
|
+
v
|
|
143
|
+
].join("\n");
|
|
144
|
+
function S(e) {
|
|
145
|
+
if (!p.existsSync(e)) return {
|
|
146
|
+
status: "not-found",
|
|
147
|
+
message: x
|
|
148
|
+
};
|
|
149
|
+
let t = s.fromPath(e);
|
|
150
|
+
return t.hasElement("Navbar.List") ? t.hasElement("AuthMenu.Root") ? {
|
|
151
|
+
status: "success",
|
|
152
|
+
changed: !1
|
|
153
|
+
} : (t.modifyScript((e) => {
|
|
154
|
+
let { source: t } = n(e, (e) => {
|
|
155
|
+
a(e, [{
|
|
156
|
+
namespaceImport: "AuthMenu",
|
|
157
|
+
moduleSpecifier: "$lib/components/ui/auth-menu"
|
|
158
|
+
}, {
|
|
159
|
+
namespaceImport: "Avatar",
|
|
160
|
+
moduleSpecifier: "$lib/components/ui/avatar"
|
|
161
|
+
}]), r(e, "data");
|
|
162
|
+
});
|
|
163
|
+
return t;
|
|
164
|
+
}), t.insertBeforeClosingTag("Navbar.List", v), t.writeTo(e), {
|
|
165
|
+
status: "success",
|
|
166
|
+
changed: t.hasChanged()
|
|
167
|
+
}) : {
|
|
168
|
+
status: "failed",
|
|
169
|
+
message: b
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/patterns/enable/auth-remote/modifies/hooks.server.ts
|
|
174
|
+
var C = e`
|
|
175
|
+
Configure handlePocketbase() with the auth option in hooks.server.ts:
|
|
176
|
+
|
|
177
|
+
handlePocketbase({
|
|
178
|
+
auth: { protectedRoutes: ['/(app)'] },
|
|
179
|
+
});
|
|
180
|
+
`, w = e`
|
|
181
|
+
Create src/hooks.server.ts with handlePocketbase:
|
|
182
|
+
|
|
183
|
+
import { handlePocketbase } from '@velastack/pocketbase';
|
|
184
|
+
|
|
185
|
+
export const handle = handlePocketbase({
|
|
186
|
+
auth: { protectedRoutes: ['/(app)'] },
|
|
187
|
+
});
|
|
188
|
+
`;
|
|
189
|
+
function T(e) {
|
|
190
|
+
if (!p.existsSync(e)) return {
|
|
191
|
+
status: "not-found",
|
|
192
|
+
message: w
|
|
193
|
+
};
|
|
194
|
+
let t = p.readFileSync(e, "utf8"), n = new h().addSourceFileAtPath(e), r = n.getDescendantsOfKind(g.CallExpression).find((e) => e.getExpression().getText() === "handlePocketbase");
|
|
195
|
+
if (!r) return {
|
|
196
|
+
status: "failed",
|
|
197
|
+
message: C
|
|
198
|
+
};
|
|
199
|
+
let a = r.getArguments();
|
|
200
|
+
if (a.length === 0) return r.addArgument("{ auth: { protectedRoutes: ['/(app)'] } }"), i(n), n.saveSync(), {
|
|
201
|
+
status: "success",
|
|
202
|
+
changed: !0
|
|
203
|
+
};
|
|
204
|
+
let o = a[0];
|
|
205
|
+
if (o.getKind() !== g.ObjectLiteralExpression) return r.insertArgument(0, "{ auth: { protectedRoutes: ['/(app)'] } }"), i(n), n.saveSync(), {
|
|
206
|
+
status: "success",
|
|
207
|
+
changed: !0
|
|
208
|
+
};
|
|
209
|
+
let s = o.asKindOrThrow(g.ObjectLiteralExpression), c = s.getProperty("auth");
|
|
210
|
+
if (!c) return s.addPropertyAssignment({
|
|
211
|
+
name: "auth",
|
|
212
|
+
initializer: "{ protectedRoutes: ['/(app)'] }"
|
|
213
|
+
}), i(n), n.saveSync(), {
|
|
214
|
+
status: "success",
|
|
215
|
+
changed: !0
|
|
216
|
+
};
|
|
217
|
+
if (c.getKind() === g.PropertyAssignment) {
|
|
218
|
+
let e = c.getInitializer();
|
|
219
|
+
if (e && e.getKind() === g.ObjectLiteralExpression) {
|
|
220
|
+
let t = e, n = t.getProperty("protectedRoutes");
|
|
221
|
+
if (!n) t.addPropertyAssignment({
|
|
222
|
+
name: "protectedRoutes",
|
|
223
|
+
initializer: "['/(app)']"
|
|
224
|
+
});
|
|
225
|
+
else if (n.getKind() === g.PropertyAssignment) {
|
|
226
|
+
let e = n.getInitializer();
|
|
227
|
+
if (e && e.getKind() === g.ArrayLiteralExpression) {
|
|
228
|
+
let t = e;
|
|
229
|
+
t.getElements().some((e) => e.getText().replace(/['"`]/g, "") === "/(app)") || t.addElement("'/(app)'");
|
|
230
|
+
} else n.setInitializer("['/(app)']");
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return i(n), n.saveSync(), {
|
|
235
|
+
status: "success",
|
|
236
|
+
changed: n.getFullText() !== t
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
//#endregion
|
|
240
|
+
//#region src/patterns/enable/auth-remote/modifies/test-setup.ts
|
|
241
|
+
var E = e`
|
|
242
|
+
// Login is a remote function, so there is no form action to post to: carry
|
|
243
|
+
// the session the way the browser does, in the \`pb_auth\` cookie.
|
|
244
|
+
async function authenticateUser(agent: Agent, user: { email: string }) {
|
|
245
|
+
const client = new PocketBase(process.env.POCKETBASE_URL!);
|
|
246
|
+
await client.collection("users").authWithPassword(user.email, testUserPassword);
|
|
247
|
+
agent.set("Cookie", client.authStore.exportToCookie().split(";")[0]);
|
|
248
|
+
}
|
|
249
|
+
`;
|
|
250
|
+
function D(e) {
|
|
251
|
+
if (!p.existsSync(e)) return {
|
|
252
|
+
status: "success",
|
|
253
|
+
changed: !1
|
|
254
|
+
};
|
|
255
|
+
let t = new h().addSourceFileAtPath(e), n = t.getFunction("authenticateUser");
|
|
256
|
+
return !n || !/\.post\(\s*["'`]\/login["'`]\s*\)/.test(n.getText()) ? {
|
|
257
|
+
status: "success",
|
|
258
|
+
changed: !1
|
|
259
|
+
} : (n.replaceWithText(E), t.saveSync(), {
|
|
260
|
+
status: "success",
|
|
261
|
+
changed: !0
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
//#endregion
|
|
265
|
+
//#region src/patterns/enable/auth-remote/generate.runtime.ts
|
|
266
|
+
async function O(e) {
|
|
267
|
+
let { input: n } = e, r = t(e), i = [];
|
|
268
|
+
await c(e.root, async (t) => {
|
|
269
|
+
r.info("Updating PocketBase mail settings"), await t.settings.update({ meta: {
|
|
270
|
+
senderName: n.senderName,
|
|
271
|
+
senderAddress: n.senderAddress
|
|
272
|
+
} }), await l();
|
|
273
|
+
let a = await t.collections.getOne("users");
|
|
274
|
+
if (!a) throw Error("Users collection not found");
|
|
275
|
+
let o = a.verificationTemplate.body.replace("{APP_URL}/_/#/auth/confirm-verification/{TOKEN}", "{APP_URL}/confirm-verification/{TOKEN}"), s = a.resetPasswordTemplate.body.replace("{APP_URL}/_/#/auth/confirm-reset/{TOKEN}", "{APP_URL}/confirm-reset/{TOKEN}"), c = a.confirmEmailChangeTemplate.body.replace("{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}", "{APP_URL}/confirm-email-change/{TOKEN}");
|
|
276
|
+
r.info("Locking down users collection rules and email templates"), await t.collections.update("users", {
|
|
277
|
+
listRule: "@request.auth.id = id",
|
|
278
|
+
viewRule: "@request.auth.id = id",
|
|
279
|
+
createRule: "@request.auth.id = id",
|
|
280
|
+
updateRule: "@request.auth.id = id",
|
|
281
|
+
deleteRule: "@request.auth.id = id",
|
|
282
|
+
verificationTemplate: { body: o },
|
|
283
|
+
resetPasswordTemplate: { body: s },
|
|
284
|
+
confirmEmailChangeTemplate: { body: c }
|
|
285
|
+
}), await l();
|
|
286
|
+
let d = u("users", "updated", e);
|
|
287
|
+
d && i.push({
|
|
288
|
+
path: d,
|
|
289
|
+
language: "ts",
|
|
290
|
+
content: p.readFileSync(d, "utf8"),
|
|
291
|
+
status: "success"
|
|
292
|
+
});
|
|
293
|
+
});
|
|
294
|
+
let a = [], s = (e) => {
|
|
295
|
+
e && a.push(e);
|
|
296
|
+
};
|
|
297
|
+
r.info("Modifying +layout.server.ts");
|
|
298
|
+
let h = m.join(e.root, "src", "routes", "+layout.server.ts");
|
|
299
|
+
s(o(h, _(h))), r.info("Modifying root layout");
|
|
300
|
+
let g = [
|
|
301
|
+
m.join(e.root, "src", "routes", "(public)", "root-layout.svelte"),
|
|
302
|
+
m.join(e.root, "src", "routes", "root-layout.svelte"),
|
|
303
|
+
m.join(e.root, "src", "routes", "(public)", "+layout.svelte"),
|
|
304
|
+
m.join(e.root, "src", "routes", "+layout.svelte")
|
|
305
|
+
], v = g.find((e) => p.existsSync(e)) ?? g[0];
|
|
306
|
+
s(o(v, S(v))), r.info("Modifying hooks.server.ts");
|
|
307
|
+
let y = m.join(e.root, "src", "hooks.server.ts");
|
|
308
|
+
s(o(y, T(y))), r.info("Modifying test/setup.ts");
|
|
309
|
+
let b = m.join(e.root, "test", "setup.ts");
|
|
310
|
+
s(o(b, D(b))), r.info("Modifying config for remote functions");
|
|
311
|
+
let x = f(e.root);
|
|
312
|
+
s(o(x.filePath, x.outcome));
|
|
313
|
+
let C = await d(e);
|
|
314
|
+
return {
|
|
315
|
+
creates: C ? [C] : [],
|
|
316
|
+
modifies: a,
|
|
317
|
+
deletes: [],
|
|
318
|
+
components: [],
|
|
319
|
+
packages: [],
|
|
320
|
+
collections: [],
|
|
321
|
+
collectionPatches: [],
|
|
322
|
+
collectionDrops: []
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
//#endregion
|
|
326
|
+
export { O as generate };
|
|
327
|
+
|
|
328
|
+
//# sourceMappingURL=generate.runtime-onBnOiS7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate.runtime-onBnOiS7.js","names":[],"sources":["../../src/patterns/enable/auth-remote/modifies/+layout.server.ts","../../src/patterns/enable/auth-remote/modifies/root-layout.svelte.ts","../../src/patterns/enable/auth-remote/modifies/hooks.server.ts","../../src/patterns/enable/auth-remote/modifies/test-setup.ts","../../src/patterns/enable/auth-remote/generate.runtime.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nexport function modifyLayoutServer(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n const snippet = dedent`\n\t\t\texport const load = async ({ locals }) => {\n\t\t\t\treturn { user: locals.pb.authStore.record };\n\t\t\t};\n\t\t`;\n\n fs.writeFileSync(layoutPath, snippet);\n return { status: \"success\", changed: true };\n }\n\n const originalSource = fs.readFileSync(layoutPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(layoutPath);\n\n // helper to add user property to an object literal if missing\n const addUserProp = (obj: import(\"ts-morph\").ObjectLiteralExpression) => {\n const hasUser = !!obj.getProperty(\"user\");\n if (!hasUser) {\n obj.addPropertyAssignment({\n name: \"user\",\n initializer: \"locals.pb.authStore.record\",\n });\n }\n };\n\n // find existing exported load (function or const with arrow)\n let loadArrow: import(\"ts-morph\").ArrowFunction | undefined;\n let loadFn:\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression\n | undefined;\n\n const varDecl = sourceFile.getVariableDeclaration(\"load\");\n if (varDecl) {\n const vs = varDecl.getFirstAncestorByKind(SyntaxKind.VariableStatement);\n const isExported = !!vs?.hasExportKeyword();\n if (isExported) {\n const directArrow = varDecl.getInitializerIfKind(\n SyntaxKind.ArrowFunction,\n );\n if (directArrow) {\n loadArrow = directArrow;\n } else {\n const init = varDecl.getInitializer();\n if (init) {\n const innerArrow = init.getFirstDescendantByKind(\n SyntaxKind.ArrowFunction,\n );\n if (innerArrow) {\n loadArrow = innerArrow;\n } else {\n const innerFnExpr = init.getFirstDescendantByKind(\n SyntaxKind.FunctionExpression,\n );\n if (innerFnExpr) {\n loadFn = innerFnExpr;\n }\n }\n }\n }\n }\n }\n\n if (!loadArrow) {\n const maybeFn = sourceFile.getFunction(\"load\");\n if (maybeFn && maybeFn.isExported()) {\n loadFn = maybeFn;\n }\n }\n\n // if no load found, create one\n if (!loadArrow && !loadFn) {\n sourceFile.addFunction({\n isExported: true,\n isAsync: true,\n name: \"load\",\n parameters: [{ name: \"{ locals }\" }],\n statements: `return { user: locals.pb.authStore.record };`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // normalize function-like to a single handle\n const fnLike:\n | import(\"ts-morph\").ArrowFunction\n | import(\"ts-morph\").FunctionDeclaration\n | import(\"ts-morph\").FunctionExpression = (loadArrow ?? loadFn!) as any;\n\n // ensure first parameter destructures locals, preserving existing information\n const params = fnLike.getParameters();\n if (params.length === 0) {\n fnLike.insertParameter(0, { name: \"{ locals }\" });\n } else {\n const first = params[0];\n const original = first.getStructure();\n const nameNode = first.getNameNode();\n if (nameNode.getKind() === SyntaxKind.ObjectBindingPattern) {\n const obp = nameNode as import(\"ts-morph\").ObjectBindingPattern;\n const hasLocals = obp\n .getElements()\n .some((el) => el.getName() === \"locals\");\n if (!hasLocals) {\n const parts = obp\n .getElements()\n .map((el) => el.getText())\n .filter(Boolean);\n const tail = parts.length > 0 ? \", \" + parts.join(\", \") : \"\";\n first.set({\n name: `{ locals${tail} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n } else {\n const currentName = first.getName();\n if (currentName !== \"locals\") {\n first.set({\n name: `{ locals, ...${currentName} }`,\n type: original.type,\n initializer: (original as any).initializer,\n });\n }\n }\n }\n\n // add user to returned object literals without altering other properties\n if (loadArrow) {\n const body = loadArrow.getBody();\n if (body.getKind() === SyntaxKind.Block) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n } else {\n // concise body\n const bodyExpr = body as import(\"ts-morph\").Expression;\n if (bodyExpr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n bodyExpr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n } else if (bodyExpr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(bodyExpr as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n } else if (loadFn) {\n const body = loadFn.getBody();\n if (body) {\n const returns = body.getDescendantsOfKind(SyntaxKind.ReturnStatement);\n returns.forEach((ret) => {\n const expr = ret.getExpression();\n if (!expr) return;\n if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(expr as import(\"ts-morph\").ObjectLiteralExpression);\n } else if (expr.getKind() === SyntaxKind.ParenthesizedExpression) {\n const inner = (\n expr as import(\"ts-morph\").ParenthesizedExpression\n ).getExpression();\n if (inner.getKind() === SyntaxKind.ObjectLiteralExpression) {\n addUserProp(inner as import(\"ts-morph\").ObjectLiteralExpression);\n }\n }\n });\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport {\n ensureImports,\n ensurePropsBinding,\n withInMemoryScript,\n} from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst AUTH_MENU_NAVBAR_ITEM = `\n\t\t<Navbar.Item\n\t\t\tclass=\"flex flex-col md:flex-row items-center space-y-2 md:space-y-0 md:space-x-4\"\n\t\t>\n\t\t\t<AuthMenu.Root>\n\t\t\t\t{#snippet user()}\n\t\t\t\t\t<AuthMenu.Trigger>\n\t\t\t\t\t\t<Avatar.Root>\n\t\t\t\t\t\t\t{#if data.user?.avatar}\n\t\t\t\t\t\t\t\t<Avatar.Image\n\t\t\t\t\t\t\t\t\tsrc=\"/api/files/users/{data.user?.id}/{data.user?.avatar}\"\n\t\t\t\t\t\t\t\t\talt={data.user?.email}\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t{/if}\n\t\t\t\t\t\t\t<Avatar.Fallback>\n\t\t\t\t\t\t\t\t{data.user?.email?.charAt(0).toUpperCase()}\n\t\t\t\t\t\t\t</Avatar.Fallback>\n\t\t\t\t\t\t</Avatar.Root>\n\t\t\t\t\t</AuthMenu.Trigger>\n\n\t\t\t\t\t<AuthMenu.Content align=\"end\">\n\t\t\t\t\t\t<AuthMenu.Item href=\"/dashboard\">Dashboard</AuthMenu.Item>\n\t\t\t\t\t\t<AuthMenu.Group>\n\t\t\t\t\t\t\t<AuthMenu.Item href=\"/settings\">Settings</AuthMenu.Item>\n\t\t\t\t\t\t\t<AuthMenu.Item>\n\t\t\t\t\t\t\t\t<form action=\"/logout\" method=\"post\">\n\t\t\t\t\t\t\t\t\t<button type=\"submit\" class=\"contents\">Logout</button>\n\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t</AuthMenu.Item>\n\t\t\t\t\t\t</AuthMenu.Group>\n\t\t\t\t\t</AuthMenu.Content>\n\t\t\t\t{/snippet}\n\n\t\t\t\t{#snippet guest()}\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"ghost\"\n\t\t\t\t\t\thref=\"/login\">Login</Button\n\t\t\t\t\t>\n\t\t\t\t\t<Button\n\t\t\t\t\t\tclass=\"w-full justify-start md:justify-center md:w-auto\"\n\t\t\t\t\t\tvariant=\"outline\"\n\t\t\t\t\t\thref=\"/signup\">Sign up</Button\n\t\t\t\t\t>\n\t\t\t\t{/snippet}\n\t\t\t</AuthMenu.Root>\n\t\t</Navbar.Item>\n\t`;\n\nconst IMPORT_SNIPPET = dedent`\n import * as AuthMenu from '$lib/components/ui/auth-menu';\n import * as Avatar from '$lib/components/ui/avatar';\n`;\n\nconst FAILURE_HINT = [\n \"Add the auth menu inside your <Navbar.List> in the root layout.\",\n \"\",\n \"Imports to add to the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup to add inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create a root layout that includes an auth menu inside <Navbar.List>.\",\n \"\",\n \"Imports for the <script> tag:\",\n \"\",\n IMPORT_SNIPPET,\n \"\",\n \"Markup inside <Navbar.List>:\",\n AUTH_MENU_NAVBAR_ITEM,\n].join(\"\\n\");\n\nexport function modifyRootLayoutSvelte(layoutPath: string): ModifyOutcome {\n if (!fs.existsSync(layoutPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const file = SvelteFile.fromPath(layoutPath);\n if (!file.hasElement(\"Navbar.List\")) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n if (file.hasElement(\"AuthMenu.Root\")) {\n return { status: \"success\", changed: false };\n }\n\n file.modifyScript((source) => {\n const { source: out } = withInMemoryScript(source, (sf) => {\n ensureImports(sf, [\n {\n namespaceImport: \"AuthMenu\",\n moduleSpecifier: \"$lib/components/ui/auth-menu\",\n },\n {\n namespaceImport: \"Avatar\",\n moduleSpecifier: \"$lib/components/ui/avatar\",\n },\n ]);\n // The menu reads `data.user`; the template's layout takes no props.\n ensurePropsBinding(sf, \"data\");\n });\n return out;\n });\n\n file.insertBeforeClosingTag(\"Navbar.List\", AUTH_MENU_NAVBAR_ITEM);\n file.writeTo(layoutPath);\n return { status: \"success\", changed: file.hasChanged() };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst FAILURE_HINT = dedent`\n Configure handlePocketbase() with the auth option in hooks.server.ts:\n\n handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create src/hooks.server.ts with handlePocketbase:\n\n import { handlePocketbase } from '@velastack/pocketbase';\n\n export const handle = handlePocketbase({\n auth: { protectedRoutes: ['/(app)'] },\n });\n`;\n\nexport function modifyHooksServer(hooksServerPath: string): ModifyOutcome {\n if (!fs.existsSync(hooksServerPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(hooksServerPath, \"utf8\");\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(hooksServerPath);\n\n // Find the handlePocketbase(...) call\n const callExpr = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => ce.getExpression().getText() === \"handlePocketbase\");\n\n if (!callExpr) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const args = callExpr.getArguments();\n if (args.length === 0) {\n callExpr.addArgument(`{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const firstArg = args[0];\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) {\n callExpr.insertArgument(0, `{ auth: { protectedRoutes: ['/(app)'] } }`);\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n const optionsObj = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Ensure auth property exists\n const authProp = optionsObj.getProperty(\"auth\");\n if (!authProp) {\n optionsObj.addPropertyAssignment({\n name: \"auth\",\n initializer: `{ protectedRoutes: ['/(app)'] }`,\n });\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n }\n\n // If auth exists, ensure protectedRoutes includes '/(app)'\n if (authProp.getKind() === SyntaxKind.PropertyAssignment) {\n const authInit = (\n authProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (authInit && authInit.getKind() === SyntaxKind.ObjectLiteralExpression) {\n const authObj = authInit as import(\"ts-morph\").ObjectLiteralExpression;\n const prProp = authObj.getProperty(\"protectedRoutes\");\n if (!prProp) {\n authObj.addPropertyAssignment({\n name: \"protectedRoutes\",\n initializer: `['/(app)']`,\n });\n } else if (prProp.getKind() === SyntaxKind.PropertyAssignment) {\n const prInit = (\n prProp as import(\"ts-morph\").PropertyAssignment\n ).getInitializer();\n if (prInit && prInit.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arr = prInit as import(\"ts-morph\").ArrayLiteralExpression;\n const hasApp = arr\n .getElements()\n .some((el) => el.getText().replace(/['\"`]/g, \"\") === \"/(app)\");\n if (!hasApp) {\n arr.addElement(`'/(app)'`);\n }\n } else {\n (prProp as import(\"ts-morph\").PropertyAssignment).setInitializer(\n `['/(app)']`,\n );\n }\n }\n }\n }\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst COOKIE_LOGIN = dedent`\n // Login is a remote function, so there is no form action to post to: carry\n // the session the way the browser does, in the \\`pb_auth\\` cookie.\n async function authenticateUser(agent: Agent, user: { email: string }) {\n const client = new PocketBase(process.env.POCKETBASE_URL!);\n await client.collection(\"users\").authWithPassword(user.email, testUserPassword);\n agent.set(\"Cookie\", client.authStore.exportToCookie().split(\";\")[0]);\n }\n`;\n\n/**\n * The template's server-test helper logs in by posting the `/login` form\n * action, which this pattern replaces with a remote function. A project\n * without the helper (or with its own) has nothing to fix.\n */\nexport function modifyTestSetup(setupPath: string): ModifyOutcome {\n if (!fs.existsSync(setupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project();\n const sourceFile = project.addSourceFileAtPath(setupPath);\n const helper = sourceFile.getFunction(\"authenticateUser\");\n\n if (!helper || !/\\.post\\(\\s*[\"'`]\\/login[\"'`]\\s*\\)/.test(helper.getText())) {\n return { status: \"success\", changed: false };\n }\n\n helper.replaceWithText(COOKIE_LOGIN);\n sourceFile.saveSync();\n return { status: \"success\", changed: true };\n}\n","import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { Options, Result, File } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../runtime/pocketbase\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { ensureSiteFile } from \"../../../runtime/site\";\nimport { modifySvelteConfigRemote } from \"../../../runtime/modify-svelte-config-remote\";\n\nimport { modifyLayoutServer } from \"./modifies/+layout.server\";\nimport { modifyRootLayoutSvelte } from \"./modifies/root-layout.svelte\";\nimport { modifyHooksServer } from \"./modifies/hooks.server\";\nimport { modifyTestSetup } from \"./modifies/test-setup\";\n\nexport async function generate(options: Options) {\n const { input } = options;\n const logger = getLogger(options);\n\n let creates: File[] = [];\n\n // Update PocketBase\n await withPocketbase(options.root, async (pb) => {\n logger.info(\"Updating PocketBase mail settings\");\n await pb.settings.update({\n meta: {\n senderName: input.senderName,\n senderAddress: input.senderAddress,\n },\n });\n await migrationDelay();\n\n const userCollection = await pb.collections.getOne(\"users\");\n\n if (!userCollection) {\n throw new Error(\"Users collection not found\");\n }\n\n const verificationTemplate =\n userCollection.verificationTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-verification/{TOKEN}\",\n \"{APP_URL}/confirm-verification/{TOKEN}\",\n );\n const resetPasswordTemplate =\n userCollection.resetPasswordTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-reset/{TOKEN}\",\n \"{APP_URL}/confirm-reset/{TOKEN}\",\n );\n const confirmEmailChangeTemplate =\n userCollection.confirmEmailChangeTemplate.body.replace(\n \"{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}\",\n \"{APP_URL}/confirm-email-change/{TOKEN}\",\n );\n\n logger.info(\"Locking down users collection rules and email templates\");\n // Update user auth rules to lock down access to the user's own account\n await pb.collections.update(\"users\", {\n listRule: \"@request.auth.id = id\",\n viewRule: \"@request.auth.id = id\",\n createRule: \"@request.auth.id = id\",\n updateRule: \"@request.auth.id = id\",\n deleteRule: \"@request.auth.id = id\",\n\n // Update email templates to VelaStack auth urls\n verificationTemplate: {\n body: verificationTemplate,\n },\n resetPasswordTemplate: {\n body: resetPasswordTemplate,\n },\n confirmEmailChangeTemplate: {\n body: confirmEmailChangeTemplate,\n },\n });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\"users\", \"updated\", options);\n if (migrationFile) {\n creates.push({\n path: migrationFile,\n language: \"ts\",\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n // Modify files\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(\"Modifying +layout.server.ts\");\n const layoutServerFile = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"+layout.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(layoutServerFile, modifyLayoutServer(layoutServerFile)),\n );\n\n logger.info(\"Modifying root layout\");\n // TODO: make this more robust by searching for Navbar.Root > Navbar.List\n // src/routes/(public)/root-layout.svelte is what vela creates by default\n const layoutCandidates = [\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"root-layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"(public)\", \"+layout.svelte\"),\n path.join(options.root, \"src\", \"routes\", \"+layout.svelte\"),\n ];\n const layoutFile =\n layoutCandidates.find((p) => fs.existsSync(p)) ?? layoutCandidates[0];\n pushResult(\n modifyOutcomeToFile(layoutFile, modifyRootLayoutSvelte(layoutFile)),\n );\n\n logger.info(\"Modifying hooks.server.ts\");\n const hooksServerFile = path.join(options.root, \"src\", \"hooks.server.ts\");\n pushResult(\n modifyOutcomeToFile(hooksServerFile, modifyHooksServer(hooksServerFile)),\n );\n\n logger.info(\"Modifying test/setup.ts\");\n const testSetupFile = path.join(options.root, \"test\", \"setup.ts\");\n pushResult(\n modifyOutcomeToFile(testSetupFile, modifyTestSetup(testSetupFile)),\n );\n\n logger.info(\"Modifying config for remote functions\");\n const remote = modifySvelteConfigRemote(options.root);\n pushResult(modifyOutcomeToFile(remote.filePath, remote.outcome));\n\n // The auth pages and the app sidebar show `site.name`.\n const siteFile = await ensureSiteFile(options);\n\n return {\n creates: siteFile ? [siteFile] : [],\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;AAMA,SAAgB,EAAmB,GAAmC;CACpE,IAAI,CAAC,EAAG,WAAW,CAAU,GAAG;EAC9B,IAAM,IAAU,CAAM;;;;;EAOtB,OADA,EAAG,cAAc,GAAY,CAAO,GAC7B;GAAE,QAAQ;GAAW,SAAS;EAAK;CAC5C;CAEA,IAAM,IAAiB,EAAG,aAAa,GAAY,MAAM,GAEnD,IAAa,IADC,EACD,CAAA,CAAQ,oBAAoB,CAAU,GAGnD,KAAe,MAAoD;EAEvE,AADkB,EAAI,YAAY,MAAM,KAEtC,EAAI,sBAAsB;GACxB,MAAM;GACN,aAAa;EACf,CAAC;CAEL,GAGI,GACA,GAKE,IAAU,EAAW,uBAAuB,MAAM;CACxD,IAAI,KACS,EAAQ,uBAAuB,EAAW,iBAChC,CAAA,EAAI,iBAAiB,GAC1B;EACd,IAAM,IAAc,EAAQ,qBAC1B,EAAW,aACb;EACA,IAAI,GACF,IAAY;OACP;GACL,IAAM,IAAO,EAAQ,eAAe;GACpC,IAAI,GAAM;IACR,IAAM,IAAa,EAAK,yBACtB,EAAW,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C;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { a as e } from "./util-BLYliuUK.js";
|
|
2
|
+
import { n as t } from "./shared-C8GtNxpm.js";
|
|
3
|
+
import { _ as n, s as r } from "./ts-morph-helpers-CeduA--o.js";
|
|
4
|
+
import i from "node:fs";
|
|
5
|
+
import a from "node:path";
|
|
6
|
+
//#region src/runtime/modify-file.ts
|
|
7
|
+
function o(t, n) {
|
|
8
|
+
let r = e(t);
|
|
9
|
+
return n.status === "success" ? n.changed ? {
|
|
10
|
+
path: t,
|
|
11
|
+
language: r,
|
|
12
|
+
content: i.readFileSync(t, "utf8"),
|
|
13
|
+
status: "success"
|
|
14
|
+
} : null : {
|
|
15
|
+
path: t,
|
|
16
|
+
language: r,
|
|
17
|
+
content: n.status === "failed" && i.existsSync(t) ? i.readFileSync(t, "utf8") : "",
|
|
18
|
+
status: n.status,
|
|
19
|
+
message: n.message
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function s(e, a) {
|
|
23
|
+
return a.status === "success" && a.changed && i.existsSync(e) && n(i.readFileSync(e, "utf8"), r).result ? {
|
|
24
|
+
modify: null,
|
|
25
|
+
delete: t(e)
|
|
26
|
+
} : {
|
|
27
|
+
modify: o(e, a),
|
|
28
|
+
delete: null
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function c(e, n) {
|
|
32
|
+
return n.status === "success" && n.changed && i.existsSync(e) && i.readFileSync(e, "utf8").trim() === "" ? {
|
|
33
|
+
modify: null,
|
|
34
|
+
delete: t(e)
|
|
35
|
+
} : {
|
|
36
|
+
modify: o(e, n),
|
|
37
|
+
delete: null
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function l(e, t) {
|
|
41
|
+
return e.filter((e) => !i.existsSync(a.join(t, e.path)));
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { c as envRevertOutcomeToFile, l as keepMissing, o as modifyOutcomeToFile, s as revertOutcomeToFile };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=modify-file-Dwfv0dCI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"modify-file-Dwfv0dCI.js","names":[],"sources":["../../src/runtime/modify-file.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\nimport { toDeleteEntry } from \"../patterns/destroy/shared\";\nimport { isEffectivelyEmpty, withInMemoryScript } from \"./ts-morph-helpers\";\n\nexport function modifyOutcomeToFile(\n filePath: string,\n outcome: ModifyOutcome,\n): File | null {\n const language = languageFromPath(filePath);\n\n if (outcome.status === \"success\") {\n if (!outcome.changed) return null;\n return {\n path: filePath,\n language,\n content: fs.readFileSync(filePath, \"utf8\"),\n status: \"success\",\n };\n }\n\n const content =\n outcome.status === \"failed\" && fs.existsSync(filePath)\n ? fs.readFileSync(filePath, \"utf8\")\n : \"\";\n\n return {\n path: filePath,\n language,\n content,\n status: outcome.status,\n message: outcome.message,\n };\n}\n\n/**\n * `modifyOutcomeToFile` for a revert that may have taken out everything the\n * file held: a script left with no statements, only comments and whitespace,\n * is reported as a delete. For hooks files a pattern created, or that ended\n * up holding nothing but what patterns put there.\n */\nexport function revertOutcomeToFile(\n filePath: string,\n outcome: ModifyOutcome,\n): { modify: File | null; delete: File | null } {\n if (\n outcome.status === \"success\" &&\n outcome.changed &&\n fs.existsSync(filePath) &&\n withInMemoryScript(fs.readFileSync(filePath, \"utf8\"), isEffectivelyEmpty)\n .result\n ) {\n return { modify: null, delete: toDeleteEntry(filePath) };\n }\n return { modify: modifyOutcomeToFile(filePath, outcome), delete: null };\n}\n\n/**\n * `modifyOutcomeToFile` for a `.env` revert: a file the revert left empty is\n * reported as a delete. The enable pattern most likely created it, and an\n * empty `.env` holds nothing worth keeping.\n */\nexport function envRevertOutcomeToFile(\n envPath: string,\n outcome: ModifyOutcome,\n): { modify: File | null; delete: File | null } {\n if (\n outcome.status === \"success\" &&\n outcome.changed &&\n fs.existsSync(envPath) &&\n fs.readFileSync(envPath, \"utf8\").trim() === \"\"\n ) {\n return { modify: null, delete: toDeleteEntry(envPath) };\n }\n return { modify: modifyOutcomeToFile(envPath, outcome), delete: null };\n}\n\n/**\n * Drop any create that already exists on disk.\n *\n * `writeResult` overwrites an existing create whose content differs and\n * reports it as a modify, which would mean a re-run silently resetting a\n * developer's edits, or a create clobbering a file other patterns have\n * already written to. The file is theirs once it exists; a pattern that has\n * something to add to it does so with a modifier.\n */\nexport function keepMissing(creates: File[], root: string): File[] {\n return creates.filter((file) => !fs.existsSync(path.join(root, file.path)));\n}\n"],"mappings":";;;;;;AAOA,SAAgB,EACd,GACA,GACa;CACb,IAAM,IAAW,EAAiB,CAAQ;CAiB1C,OAfI,EAAQ,WAAW,YAChB,EAAQ,UACN;EACL,MAAM;EACN;EACA,SAAS,EAAG,aAAa,GAAU,MAAM;EACzC,QAAQ;CACV,IAN6B,OAcxB;EACL,MAAM;EACN;EACA,SAPA,EAAQ,WAAW,YAAY,EAAG,WAAW,CAAQ,IACjD,EAAG,aAAa,GAAU,MAAM,IAChC;EAMJ,QAAQ,EAAQ;EAChB,SAAS,EAAQ;CACnB;AACF;AAQA,SAAgB,EACd,GACA,GAC8C;CAU9C,OARE,EAAQ,WAAW,aACnB,EAAQ,WACR,EAAG,WAAW,CAAQ,KACtB,EAAmB,EAAG,aAAa,GAAU,MAAM,GAAG,CAAkB,CAAC,CACtE,SAEI;EAAE,QAAQ;EAAM,QAAQ,EAAc,CAAQ;CAAE,IAElD;EAAE,QAAQ,EAAoB,GAAU,CAAO;EAAG,QAAQ;CAAK;AACxE;AAOA,SAAgB,EACd,GACA,GAC8C;CAS9C,OAPE,EAAQ,WAAW,aACnB,EAAQ,WACR,EAAG,WAAW,CAAO,KACrB,EAAG,aAAa,GAAS,MAAM,CAAC,CAAC,KAAK,MAAM,KAErC;EAAE,QAAQ;EAAM,QAAQ,EAAc,CAAO;CAAE,IAEjD;EAAE,QAAQ,EAAoB,GAAS,CAAO;EAAG,QAAQ;CAAK;AACvE;AAWA,SAAgB,EAAY,GAAiB,GAAsB;CACjE,OAAO,EAAQ,QAAQ,MAAS,CAAC,EAAG,WAAW,EAAK,KAAK,GAAM,EAAK,IAAI,CAAC,CAAC;AAC5E"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as e, n as t, r as n } from "./config-target-
|
|
1
|
+
import { i as e, n as t, r as n } from "./config-target-Bln26FJe.js";
|
|
2
2
|
//#region src/runtime/modify-svelte-config-remote.ts
|
|
3
3
|
var r = [
|
|
4
4
|
"Enable SvelteKit remote functions and Svelte async in your config",
|
|
@@ -41,4 +41,4 @@ function a(a) {
|
|
|
41
41
|
//#endregion
|
|
42
42
|
export { a as modifySvelteConfigRemote };
|
|
43
43
|
|
|
44
|
-
//# sourceMappingURL=modify-svelte-config-remote-
|
|
44
|
+
//# sourceMappingURL=modify-svelte-config-remote-BUU_EaDf.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"modify-svelte-config-remote-
|
|
1
|
+
{"version":3,"file":"modify-svelte-config-remote-BUU_EaDf.js","names":[],"sources":["../../src/runtime/modify-svelte-config-remote.ts"],"sourcesContent":["import {\n ensureBooleanTrue,\n getOrCreateObjectLiteralProperty,\n modifyConfig,\n type ConfigModifyResult,\n} from \"./config-target\";\n\nconst FAILURE_HINT = [\n \"Enable SvelteKit remote functions and Svelte async in your config\",\n \"(the sveltekit() plugin arg in vite.config, or svelte.config):\",\n \"\",\n \"experimental: { remoteFunctions: true },\",\n \"compilerOptions: { experimental: { async: true } },\",\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Enable SvelteKit remote functions and Svelte async by passing config to the\",\n \"sveltekit() plugin in vite.config.ts:\",\n \"\",\n \"import { sveltekit } from '@sveltejs/kit/vite';\",\n \"import { defineConfig } from 'vite';\",\n \"\",\n \"export default defineConfig({\",\n \" plugins: [\",\n \" sveltekit({\",\n \" experimental: { remoteFunctions: true },\",\n \" compilerOptions: { experimental: { async: true } },\",\n \" }),\",\n \" ],\",\n \"});\",\n].join(\"\\n\");\n\n/**\n * Enable SvelteKit remote functions (`experimental.remoteFunctions`) and Svelte\n * async (`compilerOptions.experimental.async`) in whichever config the project\n * uses — the inline `sveltekit()` arg in vite.config, or svelte.config.\n *\n * `remoteFunctions` is kit-namespaced (→ `kitContainer()`); `async` is a\n * root-level compiler option (→ `configObject`).\n */\nexport function modifySvelteConfigRemote(root: string): ConfigModifyResult {\n return modifyConfig(\n root,\n { notFound: NOT_FOUND_HINT, failed: FAILURE_HINT },\n (target) => {\n const kit = target.kitContainer();\n if (!kit) return false;\n const kitExperimental = getOrCreateObjectLiteralProperty(\n kit,\n \"experimental\",\n \"{}\",\n );\n if (!kitExperimental) return false;\n ensureBooleanTrue(kitExperimental, \"remoteFunctions\");\n\n const compilerObj = getOrCreateObjectLiteralProperty(\n target.configObject,\n \"compilerOptions\",\n \"{}\",\n );\n if (!compilerObj) return false;\n const compilerExperimental = getOrCreateObjectLiteralProperty(\n compilerObj,\n \"experimental\",\n \"{}\",\n );\n if (!compilerExperimental) return false;\n ensureBooleanTrue(compilerExperimental, \"async\");\n\n return true;\n },\n );\n}\n"],"mappings":";;AAOA,IAAM,IAAe;CACnB;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAEL,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAUX,SAAgB,EAAyB,GAAkC;CACzE,OAAO,EACL,GACA;EAAE,UAAU;EAAgB,QAAQ;CAAa,IAChD,MAAW;EACV,IAAM,IAAM,EAAO,aAAa;EAChC,IAAI,CAAC,GAAK,OAAO;EACjB,IAAM,IAAkB,EACtB,GACA,gBACA,IACF;EACA,IAAI,CAAC,GAAiB,OAAO;EAC7B,EAAkB,GAAiB,iBAAiB;EAEpD,IAAM,IAAc,EAClB,EAAO,cACP,mBACA,IACF;EACA,IAAI,CAAC,GAAa,OAAO;EACzB,IAAM,IAAuB,EAC3B,GACA,gBACA,IACF;EAIA,OAHK,KACL,EAAkB,GAAsB,OAAO,GAExC,MAH2B;CAIpC,CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as e } from "./rolldown-runtime-DArdT4gl.js";
|
|
2
|
-
import { i as t, n } from "./constants-
|
|
2
|
+
import { i as t, n } from "./constants-BYkd9jeJ.js";
|
|
3
3
|
import { existsSync as r, readFileSync as i, readdirSync as a } from "node:fs";
|
|
4
4
|
import o from "node:path";
|
|
5
5
|
import s from "pocketbase";
|
|
@@ -232,4 +232,4 @@ function T(e, t) {
|
|
|
232
232
|
//#endregion
|
|
233
233
|
export { w as i, b as n, v as r, x as t };
|
|
234
234
|
|
|
235
|
-
//# sourceMappingURL=pocketbase-
|
|
235
|
+
//# sourceMappingURL=pocketbase-BkhUywtb.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pocketbase-CeG5BMN2.js","names":[],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n/**\n * Ports the Fetch spec tells clients to refuse outright\n * (https://fetch.spec.whatwg.org/#port-blocking). Node's `fetch` enforces the\n * list, so a server bound to one of them is unreachable from `waitForHealth`\n * and the PocketBase SDK alike: the request fails with cause \"bad port\"\n * before a connection is even attempted. 10080 sat inside the 10000–19999\n * range ports used to be drawn from, and cost a CI run a 30-second health\n * timeout whenever the draw landed on it.\n */\nexport const BAD_PORTS: ReadonlySet<number> = new Set([\n 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,\n 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,\n 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,\n 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,\n 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,\n 6679, 6697, 10080,\n]);\n\nfunction osAssignedPort(host: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, host, () => {\n const { port } = server.address() as net.AddressInfo;\n server.close(() => resolve(port));\n });\n });\n}\n\n/**\n * A port nothing is listening on right now, taken from the OS's ephemeral\n * range so it neither collides with whatever else the machine runs nor hits\n * `BAD_PORTS`. The port is released again before this resolves, so the\n * caller's server has to bind it promptly.\n */\nexport async function freePort(host: string): Promise<number> {\n for (;;) {\n const port = await osAssignedPort(host);\n if (!BAD_PORTS.has(port)) return port;\n }\n}\n\n// Wait for the port to be available. A cold `npx pocketbase-server` on a CI\n// runner can take well over the five seconds the old default allowed.\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 60,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n/**\n * `fetch` wraps the interesting part in `cause`: an errno error for a\n * connection that was refused, or a bare string such as \"bad port\" for a\n * request undici declined to make.\n */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const { cause } = error as Error & { cause?: unknown };\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n return code || cause.message || error.message;\n }\n if (cause !== undefined) return String(cause);\n return error.message;\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 60): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n let lastFailure = \"no attempt made\";\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n lastFailure = `HTTP ${response.status}`;\n } catch (error) {\n lastFailure = describeFetchError(error);\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(\n `Timed out waiting for health check at ${url}/api/health (last attempt: ${lastFailure})`,\n ),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { freePort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport { DATA_DIR, MIGRATIONS_DIR } from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = await freePort(host);\n const commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\n )!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n // Start the PocketBase server process. The package manager wrapper (`npx`)\n // spawns the real binary as a grandchild; put the tree in its own process\n // group so it can be killed as a whole, otherwise `pocketbase serve` outlives\n // us and keeps the data directory open.\n const detached = process.platform !== \"win32\";\n const serverProcess = spawn(command, args, {\n cwd,\n stdio: \"ignore\",\n detached,\n });\n\n // A wrapper that dies before the server listens (missing binary, bad\n // arguments) would otherwise only surface as a port timeout a minute later.\n const exited = new Promise<never>((_, reject) => {\n serverProcess.once(\"exit\", (code, signal) => {\n reject(\n new Error(\n `pocketbase-server exited before listening on ${host}:${port} (${signal ?? `code ${code}`})`,\n ),\n );\n });\n serverProcess.once(\"error\", reject);\n });\n\n try {\n // Wait for the server to be ready\n await Promise.race([\n (async () => {\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n })(),\n exited,\n ]);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process tree\n stopProcessTree(serverProcess, detached);\n }\n}\n\nfunction stopProcessTree(\n child: ReturnType<typeof spawn>,\n detached: boolean,\n): void {\n if (detached && child.pid) {\n try {\n process.kill(-child.pid, \"SIGTERM\");\n return;\n } catch {\n // Group already gone or unsupported; fall through to the plain kill.\n }\n }\n child.kill();\n}\n"],"mappings":";;;;;;;;;;AAWA,IAAa,oBAAiC,IAAI,IAAI;CACpD;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CACzE;CAAI;CAAI;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACzE;CAA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K,EAChB,YAAY;GAEX,AADA,MAAM,EAAY,GAAM,CAAI,GAC5B,MAAM,EAAc,UAAU,EAAK,GAAG,GAAM;EAC9C,EAAA,CAAG,GACH,CACF,CAAC;EAED,IAAM,IAAK,IAAI,EAAW,UAAU,EAAK,GAAG,GAAM;EAMlD,AALA,MAAM,EACJ,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAM,EAAG,CAAE;CACb,UAAU;EAER,EAAgB,GAAe,CAAQ;CACzC;AACF;AAEA,SAAS,EACP,GACA,GACM;CACN,IAAI,KAAY,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAAC,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
|
|
1
|
+
{"version":3,"file":"pocketbase-BkhUywtb.js","names":[],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n/**\n * Ports the Fetch spec tells clients to refuse outright\n * (https://fetch.spec.whatwg.org/#port-blocking). Node's `fetch` enforces the\n * list, so a server bound to one of them is unreachable from `waitForHealth`\n * and the PocketBase SDK alike: the request fails with cause \"bad port\"\n * before a connection is even attempted. 10080 sat inside the 10000–19999\n * range ports used to be drawn from, and cost a CI run a 30-second health\n * timeout whenever the draw landed on it.\n */\nexport const BAD_PORTS: ReadonlySet<number> = new Set([\n 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,\n 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,\n 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,\n 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,\n 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,\n 6679, 6697, 10080,\n]);\n\nfunction osAssignedPort(host: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, host, () => {\n const { port } = server.address() as net.AddressInfo;\n server.close(() => resolve(port));\n });\n });\n}\n\n/**\n * A port nothing is listening on right now, taken from the OS's ephemeral\n * range so it neither collides with whatever else the machine runs nor hits\n * `BAD_PORTS`. The port is released again before this resolves, so the\n * caller's server has to bind it promptly.\n */\nexport async function freePort(host: string): Promise<number> {\n for (;;) {\n const port = await osAssignedPort(host);\n if (!BAD_PORTS.has(port)) return port;\n }\n}\n\n// Wait for the port to be available. A cold `npx pocketbase-server` on a CI\n// runner can take well over the five seconds the old default allowed.\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 60,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n/**\n * `fetch` wraps the interesting part in `cause`: an errno error for a\n * connection that was refused, or a bare string such as \"bad port\" for a\n * request undici declined to make.\n */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const { cause } = error as Error & { cause?: unknown };\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n return code || cause.message || error.message;\n }\n if (cause !== undefined) return String(cause);\n return error.message;\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 60): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n let lastFailure = \"no attempt made\";\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n lastFailure = `HTTP ${response.status}`;\n } catch (error) {\n lastFailure = describeFetchError(error);\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(\n `Timed out waiting for health check at ${url}/api/health (last attempt: ${lastFailure})`,\n ),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { freePort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport { DATA_DIR, MIGRATIONS_DIR } from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = await freePort(host);\n const commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\n )!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n // Start the PocketBase server process. The package manager wrapper (`npx`)\n // spawns the real binary as a grandchild; put the tree in its own process\n // group so it can be killed as a whole, otherwise `pocketbase serve` outlives\n // us and keeps the data directory open.\n const detached = process.platform !== \"win32\";\n const serverProcess = spawn(command, args, {\n cwd,\n stdio: \"ignore\",\n detached,\n });\n\n // A wrapper that dies before the server listens (missing binary, bad\n // arguments) would otherwise only surface as a port timeout a minute later.\n const exited = new Promise<never>((_, reject) => {\n serverProcess.once(\"exit\", (code, signal) => {\n reject(\n new Error(\n `pocketbase-server exited before listening on ${host}:${port} (${signal ?? `code ${code}`})`,\n ),\n );\n });\n serverProcess.once(\"error\", reject);\n });\n\n try {\n // Wait for the server to be ready\n await Promise.race([\n (async () => {\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n })(),\n exited,\n ]);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process tree\n stopProcessTree(serverProcess, detached);\n }\n}\n\nfunction stopProcessTree(\n child: ReturnType<typeof spawn>,\n detached: boolean,\n): void {\n if (detached && child.pid) {\n try {\n process.kill(-child.pid, \"SIGTERM\");\n return;\n } catch {\n // Group already gone or unsupported; fall through to the plain kill.\n }\n }\n child.kill();\n}\n"],"mappings":";;;;;;;;;;AAWA,IAAa,oBAAiC,IAAI,IAAI;CACpD;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CACzE;CAAI;CAAI;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACzE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACtE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAM;CAAM;CACxE;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CACxE;CAA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,EAAG,CAAE;CACb,UAAU;EAER,EAAgB,GAAe,CAAQ;CACzC;AACF;AAEA,SAAS,EACP,GACA,GACM;CACN,IAAI,KAAY,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAAC,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as e } from "./errors-
|
|
1
|
+
import { t as e } from "./errors-DR3gF_7a.js";
|
|
2
2
|
import { i as t } from "./util-BLYliuUK.js";
|
|
3
3
|
//#region src/core/providers.ts
|
|
4
4
|
function n(e) {
|
|
@@ -66,4 +66,4 @@ function u(e, n) {
|
|
|
66
66
|
//#endregion
|
|
67
67
|
export { o as a, r as i, u as n, c as o, s as r, i as s, l as t };
|
|
68
68
|
|
|
69
|
-
//# sourceMappingURL=providers-
|
|
69
|
+
//# sourceMappingURL=providers-BL9vJP_9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers-
|
|
1
|
+
{"version":3,"file":"providers-BL9vJP_9.js","names":[],"sources":["../../src/core/providers.ts"],"sourcesContent":["import type { EnvEdit } from \"../runtime/env\";\nimport { InvalidArgumentError } from \"./errors\";\nimport type { File, Options, Pattern, Provider } from \"./types\";\nimport { filesUnderPrefix } from \"./util\";\n\ntype ProviderPattern = Pick<Pattern, \"slug\" | \"providers\">;\n\n/** `analytics` for `enable-analytics`: how the capability is named to users. */\nexport function capabilityName(slug: string): string {\n return slug.replace(/^enable-/, \"\");\n}\n\n/** `--provider <id>` or `--provider=<id>`, for callers that hand flags through in argv. */\nexport function providerFromArgv(argv: string[]): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--provider\") return argv[i + 1];\n if (arg.startsWith(\"--provider=\")) return arg.slice(\"--provider=\".length);\n }\n return undefined;\n}\n\nexport function unknownProviderMessage(\n name: string,\n raw: string,\n providers: Provider[],\n): string {\n return [\n `Unknown provider \"${raw}\" for ${name}.`,\n \"\",\n \"Available providers:\",\n ...providers.map((provider) => ` ${provider.id}`),\n ].join(\"\\n\");\n}\n\nexport function providerChoices(providers: Provider[]): string {\n return `--provider <${providers.map((provider) => provider.id).join(\"|\")}>`;\n}\n\n/**\n * The provider a generate call should produce, from `input.provider` or\n * `--provider` in argv.\n *\n * An unknown id is rejected with the list of known ones. With no provider at\n * all, a runtime call is rejected too: the CLI always supplies one, so this\n * is a caller bug. A preview call falls back to the first declared provider,\n * because the website loads patterns with argv only.\n */\nexport function resolveProvider(\n pattern: ProviderPattern,\n options: Pick<Options, \"input\" | \"argv\" | \"env\">,\n): Provider {\n const providers = pattern.providers ?? [];\n const name = capabilityName(pattern.slug);\n if (providers.length === 0) {\n throw new Error(`${pattern.slug} declares no providers.`);\n }\n\n const raw =\n typeof options.input.provider === \"string\"\n ? options.input.provider\n : providerFromArgv(options.argv);\n\n if (raw === undefined || raw === \"\") {\n if (options.env === \"preview\") return providers[0];\n throw new InvalidArgumentError(\n `Choose a provider for ${name}: ${providerChoices(providers)}`,\n );\n }\n\n const provider = providers.find((candidate) => candidate.id === raw);\n if (!provider) {\n throw new InvalidArgumentError(\n unknownProviderMessage(name, raw, providers),\n );\n }\n return provider;\n}\n\n/**\n * The `.env` lines for a provider: `# heading`, then one `KEY=value` per\n * declared env var. `supplied` holds what the CLI collected; a blank value\n * falls back to the provider's default, else an empty assignment the\n * developer fills in later. Prompt placeholders are never written.\n */\nexport function providerEnvEdits(\n provider: Provider,\n heading: string,\n supplied: Record<string, string> = {},\n): EnvEdit[] {\n return [\n { type: \"comment\", key: heading },\n ...(provider.env ?? []).map((variable): EnvEdit => ({\n type: \"var\",\n key: variable.key,\n value: supplied[variable.key]?.trim() || variable.default || \"\",\n })),\n ];\n}\n\n/** The string values of `input.providerEnv`, as the CLI collected them. */\nexport function suppliedProviderEnv(\n options: Pick<Options, \"input\">,\n): Record<string, string> {\n const raw = options.input.providerEnv;\n if (!raw || typeof raw !== \"object\") return {};\n const values: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw)) {\n if (typeof value === \"string\") values[key] = value;\n }\n return values;\n}\n\n/**\n * Every app-relative path any provider creates, sorted, for a disable pattern\n * that removes the files whichever provider was chosen. Works on a glob taken\n * from anywhere (`../../enable/<x>/providers/**`): only the part after\n * `providers/<id>/` counts.\n */\nexport function allProviderPaths(\n providersRaw: Record<string, string>,\n): string[] {\n const paths = new Set<string>();\n for (const key of Object.keys(providersRaw)) {\n const match = key.match(/\\/providers\\/[^/]+\\/(.+)$/);\n if (match) paths.add(match[1]);\n }\n return [...paths].sort();\n}\n\n/**\n * The files under `providers/<id>/**` of a pattern, as creates. The glob map\n * is one `import.meta.glob(\"./providers/**\")` covering every provider.\n */\nexport function providerCreates(\n providersRaw: Record<string, string>,\n id: string,\n): File[] {\n const files = filesUnderPrefix(providersRaw, `./providers/${id}/`);\n return Object.values(files).sort((a, b) => a.path.localeCompare(b.path));\n}\n"],"mappings":";;;AAQA,SAAgB,EAAe,GAAsB;CACnD,OAAO,EAAK,QAAQ,YAAY,EAAE;AACpC;AAGA,SAAgB,EAAiB,GAAoC;CACnE,KAAK,IAAI,IAAI,GAAG,IAAI,EAAK,QAAQ,KAAK;EACpC,IAAM,IAAM,EAAK;EACjB,IAAI,MAAQ,cAAc,OAAO,EAAK,IAAI;EAC1C,IAAI,EAAI,WAAW,aAAa,GAAG,OAAO,EAAI,MAAM,EAAoB;CAC1E;AAEF;AAEA,SAAgB,EACd,GACA,GACA,GACQ;CACR,OAAO;EACL,qBAAqB,EAAI,QAAQ,EAAK;EACtC;EACA;EACA,GAAG,EAAU,KAAK,MAAa,KAAK,EAAS,IAAI;CACnD,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAgB,EAAgB,GAA+B;CAC7D,OAAO,eAAe,EAAU,KAAK,MAAa,EAAS,EAAE,CAAC,CAAC,KAAK,GAAG,EAAE;AAC3E;AAWA,SAAgB,EACd,GACA,GACU;CACV,IAAM,IAAY,EA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