@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 210 lines 8.8 KB
Raw
1 /**
2 * Config synthesis for driving Nuxt programmatically while keeping the
3 * project's own `nuxt.config.ts` authoritative.
4 *
5 * A Nuxt project's `nuxt.config.ts` loads natively through `loadNuxt` (c12
6 * resolves the file, its layers, and its modules exactly as `nuxi` would).
7 * This package injects its configuration through two seams:
8 *
9 * 1. **`loadNuxt` overrides** — the highest-priority config layer. We put the
10 * deploy target's nitro preset and integration-level Nuxt overrides here.
11 * 2. **The `nitro:config` hook** — runs when Nuxt initializes Nitro, after
12 * every module and layer has contributed. {@link enforceNitroConfig} is
13 * registered there and gets the last word on the keys this integration
14 * owns (the preset, and `cloudflare.deployConfig: false` — we never write
15 * a wrangler config into user projects).
16 *
17 * Hooks MUST be registered before `nuxt.ready()`: with `ready: true` the
18 * hooks fire inside `loadNuxt` itself and a late registration misses them.
19 * `Nuxt.ts` therefore always loads with `ready: false`.
20 *
21 * Conflict policy: the user's `nuxt.config.ts` may not select a different
22 * deployment preset. Because `loadNuxt` overrides shadow the user's value in
23 * the merged config, the user's raw value is read from the project's own
24 * config layer (`nuxt.options._layers[0].config`) and a foreign preset fails
25 * the build with an actionable error ({@link findPresetConflict}) instead of
26 * being silently replaced — the user's nitro output would never be deployed.
27 */
28
29 /** A minimal structural slice of a resolved nitro config (`NitroConfig`). */
30 export interface NitroConfigSlice extends Record<string, unknown> {
31 preset?: string | undefined;
32 cloudflare?: Record<string, unknown> | undefined;
33 plugins?: Array<string> | undefined;
34 }
35
36 /** The structural slice of `nuxt.options._layers` entries this package reads. */
37 export interface NuxtConfigLayer {
38 readonly cwd?: string | undefined;
39 readonly config?:
40 | {
41 readonly nitro?: { readonly preset?: string | undefined } | undefined;
42 }
43 | undefined;
44 }
45
46 /**
47 * Normalize a nitro preset name for comparison: nitro treats
48 * `cloudflare_module`, `cloudflare-module`, and `cloudflareModule` as the
49 * same preset (kebab/snake/camel-insensitive).
50 */
51 export const normalizePresetName = (name: string): string =>
52 name
53 .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
54 .replace(/[_-]+/g, "-")
55 .toLowerCase();
56
57 /** Whether two preset names identify the same nitro preset. */
58 export const isSamePreset = (a: string, b: string): boolean =>
59 normalizePresetName(a) === normalizePresetName(b);
60
61 export interface NuxtOverridesInput {
62 /**
63 * The deploy target's nitro preset (e.g. `"cloudflare_module"`), injected
64 * as the highest-priority config layer AND re-enforced by
65 * {@link enforceNitroConfig} after modules run. Omitted for the dev
66 * server: nitro's dev flow runs its own Node dev preset — the deploy
67 * preset only matters for `build`.
68 */
69 readonly nitroPreset?: string | undefined;
70 /**
71 * Integration-level Nuxt config overrides (`NuxtOptions.nuxtConfig`),
72 * merged over the user's `nuxt.config.ts` (integration wins; c12/defu
73 * performs the deep merge).
74 */
75 readonly nuxtConfig?: Record<string, unknown> | undefined;
76 /** Absolute paths of nitro plugins to append (the dev-mode platform bridge). */
77 readonly nitroPlugins?: ReadonlyArray<string> | undefined;
78 /**
79 * Paths nitro's bundler must INLINE (`nitro.externals.inline`). Injected
80 * plugins that live under `node_modules` need this: nitro's externals
81 * pass would otherwise keep them external, and an externalized plugin
82 * resolves `nitropack/runtime` against the raw package — whose
83 * `#nitro-internal-virtual/*` imports only exist inside the bundle.
84 */
85 readonly nitroExternalsInline?: ReadonlyArray<string> | undefined;
86 /**
87 * `runtimeConfig` injected over the integration overrides (the dev
88 * platform's connect info rides here). Merged over any `runtimeConfig`
89 * in `nuxtConfig`; c12 deep-merges the result with the user's own
90 * `nuxt.config.ts` runtime config.
91 */
92 readonly runtimeConfig?: Record<string, unknown> | undefined;
93 }
94
95 /**
96 * Synthesize the `overrides` object for `loadNuxt({ cwd, ready: false,
97 * overrides })`. The user's `nuxt.config.ts` remains authoritative for
98 * everything this integration does not own.
99 */
100 export const makeNuxtOverrides = (input: NuxtOverridesInput): Record<string, unknown> => {
101 const userNitro =
102 input.nuxtConfig !== undefined && isPlainObject(input.nuxtConfig["nitro"])
103 ? (input.nuxtConfig["nitro"] as Record<string, unknown>)
104 : undefined;
105 const userRuntimeConfig =
106 input.nuxtConfig !== undefined && isPlainObject(input.nuxtConfig["runtimeConfig"])
107 ? (input.nuxtConfig["runtimeConfig"] as Record<string, unknown>)
108 : undefined;
109 const userExternals = isPlainObject(userNitro?.["externals"])
110 ? (userNitro["externals"] as Record<string, unknown>)
111 : undefined;
112 const userVite =
113 input.nuxtConfig !== undefined && isPlainObject(input.nuxtConfig["vite"])
114 ? (input.nuxtConfig["vite"] as Record<string, unknown>)
115 : undefined;
116 return {
117 ...input.nuxtConfig,
118 // Warn-level vite default: rolldown-vite's native progress reporter
119 // ("transforming...") writes straight to the fd, which corrupts
120 // hosting-process reporters (e.g. alchemy-test) that can only intercept
121 // JS-level writers. Integration-level `vite.logLevel` still wins.
122 vite: { logLevel: "warn", ...userVite },
123 nitro: {
124 ...userNitro,
125 ...(input.nitroPreset !== undefined ? { preset: input.nitroPreset } : undefined),
126 ...(input.nitroPlugins !== undefined && input.nitroPlugins.length > 0
127 ? {
128 plugins: [
129 ...(Array.isArray(userNitro?.["plugins"])
130 ? (userNitro["plugins"] as Array<string>)
131 : []),
132 ...input.nitroPlugins,
133 ],
134 }
135 : undefined),
136 ...(input.nitroExternalsInline !== undefined && input.nitroExternalsInline.length > 0
137 ? {
138 externals: {
139 ...userExternals,
140 inline: [
141 ...(Array.isArray(userExternals?.["inline"])
142 ? (userExternals["inline"] as Array<unknown>)
143 : []),
144 ...input.nitroExternalsInline,
145 ],
146 },
147 }
148 : undefined),
149 },
150 ...(input.runtimeConfig !== undefined
151 ? { runtimeConfig: { ...userRuntimeConfig, ...input.runtimeConfig } }
152 : undefined),
153 };
154 };
155
156 const isPlainObject = (value: unknown): value is Record<string, unknown> =>
157 value !== null && typeof value === "object" && !Array.isArray(value);
158
159 /**
160 * Find a preset conflict in the project's own config layers: returns the
161 * user's foreign preset name, or `undefined` when the user set no preset or
162 * set (an alias of) the target's own. Layers are the project's config plus
163 * any extended layers; only values the *project tree* contributed are
164 * consulted — the merged `nuxt.options.nitro.preset` is already ours because
165 * overrides shadow it.
166 */
167 export const findPresetConflict = (
168 layers: ReadonlyArray<NuxtConfigLayer> | undefined,
169 targetPreset: string,
170 ): string | undefined => {
171 for (const layer of layers ?? []) {
172 const preset = layer.config?.nitro?.preset;
173 if (typeof preset === "string" && preset.length > 0 && !isSamePreset(preset, targetPreset)) {
174 return preset;
175 }
176 }
177 return undefined;
178 };
179
180 /** The actionable error message for a user-configured foreign preset. */
181 export const presetConflictMessage = (userPreset: string, targetPreset: string): string =>
182 `The project's nuxt.config sets \`nitro.preset: "${userPreset}"\`, but this integration ` +
183 `deploys through the "${targetPreset}" preset — a "${userPreset}" build would never be ` +
184 "deployed. Remove the `nitro.preset` (and any `NITRO_PRESET` env var) from the project " +
185 "config and let the deploy target select the preset, or run the framework's own CLI for " +
186 `a "${userPreset}" build outside this integration.`;
187
188 export interface EnforceNitroConfigOptions {
189 /** The deploy target's nitro preset — always wins. */
190 readonly preset: string;
191 /**
192 * Extra last-word mutation contributed by the deploy target (e.g. the
193 * Cloudflare target's `cloudflare.deployConfig: false` and the user-entry
194 * wiring). Runs after the preset is enforced.
195 */
196 readonly configure?: ((nitroConfig: NitroConfigSlice) => void) | undefined;
197 }
198
199 /**
200 * The `nitro:config` hook body: enforce the keys this integration owns as
201 * the last word, after user config, layers, and modules have all
202 * contributed. Mutates `nitroConfig` in place (the hook contract).
203 */
204 export const enforceNitroConfig = (
205 nitroConfig: NitroConfigSlice,
206 options: EnforceNitroConfigOptions,
207 ): void => {
208 nitroConfig.preset = options.preset;
209 options.configure?.(nitroConfig);
210 };