@velastack/patterns 0.13.1 → 0.13.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.
Files changed (44) hide show
  1. package/dist/chunks/app-d-ts-h33RrYIv.js +198 -0
  2. package/dist/chunks/app-d-ts-h33RrYIv.js.map +1 -0
  3. package/dist/chunks/app-layout.svelte-CZ0hw-pi.js +51 -0
  4. package/dist/chunks/app-layout.svelte-CZ0hw-pi.js.map +1 -0
  5. package/dist/chunks/{generate.runtime-DHJqOJTr.js → generate.runtime-Bv_16lWi.js} +2 -2
  6. package/dist/chunks/{generate.runtime-DHJqOJTr.js.map → generate.runtime-Bv_16lWi.js.map} +1 -1
  7. package/dist/chunks/{generate.runtime-DvTbN-no.js → generate.runtime-CZKIKP3B.js} +213 -175
  8. package/dist/chunks/generate.runtime-CZKIKP3B.js.map +1 -0
  9. package/dist/chunks/{generate.runtime-BEmSIAop.js → generate.runtime-C_SdcnRs.js} +2 -2
  10. package/dist/chunks/{generate.runtime-BEmSIAop.js.map → generate.runtime-C_SdcnRs.js.map} +1 -1
  11. package/dist/chunks/{generate.runtime-DGnXHELM.js → generate.runtime-CsP4c8GY.js} +78 -77
  12. package/dist/chunks/generate.runtime-CsP4c8GY.js.map +1 -0
  13. package/dist/chunks/{generate.runtime-DWHoDisZ.js → generate.runtime-CzYArKUA.js} +2 -2
  14. package/dist/chunks/{generate.runtime-DWHoDisZ.js.map → generate.runtime-CzYArKUA.js.map} +1 -1
  15. package/dist/chunks/generate.runtime-DZUPtJVF.js +429 -0
  16. package/dist/chunks/generate.runtime-DZUPtJVF.js.map +1 -0
  17. package/dist/chunks/{generate.runtime-Cgam_XCc.js → generate.runtime-DaPA2NNL.js} +2 -2
  18. package/dist/chunks/{generate.runtime-Cgam_XCc.js.map → generate.runtime-DaPA2NNL.js.map} +1 -1
  19. package/dist/chunks/{generate.runtime-i3tMIA1A.js → generate.runtime-pbIrEsa7.js} +45 -45
  20. package/dist/chunks/generate.runtime-pbIrEsa7.js.map +1 -0
  21. package/dist/chunks/i18n-BHCytiiO.js +28 -0
  22. package/dist/chunks/i18n-BHCytiiO.js.map +1 -0
  23. package/dist/chunks/test-setup-cZj1tqaf.js +176 -0
  24. package/dist/chunks/test-setup-cZj1tqaf.js.map +1 -0
  25. package/dist/chunks/translations-CiJnl574.js +189 -0
  26. package/dist/chunks/translations-CiJnl574.js.map +1 -0
  27. package/dist/chunks/{ui-Ct6YQuPw.js → ui-IkdkLwmB.js} +2 -2
  28. package/dist/chunks/{ui-Ct6YQuPw.js.map → ui-IkdkLwmB.js.map} +1 -1
  29. package/dist/chunks/write-result-C1GYInL8.js +499 -0
  30. package/dist/chunks/write-result-C1GYInL8.js.map +1 -0
  31. package/dist/index.js +735 -725
  32. package/dist/index.js.map +1 -1
  33. package/package.json +1 -1
  34. package/dist/chunks/_layout-Dju9EYqa.js +0 -60
  35. package/dist/chunks/_layout-Dju9EYqa.js.map +0 -1
  36. package/dist/chunks/generate.runtime-DGnXHELM.js.map +0 -1
  37. package/dist/chunks/generate.runtime-Dtf3tF3-.js +0 -316
  38. package/dist/chunks/generate.runtime-Dtf3tF3-.js.map +0 -1
  39. package/dist/chunks/generate.runtime-DvTbN-no.js.map +0 -1
  40. package/dist/chunks/generate.runtime-i3tMIA1A.js.map +0 -1
  41. package/dist/chunks/test-setup-CbwhAJT4.js +0 -176
  42. package/dist/chunks/test-setup-CbwhAJT4.js.map +0 -1
  43. package/dist/chunks/write-result-B5KFCqxw.js +0 -487
  44. package/dist/chunks/write-result-B5KFCqxw.js.map +0 -1
