@velastack/patterns 0.2.10 → 0.2.12

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 (98) hide show
  1. package/dist/chunks/{_layout-D0OmzCu1.js → _layout-DqH4lA_r.js} +8 -8
  2. package/dist/chunks/{_layout-D0OmzCu1.js.map → _layout-DqH4lA_r.js.map} +1 -1
  3. package/dist/chunks/{collections-DDYlpDNO.js → collections-CcL5bbBk.js} +2 -2
  4. package/dist/chunks/{collections-DDYlpDNO.js.map → collections-CcL5bbBk.js.map} +1 -1
  5. package/dist/chunks/compose-handle-D16KmBVd.js +322 -0
  6. package/dist/chunks/compose-handle-D16KmBVd.js.map +1 -0
  7. package/dist/chunks/{config-target-DOi8kI_f.js → config-target-Co-ij8p3.js} +9 -9
  8. package/dist/chunks/{config-target-DOi8kI_f.js.map → config-target-Co-ij8p3.js.map} +1 -1
  9. package/dist/chunks/format-result-Cb2hWsb8.js +64 -0
  10. package/dist/chunks/format-result-Cb2hWsb8.js.map +1 -0
  11. package/dist/chunks/{generate.runtime-AjCpCfv3.js → generate.runtime-1gbaOucO.js} +144 -137
  12. package/dist/chunks/generate.runtime-1gbaOucO.js.map +1 -0
  13. package/dist/chunks/{generate.runtime-BpYOznG5.js → generate.runtime-A8wfItN7.js} +21 -21
  14. package/dist/chunks/{generate.runtime-BpYOznG5.js.map → generate.runtime-A8wfItN7.js.map} +1 -1
  15. package/dist/chunks/{generate.runtime-BtX_9lLk.js → generate.runtime-BL7uKgW7.js} +33 -33
  16. package/dist/chunks/{generate.runtime-BtX_9lLk.js.map → generate.runtime-BL7uKgW7.js.map} +1 -1
  17. package/dist/chunks/{generate.runtime-BYJZB1ad.js → generate.runtime-BX53l-rL.js} +37 -57
  18. package/dist/chunks/generate.runtime-BX53l-rL.js.map +1 -0
  19. package/dist/chunks/{generate.runtime-DEl6b1Ti.js → generate.runtime-Bb64J0ab.js} +15 -15
  20. package/dist/chunks/{generate.runtime-DEl6b1Ti.js.map → generate.runtime-Bb64J0ab.js.map} +1 -1
  21. package/dist/chunks/{generate.runtime-DRcq4d5D.js → generate.runtime-BbNMkG4j.js} +27 -27
  22. package/dist/chunks/{generate.runtime-DRcq4d5D.js.map → generate.runtime-BbNMkG4j.js.map} +1 -1
  23. package/dist/chunks/{generate.runtime-BgezGu15.js → generate.runtime-BdPtilz4.js} +94 -93
  24. package/dist/chunks/generate.runtime-BdPtilz4.js.map +1 -0
  25. package/dist/chunks/{generate.runtime-DH9o-888.js → generate.runtime-BqxVaq5P.js} +24 -24
  26. package/dist/chunks/{generate.runtime-DH9o-888.js.map → generate.runtime-BqxVaq5P.js.map} +1 -1
  27. package/dist/chunks/{generate.runtime-fSDNxfGG.js → generate.runtime-CJVy-mMN.js} +11 -11
  28. package/dist/chunks/{generate.runtime-fSDNxfGG.js.map → generate.runtime-CJVy-mMN.js.map} +1 -1
  29. package/dist/chunks/generate.runtime-CN3v78hx.js +82 -0
  30. package/dist/chunks/generate.runtime-CN3v78hx.js.map +1 -0
  31. package/dist/chunks/generate.runtime-CSXj-ebM.js +122 -0
  32. package/dist/chunks/generate.runtime-CSXj-ebM.js.map +1 -0
  33. package/dist/chunks/{generate.runtime-B6kxV3Bi.js → generate.runtime-CVLtEsXb.js} +28 -28
  34. package/dist/chunks/{generate.runtime-B6kxV3Bi.js.map → generate.runtime-CVLtEsXb.js.map} +1 -1
  35. package/dist/chunks/{generate.runtime-B_Fk1Jjs.js → generate.runtime-CiTmbkAk.js} +31 -34
  36. package/dist/chunks/{generate.runtime-B_Fk1Jjs.js.map → generate.runtime-CiTmbkAk.js.map} +1 -1
  37. package/dist/chunks/{generate.runtime-OjW1XETW.js → generate.runtime-CwzHEcKv.js} +33 -33
  38. package/dist/chunks/{generate.runtime-OjW1XETW.js.map → generate.runtime-CwzHEcKv.js.map} +1 -1
  39. package/dist/chunks/{generate.runtime-SQhCLSah.js → generate.runtime-DAkg7Fy5.js} +13 -13
  40. package/dist/chunks/{generate.runtime-SQhCLSah.js.map → generate.runtime-DAkg7Fy5.js.map} +1 -1
  41. package/dist/chunks/{generate.runtime-DK7iXmAZ.js → generate.runtime-DPIH5sSI.js} +17 -17
  42. package/dist/chunks/{generate.runtime-DK7iXmAZ.js.map → generate.runtime-DPIH5sSI.js.map} +1 -1
  43. package/dist/chunks/{generate.runtime-CTiJEVF2.js → generate.runtime-Dj22Kx0W.js} +31 -31
  44. package/dist/chunks/{generate.runtime-CTiJEVF2.js.map → generate.runtime-Dj22Kx0W.js.map} +1 -1
  45. package/dist/chunks/{generate.runtime-CycY6kPr.js → generate.runtime-DnWw9tL1.js} +41 -41
  46. package/dist/chunks/{generate.runtime-CycY6kPr.js.map → generate.runtime-DnWw9tL1.js.map} +1 -1
  47. package/dist/chunks/{generate.runtime-DHRCNPVx.js → generate.runtime-Dx8Mcs2i.js} +27 -27
  48. package/dist/chunks/{generate.runtime-DHRCNPVx.js.map → generate.runtime-Dx8Mcs2i.js.map} +1 -1
  49. package/dist/chunks/{generate.runtime-Cq1gqxzg.js → generate.runtime-Dywp4xth.js} +22 -22
  50. package/dist/chunks/{generate.runtime-Cq1gqxzg.js.map → generate.runtime-Dywp4xth.js.map} +1 -1
  51. package/dist/chunks/{generate.runtime-Dmwhwgji.js → generate.runtime-T9DZJH8m.js} +65 -38
  52. package/dist/chunks/generate.runtime-T9DZJH8m.js.map +1 -0
  53. package/dist/chunks/{generate.runtime-vTneb2SY.js → generate.runtime-Zh5n8XpR.js} +45 -45
  54. package/dist/chunks/{generate.runtime-vTneb2SY.js.map → generate.runtime-Zh5n8XpR.js.map} +1 -1
  55. package/dist/chunks/{generate.runtime-CZQoVNt3.js → generate.runtime-d9HT4v-7.js} +33 -33
  56. package/dist/chunks/{generate.runtime-CZQoVNt3.js.map → generate.runtime-d9HT4v-7.js.map} +1 -1
  57. package/dist/chunks/{generate.runtime-Dtf2BI_5.js → generate.runtime-j1gfY6Xq.js} +9 -9
  58. package/dist/chunks/{generate.runtime-Dtf2BI_5.js.map → generate.runtime-j1gfY6Xq.js.map} +1 -1
  59. package/dist/chunks/generate.runtime-l-Tiahb2.js +170 -0
  60. package/dist/chunks/generate.runtime-l-Tiahb2.js.map +1 -0
  61. package/dist/chunks/modify-file-BlWTOkCH.js +212 -0
  62. package/dist/chunks/modify-file-BlWTOkCH.js.map +1 -0
  63. package/dist/chunks/{modify-svelte-config-remote-D3eBzcZc.js → modify-svelte-config-remote-CDKs_Qi0.js} +2 -2
  64. package/dist/chunks/{modify-svelte-config-remote-D3eBzcZc.js.map → modify-svelte-config-remote-CDKs_Qi0.js.map} +1 -1
  65. package/dist/chunks/{pocketbase-BerjVikJ.js → pocketbase-ewxQLtse.js} +16 -16
  66. package/dist/chunks/{pocketbase-BerjVikJ.js.map → pocketbase-ewxQLtse.js.map} +1 -1
  67. package/dist/chunks/{shared-Cmbzu7Od.js → shared-Bm3eMFy-.js} +2 -2
  68. package/dist/chunks/{shared-Cmbzu7Od.js.map → shared-Bm3eMFy-.js.map} +1 -1
  69. package/dist/chunks/svelte-file-B3RfgVdt.js +123 -0
  70. package/dist/chunks/svelte-file-B3RfgVdt.js.map +1 -0
  71. package/dist/chunks/{test-setup-DjbhQYZC.js → test-setup-B2hd8I-s.js} +15 -15
  72. package/dist/chunks/{test-setup-DjbhQYZC.js.map → test-setup-B2hd8I-s.js.map} +1 -1
  73. package/dist/chunks/{ui-BdkuOXPw.js → ui-CD-psDWi.js} +12 -12
  74. package/dist/chunks/{ui-BdkuOXPw.js.map → ui-CD-psDWi.js.map} +1 -1
  75. package/dist/chunks/ui-jhXrsw4T.js +12 -0
  76. package/dist/chunks/ui-jhXrsw4T.js.map +1 -0
  77. package/dist/chunks/{write-result-BVWPlGvE.js → write-result-DBKv-Q7J.js} +51 -51
  78. package/dist/chunks/{write-result-BVWPlGvE.js.map → write-result-DBKv-Q7J.js.map} +1 -1
  79. package/dist/index.d.ts +4 -3
  80. package/dist/index.js +1012 -1013
  81. package/dist/index.js.map +1 -1
  82. package/package.json +1 -1
  83. package/dist/chunks/format-result-BdAy5M8C.js +0 -50
  84. package/dist/chunks/format-result-BdAy5M8C.js.map +0 -1
  85. package/dist/chunks/generate.runtime-AjCpCfv3.js.map +0 -1
  86. package/dist/chunks/generate.runtime-BYJZB1ad.js.map +0 -1
  87. package/dist/chunks/generate.runtime-BcVAKzoY.js +0 -138
  88. package/dist/chunks/generate.runtime-BcVAKzoY.js.map +0 -1
  89. package/dist/chunks/generate.runtime-BgezGu15.js.map +0 -1
  90. package/dist/chunks/generate.runtime-D2WfvXm2.js +0 -106
  91. package/dist/chunks/generate.runtime-D2WfvXm2.js.map +0 -1
  92. package/dist/chunks/generate.runtime-DaPNrIyg.js +0 -28
  93. package/dist/chunks/generate.runtime-DaPNrIyg.js.map +0 -1
  94. package/dist/chunks/generate.runtime-Dmwhwgji.js.map +0 -1
  95. package/dist/chunks/modify-file-Cgu_WeFk.js +0 -22
  96. package/dist/chunks/modify-file-Cgu_WeFk.js.map +0 -1
  97. package/dist/chunks/ts-morph-helpers-teS3yXg-.js +0 -229
  98. package/dist/chunks/ts-morph-helpers-teS3yXg-.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"pocketbase-BerjVikJ.js","names":[],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n/**\n * Ports the Fetch spec tells clients to refuse outright\n * (https://fetch.spec.whatwg.org/#port-blocking). Node's `fetch` enforces the\n * list, so a server bound to one of them is unreachable from `waitForHealth`\n * and the PocketBase SDK alike: the request fails with cause \"bad port\"\n * before a connection is even attempted. 10080 sat inside the 10000–19999\n * range ports used to be drawn from, and cost a CI run a 30-second health\n * timeout whenever the draw landed on it.\n */\nexport const BAD_PORTS: ReadonlySet<number> = new Set([\n 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,\n 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,\n 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,\n 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,\n 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,\n 6679, 6697, 10080,\n]);\n\nfunction osAssignedPort(host: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, host, () => {\n const { port } = server.address() as net.AddressInfo;\n server.close(() => resolve(port));\n });\n });\n}\n\n/**\n * A port nothing is listening on right now, taken from the OS's ephemeral\n * range so it neither collides with whatever else the machine runs nor hits\n * `BAD_PORTS`. The port is released again before this resolves, so the\n * caller's server has to bind it promptly.\n */\nexport async function freePort(host: string): Promise<number> {\n for (;;) {\n const port = await osAssignedPort(host);\n if (!BAD_PORTS.has(port)) return port;\n }\n}\n\n// Wait for the port to be available. A cold `npx pocketbase-server` on a CI\n// runner can take well over the five seconds the old default allowed.\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 60,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n/**\n * `fetch` wraps the interesting part in `cause`: an errno error for a\n * connection that was refused, or a bare string such as \"bad port\" for a\n * request undici declined to make.\n */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const { cause } = error as Error & { cause?: unknown };\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n return code || cause.message || error.message;\n }\n if (cause !== undefined) return String(cause);\n return error.message;\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 60): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n let lastFailure = \"no attempt made\";\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n lastFailure = `HTTP ${response.status}`;\n } catch (error) {\n lastFailure = describeFetchError(error);\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(\n `Timed out waiting for health check at ${url}/api/health (last attempt: ${lastFailure})`,\n ),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { freePort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport { DATA_DIR, MIGRATIONS_DIR } from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = await freePort(host);\n const commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\n )!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n // Start the PocketBase server process. The package manager wrapper (`npx`)\n // spawns the real binary as a grandchild; put the tree in its own process\n // group so it can be killed as a whole, otherwise `pocketbase serve` outlives\n // us and keeps the data directory open.\n const detached = process.platform !== \"win32\";\n const serverProcess = spawn(command, args, {\n cwd,\n stdio: \"ignore\",\n detached,\n });\n\n // A wrapper that dies before the server listens (missing binary, bad\n // arguments) would otherwise only surface as a port timeout a minute later.\n const exited = new Promise<never>((_, reject) => {\n serverProcess.once(\"exit\", (code, signal) => {\n reject(\n new Error(\n `pocketbase-server exited before listening on ${host}:${port} (${signal ?? `code ${code}`})`,\n ),\n );\n });\n serverProcess.once(\"error\", reject);\n });\n\n try {\n // Wait for the server to be ready\n await Promise.race([\n (async () => {\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n })(),\n exited,\n ]);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process tree\n stopProcessTree(serverProcess, detached);\n }\n}\n\nfunction stopProcessTree(\n child: ReturnType<typeof spawn>,\n detached: boolean,\n): void {\n if (detached && child.pid) {\n try {\n process.kill(-child.pid, \"SIGTERM\");\n return;\n } catch {\n // Group already gone or unsupported; fall through to the plain kill.\n }\n }\n child.kill();\n}\n"],"mappings":";;;;;;;;;AAWA,IAAa,oBAAiC,IAAI,IAAI;CACpD;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CACzE;CAAI;CAAI;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACzE;CAAK;CAAK;CAAK;CAAK;CAAK;CAA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EAAY,GAAM,CAAI,GAC5B,MAAM,EAAc,UAAU,EAAK,GAAG,GAAM;EAC9C,EAAA,CAAG,GACH,CACF,CAAC;EAED,IAAM,IAAK,IAAI,EAAW,UAAU,EAAK,GAAG,GAAM;EAMlD,AALA,MAAM,EACJ,GACA,QAAQ,IAAI,4BACZ,QAAQ,IAAI,6BACd,GACA,MAAM,EAAG,CAAE;CACb,UAAU;EAER,EAAgB,GAAe,CAAQ;CACzC;AACF;AAEA,SAAS,EACP,GACA,GACM;CACN,IAAI,KAAY,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAAC,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
