@velastack/patterns 0.4.1 → 0.4.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/dist/chunks/{_layout-kkgN0IF7.js → _layout-D-FzWqn0.js} +2 -2
- package/dist/chunks/{_layout-kkgN0IF7.js.map → _layout-D-FzWqn0.js.map} +1 -1
- 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-Dz2fvKnz.js.map → collections-zzZ_HQxB.js.map} +1 -1
- package/dist/chunks/{compose-handle-D_Rz3Fzo.js → compose-handle-BDlZ7Pif.js} +2 -2
- package/dist/chunks/{compose-handle-D_Rz3Fzo.js.map → compose-handle-BDlZ7Pif.js.map} +1 -1
- package/dist/chunks/{config-target-Dx3w6WSk.js → config-target-rHgjaA8u.js} +2 -2
- package/dist/chunks/{config-target-Dx3w6WSk.js.map → config-target-rHgjaA8u.js.map} +1 -1
- package/dist/chunks/{constants-BjyMU5s8.js → constants-Rq8SCXwH.js} +2 -2
- package/dist/chunks/{constants-BjyMU5s8.js.map → constants-Rq8SCXwH.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-vars-C1NUX-bf.js → env-vars-CcE6ODqC.js} +4 -4
- package/dist/chunks/{env-vars-C1NUX-bf.js.map → env-vars-CcE6ODqC.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-DeaBlnK6.js.map → generate-B6Odfk5f.js.map} +1 -1
- package/dist/chunks/{generate-WMJo3QGZ.js → generate-Bg0E3eWm.js} +2 -2
- package/dist/chunks/{generate-WMJo3QGZ.js.map → generate-Bg0E3eWm.js.map} +1 -1
- package/dist/chunks/{generate-Gcc8iRkZ.js → generate-CFqpRi9D.js} +3 -3
- package/dist/chunks/{generate-Gcc8iRkZ.js.map → generate-CFqpRi9D.js.map} +1 -1
- package/dist/chunks/{generate-BW3l5Fxw.js → generate-CZGHByV3.js} +2 -2
- package/dist/chunks/{generate-BW3l5Fxw.js.map → generate-CZGHByV3.js.map} +1 -1
- package/dist/chunks/{generate.runtime-IlBCcXvv.js → generate.runtime-5rIc-RNL.js} +7 -7
- package/dist/chunks/{generate.runtime-IlBCcXvv.js.map → generate.runtime-5rIc-RNL.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BgTz41Zg.js → generate.runtime-BK3mR0Rj.js} +92 -140
- package/dist/chunks/generate.runtime-BK3mR0Rj.js.map +1 -0
- package/dist/chunks/generate.runtime-Bcrht4M9.js +42 -0
- package/dist/chunks/generate.runtime-Bcrht4M9.js.map +1 -0
- package/dist/chunks/{generate.runtime-cwvAoKoH.js → generate.runtime-BpMN5Uq-.js} +3 -3
- package/dist/chunks/{generate.runtime-cwvAoKoH.js.map → generate.runtime-BpMN5Uq-.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DD51OSuL.js → generate.runtime-CAn1qIQ_.js} +4 -4
- package/dist/chunks/{generate.runtime-DD51OSuL.js.map → generate.runtime-CAn1qIQ_.js.map} +1 -1
- 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-B1jVAnDI.js.map → generate.runtime-CK10Mum5.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DqD3PW-W.js → generate.runtime-CZ46nkSL.js} +3 -3
- package/dist/chunks/{generate.runtime-DqD3PW-W.js.map → generate.runtime-CZ46nkSL.js.map} +1 -1
- 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-CCr1lvo4.js.map → generate.runtime-CpMKXBkn.js.map} +1 -1
- package/dist/chunks/{generate.runtime-6FXJM8hT.js → generate.runtime-CqncBFNg.js} +5 -5
- package/dist/chunks/{generate.runtime-6FXJM8hT.js.map → generate.runtime-CqncBFNg.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C6bSvGMb.js → generate.runtime-DHHlYfTD.js} +6 -6
- package/dist/chunks/{generate.runtime-C6bSvGMb.js.map → generate.runtime-DHHlYfTD.js.map} +1 -1
- package/dist/chunks/generate.runtime-DJ9MVVPC.js +325 -0
- package/dist/chunks/generate.runtime-DJ9MVVPC.js.map +1 -0
- package/dist/chunks/generate.runtime-DJHUBL4Z.js +68 -0
- package/dist/chunks/generate.runtime-DJHUBL4Z.js.map +1 -0
- package/dist/chunks/{generate.runtime-CnPraLKv.js → generate.runtime-DVB7uuht.js} +4 -4
- package/dist/chunks/{generate.runtime-CnPraLKv.js.map → generate.runtime-DVB7uuht.js.map} +1 -1
- 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-D_sQOeQa.js.map → generate.runtime-Djas9UNy.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Ce_rwzNa.js → generate.runtime-Dl6OQ7pe.js} +4 -4
- package/dist/chunks/{generate.runtime-Ce_rwzNa.js.map → generate.runtime-Dl6OQ7pe.js.map} +1 -1
- package/dist/chunks/{generate.runtime-1-91UmM8.js → generate.runtime-DoZJHtZh.js} +4 -4
- package/dist/chunks/{generate.runtime-1-91UmM8.js.map → generate.runtime-DoZJHtZh.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C8zJRNYG.js → generate.runtime-E-zoeSKW.js} +5 -5
- package/dist/chunks/{generate.runtime-C8zJRNYG.js.map → generate.runtime-E-zoeSKW.js.map} +1 -1
- 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-CYagyR5c.js.map → generate.runtime-a3R4hqFy.js.map} +1 -1
- 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-Dtgw9IQO.js.map → generate.runtime-axm9wcQv.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DHBRyMAq.js → generate.runtime-hTKzxH2M.js} +5 -5
- package/dist/chunks/{generate.runtime-DHBRyMAq.js.map → generate.runtime-hTKzxH2M.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BA3tDKnn.js → generate.runtime-kciwaXxh.js} +5 -5
- package/dist/chunks/{generate.runtime-BA3tDKnn.js.map → generate.runtime-kciwaXxh.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B_UVGa3q.js → generate.runtime-koQxLywh.js} +5 -5
- package/dist/chunks/{generate.runtime-B_UVGa3q.js.map → generate.runtime-koQxLywh.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DM4o_QYY.js → generate.runtime-rs1ZOIET.js} +5 -5
- package/dist/chunks/{generate.runtime-DM4o_QYY.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-DV3WmZtb.js.map → generate.runtime-uLUiPgqx.js.map} +1 -1
- package/dist/chunks/{modify-file-BlDeeurK.js → modify-file-DK-tCH9k.js} +3 -3
- package/dist/chunks/{modify-file-BlDeeurK.js.map → modify-file-DK-tCH9k.js.map} +1 -1
- 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-p0TfVzxm.js.map → modify-svelte-config-remote-DhuRX4FI.js.map} +1 -1
- package/dist/chunks/modify-user-signup-BbqTiUuA.js +54 -0
- package/dist/chunks/modify-user-signup-BbqTiUuA.js.map +1 -0
- package/dist/chunks/{pocketbase-Dry6ry17.js → pocketbase-CgwbH1gI.js} +2 -2
- package/dist/chunks/{pocketbase-Dry6ry17.js.map → pocketbase-CgwbH1gI.js.map} +1 -1
- package/dist/chunks/{shared-CZC4d7Uj.js → shared-Cc_ns5-y.js} +2 -2
- package/dist/chunks/{shared-CZC4d7Uj.js.map → shared-Cc_ns5-y.js.map} +1 -1
- package/dist/chunks/{site-BwCA18Sv.js → site-lj0CDdQ1.js} +2 -2
- package/dist/chunks/{site-BwCA18Sv.js.map → site-lj0CDdQ1.js.map} +1 -1
- package/dist/chunks/{table-core-AjBpYi-y.js → table-core-DhDqT03G.js} +2 -2
- package/dist/chunks/{table-core-AjBpYi-y.js.map → table-core-DhDqT03G.js.map} +1 -1
- package/dist/chunks/{test-setup-DEmWd9Ul.js → test-setup-B9fQ5L_-.js} +5 -5
- package/dist/chunks/{test-setup-DEmWd9Ul.js.map → test-setup-B9fQ5L_-.js.map} +1 -1
- 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-X698F10c.js.map → ui-CuCsupFq.js.map} +1 -1
- package/dist/chunks/{unmodify-load-CyGzC1Hu.js → unmodify-load-Bl5vXQiL.js} +2 -2
- package/dist/chunks/{unmodify-load-CyGzC1Hu.js.map → unmodify-load-Bl5vXQiL.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-B68lvI57.js.map → write-result-DiZsCS_y.js.map} +1 -1
- package/dist/index.d.ts +134 -1
- package/dist/index.js +2240 -2005
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunks/dispatch-CXOXPLFk.js +0 -6
- package/dist/chunks/dispatch-CXOXPLFk.js.map +0 -1
- package/dist/chunks/format-result-DZ8De8KY.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-BgTz41Zg.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-CslAvllQ.js.map +0 -1
- package/dist/chunks/generate.runtime-CuNhY5hn.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/nav-user-BRIHOOpG.js +0 -6
- package/dist/chunks/nav-user-BRIHOOpG.js.map +0 -1
- package/dist/chunks/ts-morph-helpers-CDW4lhox.js.map +0 -1
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { t as e } from "./dedent-Gq6Krl4n.js";
|
|
2
|
+
import { o as t } from "./ts-morph-helpers-Bepc-Es2.js";
|
|
3
|
+
import n from "node:fs";
|
|
4
|
+
import { Project as r, QuoteKind as i, SyntaxKind as a } from "ts-morph";
|
|
5
|
+
//#region src/patterns/enable/payments/modifies/modify-user-signup.ts
|
|
6
|
+
var o = "#lib/workflows/link-stripe-customer.js", s = e`
|
|
7
|
+
// Queued here, done in the background: the Stripe calls retry on their own,
|
|
8
|
+
// and the key means a retry never makes a second customer for this user.
|
|
9
|
+
await linkStripeCustomer.run(
|
|
10
|
+
{ userId: user.id, email: form.data.email },
|
|
11
|
+
{ idempotencyKey: user.id }
|
|
12
|
+
);
|
|
13
|
+
`, c = [
|
|
14
|
+
"Could not locate the requestVerification call in signup +page.server.ts.",
|
|
15
|
+
"Start the workflow once the user exists:",
|
|
16
|
+
"",
|
|
17
|
+
`import { linkStripeCustomer } from '${o}';`,
|
|
18
|
+
"",
|
|
19
|
+
s
|
|
20
|
+
].join("\n"), l = ["Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments."].join("\n");
|
|
21
|
+
function u(e) {
|
|
22
|
+
if (!n.existsSync(e)) return {
|
|
23
|
+
status: "not-found",
|
|
24
|
+
message: l
|
|
25
|
+
};
|
|
26
|
+
let u = n.readFileSync(e, "utf8");
|
|
27
|
+
if (u.includes("linkStripeCustomer")) return {
|
|
28
|
+
status: "success",
|
|
29
|
+
changed: !1
|
|
30
|
+
};
|
|
31
|
+
let d = new r({ manipulationSettings: { quoteKind: i.Single } }).addSourceFileAtPath(e), f = d.getDescendantsOfKind(a.CallExpression).find((e) => {
|
|
32
|
+
let t = e.getExpression();
|
|
33
|
+
return t.getKind() === a.PropertyAccessExpression && t.getText().includes("requestVerification");
|
|
34
|
+
});
|
|
35
|
+
if (!f) return {
|
|
36
|
+
status: "failed",
|
|
37
|
+
message: c
|
|
38
|
+
};
|
|
39
|
+
let p = f.getFirstAncestorByKind(a.ExpressionStatement);
|
|
40
|
+
return p ? (d.addImportDeclaration({
|
|
41
|
+
namedImports: ["linkStripeCustomer"],
|
|
42
|
+
moduleSpecifier: o
|
|
43
|
+
}), p.replaceWithText(s + "\n\n" + p.getText()), t(d), d.saveSync(), {
|
|
44
|
+
status: "success",
|
|
45
|
+
changed: d.getFullText() !== u
|
|
46
|
+
}) : {
|
|
47
|
+
status: "failed",
|
|
48
|
+
message: c
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
export { u as t };
|
|
53
|
+
|
|
54
|
+
//# sourceMappingURL=modify-user-signup-BbqTiUuA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"modify-user-signup-BbqTiUuA.js","names":["dedent","formatLikeSource","fs","WORKFLOW_MODULE","RUN_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","modifyUserSignup","userSignupPath","originalSource","sourceFile","Project","QuoteKind","requestVerificationCall","SyntaxKind","expr","ce","statement"],"sources":["../../src/patterns/enable/payments/modifies/modify-user-signup.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport { Project, QuoteKind, SyntaxKind } from \"ts-morph\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\nimport { formatLikeSource } from \"../../../../runtime/ts-morph-helpers\";\n\nconst WORKFLOW_MODULE = \"#lib/workflows/link-stripe-customer.js\";\n\nconst RUN_SNIPPET = dedent`\n // Queued here, done in the background: the Stripe calls retry on their own,\n // and the key means a retry never makes a second customer for this user.\n await linkStripeCustomer.run(\n { userId: user.id, email: form.data.email },\n { idempotencyKey: user.id }\n );\n`;\n\nconst FAILURE_HINT = [\n \"Could not locate the requestVerification call in signup +page.server.ts.\",\n \"Start the workflow once the user exists:\",\n \"\",\n `import { linkStripeCustomer } from '${WORKFLOW_MODULE}';`,\n \"\",\n RUN_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create src/routes/(public)/(auth)/signup/+page.server.ts before enabling payments.\",\n].join(\"\\n\");\n\n/**\n * Starts the link-stripe-customer workflow right after the user is created.\n * The work itself lives in src/lib/workflows/link-stripe-customer.ts.\n */\nexport function modifyUserSignup(userSignupPath: string): ModifyOutcome {\n if (!fs.existsSync(userSignupPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const originalSource = fs.readFileSync(userSignupPath, \"utf8\");\n if (originalSource.includes(\"linkStripeCustomer\")) {\n return { status: \"success\", changed: false };\n }\n\n const project = new Project({\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n const sourceFile = project.addSourceFileAtPath(userSignupPath);\n\n const requestVerificationCall = sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .find((ce) => {\n const expr = ce.getExpression();\n return (\n expr.getKind() === SyntaxKind.PropertyAccessExpression &&\n expr.getText().includes(\"requestVerification\")\n );\n });\n\n if (!requestVerificationCall) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n const statement = requestVerificationCall.getFirstAncestorByKind(\n SyntaxKind.ExpressionStatement,\n );\n\n if (!statement) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n sourceFile.addImportDeclaration({\n namedImports: [\"linkStripeCustomer\"],\n moduleSpecifier: WORKFLOW_MODULE,\n });\n\n statement.replaceWithText(RUN_SNIPPET + \"\\n\\n\" + statement.getText());\n\n formatLikeSource(sourceFile);\n sourceFile.saveSync();\n\n return {\n status: \"success\",\n changed: sourceFile.getFullText() !== originalSource,\n };\n}\n"],"mappings":";;;;;AAMA,IAAMG,IAAkB,0CAElBC,IAAc,CAAM;;;;;;;GASpBC,IAAe;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rq8SCXwH.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-CgwbH1gI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pocketbase-Dry6ry17.js","names":["__exportAll","MIGRATIONS_DIR","DATA_DIR","path","PocketBase","spawn","net","BAD_PORTS","osAssignedPort","server","reject","host","resolve","port","freePort","waitForPort","attempts","tryConnect","socket","maxAttempts","describeFetchError","error","cause","waitForHealth","lastFailure","tryHealth","response","url","pocketbase_exports","authWithRetries","getMigrationFile","getPocketbaseMetadata","migrationDelay","withPocketbase","MIGRATION_DELAY_MS","ending","action","collectionName","migrationFile","readdirSync","options","file","metadataPath","cwd","existsSync","readFileSync","authSuccess","attempt","pb","email","password","dir","migrationsDir","metadata","fn","commandArgs","packageManager","detect","resolveCommand","args","detached","serverProcess","command","exited","signal","code","stopProcessTree","child"],"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,IAAaO,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;CA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AAK,SAAS,GAAM,MAAW;GAC3C,EACE,gBAAI,MACF,gDAAgDlD,EAAK,GAAGE,EAAK,IAAImD,KAAU,QAAQC,IAAO,EAC5F,CACF;EACF,CAAC,GACDJ,EAAc,KAAK,SAASnD,CAAM;CACpC,CAAC;CAED,IAAI;EAEF,MAAM,QAAQ,KAAK,EAChB,YAAY;GAEX,AADA,MAAMK,EAAYF,GAAMF,CAAI,GAC5B,MAAMY,EAAc,UAAUZ,EAAK,GAAGE,GAAM;EAC9C,EAAA,CAAG,GACHkD,CACF,CAAC;EAED,IAAMf,IAAK,IAAI5C,EAAW,UAAUO,EAAK,GAAGE,GAAM;EAMlD,AALA,MAAMgB,EACJmB,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAMM,EAAGN,CAAE;CACb,UAAU;EAER,EAAgBa,GAAeD,CAAQ;CACzC;AACF;AAEA,SAASM,EACP,GACA,GACM;CACN,IAAIN,KAAYO,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAACA,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
|
|
1
|
+
{"version":3,"file":"pocketbase-CgwbH1gI.js","names":["__exportAll","MIGRATIONS_DIR","DATA_DIR","path","PocketBase","spawn","net","BAD_PORTS","osAssignedPort","server","reject","host","resolve","port","freePort","waitForPort","attempts","tryConnect","socket","maxAttempts","describeFetchError","error","cause","waitForHealth","lastFailure","tryHealth","response","url","pocketbase_exports","authWithRetries","getMigrationFile","getPocketbaseMetadata","migrationDelay","withPocketbase","MIGRATION_DELAY_MS","ending","action","collectionName","migrationFile","readdirSync","options","file","metadataPath","cwd","existsSync","readFileSync","authSuccess","attempt","pb","email","password","dir","migrationsDir","metadata","fn","commandArgs","packageManager","detect","resolveCommand","args","detached","serverProcess","command","exited","signal","code","stopProcessTree","child"],"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,IAAaO,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;CAAM;CAAM;AACd,CAAC;AAED,SAASC,EAAe,GAA+B;CACrD,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAMC,IAASH,EAAI,aAAa;EAGhC,AAFAG,EAAO,MAAM,GACbA,EAAO,KAAK,SAASC,CAAM,GAC3BD,EAAO,OAAO,GAAGE,SAAY;GAC3B,IAAM,EAAE,YAASF,EAAO,QAAQ;GAChC,EAAO,YAAYG,EAAQC,CAAI,CAAC;EAClC,CAAC;CACH,CAAC;AACH;AAQA,eAAsBC,EAAS,GAA+B;CAC5D,SAAS;EACP,IAAMD,IAAO,MAAML,EAAeG,CAAI;EACtC,IAAI,CAACJ,EAAU,IAAIM,CAAI,GAAG,OAAOA;CACnC;AACF;AAIA,SAAgBE,EACd,GACA,GACA,IAAc,IACC;CACf,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAIC,IAAW,GAETC,UAAmB;GACvB;GAEA,IAAMC,IAAS,IAAIZ,EAAI,OA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ACA;EACAJ;EACA;EACAC;EACA;EACA,GAAGzC,EAAK,GAAGE;CACb,GAEM2C,KAAkB,MAAMC,EAAO,EAAE,OAAI,CAAC,EAAA,EAAI,QAAQ,OAClD,EAAE,YAAS,YAASC,EACxBF,GACA,WACAD,CACF;CAGA,AAAIC,MAAmB,SAAOG,EAAK,QAAQ,OAAO;CAMlD,IAAMC,IAAW,QAAQ,aAAa,SAChCC,IAAgBxD,EAAMyD,GAASH,GAAM;EACzC;EACA,OAAO;EACP;CACF,CAAC,GAIKI,IAAS,IAAI,SAAgB,GAAG,MAAW;EAQ/C,AAPAF,EAAc,KAAK,SAAS,GAAM,MAAW;GAC3C,EACE,gBAAI,MACF,gDAAgDlD,EAAK,GAAGE,EAAK,IAAImD,KAAU,QAAQC,IAAO,EAC5F,CACF;EACF,CAAC,GACDJ,EAAc,KAAK,SAASnD,CAAM;CACpC,CAAC;CAED,IAAI;EAEF,MAAM,QAAQ,KAAK,EAChB,YAAY;GAEX,AADA,MAAMK,EAAYF,GAAMF,CAAI,GAC5B,MAAMY,EAAc,UAAUZ,EAAK,GAAGE,GAAM;EAC9C,EAAA,CAAG,GACHkD,CACF,CAAC;EAED,IAAMf,IAAK,IAAI5C,EAAW,UAAUO,EAAK,GAAGE,GAAM;EAMlD,AALA,MAAMgB,EACJmB,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAMM,EAAGN,CAAE;CACb,UAAU;EAER,EAAgBa,GAAeD,CAAQ;CACzC;AACF;AAEA,SAASM,EACP,GACA,GACM;CACN,IAAIN,KAAYO,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAACA,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
|
|
@@ -15,7 +15,7 @@ async function n(e, t) {
|
|
|
15
15
|
exists: !0,
|
|
16
16
|
rowCount: 0
|
|
17
17
|
}));
|
|
18
|
-
let { withPocketbase: n } = await import("./pocketbase-
|
|
18
|
+
let { withPocketbase: n } = await import("./pocketbase-CgwbH1gI.js").then((e) => e.r), { planCollectionDrops: r } = await import("./collections-zzZ_HQxB.js"), i = [];
|
|
19
19
|
return await n(t.root, async (t) => {
|
|
20
20
|
let n = await r(t, e);
|
|
21
21
|
i.push(...n);
|
|
@@ -24,4 +24,4 @@ async function n(e, t) {
|
|
|
24
24
|
//#endregion
|
|
25
25
|
export { t as n, n as t };
|
|
26
26
|
|
|
27
|
-
//# sourceMappingURL=shared-
|
|
27
|
+
//# sourceMappingURL=shared-Cc_ns5-y.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-
|
|
1
|
+
{"version":3,"file":"shared-Cc_ns5-y.js","names":["languageFromPath","toDeleteEntry","path","planDropsForCollections","collectionNames","options","n","drops","withPocketbase","plans","planCollectionDrops","pb"],"sources":["../../src/patterns/destroy/shared.ts"],"sourcesContent":["import type { CollectionDropSpec, File, Options } from \"../../core/types\";\nimport { languageFromPath } from \"../../core/util\";\n\nexport function toDeleteEntry(path: string): File {\n return {\n path,\n language: languageFromPath(path),\n content: \"\",\n status: \"success\",\n };\n}\n\n/**\n * Build `CollectionDropSpec` entries for each collection name, with live row\n * counts from PocketBase when `env === \"runtime\"`. In preview mode, returns\n * `{ exists: true, rowCount: 0 }` placeholders.\n */\nexport async function planDropsForCollections(\n collectionNames: string[],\n options: Options,\n): Promise<CollectionDropSpec[]> {\n if (collectionNames.length === 0) return [];\n\n if (options.env !== \"runtime\") {\n return collectionNames.map((name) => ({\n name,\n exists: true,\n rowCount: 0,\n }));\n }\n\n const { withPocketbase } = await import(\"../../runtime/pocketbase\");\n const { planCollectionDrops } = await import(\"../../runtime/collections\");\n const drops: CollectionDropSpec[] = [];\n await withPocketbase(options.root, async (pb) => {\n const plans = await planCollectionDrops(pb, collectionNames);\n drops.push(...plans);\n });\n return drops;\n}\n"],"mappings":";;AAGA,SAAgBC,EAAc,GAAoB;CAChD,OAAO;EACL;EACA,UAAUD,EAAiBE,CAAI;EAC/B,SAAS;EACT,QAAQ;CACV;AACF;AAOA,eAAsBC,EACpB,GACA,GAC+B;CAC/B,IAAIC,EAAgB,WAAW,GAAG,OAAO,CAAC;CAE1C,IAAIC,EAAQ,QAAQ,WAClB,OAAOD,EAAgB,KAAK,OAAU;EACpC;EACA,QAAQ;EACR,UAAU;CACZ,EAAE;CAGJ,IAAM,EAAE,sBAAmB,MAAM,OAAO,2BAAA,CAAA,MAAA,MAAAE,EAAA,CAAA,GAClC,EAAE,2BAAwB,MAAM,OAAO,8BACvCC,IAA8B,CAAC;CAKrC,OAJA,MAAMC,EAAeH,EAAQ,MAAM,OAAO,MAAO;EAC/C,IAAMI,IAAQ,MAAMC,EAAoBC,GAAIP,CAAe;EAC3D,EAAM,KAAK,GAAGK,CAAK;CACrB,CAAC,GACMF;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as e } from "./util-BLYliuUK.js";
|
|
2
2
|
import { n as t } from "./logger-CQONztPm.js";
|
|
3
|
-
import { i as n } from "./pocketbase-
|
|
3
|
+
import { i as n } from "./pocketbase-CgwbH1gI.js";
|
|
4
4
|
import r from "node:fs";
|
|
5
5
|
import i from "node:path";
|
|
6
6
|
//#region src/runtime/site.ts
|
|
@@ -52,4 +52,4 @@ async function l(n) {
|
|
|
52
52
|
//#endregion
|
|
53
53
|
export { l as t };
|
|
54
54
|
|
|
55
|
-
//# sourceMappingURL=site-
|
|
55
|
+
//# sourceMappingURL=site-lj0CDdQ1.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"site-
|
|
1
|
+
{"version":3,"file":"site-lj0CDdQ1.js","names":["languageFromPath","getLogger","withPocketbase","fs","path","sitePath","root","siteModule","quote","name","url","value","existingName","options","appName","pb","pkg","ensureSiteFile","file"],"sources":["../../src/runtime/site.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options } from \"../core/types\";\nimport { getLogger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { withPocketbase } from \"./pocketbase\";\n\n/** Where every VelaStack app keeps its name and public URL. */\nexport function sitePath(root: string): string {\n return path.join(root, \"src\", \"lib\", \"site.ts\");\n}\n\n/**\n * `src/lib/site.ts` as the CLI templates ship it (`site.template.ts`), with\n * the placeholders filled in.\n */\nexport function siteModule(\n name: string,\n url = \"http://localhost:5173\",\n): string {\n return [\n \"/**\",\n \" * Site-wide metadata, and the one place the app's name and public URL live.\",\n \" *\",\n \" * Set `url` to where the site is deployed: canonical links, Open Graph images\",\n \" * and feeds are built from it, including in prerendered pages. With a backend,\",\n \" * `vela dev` and `vela deploy` copy `name` into PocketBase's application name\",\n \" * for the emails it sends, so change it here rather than in the admin panel.\",\n \" */\",\n \"export const site = {\",\n `\\tname: ${quote(name)},`,\n `\\turl: ${quote(url)}`,\n \"};\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Single-quoted, as the templates write their strings. */\nfunction quote(value: string): string {\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`;\n}\n\n/**\n * The name a project created before `site.ts` existed already goes by.\n *\n * Those projects kept it in PocketBase's settings, so that is asked first; the\n * package name is the fallback for a project without a backend, or one whose\n * database can't be reached.\n */\nasync function existingName(options: Options): Promise<string> {\n if (options.features.backend) {\n try {\n let appName: unknown;\n await withPocketbase(options.root, async (pb) => {\n const settings = (await pb.settings.getAll()) as {\n meta?: { appName?: unknown };\n };\n appName = settings.meta?.appName;\n });\n if (typeof appName === \"string\" && appName.trim()) return appName;\n } catch {\n // No database to ask; fall through to package.json.\n }\n }\n\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(options.root, \"package.json\"), \"utf8\"),\n ) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name.trim()) return pkg.name;\n } catch {\n // No package.json to name the site after; the placeholder stands.\n }\n return \"My App\";\n}\n\n/**\n * Create `src/lib/site.ts` for a pattern whose files import `#lib/site.js`, when\n * the project doesn't have one yet. Every template ships it; projects created\n * before that read the app name from `locals.meta` instead.\n *\n * Returns null when the file exists, so an existing one is never overwritten.\n */\nexport async function ensureSiteFile(options: Options): Promise<File | null> {\n const file = sitePath(options.root);\n if (fs.existsSync(file)) return null;\n\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options)),\n status: \"success\",\n };\n}\n"],"mappings":";;;;;;AAQA,SAAgBK,EAAS,GAAsB;CAC7C,OAAOD,EAAK,KAAKE,GAAM,OAAO,OAAO,SAAS;AAChD;AAMA,SAAgBC,EACd,GACA,IAAM,yBACE;CACR,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,WAAWC,EAAMC,CAAI,EAAE;EACvB,UAAUD,EAAME,CAAG;EACnB;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAGA,SAASF,EAAM,GAAuB;CACpC,OAAO,IAAIG,EAAM,QAAQ,OAAO,MAAM,CAAC,CAAC,QAAQ,MAAM,KAAK,EAAE;AAC/D;AASA,eAAeC,EAAa,GAAmC;CAC7D,IAAIC,EAAQ,SAAS,SACnB,IAAI;EACF,IAAIC;EAOJ,IANA,MAAMZ,EAAeW,EAAQ,MAAM,OAAO,MAAO;GAI/C,KAAU,MAHcE,EAAG,SAAS,OAAO,EAAA,CAGxB,MAAM;EAC3B,CAAC,GACG,OAAOD,KAAY,YAAYA,EAAQ,KAAK,GAAG,OAAOA;CAC5D,QAAQ,CAER;CAGF,IAAI;EACF,IAAME,IAAM,KAAK,MACfb,EAAG,aAAaC,EAAK,KAAKS,EAAQ,MAAM,cAAc,GAAG,MAAM,CACjE;EACA,IAAI,OAAOG,EAAI,QAAS,YAAYA,EAAI,KAAK,KAAK,GAAG,OAAOA,EAAI;CAClE,QAAQ,CAER;CACA,OAAO;AACT;AASA,eAAsBC,EAAe,GAAwC;CAC3E,IAAMC,IAAOb,EAASQ,EAAQ,IAAI;CAIlC,OAHIV,EAAG,WAAWe,CAAI,IAAU,QAEhCjB,EAAUY,CAAO,CAAC,CAAC,KAAK,0BAA0B,GAC3C;EACL,MAAMK;EACN,UAAUlB,EAAiBkB,CAAI;EAC/B,SAASX,EAAW,MAAMK,EAAaC,CAAO,CAAC;EAC/C,QAAQ;CACV;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as e } from "./rolldown-runtime-DArdT4gl.js";
|
|
2
2
|
import { r as t, t as n } from "./errors-DR3gF_7a.js";
|
|
3
3
|
import { n as r } from "./lib-specifier-Cngo1zF_.js";
|
|
4
|
-
import { p as i } from "./constants-
|
|
4
|
+
import { p as i } from "./constants-Rq8SCXwH.js";
|
|
5
5
|
import { existsSync as a, readFileSync as o } from "node:fs";
|
|
6
6
|
import s from "node:path";
|
|
7
7
|
var c = 1e4;
|
|
@@ -124,4 +124,4 @@ function T(e, t) {
|
|
|
124
124
|
//#endregion
|
|
125
125
|
export { f as a, u as i, v as n, _ as r, T as t };
|
|
126
126
|
|
|
127
|
-
//# sourceMappingURL=table-core-
|
|
127
|
+
//# sourceMappingURL=table-core-DhDqT03G.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-core-AjBpYi-y.js","names":["__exportAll","RegistryUnavailableError","InvalidArgumentError","libAliasPath","TANSTACK_TABLE_CORE","path","REGISTRY_TIMEOUT_MS","optionalString","value","readComponentsConfig","raw","configPath","root","existsSync","parsed","readFileSync","aliases","key","alias","DEFAULT_UI_DIR","resolveUiDir","rel","registryIndexUrl","registry","style","indexCache","parseIndex","body","items","entry","name","type","requestIndex","response","fetchImpl","url","error","reason","fetchRegistryIndex","config","options","cache","pending","table_core_exports","TABLE_CORE_COMPONENTS","assertTableCorePackage","assertTableCoreV9","declaredTableCoreMajor","MIGRATION_GUIDE","packageJsonPath","pkg","major","hasV8DataTable","index","upgradeSteps","outdatedPackage","found","tableComponents","components","component"],"sources":["../../src/runtime/registry.ts","../../src/runtime/table-core.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { RegistryItem, WriteResultRuntime } from \"../core/types\";\nimport { RegistryUnavailableError } from \"../core/errors\";\nimport { libAliasPath } from \"./lib-specifier\";\n\n/**\n * shadcn-svelte's schema defaults. A `components.json` that names no `style`\n * resolves to `nova` (not `vega`, whatever `getRegistryUrl`'s fallback says),\n * which is why the CLI's templates write the key explicitly.\n */\nexport const DEFAULT_STYLE = \"nova\";\nexport const DEFAULT_REGISTRY = \"https://shadcn-svelte.com/registry\";\nexport const DEFAULT_CSS_PATH = \"src/app.css\";\n\nconst REGISTRY_TIMEOUT_MS = 10_000;\n\nexport interface ComponentsConfig {\n style: string;\n registry: string;\n baseColor?: string;\n iconLibrary?: string;\n menuColor?: string;\n menuAccent?: string;\n aliases: Record<string, string>;\n /** `tailwind.css`: the global stylesheet, relative to the root. */\n cssPath: string;\n}\n\ninterface RawComponentsConfig {\n style?: unknown;\n registry?: unknown;\n iconLibrary?: unknown;\n menuColor?: unknown;\n menuAccent?: unknown;\n tailwind?: { css?: unknown; baseColor?: unknown };\n aliases?: Record<string, unknown>;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * The project's `components.json` with the schema defaults filled in. A\n * missing or unreadable file behaves like an empty one, so callers can still\n * compute paths and the existence checks here agree with shadcn's own.\n */\nexport function readComponentsConfig(root: string): ComponentsConfig {\n let raw: RawComponentsConfig = {};\n const configPath = path.join(root, \"components.json\");\n if (existsSync(configPath)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(configPath, \"utf8\"));\n if (parsed && typeof parsed === \"object\") {\n raw = parsed as RawComponentsConfig;\n }\n } catch {\n raw = {};\n }\n }\n\n const aliases: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw.aliases ?? {})) {\n const alias = optionalString(value);\n if (alias) aliases[key] = alias;\n }\n\n return {\n style: optionalString(raw.style) ?? DEFAULT_STYLE,\n registry: optionalString(raw.registry) ?? DEFAULT_REGISTRY,\n baseColor: optionalString(raw.tailwind?.baseColor),\n iconLibrary: optionalString(raw.iconLibrary),\n menuColor: optionalString(raw.menuColor),\n menuAccent: optionalString(raw.menuAccent),\n aliases,\n cssPath: optionalString(raw.tailwind?.css) ?? DEFAULT_CSS_PATH,\n };\n}\n\nconst DEFAULT_UI_DIR = [\"src\", \"lib\", \"components\", \"ui\"];\n\n/**\n * Where shadcn-svelte writes items: `components.json` `aliases.ui`, resolved\n * under `src/lib` for `#lib/...`, or the alias a project from before\n * SvelteKit 3 still has.\n * Anything else (a custom alias, a missing or unreadable config) falls back\n * to the default so the existence check here and shadcn's own target agree\n * for every project the CLI creates.\n */\nexport function resolveUiDir(root: string): string {\n const alias = readComponentsConfig(root).aliases.ui;\n const rel = alias === undefined ? null : libAliasPath(alias);\n if (rel === null) {\n return path.join(root, ...DEFAULT_UI_DIR);\n }\n return path.join(root, \"src\", \"lib\", ...rel.split(\"/\").filter(Boolean));\n}\n\n/** `${registry}/styles/${style}/index.json`: the items one style offers. */\nexport function registryIndexUrl(registry: string, style: string): string {\n return `${registry.replace(/\\/+$/, \"\")}/styles/${encodeURIComponent(style)}/index.json`;\n}\n\n/**\n * One request per registry URL per process, keyed on the fetch implementation\n * so an injected test double never sees another test's answer and the real\n * `fetch` shares its answer across a style switch and the installs it runs.\n */\nconst indexCache = new WeakMap<\n typeof fetch,\n Map<string, Promise<RegistryItem[]>>\n>();\n\nfunction parseIndex(body: unknown): RegistryItem[] {\n if (!Array.isArray(body)) {\n throw new Error(\"the index is not a list\");\n }\n const items: RegistryItem[] = [];\n for (const entry of body) {\n if (!entry || typeof entry !== \"object\") continue;\n const { name, type } = entry as { name?: unknown; type?: unknown };\n if (typeof name === \"string\" && typeof type === \"string\") {\n items.push({ name, type });\n }\n }\n return items;\n}\n\nasync function requestIndex(\n url: string,\n fetchImpl: typeof fetch,\n): Promise<RegistryItem[]> {\n let response: Response;\n try {\n response = await fetchImpl(url, {\n signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),\n });\n } catch (error) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `no answer within ${REGISTRY_TIMEOUT_MS / 1000}s`\n : error instanceof Error\n ? error.message\n : String(error);\n throw new RegistryUnavailableError(url, reason);\n }\n if (!response.ok) {\n throw new RegistryUnavailableError(url, `HTTP ${response.status}`);\n }\n try {\n return parseIndex(await response.json());\n } catch (error) {\n throw new RegistryUnavailableError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\n/**\n * The items the project's registry offers for a style: the configured one by\n * default, or `options.style` to look at the style a project is about to\n * switch to. Throws `RegistryUnavailableError` when the index cannot be read.\n */\nexport async function fetchRegistryIndex(\n root: string,\n options: { style?: string; runtime?: WriteResultRuntime } = {},\n): Promise<RegistryItem[]> {\n const config = readComponentsConfig(root);\n const url = registryIndexUrl(config.registry, options.style ?? config.style);\n const fetchImpl = options.runtime?.fetch ?? globalThis.fetch;\n\n let cache = indexCache.get(fetchImpl);\n if (!cache) {\n cache = new Map();\n indexCache.set(fetchImpl, cache);\n }\n let pending = cache.get(url);\n if (!pending) {\n pending = requestIndex(url, fetchImpl).catch((error: unknown) => {\n // A failed read is not worth remembering: the next command may be online.\n cache.delete(url);\n throw error;\n });\n cache.set(url, pending);\n }\n return pending;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n TANSTACK_TABLE_CORE,\n TANSTACK_TABLE_CORE_MAJOR,\n} from \"../core/constants\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { resolveUiDir } from \"./registry\";\n\n/** The components this package ships that are built on `@tanstack/table-core`. */\nexport const TABLE_CORE_COMPONENTS = [\n \"data-table\",\n \"column-header\",\n \"faceted-filter\",\n \"pagination\",\n];\n\nconst MIGRATION_GUIDE =\n \"https://tanstack.com/table/latest/docs/framework/svelte/guide/migrating\";\n\n/**\n * The major of the `@tanstack/table-core` range `package.json` declares, when\n * it names one (`^8.21.3` is 8; `latest` or `workspace:*` is undefined).\n */\nexport function declaredTableCoreMajor(root: string): number | undefined {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) return undefined;\n const pkg = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const range =\n pkg.dependencies?.[\"@tanstack/table-core\"] ??\n pkg.devDependencies?.[\"@tanstack/table-core\"];\n const major = range?.match(/^[\\^~>=v\\s]*(\\d+)/)?.[1];\n return major === undefined ? undefined : Number(major);\n}\n\n/** Whether the project's `data-table` helper is the v8 one (`createSvelteTable`). */\nfunction hasV8DataTable(root: string): boolean {\n const index = path.join(resolveUiDir(root), \"data-table\", \"index.ts\");\n return (\n existsSync(index) &&\n readFileSync(index, \"utf8\").includes(\"createSvelteTable\")\n );\n}\n\nfunction upgradeSteps(): string {\n return (\n \"Nothing was changed. To upgrade:\\n\" +\n ` 1. Install ${TANSTACK_TABLE_CORE}: npm install ${TANSTACK_TABLE_CORE}\\n` +\n ` 2. Replace the table helpers: vela ui add ${TABLE_CORE_COMPONENTS.join(\" \")} --overwrite\\n` +\n ` 3. Move existing list pages to the v9 API (createTable, tableFeatures): ${MIGRATION_GUIDE}\\n` +\n \"Then run this again.\"\n );\n}\n\n/**\n * Refuses a project still on TanStack Table v8, before anything is written.\n *\n * The scaffold list pages and the table helpers target v9. A project set up\n * before that has `@tanstack/table-core@^8` and v8 helpers; the package is\n * never upgraded by `installPackages` (it is already present) and the helpers\n * are never replaced (they already exist), so a new page would not compile,\n * and upgrading in place would break the list pages already there.\n */\nexport function assertTableCoreV9(root: string): void {\n const major = declaredTableCoreMajor(root);\n const outdatedPackage =\n major !== undefined && major < TANSTACK_TABLE_CORE_MAJOR;\n if (!outdatedPackage && !hasV8DataTable(root)) return;\n\n const found = outdatedPackage\n ? `package.json pins @tanstack/table-core ${major}.x`\n : \"its data-table helper is the v8 one (createSvelteTable)\";\n throw new InvalidArgumentError(\n `This project uses TanStack Table v8 (${found}), and scaffold list pages now need v${TANSTACK_TABLE_CORE_MAJOR}.\\n\\n` +\n upgradeSteps(),\n );\n}\n\n/**\n * Refuses to add v9 table helpers next to a v8 `@tanstack/table-core`, which\n * `installPackages` would leave in place.\n */\nexport function assertTableCorePackage(\n root: string,\n components: string[],\n): void {\n const tableComponents = components.filter((component) =>\n TABLE_CORE_COMPONENTS.includes(component),\n );\n if (tableComponents.length === 0) return;\n const major = declaredTableCoreMajor(root);\n if (major === undefined || major >= TANSTACK_TABLE_CORE_MAJOR) return;\n\n throw new InvalidArgumentError(\n `${tableComponents.join(\", \")} target${tableComponents.length === 1 ? \"s\" : \"\"} TanStack Table v${TANSTACK_TABLE_CORE_MAJOR}, and package.json pins @tanstack/table-core ${major}.x.\\n\\n` +\n `Nothing was changed. Install ${TANSTACK_TABLE_CORE} first (npm install ${TANSTACK_TABLE_CORE}), then run this again.`,\n );\n}\n"],"mappings":";;;;;;AAeA,IAAMM,IAAsB;AAwB5B,SAASC,EAAe,GAAoC;CAC1D,OAAO,OAAOC,KAAU,YAAYA,EAAM,SAAS,IAAIA,IAAQ,KAAA;AACjE;AAOA,SAAgBC,EAAqB,GAAgC;CACnE,IAAIC,IAA2B,CAAC,GAC1BC,IAAaN,EAAK,KAAKO,GAAM,iBAAiB;CACpD,IAAIC,EAAWF,CAAU,GACvB,IAAI;EACF,IAAMG,IAAkB,KAAK,MAAMC,EAAaJ,GAAY,MAAM,CAAC;EACnE,AAAIG,KAAU,OAAOA,KAAW,aAC9B,IAAMA;CAEV,QAAQ;EACN,IAAM,CAAC;CACT;CAGF,IAAME,IAAkC,CAAC;CACzC,KAAK,IAAM,CAACC,GAAKT,MAAU,OAAO,QAAQE,EAAI,WAAW,CAAC,CAAC,GAAG;EAC5D,IAAMQ,IAAQX,EAAeC,CAAK;EAClC,AAAIU,MAAO,EAAQD,KAAOC;CAC5B;CAEA,OAAO;EACL,OAAOX,EAAeG,EAAI,KAAK,KAAA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GAAG;CAClD,OAAOC,MAAU,KAAA,IAAY,KAAA,IAAY,OAAOA,CAAK;AACvD;AAGA,SAASC,EAAe,GAAuB;CAC7C,IAAMC,IAAQhD,EAAK,KAAKe,EAAaR,CAAI,GAAG,cAAc,UAAU;CACpE,OACEC,EAAWwC,CAAK,KAChBtC,EAAasC,GAAO,MAAM,CAAC,CAAC,SAAS,mBAAmB;AAE5D;AAEA,SAASC,IAAuB;CAC9B,OACE;eACgBlD,EAAoB,iBAAiBA,EAAoB,uDACnBwC,EAAsB,KAAK,GAAG,EAAE,0FACTI,EAAgB;AAGjG;AAWA,SAAgBF,EAAkB,GAAoB;CACpD,IAAMK,IAAQJ,EAAuBnC,CAAI,GACnC2C,IACJJ,MAAU,KAAA,KAAaA,IAAA;CACzB,IAAI,CAACI,KAAmB,CAACH,EAAexC,CAAI,GAAG;CAE/C,IAAM4C,IAAQD,IACV,0CAA0CJ,EAAM,MAChD;CACJ,MAAM,IAAIjD,EACR,wCAAwCsD,EAAM,+CAC5CF,EAAa,CACjB;AACF;AAMA,SAAgBT,EACd,GACA,GACM;CACN,IAAMY,IAAkBC,EAAW,QAAQ,MACzCd,EAAsB,SAASe,CAAS,CAC1C;CACA,IAAIF,EAAgB,WAAW,GAAG;CAClC,IAAMN,IAAQJ,EAAuBnC,CAAI;CACzC,IAAI,QAAU,KAAA,KAAauC,KAAA,IAE3B,MAAM,IAAIjD,EACR,GAAGuD,EAAgB,KAAK,IAAI,EAAE,SAASA,EAAgB,WAAW,IAAI,MAAM,GAAG,iEAA4FN,EAAM,sCAC/I/C,EAAoB,sBAAsBA,EAAoB,wBAClG;AACF"}
|
|
1
|
+
{"version":3,"file":"table-core-DhDqT03G.js","names":["__exportAll","RegistryUnavailableError","InvalidArgumentError","libAliasPath","TANSTACK_TABLE_CORE","path","REGISTRY_TIMEOUT_MS","optionalString","value","readComponentsConfig","raw","configPath","root","existsSync","parsed","readFileSync","aliases","key","alias","DEFAULT_UI_DIR","resolveUiDir","rel","registryIndexUrl","registry","style","indexCache","parseIndex","body","items","entry","name","type","requestIndex","response","fetchImpl","url","error","reason","fetchRegistryIndex","config","options","cache","pending","table_core_exports","TABLE_CORE_COMPONENTS","assertTableCorePackage","assertTableCoreV9","declaredTableCoreMajor","MIGRATION_GUIDE","packageJsonPath","pkg","major","hasV8DataTable","index","upgradeSteps","outdatedPackage","found","tableComponents","components","component"],"sources":["../../src/runtime/registry.ts","../../src/runtime/table-core.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { RegistryItem, WriteResultRuntime } from \"../core/types\";\nimport { RegistryUnavailableError } from \"../core/errors\";\nimport { libAliasPath } from \"./lib-specifier\";\n\n/**\n * shadcn-svelte's schema defaults. A `components.json` that names no `style`\n * resolves to `nova` (not `vega`, whatever `getRegistryUrl`'s fallback says),\n * which is why the CLI's templates write the key explicitly.\n */\nexport const DEFAULT_STYLE = \"nova\";\nexport const DEFAULT_REGISTRY = \"https://shadcn-svelte.com/registry\";\nexport const DEFAULT_CSS_PATH = \"src/app.css\";\n\nconst REGISTRY_TIMEOUT_MS = 10_000;\n\nexport interface ComponentsConfig {\n style: string;\n registry: string;\n baseColor?: string;\n iconLibrary?: string;\n menuColor?: string;\n menuAccent?: string;\n aliases: Record<string, string>;\n /** `tailwind.css`: the global stylesheet, relative to the root. */\n cssPath: string;\n}\n\ninterface RawComponentsConfig {\n style?: unknown;\n registry?: unknown;\n iconLibrary?: unknown;\n menuColor?: unknown;\n menuAccent?: unknown;\n tailwind?: { css?: unknown; baseColor?: unknown };\n aliases?: Record<string, unknown>;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * The project's `components.json` with the schema defaults filled in. A\n * missing or unreadable file behaves like an empty one, so callers can still\n * compute paths and the existence checks here agree with shadcn's own.\n */\nexport function readComponentsConfig(root: string): ComponentsConfig {\n let raw: RawComponentsConfig = {};\n const configPath = path.join(root, \"components.json\");\n if (existsSync(configPath)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(configPath, \"utf8\"));\n if (parsed && typeof parsed === \"object\") {\n raw = parsed as RawComponentsConfig;\n }\n } catch {\n raw = {};\n }\n }\n\n const aliases: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw.aliases ?? {})) {\n const alias = optionalString(value);\n if (alias) aliases[key] = alias;\n }\n\n return {\n style: optionalString(raw.style) ?? DEFAULT_STYLE,\n registry: optionalString(raw.registry) ?? DEFAULT_REGISTRY,\n baseColor: optionalString(raw.tailwind?.baseColor),\n iconLibrary: optionalString(raw.iconLibrary),\n menuColor: optionalString(raw.menuColor),\n menuAccent: optionalString(raw.menuAccent),\n aliases,\n cssPath: optionalString(raw.tailwind?.css) ?? DEFAULT_CSS_PATH,\n };\n}\n\nconst DEFAULT_UI_DIR = [\"src\", \"lib\", \"components\", \"ui\"];\n\n/**\n * Where shadcn-svelte writes items: `components.json` `aliases.ui`, resolved\n * under `src/lib` for `#lib/...`, or the alias a project from before\n * SvelteKit 3 still has.\n * Anything else (a custom alias, a missing or unreadable config) falls back\n * to the default so the existence check here and shadcn's own target agree\n * for every project the CLI creates.\n */\nexport function resolveUiDir(root: string): string {\n const alias = readComponentsConfig(root).aliases.ui;\n const rel = alias === undefined ? null : libAliasPath(alias);\n if (rel === null) {\n return path.join(root, ...DEFAULT_UI_DIR);\n }\n return path.join(root, \"src\", \"lib\", ...rel.split(\"/\").filter(Boolean));\n}\n\n/** `${registry}/styles/${style}/index.json`: the items one style offers. */\nexport function registryIndexUrl(registry: string, style: string): string {\n return `${registry.replace(/\\/+$/, \"\")}/styles/${encodeURIComponent(style)}/index.json`;\n}\n\n/**\n * One request per registry URL per process, keyed on the fetch implementation\n * so an injected test double never sees another test's answer and the real\n * `fetch` shares its answer across a style switch and the installs it runs.\n */\nconst indexCache = new WeakMap<\n typeof fetch,\n Map<string, Promise<RegistryItem[]>>\n>();\n\nfunction parseIndex(body: unknown): RegistryItem[] {\n if (!Array.isArray(body)) {\n throw new Error(\"the index is not a list\");\n }\n const items: RegistryItem[] = [];\n for (const entry of body) {\n if (!entry || typeof entry !== \"object\") continue;\n const { name, type } = entry as { name?: unknown; type?: unknown };\n if (typeof name === \"string\" && typeof type === \"string\") {\n items.push({ name, type });\n }\n }\n return items;\n}\n\nasync function requestIndex(\n url: string,\n fetchImpl: typeof fetch,\n): Promise<RegistryItem[]> {\n let response: Response;\n try {\n response = await fetchImpl(url, {\n signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),\n });\n } catch (error) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `no answer within ${REGISTRY_TIMEOUT_MS / 1000}s`\n : error instanceof Error\n ? error.message\n : String(error);\n throw new RegistryUnavailableError(url, reason);\n }\n if (!response.ok) {\n throw new RegistryUnavailableError(url, `HTTP ${response.status}`);\n }\n try {\n return parseIndex(await response.json());\n } catch (error) {\n throw new RegistryUnavailableError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\n/**\n * The items the project's registry offers for a style: the configured one by\n * default, or `options.style` to look at the style a project is about to\n * switch to. Throws `RegistryUnavailableError` when the index cannot be read.\n */\nexport async function fetchRegistryIndex(\n root: string,\n options: { style?: string; runtime?: WriteResultRuntime } = {},\n): Promise<RegistryItem[]> {\n const config = readComponentsConfig(root);\n const url = registryIndexUrl(config.registry, options.style ?? config.style);\n const fetchImpl = options.runtime?.fetch ?? globalThis.fetch;\n\n let cache = indexCache.get(fetchImpl);\n if (!cache) {\n cache = new Map();\n indexCache.set(fetchImpl, cache);\n }\n let pending = cache.get(url);\n if (!pending) {\n pending = requestIndex(url, fetchImpl).catch((error: unknown) => {\n // A failed read is not worth remembering: the next command may be online.\n cache.delete(url);\n throw error;\n });\n cache.set(url, pending);\n }\n return pending;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n TANSTACK_TABLE_CORE,\n TANSTACK_TABLE_CORE_MAJOR,\n} from \"../core/constants\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { resolveUiDir } from \"./registry\";\n\n/** The components this package ships that are built on `@tanstack/table-core`. */\nexport const TABLE_CORE_COMPONENTS = [\n \"data-table\",\n \"column-header\",\n \"faceted-filter\",\n \"pagination\",\n];\n\nconst MIGRATION_GUIDE =\n \"https://tanstack.com/table/latest/docs/framework/svelte/guide/migrating\";\n\n/**\n * The major of the `@tanstack/table-core` range `package.json` declares, when\n * it names one (`^8.21.3` is 8; `latest` or `workspace:*` is undefined).\n */\nexport function declaredTableCoreMajor(root: string): number | undefined {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) return undefined;\n const pkg = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const range =\n pkg.dependencies?.[\"@tanstack/table-core\"] ??\n pkg.devDependencies?.[\"@tanstack/table-core\"];\n const major = range?.match(/^[\\^~>=v\\s]*(\\d+)/)?.[1];\n return major === undefined ? undefined : Number(major);\n}\n\n/** Whether the project's `data-table` helper is the v8 one (`createSvelteTable`). */\nfunction hasV8DataTable(root: string): boolean {\n const index = path.join(resolveUiDir(root), \"data-table\", \"index.ts\");\n return (\n existsSync(index) &&\n readFileSync(index, \"utf8\").includes(\"createSvelteTable\")\n );\n}\n\nfunction upgradeSteps(): string {\n return (\n \"Nothing was changed. To upgrade:\\n\" +\n ` 1. Install ${TANSTACK_TABLE_CORE}: npm install ${TANSTACK_TABLE_CORE}\\n` +\n ` 2. Replace the table helpers: vela ui add ${TABLE_CORE_COMPONENTS.join(\" \")} --overwrite\\n` +\n ` 3. Move existing list pages to the v9 API (createTable, tableFeatures): ${MIGRATION_GUIDE}\\n` +\n \"Then run this again.\"\n );\n}\n\n/**\n * Refuses a project still on TanStack Table v8, before anything is written.\n *\n * The scaffold list pages and the table helpers target v9. A project set up\n * before that has `@tanstack/table-core@^8` and v8 helpers; the package is\n * never upgraded by `installPackages` (it is already present) and the helpers\n * are never replaced (they already exist), so a new page would not compile,\n * and upgrading in place would break the list pages already there.\n */\nexport function assertTableCoreV9(root: string): void {\n const major = declaredTableCoreMajor(root);\n const outdatedPackage =\n major !== undefined && major < TANSTACK_TABLE_CORE_MAJOR;\n if (!outdatedPackage && !hasV8DataTable(root)) return;\n\n const found = outdatedPackage\n ? `package.json pins @tanstack/table-core ${major}.x`\n : \"its data-table helper is the v8 one (createSvelteTable)\";\n throw new InvalidArgumentError(\n `This project uses TanStack Table v8 (${found}), and scaffold list pages now need v${TANSTACK_TABLE_CORE_MAJOR}.\\n\\n` +\n upgradeSteps(),\n );\n}\n\n/**\n * Refuses to add v9 table helpers next to a v8 `@tanstack/table-core`, which\n * `installPackages` would leave in place.\n */\nexport function assertTableCorePackage(\n root: string,\n components: string[],\n): void {\n const tableComponents = components.filter((component) =>\n TABLE_CORE_COMPONENTS.includes(component),\n );\n if (tableComponents.length === 0) return;\n const major = declaredTableCoreMajor(root);\n if (major === undefined || major >= TANSTACK_TABLE_CORE_MAJOR) return;\n\n throw new InvalidArgumentError(\n `${tableComponents.join(\", \")} target${tableComponents.length === 1 ? \"s\" : \"\"} TanStack Table v${TANSTACK_TABLE_CORE_MAJOR}, and package.json pins @tanstack/table-core ${major}.x.\\n\\n` +\n `Nothing was changed. Install ${TANSTACK_TABLE_CORE} first (npm install ${TANSTACK_TABLE_CORE}), then run this again.`,\n );\n}\n"],"mappings":";;;;;;AAeA,IAAMM,IAAsB;AAwB5B,SAASC,EAAe,GAAoC;CAC1D,OAAO,OAAOC,KAAU,YAAYA,EAAM,SAAS,IAAIA,IAAQ,KAAA;AACjE;AAOA,SAAgBC,EAAqB,GAAgC;CACnE,IAAIC,IAA2B,CAAC,GAC1BC,IAAaN,EAAK,KAAKO,GAAM,iBAAiB;CACpD,IAAIC,EAAWF,CAAU,GACvB,IAAI;EACF,IAAMG,IAAkB,KAAK,MAAMC,EAAaJ,GAAY,MAAM,CAAC;EACnE,AAAIG,KAAU,OAAOA,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iEAA4FN,EAAM,sCAC/I/C,EAAoB,sBAAsBA,EAAoB,wBAClG;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as e, t } from "./constants-
|
|
1
|
+
import { n as e, t } from "./constants-Rq8SCXwH.js";
|
|
2
2
|
import { t as n } from "./dedent-Gq6Krl4n.js";
|
|
3
|
-
import { o as r, s as i } from "./config-target-
|
|
4
|
-
import { c as a } from "./write-result-
|
|
3
|
+
import { o as r, s as i } from "./config-target-rHgjaA8u.js";
|
|
4
|
+
import { c as a } from "./write-result-DiZsCS_y.js";
|
|
5
5
|
import o from "node:fs";
|
|
6
6
|
import s from "node:path";
|
|
7
7
|
import { SyntaxKind as c } from "ts-morph";
|
|
@@ -138,7 +138,7 @@ function x(e) {
|
|
|
138
138
|
}
|
|
139
139
|
//#endregion
|
|
140
140
|
//#region src/patterns/enable/backend/modifies/test-setup.ts
|
|
141
|
-
var S = "import { beforeEach, afterEach, beforeAll } from 'vitest';\nimport supertest, { type Agent } from 'supertest';\nimport PocketBase from 'pocketbase-sveltekit';\nimport type { TestContext } from '@velastack/pocketbase/testing';\n\nconst admin = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['admin'];\nconst pb = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['pb'];\n\nconst testUserPassword = 'password';\n\nasync function authenticateUser(agent: Agent, user: { email
|
|
141
|
+
var S = "import { beforeEach, afterEach, beforeAll } from 'vitest';\nimport supertest, { type Agent } from 'supertest';\nimport PocketBase from 'pocketbase-sveltekit';\nimport type { TestContext } from '@velastack/pocketbase/testing';\n\nconst admin = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['admin'];\nconst pb = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['pb'];\n\nconst testUserPassword = 'password';\n\nasync function authenticateUser(agent: Agent, user: { email?: string }) {\n // Logs in with the password, so it needs the email (made optional by\n // enable-whatsapp, for accounts that sign in with a phone number).\n if (!user.email) {\n throw new Error('authenticateUser needs a user with an email');\n }\n await agent.post('/login').type('form').send({\n type: 'password',\n email: user.email,\n password: testUserPassword\n });\n}\n\nbeforeAll(async () => {\n await admin\n // @ts-ignore\n .collection('_superusers')\n .authWithPassword(\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!\n );\n});\n\nbeforeEach(async (context: TestContext) => {\n context.request = supertest(process.env.VITE_TEST_URL!);\n context.agent = supertest.agent(process.env.VITE_TEST_URL!) as TestContext['agent'];\n context.admin = admin;\n context.pb = pb;\n const email = `test-${Math.random().toString(36).slice(2)}@example.com`;\n context.user = await context.admin.collection('users').create({\n email,\n password: testUserPassword,\n passwordConfirm: testUserPassword\n });\n context.agent.authenticateUser = () => authenticateUser(context.agent, context.user);\n await context.pb.collection('users').authWithPassword(email, testUserPassword);\n});\n\nafterEach(async (context: TestContext) => {\n await context.pb.authStore.clear();\n await context.admin.collection('users').delete(context.user.id);\n});\n", C = "import { beforeEach } from 'vitest';\nimport supertest from 'supertest';\n\nbeforeEach(async (context: any) => {\n context.request = supertest(process.env.VITE_TEST_URL!);\n context.agent = supertest.agent(process.env.VITE_TEST_URL!);\n});\n", w = "import { defineConfig, mergeConfig } from 'vitest/config';\nimport viteConfig from './vite.config';\n\nexport default mergeConfig(\n viteConfig,\n defineConfig({\n test: {\n expect: {\n requireAssertions: true\n },\n name: 'server',\n environment: 'node',\n include: ['src/**/*.{test,spec}.{js,ts}'],\n exclude: ['src/**/*.svelte.{test,spec}.{js,ts}'],\n setupFiles: ['test/setup.ts']\n }\n })\n);\n", T = [
|
|
142
142
|
"ts",
|
|
143
143
|
"mts",
|
|
144
144
|
"js",
|
|
@@ -176,4 +176,4 @@ function O(e) {
|
|
|
176
176
|
//#endregion
|
|
177
177
|
export { O as a, g as c, D as i, _ as l, S as n, b as o, E as r, x as s, w as t };
|
|
178
178
|
|
|
179
|
-
//# sourceMappingURL=test-setup-
|
|
179
|
+
//# sourceMappingURL=test-setup-B9fQ5L_-.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-setup-DEmWd9Ul.js","names":["ADAPTER_NODE_SPEC","ADAPTER_STATIC_SPEC","NOT_FOUND_HINT","ADAPTER_STATIC$1","dedent","resolveConfigTarget","saveTarget","packageName","fs","path","ADAPTER_NODE","ADAPTER_NODE$1","ADAPTER_STATIC","ADAPTER_AUTO","FAILURE_HINT","NOT_FOUND_HINT$1","findAdapterImport","sourceFile","decl","adapterCalls","SyntaxKind","ce","modifySvelteConfig","res","root","adapterImport","target","call","args","i","unmodifySvelteConfig","POCKETBASE_BLOCK","NOT_FOUND_HINT","modifyGitignore","gitignorePath","original","next","unmodifyGitignore","cleaned","WITH_BACKEND","WITHOUT_BACKEND","VITEST_CONFIG","VITEST_CONFIG_NAMES","ext","hasVitestConfig","name","viteConfig","modifyTestSetup","testSetupPath","unmodifyTestSetup"],"sources":["../../src/patterns/enable/backend/modifies/svelte-config.ts","../../src/patterns/enable/backend/modifies/gitignore.ts","../../src/patterns/enable/backend/modifies/test-setup.ts"],"sourcesContent":["import dedent from \"dedent\";\nimport { SyntaxKind } from \"ts-morph\";\nimport {\n resolveConfigTarget,\n saveTarget,\n type ConfigModifyResult,\n type ConfigTarget,\n} from \"../../../../runtime/config-target\";\nimport { packageName } from \"../../../../runtime/write-result\";\nimport {\n ADAPTER_NODE as ADAPTER_NODE_SPEC,\n ADAPTER_STATIC as ADAPTER_STATIC_SPEC,\n} from \"../../../../core/constants\";\n\n// Imports name the package, not the versioned spec the constants install.\nconst ADAPTER_NODE = packageName(ADAPTER_NODE_SPEC);\nconst ADAPTER_STATIC = packageName(ADAPTER_STATIC_SPEC);\nconst ADAPTER_AUTO = \"@sveltejs/adapter-auto\";\n\nconst FAILURE_HINT = dedent`\n Switch the SvelteKit adapter to ${ADAPTER_NODE}:\n\n import adapter from '${ADAPTER_NODE}';\n\n // ...\n adapter: adapter()\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Configure ${ADAPTER_NODE} via the sveltekit() plugin in vite.config.ts.\n`;\n\n/**\n * The adapters this pattern moves between. adapter-auto is included because\n * that is what `sv create` ships, and a project that never chose is one the\n * backend is free to decide for.\n */\nfunction findAdapterImport(sourceFile: ConfigTarget[\"sourceFile\"]) {\n return sourceFile\n .getImportDeclarations()\n .find((decl) =>\n [ADAPTER_STATIC, ADAPTER_AUTO, ADAPTER_NODE].includes(\n decl.getModuleSpecifierValue(),\n ),\n );\n}\n\nfunction adapterCalls(sourceFile: ConfigTarget[\"sourceFile\"]) {\n return sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((ce) => ce.getExpression().getText() === \"adapter\");\n}\n\n/**\n * Switch the adapter to `@sveltejs/adapter-node` and drop its arguments in\n * vite.config, which holds the adapter import + `adapter()` call. A project with a\n * backend is served from a Node process, which is what `vela deploy` runs.\n * Operates on the import and call expression directly, so it never needs the\n * config object.\n */\nexport function modifySvelteConfig(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, {\n notFound: NOT_FOUND_HINT,\n failed: FAILURE_HINT,\n });\n if (res.status !== \"resolved\") {\n return {\n filePath: res.filePath,\n outcome: { status: res.status, message: res.message },\n };\n }\n const { target } = res;\n const adapterImport = findAdapterImport(target.sourceFile);\n if (!adapterImport) {\n return {\n filePath: target.filePath,\n outcome: { status: \"failed\", message: FAILURE_HINT },\n };\n }\n\n if (adapterImport.getModuleSpecifierValue() !== ADAPTER_NODE) {\n adapterImport.setModuleSpecifier(ADAPTER_NODE);\n }\n\n for (const call of adapterCalls(target.sourceFile)) {\n const args = call.getArguments();\n for (let i = args.length - 1; i >= 0; i--) {\n call.removeArgument(i);\n }\n }\n\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n\n/**\n * Reverse of {@link modifySvelteConfig}: switch back to\n * `@sveltejs/adapter-static` and restore the `{ fallback: '200.html' }` arg.\n * Lenient when there is no config or no adapter import: a no-op success. A\n * config that can't be edited (a leftover svelte.config) still fails.\n */\nexport function unmodifySvelteConfig(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, {\n notFound: NOT_FOUND_HINT,\n failed: FAILURE_HINT,\n });\n if (res.status === \"not-found\") {\n // Nothing to revert.\n return {\n filePath: res.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n if (res.status === \"failed\") {\n return {\n filePath: res.filePath,\n outcome: { status: \"failed\", message: res.message },\n };\n }\n const { target } = res;\n const adapterImport = findAdapterImport(target.sourceFile);\n if (!adapterImport) {\n return {\n filePath: target.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n\n if (adapterImport.getModuleSpecifierValue() !== ADAPTER_STATIC) {\n adapterImport.setModuleSpecifier(ADAPTER_STATIC);\n }\n\n for (const call of adapterCalls(target.sourceFile)) {\n if (call.getArguments().length === 0) {\n call.addArgument(\"{ fallback: '200.html' }\");\n }\n }\n\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst POCKETBASE_BLOCK = `# PocketBase\n/data/*\n!/data/fixtures\n!/data/seeds\n!/data/hooks\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create a .gitignore at the project root with the PocketBase block:\n\n # PocketBase\n /data/*\n !/data/fixtures\n !/data/seeds\n !/data/hooks\n`;\n\nexport function modifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n\n if (original.includes(\"# PocketBase\") && original.includes(\"/data/*\")) {\n return { status: \"success\", changed: false };\n }\n\n const separator = original.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const next = original + separator + POCKETBASE_BLOCK;\n fs.writeFileSync(gitignorePath, next, \"utf8\");\n\n return { status: \"success\", changed: true };\n}\n\nexport function unmodifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n\n if (!original.includes(\"# PocketBase\")) {\n return { status: \"success\", changed: false };\n }\n\n const withBlockRemoved = original.replace(\n /\\n*# PocketBase\\n\\/data\\/\\*\\n!\\/data\\/fixtures\\n!\\/data\\/seeds\\n!\\/data\\/hooks\\n?/,\n \"\\n\",\n );\n\n const cleaned = withBlockRemoved.replace(/\\n{3,}$/, \"\\n\");\n\n if (cleaned === original) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(gitignorePath, cleaned, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n// Source of truth: velastack-cli/templates/minimal/test/setup.ts\nexport const WITH_BACKEND = `import { beforeEach, afterEach, beforeAll } from 'vitest';\nimport supertest, { type Agent } from 'supertest';\nimport PocketBase from 'pocketbase-sveltekit';\nimport type { TestContext } from '@velastack/pocketbase/testing';\n\nconst admin = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['admin'];\nconst pb = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['pb'];\n\nconst testUserPassword = 'password';\n\nasync function authenticateUser(agent: Agent, user: { email: string }) {\n\\tawait agent.post('/login').type('form').send({\n\\t\\ttype: 'password',\n\\t\\temail: user.email,\n\\t\\tpassword: testUserPassword\n\\t});\n}\n\nbeforeAll(async () => {\n\\tawait admin\n\\t\\t// @ts-ignore\n\\t\\t.collection('_superusers')\n\\t\\t.authWithPassword(\n\\t\\t\\tprocess.env.POCKETBASE_SUPERUSER_EMAIL!,\n\\t\\t\\tprocess.env.POCKETBASE_SUPERUSER_PASSWORD!\n\\t\\t);\n});\n\nbeforeEach(async (context: TestContext) => {\n\\tcontext.request = supertest(process.env.VITE_TEST_URL!);\n\\tcontext.agent = supertest.agent(process.env.VITE_TEST_URL!) as TestContext['agent'];\n\\tcontext.admin = admin;\n\\tcontext.pb = pb;\n\\tcontext.user = await context.admin.collection('users').create({\n\\t\\temail: \\`test-\\${Math.random().toString(36).slice(2)}@example.com\\`,\n\\t\\tpassword: testUserPassword,\n\\t\\tpasswordConfirm: testUserPassword\n\\t});\n\\tcontext.agent.authenticateUser = () => authenticateUser(context.agent, context.user);\n\\tawait context.pb.collection('users').authWithPassword(context.user.email, testUserPassword);\n});\n\nafterEach(async (context: TestContext) => {\n\\tawait context.pb.authStore.clear();\n\\tawait context.admin.collection('users').delete(context.user.id);\n});\n`;\n\n// The static template ships no test setup at all; this is the backend-free\n// subset of the minimal one, kept so existing tests keep their agents.\nconst WITHOUT_BACKEND = `import { beforeEach } from 'vitest';\nimport supertest from 'supertest';\n\nbeforeEach(async (context: any) => {\n\\tcontext.request = supertest(process.env.VITE_TEST_URL!);\n\\tcontext.agent = supertest.agent(process.env.VITE_TEST_URL!);\n});\n`;\n\n// Source of truth: velastack-cli/templates/minimal/vitest.config.ts\nexport const VITEST_CONFIG = `import { defineConfig, mergeConfig } from 'vitest/config';\nimport viteConfig from './vite.config';\n\nexport default mergeConfig(\n\\tviteConfig,\n\\tdefineConfig({\n\\t\\ttest: {\n\\t\\t\\texpect: {\n\\t\\t\\t\\trequireAssertions: true\n\\t\\t\\t},\n\\t\\t\\tname: 'server',\n\\t\\t\\tenvironment: 'node',\n\\t\\t\\tinclude: ['src/**/*.{test,spec}.{js,ts}'],\n\\t\\t\\texclude: ['src/**/*.svelte.{test,spec}.{js,ts}'],\n\\t\\t\\tsetupFiles: ['test/setup.ts']\n\\t\\t}\n\\t})\n);\n`;\n\nconst VITEST_CONFIG_NAMES = [\"ts\", \"mts\", \"js\", \"mjs\"].flatMap((ext) => [\n `vitest.config.${ext}`,\n `vitest.workspace.${ext}`,\n]);\n\n/**\n * Whether the project already configures vitest, in a file of its own or a\n * `test` block in its vite config. Without either, `test/setup.ts` is never\n * loaded and every generated `server.test.ts` fails on its missing context.\n */\nexport function hasVitestConfig(root: string): boolean {\n if (\n VITEST_CONFIG_NAMES.some((name) => fs.existsSync(path.join(root, name)))\n ) {\n return true;\n }\n return [\"ts\", \"mts\", \"js\", \"mjs\"].some((ext) => {\n const viteConfig = path.join(root, `vite.config.${ext}`);\n return (\n fs.existsSync(viteConfig) &&\n /\\btest\\s*:/.test(fs.readFileSync(viteConfig, \"utf8\"))\n );\n });\n}\n\n/**\n * Brings an existing `test/setup.ts` up to the backend one. A project without\n * the file gets it as a create instead (see `generate.runtime.ts`), so it is\n * reported as created rather than modified.\n */\nexport function modifyTestSetup(testSetupPath: string): ModifyOutcome {\n if (!fs.existsSync(testSetupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(testSetupPath, \"utf8\");\n if (original === WITH_BACKEND) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(testSetupPath, WITH_BACKEND, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\nexport function unmodifyTestSetup(testSetupPath: string): ModifyOutcome {\n if (!fs.existsSync(testSetupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(testSetupPath, \"utf8\");\n if (original === WITHOUT_BACKEND) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(testSetupPath, WITHOUT_BACKEND, \"utf8\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;;;;;;;AAeA,IAAMU,IAAeH,EAAYP,CAAiB,GAC5CY,IAAiBL,EAAYN,CAAmB,GAChDY,IAAe,0BAEfC,IAAe,CAAM;oCACSJ,EAAa;;yBAExBA,EAAa;;;;GAMhCR,IAAiB,CAAM;cACfQ,EAAa;;AAQ3B,SAASM,EAAkB,GAAwC;CACjE,OAAOC,EACJ,sBAAsB,CAAC,CACvB,MAAM,MACL;EAACL;EAAgBC;EAAcH;CAAY,CAAC,CAAC,SAC3CQ,EAAK,wBAAwB,CAC/B,CACF;AACJ;AAEA,SAASC,EAAa,GAAwC;CAC5D,OAAOF,EACJ,qBAAqBG,EAAW,cAAc,CAAC,CAC/C,QAAQ,MAAOC,EA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UXC,IAAgB,saAoBvBC,IAAsB;CAAC;CAAM;CAAO;CAAM;AAAK,CAAC,CAAC,SAAS,MAAQ,CACtE,iBAAiBC,KACjB,oBAAoBA,GACtB,CAAC;AAOD,SAAgBC,EAAgB,GAAuB;CAMrD,OAJEF,EAAoB,MAAM,MAASlC,EAAG,WAAWC,EAAK,KAAKe,GAAMqB,CAAI,CAAC,CAAC,IAEhE,KAEF;EAAC;EAAM;EAAO;EAAM;CAAK,CAAC,CAAC,MAAM,MAAQ;EAC9C,IAAMC,IAAarC,EAAK,KAAKe,GAAM,eAAemB,GAAK;EACvD,OACEnC,EAAG,WAAWsC,CAAU,KACxB,aAAa,KAAKtC,EAAG,aAAasC,GAAY,MAAM,CAAC;CAEzD,CAAC;AACH;AAOA,SAAgBC,EAAgB,GAAsC;CAWpE,OAVI,CAACvC,EAAG,WAAWwC,CAAa,KAIfxC,EAAG,aAAawC,GAAe,MAC5C,MAAaT,IACR;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7C/B,EAAG,cAAcwC,GAAeT,GAAc,MAAM,GAC7C;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;AAEA,SAAgBU,EAAkB,GAAsC;CAWtE,OAVI,CAACzC,EAAG,WAAWwC,CAAa,KAIfxC,EAAG,aAAawC,GAAe,MAC5C,MAAaR,IACR;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7ChC,EAAG,cAAcwC,GAAeR,GAAiB,MAAM,GAChD;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
|
|
1
|
+
{"version":3,"file":"test-setup-B9fQ5L_-.js","names":["ADAPTER_NODE_SPEC","ADAPTER_STATIC_SPEC","NOT_FOUND_HINT","ADAPTER_STATIC$1","dedent","resolveConfigTarget","saveTarget","packageName","fs","path","ADAPTER_NODE","ADAPTER_NODE$1","ADAPTER_STATIC","ADAPTER_AUTO","FAILURE_HINT","NOT_FOUND_HINT$1","findAdapterImport","sourceFile","decl","adapterCalls","SyntaxKind","ce","modifySvelteConfig","res","root","adapterImport","target","call","args","i","unmodifySvelteConfig","POCKETBASE_BLOCK","NOT_FOUND_HINT","modifyGitignore","gitignorePath","original","next","unmodifyGitignore","cleaned","WITH_BACKEND","WITHOUT_BACKEND","VITEST_CONFIG","VITEST_CONFIG_NAMES","ext","hasVitestConfig","name","viteConfig","modifyTestSetup","testSetupPath","unmodifyTestSetup"],"sources":["../../src/patterns/enable/backend/modifies/svelte-config.ts","../../src/patterns/enable/backend/modifies/gitignore.ts","../../src/patterns/enable/backend/modifies/test-setup.ts"],"sourcesContent":["import dedent from \"dedent\";\nimport { SyntaxKind } from \"ts-morph\";\nimport {\n resolveConfigTarget,\n saveTarget,\n type ConfigModifyResult,\n type ConfigTarget,\n} from \"../../../../runtime/config-target\";\nimport { packageName } from \"../../../../runtime/write-result\";\nimport {\n ADAPTER_NODE as ADAPTER_NODE_SPEC,\n ADAPTER_STATIC as ADAPTER_STATIC_SPEC,\n} from \"../../../../core/constants\";\n\n// Imports name the package, not the versioned spec the constants install.\nconst ADAPTER_NODE = packageName(ADAPTER_NODE_SPEC);\nconst ADAPTER_STATIC = packageName(ADAPTER_STATIC_SPEC);\nconst ADAPTER_AUTO = \"@sveltejs/adapter-auto\";\n\nconst FAILURE_HINT = dedent`\n Switch the SvelteKit adapter to ${ADAPTER_NODE}:\n\n import adapter from '${ADAPTER_NODE}';\n\n // ...\n adapter: adapter()\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Configure ${ADAPTER_NODE} via the sveltekit() plugin in vite.config.ts.\n`;\n\n/**\n * The adapters this pattern moves between. adapter-auto is included because\n * that is what `sv create` ships, and a project that never chose is one the\n * backend is free to decide for.\n */\nfunction findAdapterImport(sourceFile: ConfigTarget[\"sourceFile\"]) {\n return sourceFile\n .getImportDeclarations()\n .find((decl) =>\n [ADAPTER_STATIC, ADAPTER_AUTO, ADAPTER_NODE].includes(\n decl.getModuleSpecifierValue(),\n ),\n );\n}\n\nfunction adapterCalls(sourceFile: ConfigTarget[\"sourceFile\"]) {\n return sourceFile\n .getDescendantsOfKind(SyntaxKind.CallExpression)\n .filter((ce) => ce.getExpression().getText() === \"adapter\");\n}\n\n/**\n * Switch the adapter to `@sveltejs/adapter-node` and drop its arguments in\n * vite.config, which holds the adapter import + `adapter()` call. A project with a\n * backend is served from a Node process, which is what `vela deploy` runs.\n * Operates on the import and call expression directly, so it never needs the\n * config object.\n */\nexport function modifySvelteConfig(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, {\n notFound: NOT_FOUND_HINT,\n failed: FAILURE_HINT,\n });\n if (res.status !== \"resolved\") {\n return {\n filePath: res.filePath,\n outcome: { status: res.status, message: res.message },\n };\n }\n const { target } = res;\n const adapterImport = findAdapterImport(target.sourceFile);\n if (!adapterImport) {\n return {\n filePath: target.filePath,\n outcome: { status: \"failed\", message: FAILURE_HINT },\n };\n }\n\n if (adapterImport.getModuleSpecifierValue() !== ADAPTER_NODE) {\n adapterImport.setModuleSpecifier(ADAPTER_NODE);\n }\n\n for (const call of adapterCalls(target.sourceFile)) {\n const args = call.getArguments();\n for (let i = args.length - 1; i >= 0; i--) {\n call.removeArgument(i);\n }\n }\n\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n\n/**\n * Reverse of {@link modifySvelteConfig}: switch back to\n * `@sveltejs/adapter-static` and restore the `{ fallback: '200.html' }` arg.\n * Lenient when there is no config or no adapter import: a no-op success. A\n * config that can't be edited (a leftover svelte.config) still fails.\n */\nexport function unmodifySvelteConfig(root: string): ConfigModifyResult {\n const res = resolveConfigTarget(root, {\n notFound: NOT_FOUND_HINT,\n failed: FAILURE_HINT,\n });\n if (res.status === \"not-found\") {\n // Nothing to revert.\n return {\n filePath: res.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n if (res.status === \"failed\") {\n return {\n filePath: res.filePath,\n outcome: { status: \"failed\", message: res.message },\n };\n }\n const { target } = res;\n const adapterImport = findAdapterImport(target.sourceFile);\n if (!adapterImport) {\n return {\n filePath: target.filePath,\n outcome: { status: \"success\", changed: false },\n };\n }\n\n if (adapterImport.getModuleSpecifierValue() !== ADAPTER_STATIC) {\n adapterImport.setModuleSpecifier(ADAPTER_STATIC);\n }\n\n for (const call of adapterCalls(target.sourceFile)) {\n if (call.getArguments().length === 0) {\n call.addArgument(\"{ fallback: '200.html' }\");\n }\n }\n\n return { filePath: target.filePath, outcome: saveTarget(target) };\n}\n","import fs from \"node:fs\";\nimport dedent from \"dedent\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst POCKETBASE_BLOCK = `# PocketBase\n/data/*\n!/data/fixtures\n!/data/seeds\n!/data/hooks\n`;\n\nconst NOT_FOUND_HINT = dedent`\n Create a .gitignore at the project root with the PocketBase block:\n\n # PocketBase\n /data/*\n !/data/fixtures\n !/data/seeds\n !/data/hooks\n`;\n\nexport function modifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n\n if (original.includes(\"# PocketBase\") && original.includes(\"/data/*\")) {\n return { status: \"success\", changed: false };\n }\n\n const separator = original.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const next = original + separator + POCKETBASE_BLOCK;\n fs.writeFileSync(gitignorePath, next, \"utf8\");\n\n return { status: \"success\", changed: true };\n}\n\nexport function unmodifyGitignore(gitignorePath: string): ModifyOutcome {\n if (!fs.existsSync(gitignorePath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(gitignorePath, \"utf8\");\n\n if (!original.includes(\"# PocketBase\")) {\n return { status: \"success\", changed: false };\n }\n\n const withBlockRemoved = original.replace(\n /\\n*# PocketBase\\n\\/data\\/\\*\\n!\\/data\\/fixtures\\n!\\/data\\/seeds\\n!\\/data\\/hooks\\n?/,\n \"\\n\",\n );\n\n const cleaned = withBlockRemoved.replace(/\\n{3,}$/, \"\\n\");\n\n if (cleaned === original) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(gitignorePath, cleaned, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\n// Source of truth: velastack-cli/templates/minimal/test/setup.ts\nexport const WITH_BACKEND = `import { beforeEach, afterEach, beforeAll } from 'vitest';\nimport supertest, { type Agent } from 'supertest';\nimport PocketBase from 'pocketbase-sveltekit';\nimport type { TestContext } from '@velastack/pocketbase/testing';\n\nconst admin = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['admin'];\nconst pb = new PocketBase(process.env.POCKETBASE_URL!) as App.Locals['pb'];\n\nconst testUserPassword = 'password';\n\nasync function authenticateUser(agent: Agent, user: { email?: string }) {\n\\t// Logs in with the password, so it needs the email (made optional by\n\\t// enable-whatsapp, for accounts that sign in with a phone number).\n\\tif (!user.email) {\n\\t\\tthrow new Error('authenticateUser needs a user with an email');\n\\t}\n\\tawait agent.post('/login').type('form').send({\n\\t\\ttype: 'password',\n\\t\\temail: user.email,\n\\t\\tpassword: testUserPassword\n\\t});\n}\n\nbeforeAll(async () => {\n\\tawait admin\n\\t\\t// @ts-ignore\n\\t\\t.collection('_superusers')\n\\t\\t.authWithPassword(\n\\t\\t\\tprocess.env.POCKETBASE_SUPERUSER_EMAIL!,\n\\t\\t\\tprocess.env.POCKETBASE_SUPERUSER_PASSWORD!\n\\t\\t);\n});\n\nbeforeEach(async (context: TestContext) => {\n\\tcontext.request = supertest(process.env.VITE_TEST_URL!);\n\\tcontext.agent = supertest.agent(process.env.VITE_TEST_URL!) as TestContext['agent'];\n\\tcontext.admin = admin;\n\\tcontext.pb = pb;\n\\tconst email = \\`test-\\${Math.random().toString(36).slice(2)}@example.com\\`;\n\\tcontext.user = await context.admin.collection('users').create({\n\\t\\temail,\n\\t\\tpassword: testUserPassword,\n\\t\\tpasswordConfirm: testUserPassword\n\\t});\n\\tcontext.agent.authenticateUser = () => authenticateUser(context.agent, context.user);\n\\tawait context.pb.collection('users').authWithPassword(email, testUserPassword);\n});\n\nafterEach(async (context: TestContext) => {\n\\tawait context.pb.authStore.clear();\n\\tawait context.admin.collection('users').delete(context.user.id);\n});\n`;\n\n// The static template ships no test setup at all; this is the backend-free\n// subset of the minimal one, kept so existing tests keep their agents.\nconst WITHOUT_BACKEND = `import { beforeEach } from 'vitest';\nimport supertest from 'supertest';\n\nbeforeEach(async (context: any) => {\n\\tcontext.request = supertest(process.env.VITE_TEST_URL!);\n\\tcontext.agent = supertest.agent(process.env.VITE_TEST_URL!);\n});\n`;\n\n// Source of truth: velastack-cli/templates/minimal/vitest.config.ts\nexport const VITEST_CONFIG = `import { defineConfig, mergeConfig } from 'vitest/config';\nimport viteConfig from './vite.config';\n\nexport default mergeConfig(\n\\tviteConfig,\n\\tdefineConfig({\n\\t\\ttest: {\n\\t\\t\\texpect: {\n\\t\\t\\t\\trequireAssertions: true\n\\t\\t\\t},\n\\t\\t\\tname: 'server',\n\\t\\t\\tenvironment: 'node',\n\\t\\t\\tinclude: ['src/**/*.{test,spec}.{js,ts}'],\n\\t\\t\\texclude: ['src/**/*.svelte.{test,spec}.{js,ts}'],\n\\t\\t\\tsetupFiles: ['test/setup.ts']\n\\t\\t}\n\\t})\n);\n`;\n\nconst VITEST_CONFIG_NAMES = [\"ts\", \"mts\", \"js\", \"mjs\"].flatMap((ext) => [\n `vitest.config.${ext}`,\n `vitest.workspace.${ext}`,\n]);\n\n/**\n * Whether the project already configures vitest, in a file of its own or a\n * `test` block in its vite config. Without either, `test/setup.ts` is never\n * loaded and every generated `server.test.ts` fails on its missing context.\n */\nexport function hasVitestConfig(root: string): boolean {\n if (\n VITEST_CONFIG_NAMES.some((name) => fs.existsSync(path.join(root, name)))\n ) {\n return true;\n }\n return [\"ts\", \"mts\", \"js\", \"mjs\"].some((ext) => {\n const viteConfig = path.join(root, `vite.config.${ext}`);\n return (\n fs.existsSync(viteConfig) &&\n /\\btest\\s*:/.test(fs.readFileSync(viteConfig, \"utf8\"))\n );\n });\n}\n\n/**\n * Brings an existing `test/setup.ts` up to the backend one. A project without\n * the file gets it as a create instead (see `generate.runtime.ts`), so it is\n * reported as created rather than modified.\n */\nexport function modifyTestSetup(testSetupPath: string): ModifyOutcome {\n if (!fs.existsSync(testSetupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(testSetupPath, \"utf8\");\n if (original === WITH_BACKEND) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(testSetupPath, WITH_BACKEND, \"utf8\");\n return { status: \"success\", changed: true };\n}\n\nexport function unmodifyTestSetup(testSetupPath: string): ModifyOutcome {\n if (!fs.existsSync(testSetupPath)) {\n return { status: \"success\", changed: false };\n }\n\n const original = fs.readFileSync(testSetupPath, \"utf8\");\n if (original === WITHOUT_BACKEND) {\n return { status: \"success\", changed: false };\n }\n\n fs.writeFileSync(testSetupPath, WITHOUT_BACKEND, \"utf8\");\n return { status: \"success\", changed: true };\n}\n"],"mappings":";;;;;;;;AAeA,IAAMU,IAAeH,EAAYP,CAAiB,GAC5CY,IAAiBL,EAAYN,CAAmB,GAChDY,IAAe,0BAEfC,IAAe,CAAM;oCACSJ,EAAa;;yBAExBA,EAAa;;;;GAMhCR,IAAiB,CAAM;cACfQ,EAAa;;AAQ3B,SAASM,EAAkB,GAAwC;CACjE,OAAOC,EACJ,sBAAsB,CAAC,CACvB,MAAM,MACL;EAACL;EAAgBC;EAAcH;CAAY,CAAC,CAAC,SAC3CQ,EAAK,wBAAwB,CAC/B,CACF;AACJ;AAEA,SAASC,EAAa,GAAwC;CAC5D,OAAOF,EACJ,qBAAqBG,EAAW,cAAc,CAAC,CAC/C,QAAQ,MAAOC,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,SAAS;AAC9D;AASA,SAAgBC,EAAmB,GAAkC;CACnE,IAAMC,IAAMlB,EAAoBmB,GAAM;EACpC,UAAUtB;EACV,QAAQY;CACV,CAAC;CACD,IAAIS,EAAI,WAAW,YACjB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AM,MAASlC,EAAG,WAAWC,EAAK,KAAKe,GAAMqB,CAAI,CAAC,CAAC,IAEhE,KAEF;EAAC;EAAM;EAAO;EAAM;CAAK,CAAC,CAAC,MAAM,MAAQ;EAC9C,IAAMC,IAAarC,EAAK,KAAKe,GAAM,eAAemB,GAAK;EACvD,OACEnC,EAAG,WAAWsC,CAAU,KACxB,aAAa,KAAKtC,EAAG,aAAasC,GAAY,MAAM,CAAC;CAEzD,CAAC;AACH;AAOA,SAAgBC,EAAgB,GAAsC;CAWpE,OAVI,CAACvC,EAAG,WAAWwC,CAAa,KAIfxC,EAAG,aAAawC,GAAe,MAC5C,MAAaT,IACR;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7C/B,EAAG,cAAcwC,GAAeT,GAAc,MAAM,GAC7C;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C;AAEA,SAAgBU,EAAkB,GAAsC;CAWtE,OAVI,CAACzC,EAAG,WAAWwC,CAAa,KAIfxC,EAAG,aAAawC,GAAe,MAC5C,MAAaR,IACR;EAAE,QAAQ;EAAW,SAAS;CAAM,KAG7ChC,EAAG,cAAcwC,GAAeR,GAAiB,MAAM,GAChD;EAAE,QAAQ;EAAW,SAAS;CAAK;AAC5C"}
|
|
@@ -127,8 +127,12 @@ function h(e) {
|
|
|
127
127
|
function g(e) {
|
|
128
128
|
return (e.match(/\n/g) ?? []).length;
|
|
129
129
|
}
|
|
130
|
-
function _(
|
|
131
|
-
let n =
|
|
130
|
+
function _(t) {
|
|
131
|
+
let n = t.getParent();
|
|
132
|
+
return e.isStatemented(n) ? n.getStatementsWithComments() : [];
|
|
133
|
+
}
|
|
134
|
+
function v(e, t) {
|
|
135
|
+
let n = _(t), r = e.getFullText(), i = [], a = t.getStart(!0);
|
|
132
136
|
for (let e = n.indexOf(t) - 1; e >= 0; e--) {
|
|
133
137
|
let t = n[e];
|
|
134
138
|
if (!h(t) || g(r.slice(t.getEnd(), a)) > 1) break;
|
|
@@ -136,39 +140,39 @@ function _(e, t) {
|
|
|
136
140
|
}
|
|
137
141
|
return i;
|
|
138
142
|
}
|
|
139
|
-
function
|
|
140
|
-
let r =
|
|
143
|
+
function y(t, n) {
|
|
144
|
+
let r = v(t, n), i = x(t, r[0] ?? n);
|
|
141
145
|
if (e.isJSDocable(n)) for (let e of n.getJsDocs()) e.remove();
|
|
142
146
|
for (let e of r.reverse()) e.remove();
|
|
143
147
|
i.restore(n);
|
|
144
148
|
}
|
|
145
|
-
function
|
|
146
|
-
let n =
|
|
149
|
+
function b(e, t) {
|
|
150
|
+
let n = v(e, t), r = _(t), i = r[r.indexOf(t) + 1], a = x(e, n[0] ?? t);
|
|
147
151
|
t.remove();
|
|
148
152
|
for (let e of n.reverse()) e.remove();
|
|
149
153
|
i && a.restore(i);
|
|
150
154
|
}
|
|
151
|
-
function
|
|
152
|
-
let n =
|
|
155
|
+
function x(e, t) {
|
|
156
|
+
let n = _(t), r = n[n.indexOf(t) - 1], i = r !== void 0 && g(e.getFullText().slice(r.getEnd(), t.getStart(!0))) > 1;
|
|
153
157
|
return { restore(t) {
|
|
154
158
|
i && r && g(e.getFullText().slice(r.getEnd(), t.getStart(!0))) < 2 && e.insertText(r.getEnd(), "\n");
|
|
155
159
|
} };
|
|
156
160
|
}
|
|
157
|
-
function
|
|
161
|
+
function S(e) {
|
|
158
162
|
return e.compilerNode.statements.every((e) => e.kind === r.EmptyStatement);
|
|
159
163
|
}
|
|
160
|
-
function
|
|
164
|
+
function C(e) {
|
|
161
165
|
let t = e.getImportDeclarations(), n = t[t.length - 1], r = n?.getNextSibling();
|
|
162
166
|
n && r && ((e.getFullText().slice(n.getEnd(), r.getStart(!0)).match(/\n/g) ?? []).length >= 2 || e.insertText(n.getEnd(), "\n"));
|
|
163
167
|
}
|
|
164
|
-
function
|
|
168
|
+
function w(t) {
|
|
165
169
|
return t.getVariableDeclarations().find((t) => t.getInitializer()?.getText() === "$props()" && e.isObjectBindingPattern(t.getNameNode()));
|
|
166
170
|
}
|
|
167
|
-
function
|
|
168
|
-
return
|
|
171
|
+
function T(e) {
|
|
172
|
+
return w(e)?.getNameNode().asKind(r.ObjectBindingPattern);
|
|
169
173
|
}
|
|
170
|
-
function
|
|
171
|
-
let n =
|
|
174
|
+
function E(e, t) {
|
|
175
|
+
let n = T(e);
|
|
172
176
|
if (!n) {
|
|
173
177
|
e.addStatements(`let { ${t} } = $props();`);
|
|
174
178
|
return;
|
|
@@ -178,15 +182,15 @@ function T(e, t) {
|
|
|
178
182
|
let i = r.map((e) => e.getText()), a = r.findIndex((e) => e.getDotDotDotToken());
|
|
179
183
|
i.splice(a === -1 ? i.length : a, 0, t), n.replaceWithText(`{ ${i.join(", ")} }`);
|
|
180
184
|
}
|
|
181
|
-
function
|
|
185
|
+
function D(e, t, n) {
|
|
182
186
|
let i = RegExp(`(?<![\\w$.])${t}(?![\\w$])`);
|
|
183
187
|
if ((n.replace(/<style[\s\S]*?<\/style>/g, "").match(/\{[^{}]*\}/g) ?? []).some((e) => i.test(e))) return;
|
|
184
|
-
let a =
|
|
188
|
+
let a = w(e), o = T(e), s = o?.getElements().find((e) => e.getName() === t && !e.getPropertyNameNode());
|
|
185
189
|
if (!a || !o || !s || e.getDescendantsOfKind(r.Identifier).some((e) => e.getText() === t && !a.containsRange(e.getPos(), e.getEnd()))) return;
|
|
186
190
|
let c = o.getElements().filter((e) => e !== s).map((e) => e.getText());
|
|
187
191
|
o.replaceWithText(`{ ${c.join(", ")} }`);
|
|
188
192
|
}
|
|
189
|
-
function
|
|
193
|
+
function O(t, n) {
|
|
190
194
|
let i = t.getDescendantsOfKind(r.BindingElement).find((e) => e.getName() === n && !e.getPropertyNameNode() && !e.getDotDotDotToken());
|
|
191
195
|
if (!i) return;
|
|
192
196
|
let a = i.getNameNode();
|
|
@@ -194,13 +198,13 @@ function D(t, n) {
|
|
|
194
198
|
let o = i.getParentIfKindOrThrow(r.ObjectBindingPattern), s = o.getElements().filter((e) => e !== i).map((e) => e.getText()), c = o.getParent();
|
|
195
199
|
s.length === 0 && e.isParameterDeclaration(c) ? c.remove() : s.length === 0 && e.isVariableDeclaration(c) ? c.getVariableStatement()?.remove() : o.replaceWithText(`{ ${s.join(", ")} }`);
|
|
196
200
|
}
|
|
197
|
-
function
|
|
201
|
+
function k(e, t) {
|
|
198
202
|
let n = e.getFunction(t);
|
|
199
203
|
if (n) return n.remove(), { wasRemoved: !0 };
|
|
200
204
|
let r = e.getVariableStatements().flatMap((e) => e.getDeclarations()).find((e) => e.getName() === t);
|
|
201
205
|
return r ? (r.remove(), { wasRemoved: !0 }) : { wasRemoved: !1 };
|
|
202
206
|
}
|
|
203
|
-
function
|
|
207
|
+
function A(e, t, n, i, a) {
|
|
204
208
|
let s = `
|
|
205
209
|
{
|
|
206
210
|
title: '${t}',
|
|
@@ -231,7 +235,7 @@ function k(e, t, n, i, a) {
|
|
|
231
235
|
wasAdded: d.wasAdded
|
|
232
236
|
};
|
|
233
237
|
}
|
|
234
|
-
function
|
|
238
|
+
function j(e, t, n) {
|
|
235
239
|
let { source: i, result: a } = c(e, (e) => {
|
|
236
240
|
let i = e.getVariableDeclarations().find((e) => e.getName() === "data")?.getInitializer();
|
|
237
241
|
if (!i || i.getKind() !== r.ObjectLiteralExpression) return { wasRemoved: !1 };
|
|
@@ -262,6 +266,6 @@ function A(e, t, n) {
|
|
|
262
266
|
};
|
|
263
267
|
}
|
|
264
268
|
//#endregion
|
|
265
|
-
export { c as _,
|
|
269
|
+
export { c as _, E as a, p as c, f as d, j as f, O as g, k as h, m as i, y as l, b as m, C as n, o, D as p, l as r, S as s, A as t, u };
|
|
266
270
|
|
|
267
|
-
//# sourceMappingURL=ts-morph-helpers-
|
|
271
|
+
//# sourceMappingURL=ts-morph-helpers-Bepc-Es2.js.map
|