@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 218 lines 9.05 KB
Raw
1 /**
2 * Support for projects with their own `vite.config.ts`.
3 *
4 * A normal SvelteKit v3 project carries all of its configuration in the Vite
5 * config file: `svelte.config.js` is gone (kit's own `plugin_root` throws if
6 * one exists on disk), and kit options — adapter, aliases, preprocess,
7 * prerender entries — are passed directly to the `sveltekit(...)` plugin call
8 * inside `vite.config.ts`.
9 *
10 * This package must honor that file natively (the user's Vite plugins, kit
11 * options, and Vite settings all apply) while still injecting the deploy
12 * target's adapter — WITHOUT constructing a second `sveltekit()` plugin
13 * instance next to the user's.
14 *
15 * Mechanism: `sveltekit(config)` validates the config eagerly and exposes it
16 * as `api.options` on the `vite-plugin-sveltekit-setup` plugin, but only
17 * *processes* it (deriving the `kit` config every later hook closes over)
18 * inside that plugin's `config: { order: "pre" }` hook. Vite runs config
19 * hooks in hook-`order` groups, and within a group in `enforce`-sorted plugin
20 * order — so an `enforce: "pre"` inline plugin whose config hook is also
21 * `order: "pre"` runs BEFORE kit's setup hook (inline plugins append after
22 * file plugins, and the file's only other `pre`-enforced kit plugin,
23 * `vite-plugin-sveltekit-resolve-svelte-config`, merely asserts no
24 * `svelte.config.js` exists). Mutating `api.options` at that point is
25 * therefore exactly as authoritative as having passed the options to
26 * `sveltekit(...)` directly.
27 *
28 * The injected plugin:
29 *
30 * 1. flattens the config's plugin option (awaiting the promises `sveltekit()`
31 * returns) and finds `vite-plugin-sveltekit-setup`;
32 * 2. fails with a descriptive error when it is absent (a `vite.config.ts`
33 * without `sveltekit()` is not a SvelteKit project — we cannot add the
34 * plugin from a config hook, Vite ignores plugins injected there);
35 * 3. merges the integration-level kit options (`SvelteKitOptions.kit`) over
36 * the user's — integration options win, mirroring Vite's inline-over-file
37 * precedence;
38 * 4. replaces the adapter with the deploy target's, warning when the user
39 * had declared their own: the adapter is the deploy-packaging seam (its
40 * output is what the target's finishing pass re-bundles and what alchemy
41 * uploads), so a foreign adapter's output would simply never be deployed.
42 * The user's file itself is untouched — running plain `vite build`
43 * outside this integration still uses their adapter.
44 */
45 import type { Adapter } from "@sveltejs/kit";
46 import type * as ViteModule from "vite";
47
48 /** The kit plugin that exposes the validated svelte config as `api.options`. */
49 export const SVELTEKIT_SETUP_PLUGIN_NAME = "vite-plugin-sveltekit-setup";
50
51 /** The name of the injected adapter/config plugin. */
52 export const CONFIG_PLUGIN_NAME = "distilled-sveltekit-config";
53
54 /**
55 * The Vite config file names this package probes for (mirrors Vite's
56 * `DEFAULT_CONFIG_FILES`) to decide between honoring a user config natively
57 * and the fully-programmatic fallback.
58 */
59 export const DEFAULT_VITE_CONFIG_FILES: ReadonlyArray<string> = [
60 "vite.config.js",
61 "vite.config.mjs",
62 "vite.config.ts",
63 "vite.config.cjs",
64 "vite.config.mts",
65 "vite.config.cts",
66 ];
67
68 /** The shape of kit's setup-plugin `api` (structural — kit doesn't export it). */
69 interface SetupPluginApi {
70 readonly options?: Record<string, unknown>;
71 }
72
73 /**
74 * Flatten Vite's `PluginOption` tree (nested arrays, promises, falsy holes)
75 * into a plain plugin list — the same normalization Vite itself performs
76 * before running config hooks.
77 */
78 export const flattenPluginOption = async (
79 option: ViteModule.PluginOption,
80 ): Promise<Array<ViteModule.Plugin>> => {
81 const resolved = await option;
82 if (resolved === null || resolved === undefined || resolved === false) {
83 return [];
84 }
85 if (Array.isArray(resolved)) {
86 const nested = await Promise.all(resolved.map(flattenPluginOption));
87 return nested.flat();
88 }
89 return [resolved as ViteModule.Plugin];
90 };
91
92 /**
93 * The top-level svelte options `sveltekit(config)` consumes at construction
94 * time (before any Vite hook runs). They cannot be applied by mutating
95 * `api.options` afterwards — `vite-plugin-svelte` was already instantiated
96 * with them — so the injector warns instead of silently dropping them.
97 */
98 const CONSTRUCTION_TIME_KEYS = ["extensions", "compilerOptions", "vitePlugin", "preprocess"];
99
100 const isPlainObject = (value: unknown): value is Record<string, unknown> =>
101 value !== null && typeof value === "object" && !Array.isArray(value);
102
103 /**
104 * Merge integration-level kit overrides over the user's validated kit config
105 * (two levels deep: nested plain objects merge key-by-key so validated
106 * defaults survive, everything else replaces).
107 */
108 export const mergeKitOptions = (
109 target: Record<string, unknown>,
110 overrides: Record<string, unknown>,
111 ): void => {
112 for (const [key, value] of Object.entries(overrides)) {
113 if (value === undefined) {
114 continue;
115 }
116 const existing = target[key];
117 if (isPlainObject(existing) && isPlainObject(value)) {
118 target[key] = { ...existing, ...value };
119 } else {
120 target[key] = value;
121 }
122 }
123 };
124
125 export interface SvelteKitConfigPluginOptions {
126 /** The deploy target's adapter — always wins over a user-declared adapter. */
127 readonly adapter: Adapter;
128 /**
129 * Integration-level kit options (`SvelteKitOptions.kit`) merged over the
130 * user's `sveltekit(...)` options (integration wins).
131 */
132 readonly kit?: Record<string, unknown> | undefined;
133 /** Warning sink. @default console.warn */
134 readonly warn?: ((message: string) => void) | undefined;
135 }
136
137 /**
138 * The inline Vite plugin injected when the project has its own
139 * `vite.config.ts`: locates the user's `sveltekit()` plugin and installs the
140 * deploy target's adapter (plus integration-level kit options) into its
141 * config before kit processes it. See the module doc for why the ordering is
142 * sound.
143 */
144 export const makeSvelteKitConfigPlugin = (
145 options: SvelteKitConfigPluginOptions,
146 ): ViteModule.Plugin => {
147 const warn =
148 options.warn ?? ((message: string) => console.warn(`[${CONFIG_PLUGIN_NAME}] ${message}`));
149 return {
150 name: CONFIG_PLUGIN_NAME,
151 enforce: "pre",
152 config: {
153 order: "pre",
154 handler: async (config) => {
155 const plugins = await flattenPluginOption(config.plugins);
156 const setup = plugins.find((plugin) => plugin.name === SVELTEKIT_SETUP_PLUGIN_NAME);
157 if (setup === undefined) {
158 throw new Error(
159 "The project's Vite config does not register the SvelteKit plugin. " +
160 "Add `sveltekit()` (from `@sveltejs/kit/vite`) to the `plugins` array of " +
161 "your Vite config file, or remove the config file to let the integration " +
162 "configure Vite programmatically.",
163 );
164 }
165 const svelteConfig = (setup.api as SetupPluginApi | undefined)?.options;
166 const nestedKit = svelteConfig?.["kit"];
167 const kit = isPlainObject(nestedKit) ? nestedKit : svelteConfig;
168
169 if (!isPlainObject(kit)) {
170 throw new Error(
171 `The "${SVELTEKIT_SETUP_PLUGIN_NAME}" plugin does not expose its config as ` +
172 "`api.options` or `api.options.kit` — the installed @sveltejs/kit version " +
173 "is incompatible with this integration's adapter injection.",
174 );
175 }
176 if (options.kit !== undefined) {
177 const { applicable, constructionTime } = Object.entries(options.kit).reduce<{
178 applicable: Record<string, unknown>;
179 constructionTime: Array<string>;
180 }>(
181 (acc, [key, value]) => {
182 if (CONSTRUCTION_TIME_KEYS.includes(key)) {
183 acc.constructionTime.push(key);
184 } else {
185 acc.applicable[key] = value;
186 }
187 return acc;
188 },
189 { applicable: {}, constructionTime: [] },
190 );
191 if (constructionTime.length > 0) {
192 warn(
193 `The kit option(s) ${constructionTime.map((key) => `"${key}"`).join(", ")} ` +
194 "cannot be injected when the project has its own Vite config file — " +
195 "pass them to the `sveltekit(...)` call in the config file instead.",
196 );
197 }
198 mergeKitOptions(kit, applicable);
199 }
200 const userAdapter = kit["adapter"];
201 if (userAdapter !== null && userAdapter !== undefined) {
202 const name =
203 isPlainObject(userAdapter) && typeof userAdapter["name"] === "string"
204 ? userAdapter["name"]
205 : "unknown";
206 warn(
207 `Replacing the adapter declared in the project's Vite config ("${name}") with ` +
208 "the deploy target's adapter: the deploy target owns build packaging, so a " +
209 "user-declared adapter's output would never be deployed. Remove the " +
210 "`adapter` option from `sveltekit(...)` to silence this warning " +
211 "(plain `vite build` outside this integration still uses it).",
212 );
213 }
214 kit["adapter"] = options.adapter;
215 },
216 },
217 };
218 };