1
+ {"version":3,"file":"pocketbase-ewxQLtse.js","names":[],"sources":["../../src/runtime/net.ts","../../src/runtime/pocketbase.ts"],"sourcesContent":["import net from \"node:net\";\n\n/**\n * Ports the Fetch spec tells clients to refuse outright\n * (https://fetch.spec.whatwg.org/#port-blocking). Node's `fetch` enforces the\n * list, so a server bound to one of them is unreachable from `waitForHealth`\n * and the PocketBase SDK alike: the request fails with cause \"bad port\"\n * before a connection is even attempted. 10080 sat inside the 10000–19999\n * range ports used to be drawn from, and cost a CI run a 30-second health\n * timeout whenever the draw landed on it.\n */\nexport const BAD_PORTS: ReadonlySet<number> = new Set([\n 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,\n 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,\n 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,\n 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,\n 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,\n 6679, 6697, 10080,\n]);\n\nfunction osAssignedPort(host: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const server = net.createServer();\n server.unref();\n server.once(\"error\", reject);\n server.listen(0, host, () => {\n const { port } = server.address() as net.AddressInfo;\n server.close(() => resolve(port));\n });\n });\n}\n\n/**\n * A port nothing is listening on right now, taken from the OS's ephemeral\n * range so it neither collides with whatever else the machine runs nor hits\n * `BAD_PORTS`. The port is released again before this resolves, so the\n * caller's server has to bind it promptly.\n */\nexport async function freePort(host: string): Promise<number> {\n for (;;) {\n const port = await osAssignedPort(host);\n if (!BAD_PORTS.has(port)) return port;\n }\n}\n\n// Wait for the port to be available. A cold `npx pocketbase-server` on a CI\n// runner can take well over the five seconds the old default allowed.\nexport function waitForPort(\n port: number,\n host: string,\n maxAttempts = 60,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n\n const tryConnect = () => {\n attempts++;\n\n const socket = new net.Socket();\n\n const onError = () => {\n socket.destroy();\n\n if (attempts === maxAttempts) {\n reject(\n new Error(`Timed out waiting for port ${port} to be available`),\n );\n return;\n }\n\n setTimeout(tryConnect, 500);\n };\n\n socket.once(\"error\", onError);\n\n socket.connect(port, host, () => {\n socket.destroy();\n resolve();\n });\n };\n\n tryConnect();\n });\n}\n\n/**\n * `fetch` wraps the interesting part in `cause`: an errno error for a\n * connection that was refused, or a bare string such as \"bad port\" for a\n * request undici declined to make.\n */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error);\n const { cause } = error as Error & { cause?: unknown };\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n return code || cause.message || error.message;\n }\n if (cause !== undefined) return String(cause);\n return error.message;\n}\n\n// Wait for the health check to be successful\nexport function waitForHealth(url: string, maxAttempts = 60): Promise<void> {\n return new Promise((resolve, reject) => {\n let attempts = 0;\n let lastFailure = \"no attempt made\";\n\n const tryHealth = async () => {\n attempts++;\n\n try {\n const response = await fetch(`${url}/api/health`);\n if (response.status === 200) {\n resolve();\n return;\n }\n lastFailure = `HTTP ${response.status}`;\n } catch (error) {\n lastFailure = describeFetchError(error);\n }\n\n if (attempts === maxAttempts) {\n reject(\n new Error(\n `Timed out waiting for health check at ${url}/api/health (last attempt: ${lastFailure})`,\n ),\n );\n return;\n }\n\n setTimeout(tryHealth, 500);\n };\n\n tryHealth();\n });\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport PocketBase from \"pocketbase\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport { freePort, waitForPort, waitForHealth } from \"./net\";\nimport type { Options } from \"../core/types\";\nimport { DATA_DIR, MIGRATIONS_DIR } from \"../core/constants\";\n\n/**\n * PocketBase names migration files with a 1-second-resolution Unix timestamp\n * (e.g. `1776099881_created_users.js`). Two schema operations issued in the\n * same wall-clock second produce files that sort alphabetically by their\n * action/collection suffix — which reverses the intended order whenever a\n * later migration depends on an earlier one. Wait out the full second between\n * migration-producing calls so the timestamps stay distinct.\n */\nconst MIGRATION_DELAY_MS = 1100;\n\nexport function migrationDelay(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, MIGRATION_DELAY_MS));\n}\n\nexport function getMigrationFile(\n collectionName: string,\n action: \"created\" | \"deleted\" | \"updated\",\n options: Options,\n): string | undefined {\n const ending = `${action}_${collectionName}.js`;\n\n // find last file with ending in migrations dir\n const migrationFiles = readdirSync(\n path.join(options.root, MIGRATIONS_DIR),\n ).filter((file) => file.endsWith(ending));\n\n const migrationFile = migrationFiles.sort().pop();\n\n if (!migrationFile) {\n return undefined;\n }\n\n return path.join(options.root, MIGRATIONS_DIR, migrationFile);\n}\n\nexport function getPocketbaseMetadata(cwd: string): {\n pocketbaseUrl: string;\n vitePort: number;\n} | null {\n const metadataPath = path.join(\n cwd,\n \"node_modules\",\n \".vite\",\n \"_pocketbase_metadata.json\",\n );\n if (existsSync(metadataPath)) {\n return JSON.parse(readFileSync(metadataPath, \"utf8\"));\n }\n return null;\n}\n\nexport async function authWithRetries(\n pb: PocketBase,\n email: string,\n password: string,\n) {\n // Retry authentication up to 3 times with 100ms backoff\n let authSuccess = false;\n for (let attempt = 1; attempt <= 3; attempt++) {\n try {\n await pb.collection(\"_superusers\").authWithPassword(email, password);\n authSuccess = true;\n break;\n } catch {\n if (attempt < 3) {\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n }\n }\n\n if (!authSuccess) {\n throw new Error(\n \"Failed to authenticate with PocketBase. Check your superuser credentials.\",\n );\n }\n}\n\nexport async function withPocketbase(\n cwd: string,\n fn: (pb: PocketBase) => Promise<void>,\n) {\n const dir = path.join(cwd, DATA_DIR);\n const migrationsDir = path.join(cwd, MIGRATIONS_DIR);\n const host = \"localhost\";\n\n if (!existsSync(dir)) {\n throw new Error(\"PocketBase data directory does not exist\");\n }\n\n // First check if the server is already running by reading node_modules/.vite/_pocketbase_metadata.json\n const metadata = getPocketbaseMetadata(cwd);\n if (metadata) {\n if (metadata.pocketbaseUrl) {\n const pb = new PocketBase(metadata.pocketbaseUrl);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n return;\n }\n }\n\n const port = await freePort(host);\n const commandArgs = [\n \"pocketbase-server\",\n \"serve\",\n \"--dir\",\n dir,\n \"--migrationsDir\",\n migrationsDir,\n \"--http\",\n `${host}:${port}`,\n ];\n\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n const { command, args } = resolveCommand(\n packageManager,\n \"execute\",\n commandArgs,\n )!;\n\n // adding --yes as the first parameter helps avoiding the \"Need to install the following packages:\" message\n if (packageManager === \"npm\") args.unshift(\"--yes\");\n\n // Start the PocketBase server process. The package manager wrapper (`npx`)\n // spawns the real binary as a grandchild; put the tree in its own process\n // group so it can be killed as a whole, otherwise `pocketbase serve` outlives\n // us and keeps the data directory open.\n const detached = process.platform !== \"win32\";\n const serverProcess = spawn(command, args, {\n cwd,\n stdio: \"ignore\",\n detached,\n });\n\n // A wrapper that dies before the server listens (missing binary, bad\n // arguments) would otherwise only surface as a port timeout a minute later.\n const exited = new Promise<never>((_, reject) => {\n serverProcess.once(\"exit\", (code, signal) => {\n reject(\n new Error(\n `pocketbase-server exited before listening on ${host}:${port} (${signal ?? `code ${code}`})`,\n ),\n );\n });\n serverProcess.once(\"error\", reject);\n });\n\n try {\n // Wait for the server to be ready\n await Promise.race([\n (async () => {\n await waitForPort(port, host);\n await waitForHealth(`http://${host}:${port}`);\n })(),\n exited,\n ]);\n\n const pb = new PocketBase(`http://${host}:${port}`);\n await authWithRetries(\n pb,\n process.env.POCKETBASE_SUPERUSER_EMAIL!,\n process.env.POCKETBASE_SUPERUSER_PASSWORD!,\n );\n await fn(pb);\n } finally {\n // Ensure we always clean up the process tree\n stopProcessTree(serverProcess, detached);\n }\n}\n\nfunction stopProcessTree(\n child: ReturnType<typeof spawn>,\n detached: boolean,\n): void {\n if (detached && child.pid) {\n try {\n process.kill(-child.pid, \"SIGTERM\");\n return;\n } catch {\n // Group already gone or unsupported; fall through to the plain kill.\n }\n }\n child.kill();\n}\n"],"mappings":";;;;;;;;;AAWA,IAAa,oBAAiC,IAAI,IAAI;CACpD;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CACzE;CAAI;CAAI;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACzE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CACtE;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAM;CAAM;CACxE;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CACxE;CAAM;CAAM;AACd,CAAC;AAED,SAAS,EAAe,GAA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,CAAQ;CACzC;AACF;AAEA,SAAS,EACP,GACA,GACM;CACN,IAAI,KAAY,EAAM,KACpB,IAAI;EACF,QAAQ,KAAK,CAAC,EAAM,KAAK,SAAS;EAClC;CACF,QAAQ,CAER;CAEF,EAAM,KAAK;AACb"}
@@ -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-BerjVikJ.js"), { planCollectionDrops: r } = await import("./collections-DDYlpDNO.js"), i = [];
18
+ let { withPocketbase: n } = await import("./pocketbase-ewxQLtse.js"), { planCollectionDrops: r } = await import("./collections-CcL5bbBk.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-Cmbzu7Od.js.map
27
+ //# sourceMappingURL=shared-Bm3eMFy-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared-Cmbzu7Od.js","names":[],"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,SAAgB,EAAc,GAAoB;CAChD,OAAO;EACL;EACA,UAAU,EAAiB,CAAI;EAC/B,SAAS;EACT,QAAQ;CACV;AACF;AAOA,eAAsB,EACpB,GACA,GAC+B;CAC/B,IAAI,EAAgB,WAAW,GAAG,OAAO,CAAC;CAE1C,IAAI,EAAQ,QAAQ,WAClB,OAAO,EAAgB,KAAK,OAAU;EACpC;EACA,QAAQ;EACR,UAAU;CACZ,EAAE;CAGJ,IAAM,EAAE,sBAAmB,MAAM,OAAO,6BAClC,EAAE,2BAAwB,MAAM,OAAO,8BACvC,IAA8B,CAAC;CAKrC,OAJA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,IAAM,IAAQ,MAAM,EAAoB,GAAI,CAAe;EAC3D,EAAM,KAAK,GAAG,CAAK;CACrB,CAAC,GACM;AACT"}
1
+ {"version":3,"file":"shared-Bm3eMFy-.js","names":[],"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,SAAgB,EAAc,GAAoB;CAChD,OAAO;EACL;EACA,UAAU,EAAiB,CAAI;EAC/B,SAAS;EACT,QAAQ;CACV;AACF;AAOA,eAAsB,EACpB,GACA,GAC+B;CAC/B,IAAI,EAAgB,WAAW,GAAG,OAAO,CAAC;CAE1C,IAAI,EAAQ,QAAQ,WAClB,OAAO,EAAgB,KAAK,OAAU;EACpC;EACA,QAAQ;EACR,UAAU;CACZ,EAAE;CAGJ,IAAM,EAAE,sBAAmB,MAAM,OAAO,6BAClC,EAAE,2BAAwB,MAAM,OAAO,8BACvC,IAA8B,CAAC;CAKrC,OAJA,MAAM,EAAe,EAAQ,MAAM,OAAO,MAAO;EAC/C,IAAM,IAAQ,MAAM,EAAoB,GAAI,CAAe;EAC3D,EAAM,KAAK,GAAG,CAAK;CACrB,CAAC,GACM;AACT"}
@@ -0,0 +1,123 @@
1
+ import e from "node:fs";
2
+ import { parse as t } from "svelte/compiler";
3
+ import n from "magic-string";
4
+ //#region src/runtime/svelte-file.ts
5
+ var r = class r {
6
+ constructor(e) {
7
+ this.source = e, this.ast = t(e, { modern: !0 }), this.s = new n(e);
8
+ }
9
+ static fromPath(t) {
10
+ return new r(e.readFileSync(t, "utf8"));
11
+ }
12
+ getScript() {
13
+ return this.scriptInner(this.ast.instance);
14
+ }
15
+ getModuleScript() {
16
+ return this.scriptInner(this.ast.module);
17
+ }
18
+ scriptInner(e) {
19
+ if (!e) return null;
20
+ let t = e.content.start, n = e.content.end;
21
+ return {
22
+ content: this.source.slice(t, n),
23
+ start: t,
24
+ end: n
25
+ };
26
+ }
27
+ modifyScript(e) {
28
+ return this.modifyScriptBlock(this.getScript(), e);
29
+ }
30
+ modifyModuleScript(e) {
31
+ return this.modifyScriptBlock(this.getModuleScript(), e);
32
+ }
33
+ modifyScriptBlock(e, t) {
34
+ if (!e) return !1;
35
+ let n = t(e.content);
36
+ return n !== e.content && (this.s.overwrite(e.start, e.end, n), !0);
37
+ }
38
+ findElement(e) {
39
+ return i(this.ast.fragment, (t) => (t.type === "Component" || t.type === "RegularElement") && t.name === e);
40
+ }
41
+ hasElement(e) {
42
+ return this.findElement(e) !== null;
43
+ }
44
+ hasAttribute(e, t) {
45
+ let n = this.findElement(e);
46
+ return n ? (n.attributes ?? []).some((e) => e.type === "Attribute" && e.name === t) : !1;
47
+ }
48
+ insertBeforeClosingTag(e, t) {
49
+ let n = this.findElement(e);
50
+ if (!n) return !1;
51
+ let r = `</${e}>`, i = this.source.lastIndexOf(r, n.end);
52
+ return i !== -1 && (this.s.appendLeft(i, t), !0);
53
+ }
54
+ replaceElement(e, t) {
55
+ let n = this.findElement(e);
56
+ return n ? (this.s.overwrite(n.start, n.end, t), !0) : !1;
57
+ }
58
+ removeElement(e) {
59
+ return this.replaceElement(e, "");
60
+ }
61
+ appendMarkup(e) {
62
+ this.s.append(e);
63
+ }
64
+ insertBeforeChildren(e) {
65
+ let t = this.ast.fragment?.nodes ?? [], n = t.findIndex((e) => e.type === "RenderTag" || e.type === "SlotElement" || e.type === "RegularElement" && e.name === "slot");
66
+ if (n === -1) return !1;
67
+ let r = e.trim();
68
+ for (let e = n - 1; e >= 0; e--) {
69
+ let n = t[e];
70
+ if (n.type !== "Text" || n.data.trim() !== "") return this.s.appendLeft(n.end, `\n${r}`), !0;
71
+ }
72
+ return this.s.appendLeft(t[n].start, `${r}\n\n`), !0;
73
+ }
74
+ appendToAttributes(e, t) {
75
+ let n = this.findElement(e);
76
+ if (!n) return !1;
77
+ let r = (n.attributes ?? []).at(-1), i = r ? r.end : n.start + `<${e}`.length;
78
+ return this.s.appendLeft(i, t), !0;
79
+ }
80
+ removeAttribute(e, t) {
81
+ let n = this.findElement(e);
82
+ if (!n) return !1;
83
+ let r = (n.attributes ?? []).find((e) => e.type === "Attribute" && e.name === t);
84
+ if (!r) return !1;
85
+ let i = r.start;
86
+ for (; i > 0 && /\s/.test(this.source[i - 1]);) i--;
87
+ return this.s.remove(i, r.end), !0;
88
+ }
89
+ hasChanged() {
90
+ return this.s.hasChanged();
91
+ }
92
+ toString() {
93
+ return this.s.toString();
94
+ }
95
+ writeTo(t) {
96
+ this.hasChanged() && e.writeFileSync(t, this.toString(), "utf8");
97
+ }
98
+ };
99
+ function i(e, t) {
100
+ let n = /* @__PURE__ */ new WeakSet();
101
+ function r(e) {
102
+ if (!e || typeof e != "object" || n.has(e)) return null;
103
+ if (n.add(e), t(e)) return e;
104
+ for (let t of Object.keys(e)) {
105
+ if (t === "parent") continue;
106
+ let n = e[t];
107
+ if (Array.isArray(n)) for (let e of n) {
108
+ let t = r(e);
109
+ if (t) return t;
110
+ }
111
+ else if (n && typeof n == "object" && "type" in n) {
112
+ let e = r(n);
113
+ if (e) return e;
114
+ }
115
+ }
116
+ return null;
117
+ }
118
+ return r(e);
119
+ }
120
+ //#endregion
121
+ export { r as t };
122
+
123
+ //# sourceMappingURL=svelte-file-B3RfgVdt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"svelte-file-B3RfgVdt.js","names":[],"sources":["../../src/runtime/svelte-file.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { parse, type AST } from \"svelte/compiler\";\nimport MagicString from \"magic-string\";\n\ntype SvelteAst = AST.Root;\ntype SvelteNode = any;\n\ninterface ScriptBlock {\n content: string;\n start: number;\n end: number;\n}\n\n/**\n * Surgical, AST-aware editing of .svelte files.\n *\n * Parses the source with svelte/compiler to discover precise character offsets,\n * then applies edits via magic-string so untouched regions remain byte-for-byte\n * identical to the original. Script-block contents are exposed as plain strings\n * so callers can hand them to ts-morph.\n */\nexport class SvelteFile {\n private readonly source: string;\n private readonly ast: SvelteAst;\n private readonly s: MagicString;\n\n constructor(source: string) {\n this.source = source;\n this.ast = parse(source, { modern: true });\n this.s = new MagicString(source);\n }\n\n static fromPath(filePath: string): SvelteFile {\n return new SvelteFile(fs.readFileSync(filePath, \"utf8\"));\n }\n\n getScript(): ScriptBlock | null {\n return this.scriptInner((this.ast as any).instance);\n }\n\n getModuleScript(): ScriptBlock | null {\n return this.scriptInner((this.ast as any).module);\n }\n\n private scriptInner(script: SvelteNode | null): ScriptBlock | null {\n if (!script) return null;\n const start = script.content.start as number;\n const end = script.content.end as number;\n return { content: this.source.slice(start, end), start, end };\n }\n\n /**\n * Replace the inner contents of <script>. Use for ts-morph round-trips.\n * Returns true when an edit was made.\n */\n modifyScript(fn: (content: string) => string): boolean {\n return this.modifyScriptBlock(this.getScript(), fn);\n }\n\n modifyModuleScript(fn: (content: string) => string): boolean {\n return this.modifyScriptBlock(this.getModuleScript(), fn);\n }\n\n private modifyScriptBlock(\n block: ScriptBlock | null,\n fn: (content: string) => string,\n ): boolean {\n if (!block) return false;\n const next = fn(block.content);\n if (next === block.content) return false;\n this.s.overwrite(block.start, block.end, next);\n return true;\n }\n\n /** First Component or RegularElement node with the given name. */\n findElement(name: string): SvelteNode | null {\n return findNode(\n (this.ast as any).fragment,\n (node) =>\n (node.type === \"Component\" || node.type === \"RegularElement\") &&\n node.name === name,\n );\n }\n\n hasElement(name: string): boolean {\n return this.findElement(name) !== null;\n }\n\n hasAttribute(componentName: string, attrName: string): boolean {\n const node = this.findElement(componentName);\n if (!node) return false;\n return (node.attributes ?? []).some(\n (attr: SvelteNode) => attr.type === \"Attribute\" && attr.name === attrName,\n );\n }\n\n /**\n * Insert content at the end of <ComponentName>'s children, just before the\n * closing tag. No-op if the element is not found.\n */\n insertBeforeClosingTag(name: string, content: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const closingTag = `</${name}>`;\n const closingPos = this.source.lastIndexOf(closingTag, node.end);\n if (closingPos === -1) return false;\n this.s.appendLeft(closingPos, content);\n return true;\n }\n\n /** Replace the element entirely (start tag through close tag). */\n replaceElement(name: string, newContent: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n this.s.overwrite(node.start, node.end, newContent);\n return true;\n }\n\n /** Remove the element (start tag through close tag). */\n removeElement(name: string): boolean {\n return this.replaceElement(name, \"\");\n }\n\n /** Append raw markup to the end of the source file. */\n appendMarkup(content: string): void {\n this.s.append(content);\n }\n\n /**\n * Insert markup so it renders before the layout's children — i.e. ahead of\n * the top-level `{@render children()}` (or legacy `<slot />`). The markup\n * lands on its own line directly after the preceding sibling, so\n *\n * <Toaster />\n *\n * {@render children?.()}\n *\n * becomes `<Toaster />\\n<AdminBar />\\n\\n{@render children?.()}`. When the\n * render tag is the first node the markup goes immediately before it.\n * Returns false (and changes nothing) if no such tag exists.\n */\n insertBeforeChildren(content: string): boolean {\n const nodes: SvelteNode[] = (this.ast as any).fragment?.nodes ?? [];\n const index = nodes.findIndex(\n (node) =>\n node.type === \"RenderTag\" ||\n node.type === \"SlotElement\" ||\n (node.type === \"RegularElement\" && node.name === \"slot\"),\n );\n if (index === -1) return false;\n\n const trimmed = content.trim();\n for (let i = index - 1; i >= 0; i--) {\n const prev = nodes[i]!;\n if (prev.type === \"Text\" && prev.data.trim() === \"\") continue;\n this.s.appendLeft(prev.end as number, `\\n${trimmed}`);\n return true;\n }\n this.s.appendLeft(nodes[index]!.start as number, `${trimmed}\\n\\n`);\n return true;\n }\n\n /**\n * Append attribute text (e.g. \" team={data.team}\") just after the last\n * existing attribute on the element's start tag.\n */\n appendToAttributes(name: string, attrs: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const last = (node.attributes ?? []).at(-1) as SvelteNode | undefined;\n const insertAt = last\n ? (last.end as number)\n : (node.start as number) + `<${name}`.length;\n this.s.appendLeft(insertAt, attrs);\n return true;\n }\n\n /**\n * Remove a named attribute from a component's start tag, including the\n * leading whitespace. No-op if the element or attribute isn't present.\n */\n removeAttribute(name: string, attrName: string): boolean {\n const node = this.findElement(name);\n if (!node) return false;\n const attr = (node.attributes ?? []).find(\n (a: SvelteNode) => a.type === \"Attribute\" && a.name === attrName,\n );\n if (!attr) return false;\n // Extend the removal backwards over the whitespace between the previous\n // token and this attribute so the tag doesn't collapse `<Foo />`.\n let start = attr.start as number;\n while (start > 0 && /\\s/.test(this.source[start - 1]!)) start--;\n this.s.remove(start, attr.end as number);\n return true;\n }\n\n hasChanged(): boolean {\n return this.s.hasChanged();\n }\n\n toString(): string {\n return this.s.toString();\n }\n\n writeTo(filePath: string): void {\n if (this.hasChanged()) {\n fs.writeFileSync(filePath, this.toString(), \"utf8\");\n }\n }\n}\n\nfunction findNode(\n root: unknown,\n predicate: (node: any) => boolean,\n): any | null {\n const seen = new WeakSet<object>();\n function visit(node: unknown): any | null {\n if (!node || typeof node !== \"object\" || seen.has(node as object)) {\n return null;\n }\n seen.add(node as object);\n if (predicate(node as any)) return node;\n for (const key of Object.keys(node as Record<string, unknown>)) {\n if (key === \"parent\") continue;\n const child = (node as Record<string, unknown>)[key];\n if (Array.isArray(child)) {\n for (const item of child) {\n const found = visit(item);\n if (found) return found;\n }\n } else if (\n child &&\n typeof child === \"object\" &&\n \"type\" in (child as object)\n ) {\n const found = visit(child);\n if (found) return found;\n }\n }\n return null;\n }\n return visit(root);\n}\n"],"mappings":";;;;AAqBA,IAAa,IAAb,MAAa,EAAW;CAKtB,YAAY,GAAgB;EAG1B,AAFA,KAAK,SAAS,GACd,KAAK,MAAM,EAAM,GAAQ,EAAE,QAAQ,GAAK,CAAC,GACzC,KAAK,IAAI,IAAI,EAAY,CAAM;CACjC;CAEA,OAAO,SAAS,GAA8B;EAC5C,OAAO,IAAI,EAAW,EAAG,aAAa,GAAU,MAAM,CAAC;CACzD;CAEA,YAAgC;EAC9B,OAAO,KAAK,YAAa,KAAK,IAAY,QAAQ;CACpD;CAEA,kBAAsC;EACpC,OAAO,KAAK,YAAa,KAAK,IAAY,MAAM;CAClD;CAEA,YAAoB,GAA+C;EACjE,IAAI,CAAC,GAAQ,OAAO;EACpB,IAAM,IAAQ,EAAO,QAAQ,OACvB,IAAM,EAAO,QAAQ;EAC3B,OAAO;GAAE,SAAS,KAAK,OAAO,MAAM,GAAO,CAAG;GAAG;GAAO;EAAI;CAC9D;CAMA,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AAwB;EAC9B,AAAI,KAAK,WAAW,KAClB,EAAG,cAAc,GAAU,KAAK,SAAS,GAAG,MAAM;CAEtD;AACF;AAEA,SAAS,EACP,GACA,GACY;CACZ,IAAM,oBAAO,IAAI,QAAgB;CACjC,SAAS,EAAM,GAA2B;EACxC,IAAI,CAAC,KAAQ,OAAO,KAAS,YAAY,EAAK,IAAI,CAAc,GAC9D,OAAO;EAGT,IADA,EAAK,IAAI,CAAc,GACnB,EAAU,CAAW,GAAG,OAAO;EACnC,KAAK,IAAM,KAAO,OAAO,KAAK,CAA+B,GAAG;GAC9D,IAAI,MAAQ,UAAU;GACtB,IAAM,IAAS,EAAiC;GAChD,IAAI,MAAM,QAAQ,CAAK,GACrB,KAAK,IAAM,KAAQ,GAAO;IACxB,IAAM,IAAQ,EAAM,CAAI;IACxB,IAAI,GAAO,OAAO;GACpB;QACK,IACL,KACA,OAAO,KAAU,YACjB,UAAW,GACX;IACA,IAAM,IAAQ,EAAM,CAAK;IACzB,IAAI,GAAO,OAAO;GACpB;EACF;EACA,OAAO;CACT;CACA,OAAO,EAAM,CAAI;AACnB"}
@@ -1,7 +1,7 @@
1
1
  import { t as e } from "./dedent-Gq6Krl4n.js";
2
- import { o as t, s as n } from "./config-target-DOi8kI_f.js";
3
- import r from "node:path";
4
- import i from "node:fs";
2
+ import { o as t, s as n } from "./config-target-Co-ij8p3.js";
3
+ import r from "node:fs";
4
+ import i from "node:path";
5
5
  import { SyntaxKind as a } from "ts-morph";
6
6
  //#region src/patterns/enable/backend/modifies/svelte-config.ts
7
7
  var o = "@sveltejs/adapter-node", s = "@sveltejs/adapter-static", c = "@sveltejs/adapter-auto", l = e`
@@ -93,27 +93,27 @@ var h = "# PocketBase\n/data/*\n!/data/fixtures\n!/data/seeds\n!/data/hooks\n",
93
93
  !/data/hooks
94
94
  `;
95
95
  function _(e) {
96
- if (!i.existsSync(e)) return {
96
+ if (!r.existsSync(e)) return {
97
97
  status: "not-found",
98
98
  message: g
99
99
  };
100
- let t = i.readFileSync(e, "utf8");
100
+ let t = r.readFileSync(e, "utf8");
101
101
  if (t.includes("# PocketBase") && t.includes("/data/*")) return {
102
102
  status: "success",
103
103
  changed: !1
104
104
  };
105
105
  let n = t + (t.endsWith("\n") ? "\n" : "\n\n") + h;
106
- return i.writeFileSync(e, n, "utf8"), {
106
+ return r.writeFileSync(e, n, "utf8"), {
107
107
  status: "success",
108
108
  changed: !0
109
109
  };
110
110
  }
111
111
  function v(e) {
112
- if (!i.existsSync(e)) return {
112
+ if (!r.existsSync(e)) return {
113
113
  status: "success",
114
114
  changed: !1
115
115
  };
116
- let t = i.readFileSync(e, "utf8");
116
+ let t = r.readFileSync(e, "utf8");
117
117
  if (!t.includes("# PocketBase")) return {
118
118
  status: "success",
119
119
  changed: !1
@@ -122,7 +122,7 @@ function v(e) {
122
122
  return n === t ? {
123
123
  status: "success",
124
124
  changed: !1
125
- } : (i.writeFileSync(e, n, "utf8"), {
125
+ } : (r.writeFileSync(e, n, "utf8"), {
126
126
  status: "success",
127
127
  changed: !0
128
128
  });
@@ -131,22 +131,22 @@ function v(e) {
131
131
  //#region src/patterns/enable/backend/modifies/test-setup.ts
132
132
  var y = "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 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 context.user = await context.admin.collection('users').create({\n email: `test-${Math.random().toString(36).slice(2)}@example.com`,\n password: testUserPassword,\n passwordConfirm: testUserPassword\n });\n context.agent.authenticateUser = () => authenticateUser(context.agent, context.user);\n await context.pb.collection('users').authWithPassword(context.user.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", b = "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";
133
133
  function x(e) {
134
- return i.existsSync(e) ? i.readFileSync(e, "utf8") === y ? {
134
+ return r.existsSync(e) ? r.readFileSync(e, "utf8") === y ? {
135
135
  status: "success",
136
136
  changed: !1
137
- } : (i.writeFileSync(e, y, "utf8"), {
137
+ } : (r.writeFileSync(e, y, "utf8"), {
138
138
  status: "success",
139
139
  changed: !0
140
- }) : (i.mkdirSync(r.dirname(e), { recursive: !0 }), i.writeFileSync(e, y, "utf8"), {
140
+ }) : (r.mkdirSync(i.dirname(e), { recursive: !0 }), r.writeFileSync(e, y, "utf8"), {
141
141
  status: "success",
142
142
  changed: !0
143
143
  });
144
144
  }
145
145
  function S(e) {
146
- return !i.existsSync(e) || i.readFileSync(e, "utf8") === b ? {
146
+ return !r.existsSync(e) || r.readFileSync(e, "utf8") === b ? {
147
147
  status: "success",
148
148
  changed: !1
149
- } : (i.writeFileSync(e, b, "utf8"), {
149
+ } : (r.writeFileSync(e, b, "utf8"), {
150
150
  status: "success",
151
151
  changed: !0
152
152
  });
@@ -154,4 +154,4 @@ function S(e) {
154
154
  //#endregion
155
155
  export { p as a, v as i, S as n, m as o, _ as r, x as t };
156
156
 
157
- //# sourceMappingURL=test-setup-DjbhQYZC.js.map
157
+ //# sourceMappingURL=test-setup-B2hd8I-s.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"test-setup-DjbhQYZC.js","names":[],"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\";\n\nconst ADAPTER_NODE = \"@sveltejs/adapter-node\";\nconst ADAPTER_STATIC = \"@sveltejs/adapter-static\";\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 * whichever file holds the adapter import + `adapter()` call (vite.config when\n * the project uses inline config, else svelte.config). 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 — if no config or no adapter import is found, it's a no-op success.\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 !== \"resolved\") {\n // Nothing to revert — treat missing/unparseable config as a no-op.\n return {\n filePath: res.filePath,\n outcome: { status: \"success\", changed: false },\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\nconst 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\nexport function modifyTestSetup(testSetupPath: string): ModifyOutcome {\n if (!fs.existsSync(testSetupPath)) {\n // The static template has no test/ directory; a backend brings server\n // tests with it, so the setup is created rather than reported missing.\n fs.mkdirSync(path.dirname(testSetupPath), { recursive: true });\n fs.writeFileSync(testSetupPath, WITH_BACKEND, \"utf8\");\n return { status: \"success\", changed: true };\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":";;;;;;AASA,IAAM,IAAe,0BACf,IAAiB,4BACjB,IAAe,0BAEf,IAAe,CAAM;oCACS,EAAa;;yBAExB,EAAa;;;;GAMhC,IAAiB,CAAM;cACf,EAAa;;AAQ3B,SAAS,EAAkB,GAAwC;CACjE,OAAO,EACJ,sBAAsB,CAAC,CACvB,MAAM,MACL;EAAC;EAAgB;EAAc;CAAY,CAAC,CAAC,SAC3C,EAAK,wBAAwB,CAC/B,CACF;AACJ;AAEA,SAAS,EAAa,GAAwC;CAC5D,OAAO,EACJ,qBAAqB,EAAW,cAAc,CAAC,CAC/C,QAAQ,MAAO,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,SAAS;AAC9D;AAUA,SAAgB,EAAmB,GAAkC;CACnE,IAAM,IAAM,EAAoB,GAAM;EACpC,UAAU;EACV,QAAQ;CACV,CAAC;CACD,IAAI,EAAI,WAAW,YACjB,OAAO;EACL,UAAU,EAAI;EACd,SAAS;GAAE,QAAQ,EAAI;GAAQ,SAAS,EAAI;EAAQ;CACtD;CAEF,IAAM,EAAE,cAAW,GACb,IAAgB,EAAkB,EAAO,UAAU;CACzD,IAAI,CAAC,GACH,OAAO;E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}
1
+ {"version":3,"file":"test-setup-B2hd8I-s.js","names":[],"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\";\n\nconst ADAPTER_NODE = \"@sveltejs/adapter-node\";\nconst ADAPTER_STATIC = \"@sveltejs/adapter-static\";\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 * whichever file holds the adapter import + `adapter()` call (vite.config when\n * the project uses inline config, else svelte.config). 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 — if no config or no adapter import is found, it's a no-op success.\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 !== \"resolved\") {\n // Nothing to revert — treat missing/unparseable config as a no-op.\n return {\n filePath: res.filePath,\n outcome: { status: \"success\", changed: false },\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\nconst 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\nexport function modifyTestSetup(testSetupPath: string): ModifyOutcome {\n if (!fs.existsSync(testSetupPath)) {\n // The static template has no test/ directory; a backend brings server\n // tests with it, so the setup is created rather than reported missing.\n fs.mkdirSync(path.dirname(testSetupPath), { recursive: true });\n fs.writeFileSync(testSetupPath, WITH_BACKEND, \"utf8\");\n return { status: \"success\", changed: true };\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":";;;;;;AASA,IAAM,IAAe,0BACf,IAAiB,4BACjB,IAAe,0BAEf,IAAe,CAAM;oCACS,EAAa;;yBAExB,EAAa;;;;GAMhC,IAAiB,CAAM;cACf,EAAa;;AAQ3B,SAAS,EAAkB,GAAwC;CACjE,OAAO,EACJ,sBAAsB,CAAC,CACvB,MAAM,MACL;EAAC;EAAgB;EAAc;CAAY,CAAC,CAAC,SAC3C,EAAK,wBAAwB,CAC/B,CACF;AACJ;AAEA,SAAS,EAAa,GAAwC;CAC5D,OAAO,EACJ,qBAAqB,EAAW,cAAc,CAAC,CAC/C,QAAQ,MAAO,EAAG,cAAc,CAAC,CAAC,QAAQ,MAAM,SAAS;AAC9D;AAUA,SAAgB,EAAmB,GAAkC;CACnE,IAAM,IAAM,EAAoB,GAAM;EACpC,UAAU;EACV,QAAQ;CACV,CAAC;CACD,IAAI,EAAI,WAAW,YACjB,OAAO;EACL,UAAU,EAAI;EACd,SAAS;GAAE,QAAQ,EAAI;GAAQ,SAAS,EAAI;EAAQ;CACtD;CAEF,IAAM,EAAE,cAAW,GACb,IAAgB,EAAkB,EAAO,UAAU;CACzD,IAAI,CAAC,GACH,OAAO;EACL,UAAU,EAAO;EACjB,SAAS;GAAE,QAAQ;GAAU,SAAS;EAAa;CACrD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import { n } from "./logger-CQONztPm.js";
3
- import { executeCommand as r, formatPaths as i, getAllCustomComponents as a, installComponents as o, installedComponents as s, installedPackagesFromProject as c, isCustomComponent as l, n as u, t as d } from "./write-result-BVWPlGvE.js";
4
- import f from "node:path";
5
- import { existsSync as p, readFileSync as m, writeFileSync as h } from "node:fs";
3
+ import { executeCommand as r, formatPaths as i, getAllCustomComponents as a, installComponents as o, installedComponents as s, installedPackagesFromProject as c, isCustomComponent as l, n as u, t as d } from "./write-result-DBKv-Q7J.js";
4
+ import { existsSync as f, readFileSync as p, writeFileSync as m } from "node:fs";
5
+ import h from "node:path";
6
6
  import { createRequire as g } from "node:module";
7
7
  import { pathToFileURL as _ } from "node:url";
8
8
  //#region src/runtime/shadcn-preset.ts
9
9
  async function v(e) {
10
10
  let t;
11
11
  try {
12
- t = g(f.join(e, "package.json")).resolve("shadcn-svelte/preset");
12
+ t = g(h.join(e, "package.json")).resolve("shadcn-svelte/preset");
13
13
  } catch (t) {
14
14
  let n = t instanceof Error ? t.message : String(t);
15
15
  throw Error(`Could not load shadcn-svelte/preset from ${e}: ${n}\nInstall the project's dependencies (shadcn-svelte >= 1.6) and try again.`);
@@ -72,12 +72,12 @@ function w(e, n, r) {
72
72
  if (!r.includes(n)) throw new t(`Unknown ${e} "${n}". Choose one of: ${r.join(", ")}.`);
73
73
  }
74
74
  function T(e, t) {
75
- let n = f.join(e, S);
76
- if (!p(n)) throw Error(`${S} not found in ${e}; this does not look like a shadcn-svelte project.`);
77
- let r = m(n, "utf8"), i = JSON.parse(r);
75
+ let n = h.join(e, S);
76
+ if (!f(n)) throw Error(`${S} not found in ${e}; this does not look like a shadcn-svelte project.`);
77
+ let r = p(n, "utf8"), i = JSON.parse(r);
78
78
  i.style = t;
79
79
  let a = r.includes("\n ") ? " " : 2;
80
- h(n, `${JSON.stringify(i, null, a)}\n`, "utf8");
80
+ m(n, `${JSON.stringify(i, null, a)}\n`, "utf8");
81
81
  }
82
82
  function E(e) {
83
83
  return new Set(e.filter((e) => e.type === "registry:ui").map((e) => e.name));
@@ -139,9 +139,9 @@ async function A(e, t, n, r, i, a, o) {
139
139
  }, n), ["font"], r);
140
140
  let c = u(e).cssPath;
141
141
  i.push(c, "package.json");
142
- let l = f.join(e, c);
143
- if (p(l)) {
144
- let e = new Set([s.font, s.fontHeading].filter(Boolean)), t = k(m(l, "utf8")).filter((t) => !e.has(t));
142
+ let l = h.join(e, c);
143
+ if (f(l)) {
144
+ let e = new Set([s.font, s.fontHeading].filter(Boolean)), t = k(p(l, "utf8")).filter((t) => !e.has(t));
145
145
  t.length > 0 && a.push(`${c} still imports ${t.map((e) => `@fontsource-variable/${e}`).join(", ")} from the previous style; remove the import and the package if nothing else uses them.`);
146
146
  }
147
147
  }
@@ -170,4 +170,4 @@ async function N(e, t) {
170
170
  //#endregion
171
171
  export { M as applyBaseColor, N as applyTheme, C as listComponents, D as switchStyle };
172
172
 
173
- //# sourceMappingURL=ui-BdkuOXPw.js.map
173
+ //# sourceMappingURL=ui-CD-psDWi.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ui-BdkuOXPw.js","names":[],"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,eAAsB,EAAW,GAAqC;CACpE,IAAI;CACJ,IAAI;EACF,IAAW,EAAc,EAAK,KAAK,GAAM,cA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,CAAC;CAC3C,EAAc,KAAK,GAAS,cAAc;CAK1C,IAAM,IAAU,EAAK,KAAK,GAAM,CAAO;CACvC,IAAI,EAAW,CAAO,GAAG;EACvB,IAAM,IAAS,IAAI,IAAI,CAAC,EAAM,MAAM,EAAM,WAAW,CAAC,CAAC,OAAO,OAAO,CAAC,GAChE,IAAQ,EAAkB,EAAa,GAAS,MAAM,CAAC,CAAC,CAAC,QAC5D,MAAW,CAAC,EAAO,IAAI,CAAM,CAChC;EACA,AAAI,EAAM,SAAS,KACjB,EAAM,KACJ,GAAG,EAAQ,iBAAiB,EAAM,KAAK,MAAM,wBAAwB,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,uFACvF;CAEJ;AACF;AAEA,eAAe,EACb,GACA,GACA,GAC4B;CAC5B,IAAM,IAAS,MAAM,EAAW,CAAI;CAgBpC,AAfI,EAAU,aACZ,EACE,cACA,EAAU,WACV,EAAO,sBACT,GAEF,EAAY,SAAS,EAAU,OAAO,EAAO,iBAAiB,GAQ9D,MAAM,EAAY,GAAM,MALL,EACjB,GACA;EAAE,GAAG;EAAW,YAAY,EAAU;CAAM,GAC5C,CACF,GAC8B,CAAC,OAAO,GAAG,CAAO;CAEhD,IAAM,IAAS,EAAqB,CAAI;CACxC,OAAO;EACL,WAAW,EAAO,aAAa,EAAU,aAAa;EACtD,OAAO,EAAU;EACjB,eAAe,CAAC,EAAO,SAAS,CAAe;CACjD;AACF;AAOA,eAAsB,EACpB,GACA,GAC4B;CAC5B,OAAO,EACL,EAAQ,MACR;EAAE,WAAW,EAAQ;EAAO,OAAO,EAAQ;CAAM,GACjD,CACF;AACF;AAGA,eAAsB,EACpB,GACA,GAC4B;CAC5B,OAAO,EAAY,EAAQ,MAAM,EAAE,OAAO,EAAQ,MAAM,GAAG,CAAO;AACpE"}
1
+ {"version":3,"file":"ui-CD-psDWi.js","names":[],"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,eAAsB,EAAW,GAAqC;CACpE,IAAI;CACJ,IAAI;EACF,IAAW,EAAc,EAAK,KAAK,GAAM,cAAc,CAAC,CAAC,CAAC,QACxD,sBACF;CACF,SAAS,GAAO;EACd,IAAM,IAAS,aAAiB,QAAQ,EAAM,UAAU,OAAO,CAAK;EACpE,MAAU,MACR,4CAA4C,EAAK,IAAI,EAAO,2EAE9D;CACF;CAIA,OAAO,MAHuB;;EACT,EAAc,CAAQ,CAAC,CAAC;;AAG/C;AAQA,IAAa,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,eAAsB,EACpB,GACA,GACA,GACiB;CACjB,IAAM,EAAE,oBAAiB,KAAW,MAAM,EAAW,CAAI,GACnD,IAAS,EAAqB,CAAI,GAClC,IAAiC,EAAE,OAAO,EAAO,MAAM;CAK7D,OAJI,EAAO,cAAW,EAAQ,YAAY,EAAO,YAC7C,EAAO,gBAAa,EAAQ,cAAc,EAAO,cACjD,EAAO,cAAW,EAAQ,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qB,CAAI;CACxC,OAAO;EACL,WAAW,EAAO,aAAa,EAAU,aAAa;EACtD,OAAO,EAAU;EACjB,eAAe,CAAC,EAAO,SAAS,CAAe;CACjD;AACF;AAOA,eAAsB,EACpB,GACA,GAC4B;CAC5B,OAAO,EACL,EAAQ,MACR;EAAE,WAAW,EAAQ;EAAO,OAAO,EAAQ;CAAM,GACjD,CACF;AACF;AAGA,eAAsB,EACpB,GACA,GAC4B;CAC5B,OAAO,EAAY,EAAQ,MAAM,EAAE,OAAO,EAAQ,MAAM,GAAG,CAAO;AACpE"}
@@ -0,0 +1,12 @@
1
+ import { t as e } from "./errors-D6gyegUK.js";
2
+ //#region src/core/field/ui.ts
3
+ var t = ["shadcn", "plain"];
4
+ function n(n) {
5
+ let r = n.input.ui ?? n.features.ui ?? "shadcn";
6
+ if (!t.includes(r)) throw new e(`Unknown ui "${r}". Expected one of: ${t.join(", ")}.`);
7
+ return r;
8
+ }
9
+ //#endregion
10
+ export { n as t };
11
+
12
+ //# sourceMappingURL=ui-jhXrsw4T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ui-jhXrsw4T.js","names":[],"sources":["../../src/core/field/ui.ts"],"sourcesContent":["import { InvalidArgumentError } from \"../errors\";\nimport type { Options } from \"../types\";\n\n/**\n * Which markup the form generators (and enable-i18n's language select) emit:\n * `shadcn` is formsnap plus the project's `$lib/components/ui/*`; `plain` is\n * native elements, for projects without shadcn-svelte and tailwind.\n */\nexport type Ui = \"shadcn\" | \"plain\";\n\nconst UIS: Ui[] = [\"shadcn\", \"plain\"];\n\n/**\n * An explicit `input.ui` wins over the detected `features.ui`. Absent from\n * both means `shadcn`, so callers that predate the option are unchanged.\n */\nexport function resolveUi(options: Pick<Options, \"input\" | \"features\">): Ui {\n const ui = options.input.ui ?? options.features.ui ?? \"shadcn\";\n if (!UIS.includes(ui)) {\n throw new InvalidArgumentError(\n `Unknown ui \"${ui}\". Expected one of: ${UIS.join(\", \")}.`,\n );\n }\n return ui;\n}\n"],"mappings":";;AAUA,IAAM,IAAY,CAAC,UAAU,OAAO;AAMpC,SAAgB,EAAU,GAAkD;CAC1E,IAAM,IAAK,EAAQ,MAAM,MAAM,EAAQ,SAAS,MAAM;CACtD,IAAI,CAAC,EAAI,SAAS,CAAE,GAClB,MAAM,IAAI,EACR,eAAe,EAAG,sBAAsB,EAAI,KAAK,IAAI,EAAE,EACzD;CAEF,OAAO;AACT"}