@@ -0,0 +1,176 @@
1
+ import { n as e, t } from "./constants-DpK-r_m5.js";
2
+ import { t as n } from "./dedent-CCUOcPFW.js";
3
+ import { o as r, s as i } from "./config-target-DJbVHwHl.js";
4
+ import { c as a } from "./write-result-C1GYInL8.js";
5
+ import o from "node:fs";
6
+ import s from "node:path";
7
+ import { SyntaxKind as c } from "ts-morph";
8
+ // src/patterns/enable/backend/modifies/svelte-config.ts
9
+ var l = a(t), u = a(e), d = "@sveltejs/adapter-auto", f = n`
10
+ Switch the SvelteKit adapter to ${l}:
11
+
12
+ import adapter from '${l}';
13
+
14
+ // ...
15
+ adapter: adapter()
16
+ `, p = n`
17
+ Configure ${l} via the sveltekit() plugin in vite.config.ts.
18
+ `;
19
+ function m(e) {
20
+ return e.getImportDeclarations().find((e) => [
21
+ u,
22
+ d,
23
+ l
24
+ ].includes(e.getModuleSpecifierValue()));
25
+ }
26
+ function h(e) {
27
+ return e.getDescendantsOfKind(c.CallExpression).filter((e) => e.getExpression().getText() === "adapter");
28
+ }
29
+ function g(e) {
30
+ let t = r(e, {
31
+ notFound: p,
32
+ failed: f
33
+ });
34
+ if (t.status !== "resolved") return {
35
+ filePath: t.filePath,
36
+ outcome: {
37
+ status: t.status,
38
+ message: t.message
39
+ }
40
+ };
41
+ let { target: n } = t, a = m(n.sourceFile);
42
+ if (!a) return {
43
+ filePath: n.filePath,
44
+ outcome: {
45
+ status: "failed",
46
+ message: f
47
+ }
48
+ };
49
+ a.getModuleSpecifierValue() !== l && a.setModuleSpecifier(l);
50
+ for (let e of h(n.sourceFile)) {
51
+ let t = e.getArguments();
52
+ for (let n = t.length - 1; n >= 0; n--) e.removeArgument(n);
53
+ }
54
+ return {
55
+ filePath: n.filePath,
56
+ outcome: i(n)
57
+ };
58
+ }
59
+ function _(e) {
60
+ let t = r(e, {
61
+ notFound: p,
62
+ failed: f
63
+ });
64
+ if (t.status === "not-found") return {
65
+ filePath: t.filePath,
66
+ outcome: {
67
+ status: "success",
68
+ changed: !1
69
+ }
70
+ };
71
+ if (t.status === "failed") return {
72
+ filePath: t.filePath,
73
+ outcome: {
74
+ status: "failed",
75
+ message: t.message
76
+ }
77
+ };
78
+ let { target: n } = t, a = m(n.sourceFile);
79
+ if (!a) return {
80
+ filePath: n.filePath,
81
+ outcome: {
82
+ status: "success",
83
+ changed: !1
84
+ }
85
+ };
86
+ a.getModuleSpecifierValue() !== u && a.setModuleSpecifier(u);
87
+ for (let e of h(n.sourceFile)) e.getArguments().length === 0 && e.addArgument("{ fallback: '200.html' }");
88
+ return {
89
+ filePath: n.filePath,
90
+ outcome: i(n)
91
+ };
92
+ }
93
+ // src/patterns/enable/backend/modifies/gitignore.ts
94
+ var v = "# PocketBase\n/data/*\n!/data/fixtures\n!/data/seeds\n!/data/hooks\n", y = n`
95
+ Create a .gitignore at the project root with the PocketBase block:
96
+
97
+ # PocketBase
98
+ /data/*
99
+ !/data/fixtures
100
+ !/data/seeds
101
+ !/data/hooks
102
+ `;
103
+ function b(e) {
104
+ if (!o.existsSync(e)) return {
105
+ status: "not-found",
106
+ message: y
107
+ };
108
+ let t = o.readFileSync(e, "utf8");
109
+ if (t.includes("# PocketBase") && t.includes("/data/*")) return {
110
+ status: "success",
111
+ changed: !1
112
+ };
113
+ let n = t + (t.endsWith("\n") ? "\n" : "\n\n") + v;
114
+ return o.writeFileSync(e, n, "utf8"), {
115
+ status: "success",
116
+ changed: !0
117
+ };
118
+ }
119
+ function x(e) {
120
+ if (!o.existsSync(e)) return {
121
+ status: "success",
122
+ changed: !1
123
+ };
124
+ let t = o.readFileSync(e, "utf8");
125
+ if (!t.includes("# PocketBase")) return {
126
+ status: "success",
127
+ changed: !1
128
+ };
129
+ let n = t.replace(/\n*# PocketBase\n\/data\/\*\n!\/data\/fixtures\n!\/data\/seeds\n!\/data\/hooks\n?/, "\n").replace(/\n{3,}$/, "\n");
130
+ return n === t ? {
131
+ status: "success",
132
+ changed: !1
133
+ } : (o.writeFileSync(e, n, "utf8"), {
134
+ status: "success",
135
+ changed: !0
136
+ });
137
+ }
138
+ // src/patterns/enable/backend/modifies/test-setup.ts
139
+ var S = "import { beforeEach, afterEach, beforeAll, inject } from 'vitest';\nimport supertest, { type Agent } from 'supertest';\nimport PocketBase from 'pocketbase-sveltekit';\nimport type { TestContext } from '@velastack/pocketbase/testing';\nimport type {} from 'vela/testing';\n\n// The servers `vela/testing` started: a throwaway PocketBase and the app.\nconst servers = inject('vela');\nif (!servers) {\n throw new Error(\n \"Server tests need the servers `vela/testing` starts. Add `globalSetup: ['vela/testing']` to the test config in vitest.config.ts.\"\n );\n}\n\nconst admin = new PocketBase(servers.pocketbaseUrl) as App.Locals['admin'];\nconst pb = new PocketBase(servers.pocketbaseUrl) 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(servers.superuser.email, servers.superuser.password);\n});\n\nbeforeEach(async (context: TestContext) => {\n context.request = supertest(servers.appUrl);\n context.agent = supertest.agent(servers.appUrl) 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 { configDefaults, 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 environment: 'node',\n passWithNoTests: true,\n // Server tests reach the app over HTTP and import nothing from it, so\n // watch mode cannot see which tests an edit affects. Rerun them all.\n forceRerunTriggers: [\n '**/package.json/**',\n '**/{vitest,vite}.config.*/**',\n 'src/routes/**',\n 'src/lib/server/**',\n 'src/hooks.server.ts',\n 'data/hooks/**'\n ],\n projects: [\n {\n extends: true,\n test: {\n // `server.test.ts` next to a route, `<name>.server.test.ts` elsewhere:\n // tests that run against the app and its database.\n name: 'server',\n include: ['src/**/*server.{test,spec}.{js,ts}'],\n // Starts a throwaway PocketBase and the app before the first test\n // file, and stops them after the last. Every way of running vitest\n // gets the same servers: `vela test:server`, `vitest`, `vitest --watch`,\n // an editor's test runner.\n globalSetup: ['vela/testing'],\n setupFiles: ['test/setup.ts']\n }\n },\n {\n extends: true,\n test: {\n // Every other test: pure functions, no servers, no setup file.\n name: 'unit',\n include: ['src/**/*.{test,spec}.{js,ts}'],\n exclude: [\n ...configDefaults.exclude,\n 'src/**/*server.{test,spec}.{js,ts}',\n 'src/**/*.svelte.{test,spec}.{js,ts}'\n ]\n }\n }\n ]\n }\n })\n);\n", T = [
140
+ "ts",
141
+ "mts",
142
+ "js",
143
+ "mjs"
144
+ ].flatMap((e) => [`vitest.config.${e}`, `vitest.workspace.${e}`]);
145
+ function E(e) {
146
+ return T.some((t) => o.existsSync(s.join(e, t))) ? !0 : [
147
+ "ts",
148
+ "mts",
149
+ "js",
150
+ "mjs"
151
+ ].some((t) => {
152
+ let n = s.join(e, `vite.config.${t}`);
153
+ return o.existsSync(n) && /\btest\s*:/.test(o.readFileSync(n, "utf8"));
154
+ });
155
+ }
156
+ function D(e) {
157
+ return !o.existsSync(e) || o.readFileSync(e, "utf8") === "import { beforeEach, afterEach, beforeAll, inject } from 'vitest';\nimport supertest, { type Agent } from 'supertest';\nimport PocketBase from 'pocketbase-sveltekit';\nimport type { TestContext } from '@velastack/pocketbase/testing';\nimport type {} from 'vela/testing';\n\n// The servers `vela/testing` started: a throwaway PocketBase and the app.\nconst servers = inject('vela');\nif (!servers) {\n throw new Error(\n \"Server tests need the servers `vela/testing` starts. Add `globalSetup: ['vela/testing']` to the test config in vitest.config.ts.\"\n );\n}\n\nconst admin = new PocketBase(servers.pocketbaseUrl) as App.Locals['admin'];\nconst pb = new PocketBase(servers.pocketbaseUrl) 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(servers.superuser.email, servers.superuser.password);\n});\n\nbeforeEach(async (context: TestContext) => {\n context.request = supertest(servers.appUrl);\n context.agent = supertest.agent(servers.appUrl) 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" ? {
158
+ status: "success",
159
+ changed: !1
160
+ } : (o.writeFileSync(e, S, "utf8"), {
161
+ status: "success",
162
+ changed: !0
163
+ });
164
+ }
165
+ function O(e) {
166
+ return !o.existsSync(e) || o.readFileSync(e, "utf8") === C ? {
167
+ status: "success",
168
+ changed: !1
169
+ } : (o.writeFileSync(e, C, "utf8"), {
170
+ status: "success",
171
+ changed: !0
172
+ });
173
+ }
174
+ 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 };
175
+
176
+ //# sourceMappingURL=test-setup-cZj1tqaf.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test-setup-cZj1tqaf.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, inject } from 'vitest';\nimport supertest, { type Agent } from 'supertest';\nimport PocketBase from 'pocketbase-sveltekit';\nimport type { TestContext } from '@velastack/pocketbase/testing';\nimport type {} from 'vela/testing';\n\n// The servers \\`vela/testing\\` started: a throwaway PocketBase and the app.\nconst servers = inject('vela');\nif (!servers) {\n\\tthrow new Error(\n\\t\\t\"Server tests need the servers \\`vela/testing\\` starts. Add \\`globalSetup: ['vela/testing']\\` to the test config in vitest.config.ts.\"\n\\t);\n}\n\nconst admin = new PocketBase(servers.pocketbaseUrl) as App.Locals['admin'];\nconst pb = new PocketBase(servers.pocketbaseUrl) 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(servers.superuser.email, servers.superuser.password);\n});\n\nbeforeEach(async (context: TestContext) => {\n\\tcontext.request = supertest(servers.appUrl);\n\\tcontext.agent = supertest.agent(servers.appUrl) 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 { configDefaults, 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\\tenvironment: 'node',\n\\t\\t\\tpassWithNoTests: true,\n\\t\\t\\t// Server tests reach the app over HTTP and import nothing from it, so\n\\t\\t\\t// watch mode cannot see which tests an edit affects. Rerun them all.\n\\t\\t\\tforceRerunTriggers: [\n\\t\\t\\t\\t'**/package.json/**',\n\\t\\t\\t\\t'**/{vitest,vite}.config.*/**',\n\\t\\t\\t\\t'src/routes/**',\n\\t\\t\\t\\t'src/lib/server/**',\n\\t\\t\\t\\t'src/hooks.server.ts',\n\\t\\t\\t\\t'data/hooks/**'\n\\t\\t\\t],\n\\t\\t\\tprojects: [\n\\t\\t\\t\\t{\n\\t\\t\\t\\t\\textends: true,\n\\t\\t\\t\\t\\ttest: {\n\\t\\t\\t\\t\\t\\t// \\`server.test.ts\\` next to a route, \\`<name>.server.test.ts\\` elsewhere:\n\\t\\t\\t\\t\\t\\t// tests that run against the app and its database.\n\\t\\t\\t\\t\\t\\tname: 'server',\n\\t\\t\\t\\t\\t\\tinclude: ['src/**/*server.{test,spec}.{js,ts}'],\n\\t\\t\\t\\t\\t\\t// Starts a throwaway PocketBase and the app before the first test\n\\t\\t\\t\\t\\t\\t// file, and stops them after the last. Every way of running vitest\n\\t\\t\\t\\t\\t\\t// gets the same servers: \\`vela test:server\\`, \\`vitest\\`, \\`vitest --watch\\`,\n\\t\\t\\t\\t\\t\\t// an editor's test runner.\n\\t\\t\\t\\t\\t\\tglobalSetup: ['vela/testing'],\n\\t\\t\\t\\t\\t\\tsetupFiles: ['test/setup.ts']\n\\t\\t\\t\\t\\t}\n\\t\\t\\t\\t},\n\\t\\t\\t\\t{\n\\t\\t\\t\\t\\textends: true,\n\\t\\t\\t\\t\\ttest: {\n\\t\\t\\t\\t\\t\\t// Every other test: pure functions, no servers, no setup file.\n\\t\\t\\t\\t\\t\\tname: 'unit',\n\\t\\t\\t\\t\\t\\tinclude: ['src/**/*.{test,spec}.{js,ts}'],\n\\t\\t\\t\\t\\t\\texclude: [\n\\t\\t\\t\\t\\t\\t\\t...configDefaults.exclude,\n\\t\\t\\t\\t\\t\\t\\t'src/**/*server.{test,spec}.{js,ts}',\n\\t\\t\\t\\t\\t\\t\\t'src/**/*.svelte.{test,spec}.{js,ts}'\n\\t\\t\\t\\t\\t\\t]\n\\t\\t\\t\\t\\t}\n\\t\\t\\t\\t}\n\\t\\t\\t]\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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en\\n\"\n\"Language: es\\n\"\n\"MIME-Version: 1.0\\n\"\n\"Content-Type: text/plain; charset=utf-8\\n\"\n\"Content-Transfer-Encoding: 8bit\\n\"\n\"Plural-Forms: nplurals=3\\n\"\n\"X-Plurals-Order: one, many, other\\n\"", i = (e) => `"${e.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n")}"`, a = (e) => e.replace(/\\(.)/g, (e, t) => t === "n" ? "\n" : t);
5
+ function o(e, t) {
6
+ let n = e.split("\n"), r = n.findIndex((e) => e.startsWith(`${t} "`));
7
+ if (r === -1) return null;
8
+ let i = [n[r].slice(t.length + 1)];
9
+ for (let e = r + 1; e < n.length && n[e].startsWith("\""); e++) i.push(n[e]);
10
+ return i.map((e) => a(e.trim().slice(1, -1))).join("");
11
+ }
12
+ function s(e) {
13
+ return [
14
+ `#: ${e.reference}`,
15
+ `msgid ${i(e.msgid)}`,
16
+ `msgstr ${i(e.msgstr)}`
17
+ ].join("\n");
18
+ }
19
+ function c(e, t) {
20
+ let n = (e ?? r).replace(/\s+$/, "").split(/\n{2,}/), a = /* @__PURE__ */ new Map();
21
+ n.forEach((e, t) => {
22
+ if (e.includes("\nmsgctxt ") || e.startsWith("msgctxt ") || e.includes("\nmsgid_plural ")) return;
23
+ let n = o(e, "msgid");
24
+ n && a.set(n, t);
25
+ });
26
+ let c = e === null;
27
+ for (let e of t) {
28
+ let t = a.get(e.msgid);
29
+ t === void 0 ? (a.set(e.msgid, n.length), n.push(s(e)), c = !0) : o(n[t], "msgstr") === "" && (n[t] = n[t].replace(/^msgstr ""$/m, `msgstr ${i(e.msgstr)}`), c = !0);
30
+ }
31
+ return {
32
+ source: c ? n.join("\n\n") + "\n" : e ?? "",
33
+ changed: c
34
+ };
35
+ }
36
+ function l(n, r) {
37
+ let i = /* @__PURE__ */ new Map();
38
+ return r.filter((r) => (i.has(r.reference) || i.set(r.reference, e.existsSync(t.join(n, r.reference))), i.get(r.reference)));
39
+ }
40
+ function u(n) {
41
+ let r = t.join(n, "wuchale.config.js");
42
+ if (!e.existsSync(r)) return !1;
43
+ let i = /\blocales\s*:\s*\[([^\]]*)\]/.exec(e.readFileSync(r, "utf8"));
44
+ return i !== null && /["']es["']/.test(i[1]);
45
+ }
46
+ function d(r, i) {
47
+ let a = {
48
+ create: null,
49
+ modify: null
50
+ };
51
+ if (i.length === 0) return a;
52
+ let o = t.join(r, n);
53
+ if (!e.existsSync(o)) return {
54
+ create: {
55
+ path: n,
56
+ language: "text",
57
+ content: c(null, i).source,
58
+ status: "success"
59
+ },
60
+ modify: null
61
+ };
62
+ let s = c(e.readFileSync(o, "utf8"), i);
63
+ return s.changed ? (e.writeFileSync(o, s.source), {
64
+ create: null,
65
+ modify: {
66
+ path: o,
67
+ language: "text",
68
+ content: s.source,
69
+ status: "success"
70
+ }
71
+ }) : a;
72
+ }
73
+ // src/patterns/enable/auth/translations.ts
74
+ var f = "src/routes/(public)/(auth)", p = "src/routes/(app)", m = `${f}/login/+page.svelte`, h = `${f}/signup/+page.svelte`, g = `${p}/settings/+page.svelte`, _ = (e, t) => Object.entries(t).map(([t, n]) => ({
75
+ reference: e,
76
+ msgid: t,
77
+ msgstr: n
78
+ })), v = [
79
+ ..._(m, {
80
+ Login: "Iniciar sesión",
81
+ Logout: "Cerrar sesión",
82
+ Settings: "Configuración",
83
+ Dashboard: "Panel",
84
+ "Choose a login method": "Elige cómo iniciar sesión",
85
+ "Use your email to login": "Usa tu correo para iniciar sesión",
86
+ "Welcome back": "Qué gusto verte de nuevo",
87
+ "Login is disabled": "El inicio de sesión está desactivado",
88
+ "Check back later for login options": "Vuelve más tarde para ver las opciones de inicio de sesión",
89
+ "<0/> Login with {0}": "<0/> Iniciar sesión con {0}",
90
+ "Or continue with": "O continúa con",
91
+ Email: "Correo electrónico",
92
+ Password: "Contraseña",
93
+ "Forgot your password?": "¿Olvidaste tu contraseña?",
94
+ "Use one-time code instead": "Usar un código de un solo uso",
95
+ "Continue with password": "Continuar con contraseña",
96
+ "Send one-time code": "Enviar código de un solo uso",
97
+ "Don't have an account? <0>Sign up</0>": "¿No tienes una cuenta? <0>Regístrate</0>",
98
+ "By clicking continue, you agree to our <0>Terms of Service</0> and <1>Privacy Policy</1>.": "Al continuar, aceptas nuestros <0>Términos del servicio</0> y nuestra <1>Política de privacidad</1>."
99
+ }),
100
+ ..._(`${f}/login/+page.ts`, { "Log in": "Iniciar sesión" }),
101
+ ..._(h, {
102
+ "Choose a sign up method": "Elige cómo registrarte",
103
+ "Use your email to sign up": "Usa tu correo para registrarte",
104
+ "Create an account": "Crea una cuenta",
105
+ "Signups are disabled": "El registro está desactivado",
106
+ "Check back later for signup options": "Vuelve más tarde para ver las opciones de registro",
107
+ "<0/> Sign up with {0}": "<0/> Registrarte con {0}",
108
+ "Confirm Password": "Confirmar contraseña",
109
+ "Create account": "Crear cuenta",
110
+ "Already have an account? <0>Log in</0>": "¿Ya tienes una cuenta? <0>Inicia sesión</0>"
111
+ }),
112
+ ..._(`${f}/signup/+page.ts`, { "Sign up": "Crear cuenta" }),
113
+ ..._(`${f}/signup/+page.server.ts`, {
114
+ "Failed to send the code.": "No pudimos enviar el código.",
115
+ "We sent a confirmation link to your email.": "Te enviamos un enlace de confirmación a tu correo."
116
+ }),
117
+ ..._(`${f}/reset/+page.svelte`, {
118
+ "Reset your password": "Restablece tu contraseña",
119
+ "Enter your email to reset your password": "Escribe tu correo para restablecer tu contraseña",
120
+ "Send reset link": "Enviar enlace",
121
+ "Remembered your password? <0>Log in</0>": "¿Recordaste tu contraseña? <0>Inicia sesión</0>"
122
+ }),
123
+ ..._(`${f}/reset/+page.ts`, { "Reset password": "Restablecer contraseña" }),
124
+ ..._(`${f}/reset/+page.server.ts`, { "We sent a password reset link to your email.": "Te enviamos un enlace a tu correo para restablecer tu contraseña." }),
125
+ ..._(`${f}/confirm-reset/[token]/+page.svelte`, { "Enter your new password": "Escribe tu nueva contraseña" }),
126
+ ..._(`${f}/confirm-reset/[token]/+page.ts`, { "Confirm password reset": "Confirmar restablecimiento de contraseña" }),
127
+ ..._(`${f}/confirm-reset/[token]/+page.server.ts`, { "Password reset successfully.": "Tu contraseña se restableció correctamente." }),
128
+ ..._(`${f}/confirm-email-change/[token]/+page.svelte`, {
129
+ "Confirm email change": "Confirmar cambio de correo",
130
+ "Confirm your email change": "Confirma el cambio de correo",
131
+ "Enter your password to confirm your email change": "Escribe tu contraseña para confirmar el cambio de correo"
132
+ }),
133
+ ..._(`${f}/confirm-email-change/[token]/+page.server.ts`, { "Email changed successfully.": "Tu correo se cambió correctamente." }),
134
+ ..._(`${f}/otp/[token]/+page.svelte`, {
135
+ "Verify code": "Verificar código",
136
+ "Enter your OTP code": "Escribe tu código",
137
+ "Enter the code sent to your email": "Escribe el código que enviamos a tu correo",
138
+ "OTP code": "Código de un solo uso"
139
+ }),
140
+ ..._(`${f}/welcome/+page.svelte`, {
141
+ "Welcome!": "¡Te damos la bienvenida!",
142
+ "What should we call you?": "¿Cómo quieres que te llamemos?",
143
+ Name: "Nombre",
144
+ Continue: "Continuar",
145
+ "Skip for now": "Omitir por ahora"
146
+ }),
147
+ ..._(`${f}/welcome/+page.ts`, { Welcome: "Bienvenida" }),
148
+ ..._(`${p}/+layout.server.ts`, { Home: "Inicio" }),
149
+ ..._("src/lib/components/nav-user.svelte", {
150
+ "<0/> Light mode": "<0/> Modo claro",
151
+ "<0/> Dark mode": "<0/> Modo oscuro",
152
+ "<0/> Log out": "<0/> Cerrar sesión"
153
+ }),
154
+ ..._(g, {
155
+ Profile: "Perfil",
156
+ "Your profile information.": "La información de tu perfil.",
157
+ Avatar: "Avatar",
158
+ "Upload a new avatar for your profile.": "Sube un nuevo avatar para tu perfil.",
159
+ "Remove avatar": "Quitar avatar",
160
+ "Upload new picture": "Subir nueva foto",
161
+ "Display email publicly": "Mostrar mi correo públicamente",
162
+ "By clicking this checkbox, your email will be displayed publicly.": "Al marcar esta casilla, tu correo se mostrará públicamente.",
163
+ "Save changes": "Guardar cambios",
164
+ "The email address associated with your account.": "El correo electrónico asociado a tu cuenta.",
165
+ Verified: "Verificado",
166
+ Unverified: "Sin verificar",
167
+ "Resend verification email": "Reenviar correo de verificación",
168
+ "Change email": "Cambiar correo",
169
+ "Enter your new email address. You will receive a verification email.": "Escribe tu nuevo correo electrónico. Recibirás un correo de verificación.",
170
+ "Your password is used to log in to your account.": "Tu contraseña se usa para iniciar sesión en tu cuenta.",
171
+ "New password": "Nueva contraseña",
172
+ "Confirm new password": "Confirmar nueva contraseña",
173
+ "Update password": "Actualizar contraseña"
174
+ }),
175
+ ..._(`${p}/settings/+page.server.ts`, {
176
+ "Profile updated successfully.": "Tu perfil se actualizó correctamente.",
177
+ "We sent a confirmation link to your new email.": "Te enviamos un enlace de confirmación a tu nuevo correo.",
178
+ "Password updated successfully.": "Tu contraseña se actualizó correctamente.",
179
+ "Your account has no email.": "Tu cuenta no tiene correo.",
180
+ "We sent a verification email to your email.": "Te enviamos un correo de verificación."
181
+ }),
182
+ ..._(`${f}/login/form.remote.ts`, { "Failed to authenticate.": "No pudimos iniciar tu sesión." }),
183
+ ..._(`${f}/signup/form.remote.ts`, { "Failed to create account.": "No pudimos crear tu cuenta." }),
184
+ ..._(`${f}/otp/[token]/form.remote.ts`, { "Failed to verify code.": "No pudimos verificar el código." }),
185
+ ..._(`${p}/settings/form.remote.ts`, { "Upload new picture <0/>": "Subir nueva foto <0/>" })
186
+ ];
187
+ export { c as a, d as i, l as n, u as r, v as t };
188
+
189
+ //# sourceMappingURL=translations-CiJnl574.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translations-CiJnl574.js","names":["fs","path","SPANISH_CATALOG","HEADER","quote","text","unquote","char","field","lines","block","at","line","keyword","parts","i","part","entryBlock","entry","withTranslations","blocks","source","byMsgid","msgid","index","changed","entries","entriesInProject","present","root","hasSpanish","configPath","locales","translateCatalog","none","catalogPath","result","AUTH","APP","LOGIN","SIGNUP","SETTINGS","messages","translations","msgstr","AUTH_TRANSLATIONS"],"sources":["../../src/runtime/wuchale-catalog.ts","../../src/patterns/enable/auth/translations.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File } from \"../core/types\";\n\n/**\n * `src/locales/es.po`: the Spanish a pattern ships for the pages it writes.\n *\n * enable-i18n sets a project up with English and Spanish, and wuchale leaves\n * a message it has no translation for in English without saying so. A pattern\n * whose pages a visitor reads keeps the Spanish for them as a list of\n * entries; whichever of the two patterns is enabled second merges that list\n * into the catalog: enable-i18n for the pages already in the project, the\n * other pattern for its own pages when the project already has i18n.\n *\n * Only what is missing is filled in. A translation the developer wrote, or\n * changed, is never replaced.\n */\nexport const SPANISH_CATALOG = \"src/locales/es.po\";\n\nexport interface CatalogEntry {\n /** The message as wuchale extracts it (`Don't have an account? <0>Sign up</0>`). */\n msgid: string;\n msgstr: string;\n /** A file the message is in, relative to the project root. */\n reference: string;\n}\n\n// What wuchale writes for `es`. It rewrites the file on the next extraction,\n// keeping the translations and adding the source locale's catalog.\nconst HEADER = [\n 'msgid \"\"',\n 'msgstr \"\"',\n '\"Source-Language: en\\\\n\"',\n '\"Language: es\\\\n\"',\n '\"MIME-Version: 1.0\\\\n\"',\n '\"Content-Type: text/plain; charset=utf-8\\\\n\"',\n '\"Content-Transfer-Encoding: 8bit\\\\n\"',\n '\"Plural-Forms: nplurals=3\\\\n\"',\n '\"X-Plurals-Order: one, many, other\\\\n\"',\n].join(\"\\n\");\n\nconst quote = (text: string) =>\n `\"${text.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"').replace(/\\n/g, \"\\\\n\")}\"`;\n\nconst unquote = (text: string) =>\n text.replace(/\\\\(.)/g, (_, char: string) => (char === \"n\" ? \"\\n\" : char));\n\n/** A `msgid` or `msgstr` value: the quoted string, and any continuation lines. */\nfunction field(block: string, keyword: \"msgid\" | \"msgstr\"): string | null {\n const lines = block.split(\"\\n\");\n const at = lines.findIndex((line) => line.startsWith(`${keyword} \"`));\n if (at === -1) return null;\n const parts = [lines[at].slice(keyword.length + 1)];\n for (let i = at + 1; i < lines.length && lines[i].startsWith('\"'); i++) {\n parts.push(lines[i]);\n }\n return parts.map((part) => unquote(part.trim().slice(1, -1))).join(\"\");\n}\n\nfunction entryBlock(entry: CatalogEntry): string {\n return [\n `#: ${entry.reference}`,\n `msgid ${quote(entry.msgid)}`,\n `msgstr ${quote(entry.msgstr)}`,\n ].join(\"\\n\");\n}\n\n/**\n * `source` (a `.po` catalog, or null for a project that has none yet) with\n * `entries` filled in: an entry the catalog lacks is added, one it holds\n * untranslated gets its translation, and one that is translated is left as\n * it is. Plural and context entries are not touched.\n */\nexport function withTranslations(\n source: string | null,\n entries: CatalogEntry[],\n): { source: string; changed: boolean } {\n const blocks = (source ?? HEADER).replace(/\\s+$/, \"\").split(/\\n{2,}/);\n const byMsgid = new Map<string, number>();\n blocks.forEach((block, index) => {\n if (block.includes(\"\\nmsgctxt \") || block.startsWith(\"msgctxt \")) return;\n if (block.includes(\"\\nmsgid_plural \")) return;\n const msgid = field(block, \"msgid\");\n if (msgid) byMsgid.set(msgid, index);\n });\n\n let changed = source === null;\n for (const entry of entries) {\n const index = byMsgid.get(entry.msgid);\n if (index === undefined) {\n byMsgid.set(entry.msgid, blocks.length);\n blocks.push(entryBlock(entry));\n changed = true;\n continue;\n }\n if (field(blocks[index], \"msgstr\") !== \"\") continue;\n // The untranslated `msgstr \"\"` is the last field of its block.\n blocks[index] = blocks[index].replace(\n /^msgstr \"\"$/m,\n `msgstr ${quote(entry.msgstr)}`,\n );\n changed = true;\n }\n\n return {\n source: changed ? blocks.join(\"\\n\\n\") + \"\\n\" : (source ?? \"\"),\n changed,\n };\n}\n\n/** The entries whose file is in the project. */\nexport function entriesInProject(\n root: string,\n entries: CatalogEntry[],\n): CatalogEntry[] {\n const present = new Map<string, boolean>();\n return entries.filter((entry) => {\n if (!present.has(entry.reference)) {\n present.set(\n entry.reference,\n fs.existsSync(path.join(root, entry.reference)),\n );\n }\n return present.get(entry.reference);\n });\n}\n\n/**\n * Whether the project's wuchale config still lists Spanish: `locales` is the\n * developer's to change, and a pattern does not bring a language back.\n */\nexport function hasSpanish(root: string): boolean {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return false;\n const locales = /\\blocales\\s*:\\s*\\[([^\\]]*)\\]/.exec(\n fs.readFileSync(configPath, \"utf8\"),\n );\n return locales !== null && /[\"']es[\"']/.test(locales[1]);\n}\n\n/**\n * Merge `entries` into the project's Spanish catalog. An existing catalog is\n * edited in place and returned as a modify; a project without one gets it as\n * a create, for the pattern's result to write. Both are empty when there is\n * nothing to add.\n */\nexport function translateCatalog(\n root: string,\n entries: CatalogEntry[],\n): { create: File | null; modify: File | null } {\n const none = { create: null, modify: null };\n if (entries.length === 0) return none;\n\n const catalogPath = path.join(root, SPANISH_CATALOG);\n if (!fs.existsSync(catalogPath)) {\n return {\n create: {\n path: SPANISH_CATALOG,\n language: \"text\",\n content: withTranslations(null, entries).source,\n status: \"success\",\n },\n modify: null,\n };\n }\n\n const result = withTranslations(\n fs.readFileSync(catalogPath, \"utf8\"),\n entries,\n );\n if (!result.changed) return none;\n fs.writeFileSync(catalogPath, result.source);\n return {\n create: null,\n modify: {\n path: catalogPath,\n language: \"text\",\n content: result.source,\n status: \"success\",\n },\n };\n}\n","import type { CatalogEntry } from \"../../../runtime/wuchale-catalog\";\n\nconst AUTH = \"src/routes/(public)/(auth)\";\nconst APP = \"src/routes/(app)\";\nconst LOGIN = `${AUTH}/login/+page.svelte`;\nconst SIGNUP = `${AUTH}/signup/+page.svelte`;\nconst SETTINGS = `${APP}/settings/+page.svelte`;\n\n/** The messages of one file, keyed by the text wuchale extracts. */\nconst messages = (\n reference: string,\n translations: Record<string, string>,\n): CatalogEntry[] =>\n Object.entries(translations).map(([msgid, msgstr]) => ({\n reference,\n msgid,\n msgstr,\n }));\n\n/**\n * Spanish for what enable-auth and enable-auth-remote write: the sign-in\n * pages, the signed-in shell and settings page, and the links they add to the\n * public navbar. Merged into `src/locales/es.po` by whichever of the auth\n * pattern and enable-i18n runs second (see `runtime/wuchale-catalog`).\n *\n * The keys are the messages as wuchale extracts them from the templates in\n * each pattern's `creates/`, so a template whose text changes needs its key\n * changed here: a\n * key that matches nothing is carried in the catalog and never shown. A\n * message used by several files is listed once, under the first.\n */\nexport const AUTH_TRANSLATIONS: CatalogEntry[] = [\n // The navbar links are in the root layout, which a project has with or\n // without auth, so they are filed under the page they lead to.\n ...messages(LOGIN, {\n Login: \"Iniciar sesión\",\n Logout: \"Cerrar sesión\",\n Settings: \"Configuración\",\n Dashboard: \"Panel\",\n\n \"Choose a login method\": \"Elige cómo iniciar sesión\",\n \"Use your email to login\": \"Usa tu correo para iniciar sesión\",\n \"Welcome back\": \"Qué gusto verte de nuevo\",\n \"Login is disabled\": \"El inicio de sesión está desactivado\",\n \"Check back later for login options\":\n \"Vuelve más tarde para ver las opciones de inicio de sesión\",\n \"<0/> Login with {0}\": \"<0/> Iniciar sesión con {0}\",\n \"Or continue with\": \"O continúa con\",\n Email: \"Correo electrónico\",\n Password: \"Contraseña\",\n \"Forgot your password?\": \"¿Olvidaste tu contraseña?\",\n \"Use one-time code instead\": \"Usar un código de un solo uso\",\n \"Continue with password\": \"Continuar con contraseña\",\n \"Send one-time code\": \"Enviar código de un solo uso\",\n \"Don't have an account? <0>Sign up</0>\":\n \"¿No tienes una cuenta? <0>Regístrate</0>\",\n \"By clicking continue, you agree to our <0>Terms of Service</0> and <1>Privacy Policy</1>.\":\n \"Al continuar, aceptas nuestros <0>Términos del servicio</0> y nuestra <1>Política de privacidad</1>.\",\n }),\n ...messages(`${AUTH}/login/+page.ts`, {\n \"Log in\": \"Iniciar sesión\",\n }),\n\n ...messages(SIGNUP, {\n \"Choose a sign up method\": \"Elige cómo registrarte\",\n \"Use your email to sign up\": \"Usa tu correo para registrarte\",\n \"Create an account\": \"Crea una cuenta\",\n \"Signups are disabled\": \"El registro está desactivado\",\n \"Check back later for signup options\":\n \"Vuelve más tarde para ver las opciones de registro\",\n \"<0/> Sign up with {0}\": \"<0/> Registrarte con {0}\",\n \"Confirm Password\": \"Confirmar contraseña\",\n \"Create account\": \"Crear cuenta\",\n \"Already have an account? <0>Log in</0>\":\n \"¿Ya tienes una cuenta? <0>Inicia sesión</0>\",\n }),\n ...messages(`${AUTH}/signup/+page.ts`, {\n \"Sign up\": \"Crear cuenta\",\n }),\n ...messages(`${AUTH}/signup/+page.server.ts`, {\n \"Failed to send the code.\": \"No pudimos enviar el código.\",\n \"We sent a confirmation link to your email.\":\n \"Te enviamos un enlace de confirmación a tu correo.\",\n }),\n\n ...messages(`${AUTH}/reset/+page.svelte`, {\n \"Reset your password\": \"Restablece tu contraseña\",\n \"Enter your email to reset your password\":\n \"Escribe tu correo para restablecer tu contraseña\",\n \"Send reset link\": \"Enviar enlace\",\n \"Remembered your password? <0>Log in</0>\":\n \"¿Recordaste tu contraseña? <0>Inicia sesión</0>\",\n }),\n ...messages(`${AUTH}/reset/+page.ts`, {\n \"Reset password\": \"Restablecer contraseña\",\n }),\n ...messages(`${AUTH}/reset/+page.server.ts`, {\n \"We sent a password reset link to your email.\":\n \"Te enviamos un enlace a tu correo para restablecer tu contraseña.\",\n }),\n\n ...messages(`${AUTH}/confirm-reset/[token]/+page.svelte`, {\n \"Enter your new password\": \"Escribe tu nueva contraseña\",\n }),\n ...messages(`${AUTH}/confirm-reset/[token]/+page.ts`, {\n \"Confirm password reset\": \"Confirmar restablecimiento de contraseña\",\n }),\n ...messages(`${AUTH}/confirm-reset/[token]/+page.server.ts`, {\n \"Password reset successfully.\":\n \"Tu contraseña se restableció correctamente.\",\n }),\n\n ...messages(`${AUTH}/confirm-email-change/[token]/+page.svelte`, {\n \"Confirm email change\": \"Confirmar cambio de correo\",\n \"Confirm your email change\": \"Confirma el cambio de correo\",\n \"Enter your password to confirm your email change\":\n \"Escribe tu contraseña para confirmar el cambio de correo\",\n }),\n ...messages(`${AUTH}/confirm-email-change/[token]/+page.server.ts`, {\n \"Email changed successfully.\": \"Tu correo se cambió correctamente.\",\n }),\n\n ...messages(`${AUTH}/otp/[token]/+page.svelte`, {\n \"Verify code\": \"Verificar código\",\n \"Enter your OTP code\": \"Escribe tu código\",\n \"Enter the code sent to your email\":\n \"Escribe el código que enviamos a tu correo\",\n \"OTP code\": \"Código de un solo uso\",\n }),\n\n ...messages(`${AUTH}/welcome/+page.svelte`, {\n \"Welcome!\": \"¡Te damos la bienvenida!\",\n \"What should we call you?\": \"¿Cómo quieres que te llamemos?\",\n Name: \"Nombre\",\n Continue: \"Continuar\",\n \"Skip for now\": \"Omitir por ahora\",\n }),\n ...messages(`${AUTH}/welcome/+page.ts`, {\n Welcome: \"Bienvenida\",\n }),\n\n ...messages(`${APP}/+layout.server.ts`, {\n Home: \"Inicio\",\n }),\n ...messages(\"src/lib/components/nav-user.svelte\", {\n \"<0/> Light mode\": \"<0/> Modo claro\",\n \"<0/> Dark mode\": \"<0/> Modo oscuro\",\n \"<0/> Log out\": \"<0/> Cerrar sesión\",\n }),\n\n ...messages(SETTINGS, {\n Profile: \"Perfil\",\n \"Your profile information.\": \"La información de tu perfil.\",\n Avatar: \"Avatar\",\n \"Upload a new avatar for your profile.\":\n \"Sube un nuevo avatar para tu perfil.\",\n \"Remove avatar\": \"Quitar avatar\",\n \"Upload new picture\": \"Subir nueva foto\",\n \"Display email publicly\": \"Mostrar mi correo públicamente\",\n \"By clicking this checkbox, your email will be displayed publicly.\":\n \"Al marcar esta casilla, tu correo se mostrará públicamente.\",\n \"Save changes\": \"Guardar cambios\",\n \"The email address associated with your account.\":\n \"El correo electrónico asociado a tu cuenta.\",\n Verified: \"Verificado\",\n Unverified: \"Sin verificar\",\n \"Resend verification email\": \"Reenviar correo de verificación\",\n \"Change email\": \"Cambiar correo\",\n \"Enter your new email address. You will receive a verification email.\":\n \"Escribe tu nuevo correo electrónico. Recibirás un correo de verificación.\",\n \"Your password is used to log in to your account.\":\n \"Tu contraseña se usa para iniciar sesión en tu cuenta.\",\n \"New password\": \"Nueva contraseña\",\n \"Confirm new password\": \"Confirmar nueva contraseña\",\n \"Update password\": \"Actualizar contraseña\",\n }),\n ...messages(`${APP}/settings/+page.server.ts`, {\n \"Profile updated successfully.\": \"Tu perfil se actualizó correctamente.\",\n \"We sent a confirmation link to your new email.\":\n \"Te enviamos un enlace de confirmación a tu nuevo correo.\",\n \"Password updated successfully.\":\n \"Tu contraseña se actualizó correctamente.\",\n \"Your account has no email.\": \"Tu cuenta no tiene correo.\",\n \"We sent a verification email to your email.\":\n \"Te enviamos un correo de verificación.\",\n }),\n\n // enable-auth-remote writes the same pages at the same paths, so everything\n // above covers it. These are the messages only it has, filed under its\n // remote functions so a project with the form-action pages is not handed\n // them.\n ...messages(`${AUTH}/login/form.remote.ts`, {\n \"Failed to authenticate.\": \"No pudimos iniciar tu sesión.\",\n }),\n ...messages(`${AUTH}/signup/form.remote.ts`, {\n \"Failed to create account.\": \"No pudimos crear tu cuenta.\",\n }),\n ...messages(`${AUTH}/otp/[token]/form.remote.ts`, {\n \"Failed to verify code.\": \"No pudimos verificar el código.\",\n }),\n ...messages(`${APP}/settings/form.remote.ts`, {\n \"Upload new picture <0/>\": \"Subir nueva foto <0/>\",\n }),\n];\n"],"mappings":";;;AAiBA,IAAaE,IAAkB,qBAYzBC,IAAS,yQAYTC,KAAS,MACb,IAAIC,EAAK,QAAQ,OAAO,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAK,CAAC,CAAC,QAAQ,OAAO,KAAK,EAAE,IAEvEC,KAAW,MACfD,EAAK,QAAQ,WAAW,GAAG,MAAkBE,MAAS,MAAM,OAAOA,CAAK;AAG1E,SAASC,EAAM,GAAe,GAA4C;CACxE,IAAMC,IAAQC,EAAM,MAAM,IAAI,GACxBC,IAAKF,EAAM,WAAW,MAASG,EAAK,WAAW,GAAGC,EAAQ,GAAG,CAAC;CACpE,IAAIF,MAAO,IAAI,OAAO;CACtB,IAAMG,IAAQ,CAACL,EAAME,EAAG,CAAC,MAAME,EAAQ,SAAS,CAAC,CAAC;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B,EAC5C,2BAA2B,wBAC7B,CAAC;AACH"}
@@ -1,7 +1,7 @@
1
1
  import { r as e, t } from "./errors-DdSUZI8f.js";
2
2
  import { n } from "./logger-t1HxmpG2.js";
3
3
  import { i as r, r as i } from "./table-core-BXmnfjln.js";
4
- import { a, i as o, n as s, o as c, r as l, s as u, t as d } from "./write-result-B5KFCqxw.js";
4
+ import { a, i as o, n as s, o as c, r as l, s as u, t as d } from "./write-result-C1GYInL8.js";
5
5
  import { existsSync as f, readFileSync as p, writeFileSync as m } from "node:fs";
6
6
  import h from "node:path";
7
7
  import { createRequire as g } from "node:module";
@@ -169,4 +169,4 @@ async function N(e, t) {
169
169
  }
170
170
  export { M as applyBaseColor, N as applyTheme, C as listComponents, D as switchStyle };
171
171
 
172
- //# sourceMappingURL=ui-Ct6YQuPw.js.map
172
+ //# sourceMappingURL=ui-IkdkLwmB.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ui-Ct6YQuPw.js","names":["RegistryUnavailableError","readComponentsConfig","fetchRegistryIndex","installComponents","formatPaths","installedPackagesFromProject","getAllCustomComponents","isCustomComponent","executeCommand","path","loadPreset","resolved","createRequire","root","error","reason","pathToFileURL","STYLE_FONTS","presetFor","preset","config","current","encodePreset","overrides","applyPreset","code","only","runtime","COMPONENTS_JSON","listComponents","options","result","installedComponents","assertOneOf","value","InvalidArgumentError","kind","choices","writeStyle","configPath","existsSync","text","readFileSync","style","indent","registryUiNames","index","item","switchStyle","logger","getLogger","unchanged","offered","reinstall","component","packagesBefore","filesModified","reinstalled","hints","font","applyStyleFont","packages","name","FONTSOURCE_IMPORT","fontsourceImports","css","match","fonts","cssPath","cssFile","wanted","stale","family","f","applyColors","applyBaseColor","applyTheme"],"sources":["../../src/runtime/shadcn-preset.ts","../../src/runtime/ui.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { WriteResultRuntime } from \"../core/types\";\nimport { readComponentsConfig } from \"./registry\";\nimport { executeCommand, formatPaths } from \"./write-result\";\n\n/**\n * What a shadcn-svelte preset code carries. Mirrors `PresetConfig` from\n * `shadcn-svelte/preset` as plain strings, so this package's types do not\n * depend on a package its consumers may not have installed.\n */\nexport interface PresetConfig {\n style: string;\n baseColor: string;\n theme: string;\n chartColor?: string;\n iconLibrary: string;\n font: string;\n fontHeading: string;\n radius: string;\n menuAccent: string;\n menuColor: string;\n}\n\n/** The part of `shadcn-svelte/preset` this package uses. */\nexport interface ShadcnPreset {\n PRESET_STYLES: readonly string[];\n PRESET_BASE_COLOR_KEYS: readonly string[];\n PRESET_THEME_KEYS: readonly string[];\n PRESET_FONTS: readonly string[];\n PRESET_ICON_LIBRARIES: readonly string[];\n encodePreset(config: Partial<PresetConfig>): string;\n decodePreset(code: string): PresetConfig | null;\n}\n\nexport type PresetPart = \"theme\" | \"font\";\n\n/**\n * The encoder from the *project's* shadcn-svelte, so every preset code is\n * produced by the same version that consumes it and the value lists can\n * never drift from what `apply` accepts.\n */\nexport async function loadPreset(root: string): Promise<ShadcnPreset> {\n let resolved: string;\n try {\n resolved = createRequire(path.join(root, \"package.json\")).resolve(\n \"shadcn-svelte/preset\",\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Could not load shadcn-svelte/preset from ${root}: ${reason}\\n` +\n \"Install the project's dependencies (shadcn-svelte >= 1.6) and try again.\",\n );\n }\n const module: unknown = await import(\n /* @vite-ignore */ pathToFileURL(resolved).href\n );\n return module as ShadcnPreset;\n}\n\n/**\n * The font each style is designed with. shadcn-svelte keeps this table inside\n * its bundle (the `create` presets) without exporting it, so it is vendored\n * here; `shadcn-preset.test.ts` checks it still covers every style the\n * installed shadcn-svelte knows.\n */\nexport const STYLE_FONTS: Record<\n string,\n { font: string; fontHeading?: string }\n> = {\n nova: { font: \"geist\" },\n vega: { font: \"inter\" },\n maia: { font: \"figtree\" },\n lyra: { font: \"jetbrains-mono\" },\n mira: { font: \"inter\" },\n luma: { font: \"inter\" },\n sera: { font: \"noto-sans\", fontHeading: \"playfair-display\" },\n rhea: { font: \"inter\" },\n};\n\n/**\n * A preset code for the project as it is, with `overrides` on top: the style,\n * base color, icon library and menu settings come from `components.json` so\n * an `apply --only theme` keeps everything it does not mean to change.\n * Values shadcn-svelte does not know (a `slate` from an older template) fall\n * back to its defaults inside `encodePreset`.\n */\nexport async function presetFor(\n root: string,\n overrides: Partial<PresetConfig>,\n preset?: ShadcnPreset,\n): Promise<string> {\n const { encodePreset } = preset ?? (await loadPreset(root));\n const config = readComponentsConfig(root);\n const current: Partial<PresetConfig> = { style: config.style };\n if (config.baseColor) current.baseColor = config.baseColor;\n if (config.iconLibrary) current.iconLibrary = config.iconLibrary;\n if (config.menuColor) current.menuColor = config.menuColor;\n if (config.menuAccent) current.menuAccent = config.menuAccent;\n return encodePreset({ ...current, ...overrides });\n}\n\n/**\n * `shadcn-svelte apply --preset <code> --only <parts> --yes` through the\n * project's package manager. `theme` rewrites the token values in `:root` /\n * `.dark` and records the base color in `components.json`; `font` adds the\n * fontsource import, dependency and `--font-sans`. Both leave the rest of the\n * stylesheet alone but write it in the registry's formatting, so the file is\n * run through the project's prettier afterwards.\n */\nexport async function applyPreset(\n root: string,\n code: string,\n only: PresetPart[],\n runtime?: WriteResultRuntime,\n): Promise<void> {\n await executeCommand(\n root,\n \"execute\",\n [\"shadcn-svelte\", \"apply\", \"--preset\", code, \"--only\", ...only, \"--yes\"],\n runtime,\n );\n await formatPaths(root, [readComponentsConfig(root).cssPath]);\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n ApplyBaseColorOptions,\n ApplyColorsResult,\n ApplyThemeOptions,\n Component,\n ListComponentsOptions,\n ListComponentsResult,\n RegistryItem,\n SwitchStyleOptions,\n SwitchStyleResult,\n WriteResultRuntime,\n} from \"../core/types\";\nimport { InvalidArgumentError, RegistryUnavailableError } from \"../core/errors\";\nimport { getLogger } from \"../core/logger\";\nimport { fetchRegistryIndex, readComponentsConfig } from \"./registry\";\nimport {\n applyPreset,\n loadPreset,\n presetFor,\n STYLE_FONTS,\n type ShadcnPreset,\n} from \"./shadcn-preset\";\nimport {\n getAllCustomComponents,\n installComponents,\n installedComponents,\n installedPackagesFromProject,\n isCustomComponent,\n} from \"./write-result\";\n\nconst COMPONENTS_JSON = \"components.json\";\n\n/**\n * What a project has and what it could add: the ui directory, this package's\n * bundled components, and the registry index of the configured style. A\n * registry that cannot be read leaves the first two intact and says why.\n */\nexport async function listComponents(\n options: ListComponentsOptions,\n runtime?: WriteResultRuntime,\n): Promise<ListComponentsResult> {\n const { root } = options;\n const { style } = readComponentsConfig(root);\n const result: ListComponentsResult = {\n style,\n installed: installedComponents(root),\n custom: getAllCustomComponents(),\n registry: [],\n };\n try {\n result.registry = await fetchRegistryIndex(root, { runtime });\n } catch (error) {\n if (!(error instanceof RegistryUnavailableError)) throw error;\n result.registryUnavailable = error.message;\n }\n return result;\n}\n\nfunction assertOneOf(\n kind: string,\n value: string,\n choices: readonly string[],\n): void {\n if (choices.includes(value)) return;\n throw new InvalidArgumentError(\n `Unknown ${kind} \"${value}\". Choose one of: ${choices.join(\", \")}.`,\n );\n}\n\n/**\n * Rewrites `style` in `components.json` and nothing else, keeping the file's\n * indentation so the change reads as the one-line diff it is.\n */\nfunction writeStyle(root: string, style: string): void {\n const configPath = path.join(root, COMPONENTS_JSON);\n if (!existsSync(configPath)) {\n throw new Error(\n `${COMPONENTS_JSON} not found in ${root}; this does not look like a shadcn-svelte project.`,\n );\n }\n const text = readFileSync(configPath, \"utf8\");\n const config = JSON.parse(text) as Record<string, unknown>;\n config.style = style;\n const indent = text.includes(\"\\n\\t\") ? \"\\t\" : 2;\n writeFileSync(\n configPath,\n `${JSON.stringify(config, null, indent)}\\n`,\n \"utf8\",\n );\n}\n\nfunction registryUiNames(index: RegistryItem[]): Set<string> {\n return new Set(\n index\n .filter((item) => item.type === \"registry:ui\")\n .map((item) => item.name),\n );\n}\n\n/**\n * Moves a project to another shadcn-svelte style. Every installed component\n * the new style's registry also offers is re-added from there (their local\n * edits are lost, which is what `confirm` is for); this package's own\n * components and anything the registry does not know are left alone. The\n * style's preset font follows unless `font` is false.\n */\nexport async function switchStyle(\n options: SwitchStyleOptions,\n runtime?: WriteResultRuntime,\n): Promise<SwitchStyleResult> {\n const { root, style, font = true } = options;\n const logger = getLogger(options);\n const preset = await loadPreset(root);\n assertOneOf(\"style\", style, preset.PRESET_STYLES);\n\n const unchanged: SwitchStyleResult = {\n status: \"unchanged\",\n style,\n reinstalled: [],\n filesModified: [],\n packages: [],\n hints: [],\n };\n if (readComponentsConfig(root).style === style) {\n return unchanged;\n }\n\n const index = await fetchRegistryIndex(root, { style, runtime });\n const offered = registryUiNames(index);\n const reinstall = installedComponents(root).filter(\n (component) => offered.has(component) && !isCustomComponent(component),\n );\n\n if (options.confirm && !(await options.confirm(reinstall))) {\n return { ...unchanged, status: \"cancelled\" };\n }\n\n const packagesBefore = installedPackagesFromProject(root);\n writeStyle(root, style);\n const filesModified = [COMPONENTS_JSON];\n\n let reinstalled: Component[] = [];\n if (reinstall.length > 0) {\n const outcome = await installComponents(\n { root, components: reinstall, overwrite: true, logger },\n runtime,\n );\n reinstalled = outcome.installed;\n }\n\n const hints: string[] = [];\n if (font) {\n await applyStyleFont(\n root,\n style,\n preset,\n runtime,\n filesModified,\n hints,\n logger,\n );\n }\n\n const packages = [...installedPackagesFromProject(root)]\n .filter((name) => !packagesBefore.has(name))\n .sort();\n\n return {\n status: \"switched\",\n style,\n reinstalled,\n filesModified,\n packages,\n hints,\n };\n}\n\nconst FONTSOURCE_IMPORT =\n /@import\\s+[\"']@fontsource(?:-variable)?\\/([^\"']+)[\"']/g;\n\n/** The fontsource families a stylesheet imports, in order. */\nfunction fontsourceImports(css: string): string[] {\n return [...css.matchAll(FONTSOURCE_IMPORT)].map((match) => match[1]!);\n}\n\nasync function applyStyleFont(\n root: string,\n style: string,\n preset: ShadcnPreset,\n runtime: WriteResultRuntime | undefined,\n filesModified: string[],\n hints: string[],\n logger: ReturnType<typeof getLogger>,\n): Promise<void> {\n const fonts = STYLE_FONTS[style];\n if (!fonts) {\n logger.info(\n `No preset font is known for the ${style} style; leaving fonts unchanged.`,\n );\n return;\n }\n logger.info(`Applying the ${style} font (${fonts.font})`);\n const code = await presetFor(root, { style, ...fonts }, preset);\n await applyPreset(root, code, [\"font\"], runtime);\n\n const cssPath = readComponentsConfig(root).cssPath;\n filesModified.push(cssPath, \"package.json\");\n\n // `apply --only font` adds the new font beside whatever was imported before\n // and leaves it to the project to drop the old one; a font nobody uses\n // still ships to every visitor.\n const cssFile = path.join(root, cssPath);\n if (existsSync(cssFile)) {\n const wanted = new Set([fonts.font, fonts.fontHeading].filter(Boolean));\n const stale = fontsourceImports(readFileSync(cssFile, \"utf8\")).filter(\n (family) => !wanted.has(family),\n );\n if (stale.length > 0) {\n hints.push(\n `${cssPath} still imports ${stale.map((f) => `@fontsource-variable/${f}`).join(\", \")} from the previous style; remove the import and the package if nothing else uses them.`,\n );\n }\n }\n}\n\nasync function applyColors(\n root: string,\n overrides: { baseColor?: string; theme: string },\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n const preset = await loadPreset(root);\n if (overrides.baseColor) {\n assertOneOf(\n \"base color\",\n overrides.baseColor,\n preset.PRESET_BASE_COLOR_KEYS,\n );\n }\n assertOneOf(\"theme\", overrides.theme, preset.PRESET_THEME_KEYS);\n\n // Charts follow the accent, as shadcn-svelte's own presets do.\n const code = await presetFor(\n root,\n { ...overrides, chartColor: overrides.theme },\n preset,\n );\n await applyPreset(root, code, [\"theme\"], runtime);\n\n const config = readComponentsConfig(root);\n return {\n baseColor: config.baseColor ?? overrides.baseColor ?? \"\",\n theme: overrides.theme,\n filesModified: [config.cssPath, COMPONENTS_JSON],\n };\n}\n\n/**\n * Sets the base (gray) palette. The accent is reset to the base color as\n * well, since `components.json` records only the base color; `applyTheme`\n * puts an accent back on top.\n */\nexport async function applyBaseColor(\n options: ApplyBaseColorOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(\n options.root,\n { baseColor: options.color, theme: options.color },\n runtime,\n );\n}\n\n/** Sets the accent (primary, ring, charts) and keeps the base palette. */\nexport async function applyTheme(\n options: ApplyThemeOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(options.root, { theme: options.theme }, runtime);\n}\n"],"mappings":";;;;;;;;;AA2CA,eAAsBU,EAAW,GAAqC;CACpE,IAAIC;CACJ,IAAI;EACF,IAAWC,EAAcH,EAAK,KAAKI,GAAM,cAAc,CAAC,CAAC,CAAC,QACxD,sBACF;CACF,SAASC,GAAO;EACd,IAAMC,IAASD,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK;EACpE,MAAU,MACR,4CAA4CD,EAAK,IAAIE,EAAO,2EAE9D;CACF;CAIA,OAAO,MAHuB;;EACTC,EAAcL,CAAQ,CAAC,CAAC;;AAG/C;AAQA,IAAaM,IAGT;CACF,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,UAAU;CACxB,MAAM,EAAE,MAAM,iBAAiB;CAC/B,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM;EAAE,MAAM;EAAa,aAAa;CAAmB;CAC3D,MAAM,EAAE,MAAM,QAAQ;AACxB;AASA,eAAsBC,EACpB,GACA,GACA,GACiB;CACjB,IAAM,EAAE,oBAAiBC,KAAW,MAAMT,EAAWG,CAAI,GACnDO,IAASnB,EAAqBY,CAAI,GAClCQ,IAAiC,EAAE,OAAOD,EAAO,MAAM;CAK7D,OAJIA,EAAO,cAAW,EAAQ,YAAYA,EAAO,YAC7CA,EAAO,gBAAa,EAAQ,cAAcA,EAAO,cACjDA,EAAO,cAAW,EAAQ,YAAYA,EAAO,YAC7CA,EAAO,eAAY,EAAQ,aAAaA,EAAO,aAC5C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,EAAO,sBACT,GAEFc,EAAY,SAASV,EAAU,OAAOJ,EAAO,iBAAiB,GAQ9D,MAAMK,EAAYX,GAAM,MALLK,EACjBL,GACA;EAAE,GAAGU;EAAW,YAAYA,EAAU;CAAM,GAC5CJ,CACF,GAC8B,CAAC,OAAO,GAAGQ,CAAO;CAEhD,IAAMP,IAASnB,EAAqBY,CAAI;CACxC,OAAO;EACL,WAAWO,EAAO,aAAaG,EAAU,aAAa;EACtD,OAAOA,EAAU;EACjB,eAAe,CAACH,EAAO,SAASQ,CAAe;CACjD;AACF;AAOA,eAAsB+C,EACpB,GACA,GAC4B;CAC5B,OAAOD,EACL5C,EAAQ,MACR;EAAE,WAAWA,EAAQ;EAAO,OAAOA,EAAQ;CAAM,GACjDH,CACF;AACF;AAGA,eAAsBiD,EACpB,GACA,GAC4B;CAC5B,OAAOF,EAAY5C,EAAQ,MAAM,EAAE,OAAOA,EAAQ,MAAM,GAAGH,CAAO;AACpE"}
1
+ {"version":3,"file":"ui-IkdkLwmB.js","names":["RegistryUnavailableError","readComponentsConfig","fetchRegistryIndex","installComponents","formatPaths","installedPackagesFromProject","getAllCustomComponents","isCustomComponent","executeCommand","path","loadPreset","resolved","createRequire","root","error","reason","pathToFileURL","STYLE_FONTS","presetFor","preset","config","current","encodePreset","overrides","applyPreset","code","only","runtime","COMPONENTS_JSON","listComponents","options","result","installedComponents","assertOneOf","value","InvalidArgumentError","kind","choices","writeStyle","configPath","existsSync","text","readFileSync","style","indent","registryUiNames","index","item","switchStyle","logger","getLogger","unchanged","offered","reinstall","component","packagesBefore","filesModified","reinstalled","hints","font","applyStyleFont","packages","name","FONTSOURCE_IMPORT","fontsourceImports","css","match","fonts","cssPath","cssFile","wanted","stale","family","f","applyColors","applyBaseColor","applyTheme"],"sources":["../../src/runtime/shadcn-preset.ts","../../src/runtime/ui.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { WriteResultRuntime } from \"../core/types\";\nimport { readComponentsConfig } from \"./registry\";\nimport { executeCommand, formatPaths } from \"./write-result\";\n\n/**\n * What a shadcn-svelte preset code carries. Mirrors `PresetConfig` from\n * `shadcn-svelte/preset` as plain strings, so this package's types do not\n * depend on a package its consumers may not have installed.\n */\nexport interface PresetConfig {\n style: string;\n baseColor: string;\n theme: string;\n chartColor?: string;\n iconLibrary: string;\n font: string;\n fontHeading: string;\n radius: string;\n menuAccent: string;\n menuColor: string;\n}\n\n/** The part of `shadcn-svelte/preset` this package uses. */\nexport interface ShadcnPreset {\n PRESET_STYLES: readonly string[];\n PRESET_BASE_COLOR_KEYS: readonly string[];\n PRESET_THEME_KEYS: readonly string[];\n PRESET_FONTS: readonly string[];\n PRESET_ICON_LIBRARIES: readonly string[];\n encodePreset(config: Partial<PresetConfig>): string;\n decodePreset(code: string): PresetConfig | null;\n}\n\nexport type PresetPart = \"theme\" | \"font\";\n\n/**\n * The encoder from the *project's* shadcn-svelte, so every preset code is\n * produced by the same version that consumes it and the value lists can\n * never drift from what `apply` accepts.\n */\nexport async function loadPreset(root: string): Promise<ShadcnPreset> {\n let resolved: string;\n try {\n resolved = createRequire(path.join(root, \"package.json\")).resolve(\n \"shadcn-svelte/preset\",\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Could not load shadcn-svelte/preset from ${root}: ${reason}\\n` +\n \"Install the project's dependencies (shadcn-svelte >= 1.6) and try again.\",\n );\n }\n const module: unknown = await import(\n /* @vite-ignore */ pathToFileURL(resolved).href\n );\n return module as ShadcnPreset;\n}\n\n/**\n * The font each style is designed with. shadcn-svelte keeps this table inside\n * its bundle (the `create` presets) without exporting it, so it is vendored\n * here; `shadcn-preset.test.ts` checks it still covers every style the\n * installed shadcn-svelte knows.\n */\nexport const STYLE_FONTS: Record<\n string,\n { font: string; fontHeading?: string }\n> = {\n nova: { font: \"geist\" },\n vega: { font: \"inter\" },\n maia: { font: \"figtree\" },\n lyra: { font: \"jetbrains-mono\" },\n mira: { font: \"inter\" },\n luma: { font: \"inter\" },\n sera: { font: \"noto-sans\", fontHeading: \"playfair-display\" },\n rhea: { font: \"inter\" },\n};\n\n/**\n * A preset code for the project as it is, with `overrides` on top: the style,\n * base color, icon library and menu settings come from `components.json` so\n * an `apply --only theme` keeps everything it does not mean to change.\n * Values shadcn-svelte does not know (a `slate` from an older template) fall\n * back to its defaults inside `encodePreset`.\n */\nexport async function presetFor(\n root: string,\n overrides: Partial<PresetConfig>,\n preset?: ShadcnPreset,\n): Promise<string> {\n const { encodePreset } = preset ?? (await loadPreset(root));\n const config = readComponentsConfig(root);\n const current: Partial<PresetConfig> = { style: config.style };\n if (config.baseColor) current.baseColor = config.baseColor;\n if (config.iconLibrary) current.iconLibrary = config.iconLibrary;\n if (config.menuColor) current.menuColor = config.menuColor;\n if (config.menuAccent) current.menuAccent = config.menuAccent;\n return encodePreset({ ...current, ...overrides });\n}\n\n/**\n * `shadcn-svelte apply --preset <code> --only <parts> --yes` through the\n * project's package manager. `theme` rewrites the token values in `:root` /\n * `.dark` and records the base color in `components.json`; `font` adds the\n * fontsource import, dependency and `--font-sans`. Both leave the rest of the\n * stylesheet alone but write it in the registry's formatting, so the file is\n * run through the project's prettier afterwards.\n */\nexport async function applyPreset(\n root: string,\n code: string,\n only: PresetPart[],\n runtime?: WriteResultRuntime,\n): Promise<void> {\n await executeCommand(\n root,\n \"execute\",\n [\"shadcn-svelte\", \"apply\", \"--preset\", code, \"--only\", ...only, \"--yes\"],\n runtime,\n );\n await formatPaths(root, [readComponentsConfig(root).cssPath]);\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n ApplyBaseColorOptions,\n ApplyColorsResult,\n ApplyThemeOptions,\n Component,\n ListComponentsOptions,\n ListComponentsResult,\n RegistryItem,\n SwitchStyleOptions,\n SwitchStyleResult,\n WriteResultRuntime,\n} from \"../core/types\";\nimport { InvalidArgumentError, RegistryUnavailableError } from \"../core/errors\";\nimport { getLogger } from \"../core/logger\";\nimport { fetchRegistryIndex, readComponentsConfig } from \"./registry\";\nimport {\n applyPreset,\n loadPreset,\n presetFor,\n STYLE_FONTS,\n type ShadcnPreset,\n} from \"./shadcn-preset\";\nimport {\n getAllCustomComponents,\n installComponents,\n installedComponents,\n installedPackagesFromProject,\n isCustomComponent,\n} from \"./write-result\";\n\nconst COMPONENTS_JSON = \"components.json\";\n\n/**\n * What a project has and what it could add: the ui directory, this package's\n * bundled components, and the registry index of the configured style. A\n * registry that cannot be read leaves the first two intact and says why.\n */\nexport async function listComponents(\n options: ListComponentsOptions,\n runtime?: WriteResultRuntime,\n): Promise<ListComponentsResult> {\n const { root } = options;\n const { style } = readComponentsConfig(root);\n const result: ListComponentsResult = {\n style,\n installed: installedComponents(root),\n custom: getAllCustomComponents(),\n registry: [],\n };\n try {\n result.registry = await fetchRegistryIndex(root, { runtime });\n } catch (error) {\n if (!(error instanceof RegistryUnavailableError)) throw error;\n result.registryUnavailable = error.message;\n }\n return result;\n}\n\nfunction assertOneOf(\n kind: string,\n value: string,\n choices: readonly string[],\n): void {\n if (choices.includes(value)) return;\n throw new InvalidArgumentError(\n `Unknown ${kind} \"${value}\". Choose one of: ${choices.join(\", \")}.`,\n );\n}\n\n/**\n * Rewrites `style` in `components.json` and nothing else, keeping the file's\n * indentation so the change reads as the one-line diff it is.\n */\nfunction writeStyle(root: string, style: string): void {\n const configPath = path.join(root, COMPONENTS_JSON);\n if (!existsSync(configPath)) {\n throw new Error(\n `${COMPONENTS_JSON} not found in ${root}; this does not look like a shadcn-svelte project.`,\n );\n }\n const text = readFileSync(configPath, \"utf8\");\n const config = JSON.parse(text) as Record<string, unknown>;\n config.style = style;\n const indent = text.includes(\"\\n\\t\") ? \"\\t\" : 2;\n writeFileSync(\n configPath,\n `${JSON.stringify(config, null, indent)}\\n`,\n \"utf8\",\n );\n}\n\nfunction registryUiNames(index: RegistryItem[]): Set<string> {\n return new Set(\n index\n .filter((item) => item.type === \"registry:ui\")\n .map((item) => item.name),\n );\n}\n\n/**\n * Moves a project to another shadcn-svelte style. Every installed component\n * the new style's registry also offers is re-added from there (their local\n * edits are lost, which is what `confirm` is for); this package's own\n * components and anything the registry does not know are left alone. The\n * style's preset font follows unless `font` is false.\n */\nexport async function switchStyle(\n options: SwitchStyleOptions,\n runtime?: WriteResultRuntime,\n): Promise<SwitchStyleResult> {\n const { root, style, font = true } = options;\n const logger = getLogger(options);\n const preset = await loadPreset(root);\n assertOneOf(\"style\", style, preset.PRESET_STYLES);\n\n const unchanged: SwitchStyleResult = {\n status: \"unchanged\",\n style,\n reinstalled: [],\n filesModified: [],\n packages: [],\n hints: [],\n };\n if (readComponentsConfig(root).style === style) {\n return unchanged;\n }\n\n const index = await fetchRegistryIndex(root, { style, runtime });\n const offered = registryUiNames(index);\n const reinstall = installedComponents(root).filter(\n (component) => offered.has(component) && !isCustomComponent(component),\n );\n\n if (options.confirm && !(await options.confirm(reinstall))) {\n return { ...unchanged, status: \"cancelled\" };\n }\n\n const packagesBefore = installedPackagesFromProject(root);\n writeStyle(root, style);\n const filesModified = [COMPONENTS_JSON];\n\n let reinstalled: Component[] = [];\n if (reinstall.length > 0) {\n const outcome = await installComponents(\n { root, components: reinstall, overwrite: true, logger },\n runtime,\n );\n reinstalled = outcome.installed;\n }\n\n const hints: string[] = [];\n if (font) {\n await applyStyleFont(\n root,\n style,\n preset,\n runtime,\n filesModified,\n hints,\n logger,\n );\n }\n\n const packages = [...installedPackagesFromProject(root)]\n .filter((name) => !packagesBefore.has(name))\n .sort();\n\n return {\n status: \"switched\",\n style,\n reinstalled,\n filesModified,\n packages,\n hints,\n };\n}\n\nconst FONTSOURCE_IMPORT =\n /@import\\s+[\"']@fontsource(?:-variable)?\\/([^\"']+)[\"']/g;\n\n/** The fontsource families a stylesheet imports, in order. */\nfunction fontsourceImports(css: string): string[] {\n return [...css.matchAll(FONTSOURCE_IMPORT)].map((match) => match[1]!);\n}\n\nasync function applyStyleFont(\n root: string,\n style: string,\n preset: ShadcnPreset,\n runtime: WriteResultRuntime | undefined,\n filesModified: string[],\n hints: string[],\n logger: ReturnType<typeof getLogger>,\n): Promise<void> {\n const fonts = STYLE_FONTS[style];\n if (!fonts) {\n logger.info(\n `No preset font is known for the ${style} style; leaving fonts unchanged.`,\n );\n return;\n }\n logger.info(`Applying the ${style} font (${fonts.font})`);\n const code = await presetFor(root, { style, ...fonts }, preset);\n await applyPreset(root, code, [\"font\"], runtime);\n\n const cssPath = readComponentsConfig(root).cssPath;\n filesModified.push(cssPath, \"package.json\");\n\n // `apply --only font` adds the new font beside whatever was imported before\n // and leaves it to the project to drop the old one; a font nobody uses\n // still ships to every visitor.\n const cssFile = path.join(root, cssPath);\n if (existsSync(cssFile)) {\n const wanted = new Set([fonts.font, fonts.fontHeading].filter(Boolean));\n const stale = fontsourceImports(readFileSync(cssFile, \"utf8\")).filter(\n (family) => !wanted.has(family),\n );\n if (stale.length > 0) {\n hints.push(\n `${cssPath} still imports ${stale.map((f) => `@fontsource-variable/${f}`).join(\", \")} from the previous style; remove the import and the package if nothing else uses them.`,\n );\n }\n }\n}\n\nasync function applyColors(\n root: string,\n overrides: { baseColor?: string; theme: string },\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n const preset = await loadPreset(root);\n if (overrides.baseColor) {\n assertOneOf(\n \"base color\",\n overrides.baseColor,\n preset.PRESET_BASE_COLOR_KEYS,\n );\n }\n assertOneOf(\"theme\", overrides.theme, preset.PRESET_THEME_KEYS);\n\n // Charts follow the accent, as shadcn-svelte's own presets do.\n const code = await presetFor(\n root,\n { ...overrides, chartColor: overrides.theme },\n preset,\n );\n await applyPreset(root, code, [\"theme\"], runtime);\n\n const config = readComponentsConfig(root);\n return {\n baseColor: config.baseColor ?? overrides.baseColor ?? \"\",\n theme: overrides.theme,\n filesModified: [config.cssPath, COMPONENTS_JSON],\n };\n}\n\n/**\n * Sets the base (gray) palette. The accent is reset to the base color as\n * well, since `components.json` records only the base color; `applyTheme`\n * puts an accent back on top.\n */\nexport async function applyBaseColor(\n options: ApplyBaseColorOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(\n options.root,\n { baseColor: options.color, theme: options.color },\n runtime,\n );\n}\n\n/** Sets the accent (primary, ring, charts) and keeps the base palette. */\nexport async function applyTheme(\n options: ApplyThemeOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(options.root, { theme: options.theme }, runtime);\n}\n"],"mappings":";;;;;;;;;AA2CA,eAAsBU,EAAW,GAAqC;CACpE,IAAIC;CACJ,IAAI;EACF,IAAWC,EAAcH,EAAK,KAAKI,GAAM,cAAc,CAAC,CAAC,CAAC,QACxD,sBACF;CACF,SAASC,GAAO;EACd,IAAMC,IAASD,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK;EACpE,MAAU,MACR,4CAA4CD,EAAK,IAAIE,EAAO,2EAE9D;CACF;CAIA,OAAO,MAHuB;;EACTC,EAAcL,CAAQ,CAAC,CAAC;;AAG/C;AAQA,IAAaM,IAGT;CACF,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,UAAU;CACxB,MAAM,EAAE,MAAM,iBAAiB;CAC/B,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM;EAAE,MAAM;EAAa,aAAa;CAAmB;CAC3D,MAAM,EAAE,MAAM,QAAQ;AACxB;AASA,eAAsBC,EACpB,GACA,GACA,GACiB;CACjB,IAAM,EAAE,oBAAiBC,KAAW,MAAMT,EAAWG,CAAI,GACnDO,IAASnB,EAAqBY,CAAI,GAClCQ,IAAiC,EAAE,OAAOD,EAAO,MAAM;CAK7D,OAJIA,EAAO,cAAW,EAAQ,YAAYA,EAAO,YAC7CA,EAAO,gBAAa,EAAQ,cAAcA,EAAO,cACjDA,EAAO,cAAW,EAAQ,YAAYA,EAAO,YAC7CA,EAA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