@studiometa/foehn-vite-plugin 0.7.1 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Studio Meta
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -56,13 +56,19 @@ The plugin enables Vite's native manifest generation (`build.manifest: true`). T
56
56
 
57
57
  During development, the plugin writes a `hot` file inside `outDir` containing the dev server URL. It creates `outDir` when needed, so the dev server works before the first build. `ViteManifest::fromTheme()` reads the same file to detect dev mode and inject the Vite client script. If you change `hotFile`, pass the same name as the second argument of `fromTheme()`. The plugin removes the file when the dev server stops, also on Ctrl+C, and at the end of a build.
58
58
 
59
+ ### Browser Errors
60
+
61
+ With Vite 8, the plugin turns on [`server.forwardConsole`](https://vite.dev/config/server-options#server-forwardconsole), which Vite turns on only inside a coding agent. The Vite client in the page then sends the console errors and warnings, the uncaught errors and the unhandled promise rejections to the dev server, which prints them in its terminal. The plugin also writes each one to `browser-errors.jsonl` in `outDir`, beside the hot file, as one JSON object per line with the source file and line (mapped through the module's source map). The file is rotated at 256 KB and keeps 3 files at most. `wp foehn errors --browser` reads it, so an agent in another terminal can read the errors of the page.
62
+
63
+ Set `server.forwardConsole: false` to turn off the terminal output and the file. Vite 6 and 7 send nothing.
64
+
59
65
  ### File Watching
60
66
 
61
67
  The plugin watches files matching the `reload` patterns and triggers a full page reload when they change. This is useful for PHP and Twig files that don't go through Vite.
62
68
 
63
69
  ### DDEV Integration
64
70
 
65
- When a `.ddev/config.yaml` file is detected, the plugin proxies the dev server to the DDEV site. Vite keeps every request it can serve (its own `/@` routes, `/node_modules/`, the HMR connection and every file under the Vite root or the public directory) and sends the others, such as WordPress pages, to DDEV.
71
+ When a `.ddev/config.yaml` file is detected, the plugin proxies the dev server to the DDEV site. Vite keeps every request it can serve (its own `/@` routes, `/node_modules/`, the HMR connection and every file under the Vite root or the public directory) and sends the others, such as WordPress pages, to DDEV. The plugin also adds the DDEV site to `server.cors`, so a page opened on the DDEV URL can load `/@vite/client` (Vite allows only localhost pages by default). A `server.cors` in your config is kept as is.
66
72
 
67
73
  ## Options
68
74
 
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
- import { rmSync, statSync } from "node:fs";
1
+ import { appendFileSync, mkdirSync, renameSync, rmSync, statSync } from "node:fs";
2
2
  import { constants } from "node:os";
3
- import { dirname, join, relative, resolve } from "node:path";
3
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
4
+ import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
4
5
  import fastGlob from "fast-glob";
5
6
  import { mkdir, readFile, writeFile } from "node:fs/promises";
6
7
  //#region src/options.ts
@@ -111,7 +112,112 @@ function removeHotFile(hotPath) {
111
112
  rmSync(hotPath, { force: true });
112
113
  }
113
114
  //#endregion
115
+ //#region src/utils/browser-log.ts
116
+ /**
117
+ * The browser log: the console errors and the uncaught errors of the pages the dev
118
+ * server serves, one JSON object per line, for `wp foehn errors --browser`.
119
+ *
120
+ * The file has a cap, as the PHP error log does. When the next entry would make it
121
+ * larger than `MAX_BYTES`, it becomes `browser-errors.1.jsonl`, the previous
122
+ * `browser-errors.1.jsonl` becomes `browser-errors.2.jsonl`, and the oldest file is
123
+ * deleted. So the log never holds more than `MAX_FILES` files of `MAX_BYTES`.
124
+ */
125
+ var BROWSER_LOG = "browser-errors";
126
+ /** The characters of a message the entry keeps. */
127
+ var MAX_MESSAGE = 2e3;
128
+ /** The frames of the project's own code the entry keeps. */
129
+ var MAX_OWN_FRAMES = 8;
130
+ /**
131
+ * The entry of one forwarded event.
132
+ *
133
+ * An uncaught error or an unhandled rejection gives the frames of the project's own
134
+ * code, mapped back to the source, then the number of other frames. A console call
135
+ * has no stack.
136
+ */
137
+ async function browserEntry(payload, resolve, now = /* @__PURE__ */ new Date()) {
138
+ const time = now.toISOString().replace(/\.\d+Z$/, "Z");
139
+ if (payload.type === "log") return {
140
+ time,
141
+ level: "console",
142
+ class: `console.${payload.data.level}`,
143
+ message: shorten(payload.data.message),
144
+ file: null,
145
+ line: null,
146
+ stack: []
147
+ };
148
+ const own = [];
149
+ let first = null;
150
+ let others = 0;
151
+ for (const frame of parseStack(payload.data.stack ?? "")) {
152
+ const position = own.length < MAX_OWN_FRAMES ? await resolve(frame.url, frame.line, frame.column) : null;
153
+ if (position === null) {
154
+ others++;
155
+ continue;
156
+ }
157
+ first ??= position;
158
+ own.push(`${position.file}:${position.line}${frame.fn === "" ? "" : ` ${frame.fn}()`}`);
159
+ }
160
+ if (others > 0) own.push(`+${others} other ${others === 1 ? "frame" : "frames"}`);
161
+ return {
162
+ time,
163
+ level: payload.type === "error" ? "error" : "rejection",
164
+ class: shorten(payload.data.name),
165
+ message: shorten(payload.data.message),
166
+ file: first?.file ?? null,
167
+ line: first?.line ?? null,
168
+ stack: own
169
+ };
170
+ }
171
+ /**
172
+ * The frames of a stack, as Chromium (`at fn (url:line:column)`) and Firefox or
173
+ * Safari (`fn@url:line:column`) write them. Other lines, such as the message, are
174
+ * skipped.
175
+ */
176
+ function parseStack(stack) {
177
+ const frames = [];
178
+ for (const text of stack.split("\n")) {
179
+ const match = /^\s*at\s+(?:(.*?)\s+\()?(.+?):(\d+):(\d+)\)?\s*$/.exec(text) ?? /^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/.exec(text);
180
+ if (match) frames.push({
181
+ fn: match[1] ?? "",
182
+ url: match[2],
183
+ line: Number(match[3]),
184
+ column: Number(match[4])
185
+ });
186
+ }
187
+ return frames;
188
+ }
189
+ /**
190
+ * Add an entry at the end of the log in `directory`. Synchronous, so two events
191
+ * never rotate the files at the same time.
192
+ */
193
+ function appendBrowserEntry(directory, entry) {
194
+ const line = `${JSON.stringify(entry)}\n`;
195
+ const file = logFile(directory, 0);
196
+ mkdirSync(directory, { recursive: true });
197
+ const size = statSync(file, { throwIfNoEntry: false })?.size ?? 0;
198
+ if (size > 0 && size + Buffer.byteLength(line) > 262144) {
199
+ rmSync(logFile(directory, 2), { force: true });
200
+ for (let index = 1; index >= 0; index--) if (statSync(logFile(directory, index), { throwIfNoEntry: false })) renameSync(logFile(directory, index), logFile(directory, index + 1));
201
+ }
202
+ appendFileSync(file, line, "utf-8");
203
+ }
204
+ /**
205
+ * The path of one file of the log: `browser-errors.jsonl`, then
206
+ * `browser-errors.1.jsonl` and `browser-errors.2.jsonl`.
207
+ */
208
+ function logFile(directory, index) {
209
+ return join(directory, `${BROWSER_LOG}${index === 0 ? "" : `.${index}`}.jsonl`);
210
+ }
211
+ function shorten(text) {
212
+ return text.length > MAX_MESSAGE ? `${text.slice(0, MAX_MESSAGE)}…` : text;
213
+ }
214
+ //#endregion
114
215
  //#region src/plugin.ts
216
+ /**
217
+ * The origins Vite allows by default (`defaultAllowedOrigins`, exported by Vite
218
+ * 6.0.9 and later only).
219
+ */
220
+ var LOCALHOST_ORIGINS = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/;
115
221
  /** Signals that end the process without Vite closing the server first. */
116
222
  var EXIT_SIGNALS = ["SIGINT", "SIGHUP"];
117
223
  /**
@@ -125,7 +231,7 @@ function foehn(options) {
125
231
  return [{
126
232
  name: "foehn",
127
233
  enforce: "pre",
128
- async config(_userConfig, { command: _command }) {
234
+ async config(userConfig) {
129
235
  const entries = await resolveGlobPatterns(resolvedOptions.input, resolvedOptions.themeDir);
130
236
  const ddevConfig = await detectDdev(resolvedOptions.themeDir);
131
237
  const proxyTarget = ddevConfig ? getDdevSiteUrl(ddevConfig) : void 0;
@@ -135,18 +241,26 @@ function foehn(options) {
135
241
  outDir,
136
242
  rollupOptions: { input: entries }
137
243
  },
138
- server: proxyTarget ? { proxy: { "/": {
139
- target: proxyTarget,
140
- changeOrigin: true,
141
- secure: false,
142
- bypass: (req) => isServedByVite(req, config) ? req.url : void 0
143
- } } } : void 0
244
+ server: {
245
+ forwardConsole: userConfig.server?.forwardConsole ?? true,
246
+ cors: userConfig.server?.cors ?? (proxyTarget ? { origin: [LOCALHOST_ORIGINS, new URL(proxyTarget).origin] } : void 0),
247
+ proxy: proxyTarget ? { "/": {
248
+ target: proxyTarget,
249
+ changeOrigin: true,
250
+ secure: false,
251
+ bypass: (req) => isServedByVite(req, config) ? req.url : void 0
252
+ } } : void 0
253
+ }
144
254
  };
145
255
  },
146
256
  configResolved(resolvedConfig) {
147
257
  config = resolvedConfig;
148
258
  },
149
259
  configureServer(server) {
260
+ const client = server.environments.client;
261
+ client.hot.on("vite:forward-console", (payload) => {
262
+ browserEntry(payload, (url, line, column) => findSource(client, config.root, url, line, column)).then((entry) => appendBrowserEntry(outDir, entry)).catch((error) => config.logger.warn(`[foehn] Cannot write the browser log: ${error.message}`));
263
+ });
150
264
  const httpServer = server.httpServer;
151
265
  if (!httpServer) return;
152
266
  httpServer.once("listening", async () => {
@@ -212,6 +326,40 @@ function isServedByVite(req, config) {
212
326
  return [config.root, config.publicDir].some((dir) => dir !== "" && statSync(join(dir, path), { throwIfNoEntry: false })?.isFile());
213
327
  }
214
328
  /**
329
+ * The place in the project's source of a position in a module the browser loaded:
330
+ * the module's file relative to the Vite root, and the line mapped back through
331
+ * the module's source map (TypeScript, JSX and Vue change the line numbers).
332
+ * `null` for a module of a dependency, a URL of another server, or a module the
333
+ * dev server has not served.
334
+ */
335
+ async function findSource(environment, root, url, line, column) {
336
+ let path;
337
+ try {
338
+ const parsed = new URL(url);
339
+ path = decodeURIComponent(parsed.pathname) + parsed.search;
340
+ } catch {
341
+ return null;
342
+ }
343
+ const module = await environment.moduleGraph.getModuleByUrl(path);
344
+ const file = module?.file ? relative(root, module.file) : "";
345
+ if (file === "" || file.startsWith("..") || isAbsolute(file) || file.includes("node_modules")) return null;
346
+ const map = module?.transformResult?.map;
347
+ if (map && map.mappings !== "") {
348
+ const original = originalPositionFor(new TraceMap(map), {
349
+ line,
350
+ column: Math.max(column - 1, 0)
351
+ });
352
+ if (original.line !== null) return {
353
+ file,
354
+ line: original.line
355
+ };
356
+ }
357
+ return {
358
+ file,
359
+ line
360
+ };
361
+ }
362
+ /**
215
363
  * Get the URL a browser reaches the dev server at.
216
364
  */
217
365
  function getServerUrl(address, config) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/options.ts","../src/utils/glob.ts","../src/utils/ddev.ts","../src/utils/hot.ts","../src/plugin.ts"],"sourcesContent":["/**\n * Options for the Føhn Vite plugin.\n */\nexport interface FoehnPluginOptions {\n /**\n * Glob patterns for entry points.\n * @example [\"src/js/app.js\", \"src/css/app.css\"]\n */\n input: string | string[];\n\n /**\n * Files to watch for full reload.\n * @default [\"templates/**\\/*.twig\"]\n */\n reload?: string | string[];\n\n /**\n * Output directory for built assets.\n * @default \"dist\"\n */\n outDir?: string;\n\n /**\n * Theme directory context.\n * @default process.cwd()\n */\n themeDir?: string;\n\n /**\n * Name of the hot file generated during development, written inside\n * `outDir`. Pass the same name to `ViteManifest::fromTheme()` when you\n * change it.\n * @default \"hot\"\n */\n hotFile?: string;\n}\n\n/**\n * Resolved options with all defaults applied.\n */\nexport interface ResolvedFoehnPluginOptions {\n input: string[];\n reload: string[];\n outDir: string;\n themeDir: string;\n hotFile: string;\n}\n\n/**\n * Default values for optional options.\n */\nexport const defaultOptions: Omit<ResolvedFoehnPluginOptions, \"input\"> = {\n reload: [\"templates/**/*.twig\"],\n outDir: \"dist\",\n themeDir: process.cwd(),\n hotFile: \"hot\",\n};\n\n/**\n * Normalize and resolve plugin options.\n */\nexport function resolveOptions(options: FoehnPluginOptions): ResolvedFoehnPluginOptions {\n const input = Array.isArray(options.input) ? options.input : [options.input];\n\n const reload = options.reload\n ? Array.isArray(options.reload)\n ? options.reload\n : [options.reload]\n : defaultOptions.reload;\n\n return {\n input,\n reload,\n outDir: options.outDir ?? defaultOptions.outDir,\n themeDir: options.themeDir ?? defaultOptions.themeDir,\n hotFile: options.hotFile ?? defaultOptions.hotFile,\n };\n}\n","import fastGlob from \"fast-glob\";\nimport { resolve, relative } from \"node:path\";\n\n/**\n * Resolve glob patterns to absolute file paths.\n */\nexport async function resolveGlobPatterns(\n patterns: string[],\n cwd: string,\n): Promise<Record<string, string>> {\n const entries: Record<string, string> = {};\n\n for (const pattern of patterns) {\n // Check if pattern contains glob characters\n if (pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"{\")) {\n const files = await fastGlob(pattern, { cwd, absolute: true });\n for (const file of files) {\n const relativePath = relative(cwd, file);\n // Remove extension for entry name\n const name = relativePath.replace(/\\.[^/.]+$/, \"\");\n entries[name] = file;\n }\n } else {\n // Direct file path\n const absolutePath = resolve(cwd, pattern);\n const name = pattern.replace(/\\.[^/.]+$/, \"\");\n entries[name] = absolutePath;\n }\n }\n\n return entries;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\n\n/**\n * DDEV project configuration structure.\n */\nexport interface DdevConfig {\n name: string;\n router_http_port?: string;\n router_https_port?: string;\n}\n\n/**\n * Detect DDEV configuration from the project root.\n * Returns null if no DDEV config is found.\n */\nexport async function detectDdev(projectRoot: string): Promise<DdevConfig | null> {\n const configPath = resolve(projectRoot, \".ddev/config.yaml\");\n\n try {\n const content = await readFile(configPath, \"utf-8\");\n return parseDdevConfig(content);\n } catch {\n return null;\n }\n}\n\n/**\n * Parse DDEV YAML config (simple parser, no dependency needed).\n */\nfunction parseDdevConfig(content: string): DdevConfig {\n const lines = content.split(\"\\n\");\n const config: Record<string, string> = {};\n\n for (const line of lines) {\n const match = line.match(/^(\\w+):\\s*(.+)$/);\n if (match) {\n const key = match[1];\n let value = match[2].trim();\n // Remove quotes if present\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n config[key] = value;\n }\n }\n\n return {\n name: config.name ?? \"unknown\",\n router_http_port: config.router_http_port,\n router_https_port: config.router_https_port,\n };\n}\n\n/**\n * Get the DDEV site URL for proxy configuration.\n */\nexport function getDdevSiteUrl(config: DdevConfig): string {\n const port = config.router_https_port ?? \"443\";\n const portSuffix = port === \"443\" ? \"\" : `:${port}`;\n return `https://${config.name}.ddev.site${portSuffix}`;\n}\n","import { rmSync } from \"node:fs\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\n/**\n * Write the hot file with the dev server URL.\n * The PHP side reads this file to detect dev mode and inject the Vite client.\n * The directory is created when it does not exist yet, so the dev server works\n * before the first build.\n */\nexport async function writeHotFile(hotPath: string, serverUrl: string): Promise<void> {\n await mkdir(dirname(hotPath), { recursive: true });\n await writeFile(hotPath, serverUrl, \"utf-8\");\n}\n\n/**\n * Remove the hot file when the dev server stops. Synchronous, so it is done\n * before a process that is exiting goes away. A missing file is not an error.\n */\nexport function removeHotFile(hotPath: string): void {\n rmSync(hotPath, { force: true });\n}\n","import { statSync } from \"node:fs\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport { constants } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport type { Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport type { FoehnPluginOptions, ResolvedFoehnPluginOptions } from \"./options.js\";\nimport { resolveOptions } from \"./options.js\";\nimport {\n resolveGlobPatterns,\n detectDdev,\n getDdevSiteUrl,\n writeHotFile,\n removeHotFile,\n} from \"./utils/index.js\";\n\n/** Signals that end the process without Vite closing the server first. */\nconst EXIT_SIGNALS = [\"SIGINT\", \"SIGHUP\"] as const;\n\n/**\n * Creates the Føhn Vite plugin.\n */\nexport function foehn(options: FoehnPluginOptions): Plugin[] {\n const resolvedOptions = resolveOptions(options);\n const outDir = resolve(resolvedOptions.themeDir, resolvedOptions.outDir);\n // Inside the build output, where `ViteManifest` looks for it.\n const hotPath = resolve(outDir, resolvedOptions.hotFile);\n let config: ResolvedConfig;\n\n const mainPlugin: Plugin = {\n name: \"foehn\",\n enforce: \"pre\",\n\n async config(_userConfig, { command: _command }) {\n const entries = await resolveGlobPatterns(\n resolvedOptions.input,\n resolvedOptions.themeDir,\n );\n\n // Detect DDEV for proxy configuration\n const ddevConfig = await detectDdev(resolvedOptions.themeDir);\n const proxyTarget = ddevConfig ? getDdevSiteUrl(ddevConfig) : undefined;\n\n return {\n build: {\n manifest: true,\n outDir,\n rollupOptions: {\n input: entries,\n },\n },\n server: proxyTarget\n ? {\n proxy: {\n // Vite answers what it can serve, DDEV the rest\n \"/\": {\n target: proxyTarget,\n changeOrigin: true,\n secure: false,\n bypass: (req) =>\n isServedByVite(req, config) ? req.url : undefined,\n },\n },\n }\n : undefined,\n };\n },\n\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n\n configureServer(server: ViteDevServer) {\n const httpServer = server.httpServer;\n if (!httpServer) {\n return;\n }\n\n // Write hot file when server starts, with the address it listens on\n httpServer.once(\"listening\", async () => {\n const address = httpServer.address();\n if (typeof address === \"object\" && address) {\n await writeHotFile(hotPath, getServerUrl(address, config));\n }\n });\n\n // Vite closes the server on SIGTERM only. Ctrl+C (SIGINT) and a\n // closed terminal (SIGHUP) kill the process, and a hot file left\n // behind points every WordPress page at a dead server.\n const onSignal = (signal: NodeJS.Signals) => {\n removeHotFile(hotPath);\n process.exit(128 + constants.signals[signal]);\n };\n for (const signal of EXIT_SIGNALS) {\n process.on(signal, onSignal);\n }\n\n // Remove hot file when server closes\n httpServer.on(\"close\", () => {\n removeHotFile(hotPath);\n for (const signal of EXIT_SIGNALS) {\n process.off(signal, onSignal);\n }\n });\n },\n\n buildEnd() {\n // Ensure hot file is removed after build\n if (config.command === \"build\") {\n removeHotFile(hotPath);\n }\n },\n };\n\n // Separate plugin for file watching (full reload)\n const reloadPlugin = createReloadPlugin(resolvedOptions);\n\n return [mainPlugin, reloadPlugin];\n}\n\n/**\n * Creates a plugin that watches files for full reload.\n */\nfunction createReloadPlugin(options: ResolvedFoehnPluginOptions): Plugin {\n return {\n name: \"foehn:reload\",\n\n configureServer(server: ViteDevServer) {\n // Watch files for full reload\n for (const pattern of options.reload) {\n const fullPattern = resolve(options.themeDir, pattern);\n server.watcher.add(fullPattern);\n }\n\n server.watcher.on(\"change\", (file) => {\n // Check if the changed file matches any reload pattern\n const shouldReload = options.reload.some((pattern) => {\n const fullPattern = resolve(options.themeDir, pattern);\n return matchPattern(file, fullPattern);\n });\n\n if (shouldReload) {\n server.ws.send({ type: \"full-reload\" });\n }\n });\n },\n };\n}\n\n/**\n * Simple pattern matching for file paths.\n */\nfunction matchPattern(file: string, pattern: string): boolean {\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/\\*\\*/g, \"<<<GLOBSTAR>>>\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/<<<GLOBSTAR>>>/g, \".*\")\n .replace(/\\?/g, \".\");\n\n return new RegExp(`^${regexPattern}$`).test(file);\n}\n\n/**\n * Whether the dev server answers a request itself: its internal routes\n * (`/@vite/client`, `/@fs/`, `/@id/`, `/__open-in-editor`), dependencies, the\n * HMR ping, and every file under the root or the public directory, whatever\n * the query (`?import`, `?direct`, `?v=`).\n */\nfunction isServedByVite(req: IncomingMessage, config: ResolvedConfig): boolean {\n if (req.headers.accept === \"text/x-vite-ping\") {\n return true;\n }\n\n let path: string;\n try {\n path = decodeURIComponent((req.url ?? \"/\").split(/[?#]/)[0]);\n } catch {\n // A malformed URL is not a module, let WordPress answer it\n return false;\n }\n\n if (path.startsWith(\"/@\") || path.startsWith(\"/__\") || path.startsWith(\"/node_modules/\")) {\n return true;\n }\n\n return [config.root, config.publicDir].some(\n (dir) => dir !== \"\" && statSync(join(dir, path), { throwIfNoEntry: false })?.isFile(),\n );\n}\n\n/**\n * Get the URL a browser reaches the dev server at.\n */\nfunction getServerUrl(address: AddressInfo, config: ResolvedConfig): string {\n const protocol = config.server.https ? \"https\" : \"http\";\n const host = [\"::\", \"0.0.0.0\", \"::1\", \"127.0.0.1\"].includes(address.address)\n ? \"localhost\"\n : address.family === \"IPv6\"\n ? `[${address.address}]`\n : address.address;\n return `${protocol}://${host}:${address.port}`;\n}\n"],"mappings":";;;;;;;;;AAmDA,IAAa,iBAA4D;CACrE,QAAQ,CAAC,qBAAqB;CAC9B,QAAQ;CACR,UAAU,QAAQ,IAAI;CACtB,SAAS;AACb;;;;AAKA,SAAgB,eAAe,SAAyD;CASpF,OAAO;EACH,OATU,MAAM,QAAQ,QAAQ,KAAK,IAAI,QAAQ,QAAQ,CAAC,QAAQ,KAAK;EAUvE,QARW,QAAQ,SACjB,MAAM,QAAQ,QAAQ,MAAM,IACxB,QAAQ,SACR,CAAC,QAAQ,MAAM,IACnB,eAAe;EAKjB,QAAQ,QAAQ,UAAU,eAAe;EACzC,UAAU,QAAQ,YAAY,eAAe;EAC7C,SAAS,QAAQ,WAAW,eAAe;CAC/C;AACJ;;;;;;ACvEA,eAAsB,oBAClB,UACA,KAC+B;CAC/B,MAAM,UAAkC,CAAC;CAEzC,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EAAE;CAC/D,QAAQ;EAEJ,OAAO;CACX;CAEA,IAAI,KAAK,WAAW,IAAI,KAAK,KAAK,WAAW,KAAK,KAAK,KAAK,WAAW,gBAAgB,GACnF,OAAO;CAGX,OAAO,CAAC,OAAO,MAAM,OAAO,SAAS,CAAC,CAAC,MAClC,QAAQ,QAAQ,MAAM,SAAS,KAAK,KAAK,IAAI,GAAG,EAAE,gBAAgB,MAAM,CAAC,CAAC,EAAE,OAAO,CACxF;AACJ;;;;AAKA,SAAS,aAAa,SAAsB,QAAgC;CAOxE,OAAO,GANU,OAAO,OAAO,QAAQ,UAAU,OAM9B,KALN;EAAC;EAAM;EAAW;EAAO;CAAW,CAAC,CAAC,SAAS,QAAQ,OAAO,IACrE,cACA,QAAQ,WAAW,SACjB,IAAI,QAAQ,QAAQ,KACpB,QAAQ,QACa,GAAG,QAAQ;AAC5C"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/options.ts","../src/utils/glob.ts","../src/utils/ddev.ts","../src/utils/hot.ts","../src/utils/browser-log.ts","../src/plugin.ts"],"sourcesContent":["/**\n * Options for the Føhn Vite plugin.\n */\nexport interface FoehnPluginOptions {\n /**\n * Glob patterns for entry points.\n * @example [\"src/js/app.js\", \"src/css/app.css\"]\n */\n input: string | string[];\n\n /**\n * Files to watch for full reload.\n * @default [\"templates/**\\/*.twig\"]\n */\n reload?: string | string[];\n\n /**\n * Output directory for built assets.\n * @default \"dist\"\n */\n outDir?: string;\n\n /**\n * Theme directory context.\n * @default process.cwd()\n */\n themeDir?: string;\n\n /**\n * Name of the hot file generated during development, written inside\n * `outDir`. Pass the same name to `ViteManifest::fromTheme()` when you\n * change it.\n * @default \"hot\"\n */\n hotFile?: string;\n}\n\n/**\n * Resolved options with all defaults applied.\n */\nexport interface ResolvedFoehnPluginOptions {\n input: string[];\n reload: string[];\n outDir: string;\n themeDir: string;\n hotFile: string;\n}\n\n/**\n * Default values for optional options.\n */\nexport const defaultOptions: Omit<ResolvedFoehnPluginOptions, \"input\"> = {\n reload: [\"templates/**/*.twig\"],\n outDir: \"dist\",\n themeDir: process.cwd(),\n hotFile: \"hot\",\n};\n\n/**\n * Normalize and resolve plugin options.\n */\nexport function resolveOptions(options: FoehnPluginOptions): ResolvedFoehnPluginOptions {\n const input = Array.isArray(options.input) ? options.input : [options.input];\n\n const reload = options.reload\n ? Array.isArray(options.reload)\n ? options.reload\n : [options.reload]\n : defaultOptions.reload;\n\n return {\n input,\n reload,\n outDir: options.outDir ?? defaultOptions.outDir,\n themeDir: options.themeDir ?? defaultOptions.themeDir,\n hotFile: options.hotFile ?? defaultOptions.hotFile,\n };\n}\n","import fastGlob from \"fast-glob\";\nimport { resolve, relative } from \"node:path\";\n\n/**\n * Resolve glob patterns to absolute file paths.\n */\nexport async function resolveGlobPatterns(\n patterns: string[],\n cwd: string,\n): Promise<Record<string, string>> {\n const entries: Record<string, string> = {};\n\n for (const pattern of patterns) {\n // Check if pattern contains glob characters\n if (pattern.includes(\"*\") || pattern.includes(\"?\") || pattern.includes(\"{\")) {\n const files = await fastGlob(pattern, { cwd, absolute: true });\n for (const file of files) {\n const relativePath = relative(cwd, file);\n // Remove extension for entry name\n const name = relativePath.replace(/\\.[^/.]+$/, \"\");\n entries[name] = file;\n }\n } else {\n // Direct file path\n const absolutePath = resolve(cwd, pattern);\n const name = pattern.replace(/\\.[^/.]+$/, \"\");\n entries[name] = absolutePath;\n }\n }\n\n return entries;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\n\n/**\n * DDEV project configuration structure.\n */\nexport interface DdevConfig {\n name: string;\n router_http_port?: string;\n router_https_port?: string;\n}\n\n/**\n * Detect DDEV configuration from the project root.\n * Returns null if no DDEV config is found.\n */\nexport async function detectDdev(projectRoot: string): Promise<DdevConfig | null> {\n const configPath = resolve(projectRoot, \".ddev/config.yaml\");\n\n try {\n const content = await readFile(configPath, \"utf-8\");\n return parseDdevConfig(content);\n } catch {\n return null;\n }\n}\n\n/**\n * Parse DDEV YAML config (simple parser, no dependency needed).\n */\nfunction parseDdevConfig(content: string): DdevConfig {\n const lines = content.split(\"\\n\");\n const config: Record<string, string> = {};\n\n for (const line of lines) {\n const match = line.match(/^(\\w+):\\s*(.+)$/);\n if (match) {\n const key = match[1];\n let value = match[2].trim();\n // Remove quotes if present\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n config[key] = value;\n }\n }\n\n return {\n name: config.name ?? \"unknown\",\n router_http_port: config.router_http_port,\n router_https_port: config.router_https_port,\n };\n}\n\n/**\n * Get the DDEV site URL for proxy configuration.\n */\nexport function getDdevSiteUrl(config: DdevConfig): string {\n const port = config.router_https_port ?? \"443\";\n const portSuffix = port === \"443\" ? \"\" : `:${port}`;\n return `https://${config.name}.ddev.site${portSuffix}`;\n}\n","import { rmSync } from \"node:fs\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\n/**\n * Write the hot file with the dev server URL.\n * The PHP side reads this file to detect dev mode and inject the Vite client.\n * The directory is created when it does not exist yet, so the dev server works\n * before the first build.\n */\nexport async function writeHotFile(hotPath: string, serverUrl: string): Promise<void> {\n await mkdir(dirname(hotPath), { recursive: true });\n await writeFile(hotPath, serverUrl, \"utf-8\");\n}\n\n/**\n * Remove the hot file when the dev server stops. Synchronous, so it is done\n * before a process that is exiting goes away. A missing file is not an error.\n */\nexport function removeHotFile(hotPath: string): void {\n rmSync(hotPath, { force: true });\n}\n","import { appendFileSync, mkdirSync, renameSync, rmSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * The browser log: the console errors and the uncaught errors of the pages the dev\n * server serves, one JSON object per line, for `wp foehn errors --browser`.\n *\n * The file has a cap, as the PHP error log does. When the next entry would make it\n * larger than `MAX_BYTES`, it becomes `browser-errors.1.jsonl`, the previous\n * `browser-errors.1.jsonl` becomes `browser-errors.2.jsonl`, and the oldest file is\n * deleted. So the log never holds more than `MAX_FILES` files of `MAX_BYTES`.\n */\nexport const BROWSER_LOG = \"browser-errors\";\n\nexport const MAX_BYTES = 256 * 1024;\n\nexport const MAX_FILES = 3;\n\n/** The characters of a message the entry keeps. */\nconst MAX_MESSAGE = 2000;\n\n/** The frames of the project's own code the entry keeps. */\nconst MAX_OWN_FRAMES = 8;\n\n/**\n * What the Vite client sends on `vite:forward-console` (Vite 8 `server.forwardConsole`).\n */\nexport type ForwardConsolePayload =\n | {\n type: \"error\" | \"unhandled-rejection\";\n data: { name: string; message: string; stack?: string };\n }\n | { type: \"log\"; data: { level: string; message: string } };\n\n/**\n * A place in a source file of the project, relative to the Vite root.\n */\nexport interface SourcePosition {\n file: string;\n line: number;\n}\n\n/**\n * Finds the source file and line of a position in a module the browser loaded, or\n * `null` when the module is not the project's own code (a dependency, another\n * origin, an unknown URL).\n */\nexport type FrameResolver = (\n url: string,\n line: number,\n column: number,\n) => Promise<SourcePosition | null>;\n\n/**\n * One entry of the browser log. The fields are the ones `wp foehn errors` prints.\n */\nexport interface BrowserEntry {\n time: string;\n level: \"error\" | \"rejection\" | \"console\";\n class: string;\n message: string;\n file: string | null;\n line: number | null;\n stack: string[];\n}\n\n/**\n * The entry of one forwarded event.\n *\n * An uncaught error or an unhandled rejection gives the frames of the project's own\n * code, mapped back to the source, then the number of other frames. A console call\n * has no stack.\n */\nexport async function browserEntry(\n payload: ForwardConsolePayload,\n resolve: FrameResolver,\n now: Date = new Date(),\n): Promise<BrowserEntry> {\n const time = now.toISOString().replace(/\\.\\d+Z$/, \"Z\");\n\n if (payload.type === \"log\") {\n return {\n time,\n level: \"console\",\n class: `console.${payload.data.level}`,\n message: shorten(payload.data.message),\n file: null,\n line: null,\n stack: [],\n };\n }\n\n const own: string[] = [];\n let first: SourcePosition | null = null;\n let others = 0;\n\n for (const frame of parseStack(payload.data.stack ?? \"\")) {\n const position =\n own.length < MAX_OWN_FRAMES ? await resolve(frame.url, frame.line, frame.column) : null;\n\n if (position === null) {\n others++;\n continue;\n }\n\n first ??= position;\n own.push(`${position.file}:${position.line}${frame.fn === \"\" ? \"\" : ` ${frame.fn}()`}`);\n }\n\n if (others > 0) {\n own.push(`+${others} other ${others === 1 ? \"frame\" : \"frames\"}`);\n }\n\n return {\n time,\n level: payload.type === \"error\" ? \"error\" : \"rejection\",\n class: shorten(payload.data.name),\n message: shorten(payload.data.message),\n file: first?.file ?? null,\n line: first?.line ?? null,\n stack: own,\n };\n}\n\n/**\n * The frames of a stack, as Chromium (`at fn (url:line:column)`) and Firefox or\n * Safari (`fn@url:line:column`) write them. Other lines, such as the message, are\n * skipped.\n */\nexport function parseStack(\n stack: string,\n): Array<{ fn: string; url: string; line: number; column: number }> {\n const frames = [];\n\n for (const text of stack.split(\"\\n\")) {\n const match =\n /^\\s*at\\s+(?:(.*?)\\s+\\()?(.+?):(\\d+):(\\d+)\\)?\\s*$/.exec(text) ??\n /^\\s*(.*?)@(.+?):(\\d+):(\\d+)\\s*$/.exec(text);\n\n if (match) {\n frames.push({\n fn: match[1] ?? \"\",\n url: match[2],\n line: Number(match[3]),\n column: Number(match[4]),\n });\n }\n }\n\n return frames;\n}\n\n/**\n * Add an entry at the end of the log in `directory`. Synchronous, so two events\n * never rotate the files at the same time.\n */\nexport function appendBrowserEntry(directory: string, entry: BrowserEntry): void {\n const line = `${JSON.stringify(entry)}\\n`;\n const file = logFile(directory, 0);\n\n mkdirSync(directory, { recursive: true });\n\n const size = statSync(file, { throwIfNoEntry: false })?.size ?? 0;\n\n if (size > 0 && size + Buffer.byteLength(line) > MAX_BYTES) {\n rmSync(logFile(directory, MAX_FILES - 1), { force: true });\n\n for (let index = MAX_FILES - 2; index >= 0; index--) {\n if (statSync(logFile(directory, index), { throwIfNoEntry: false })) {\n renameSync(logFile(directory, index), logFile(directory, index + 1));\n }\n }\n }\n\n appendFileSync(file, line, \"utf-8\");\n}\n\n/**\n * The path of one file of the log: `browser-errors.jsonl`, then\n * `browser-errors.1.jsonl` and `browser-errors.2.jsonl`.\n */\nexport function logFile(directory: string, index: number): string {\n return join(directory, `${BROWSER_LOG}${index === 0 ? \"\" : `.${index}`}.jsonl`);\n}\n\nfunction shorten(text: string): string {\n return text.length > MAX_MESSAGE ? `${text.slice(0, MAX_MESSAGE)}…` : text;\n}\n","import { statSync } from \"node:fs\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport { constants } from \"node:os\";\nimport { isAbsolute, join, relative, resolve } from \"node:path\";\nimport { originalPositionFor, TraceMap, type SourceMapInput } from \"@jridgewell/trace-mapping\";\nimport type { DevEnvironment, Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport type { FoehnPluginOptions, ResolvedFoehnPluginOptions } from \"./options.js\";\nimport { resolveOptions } from \"./options.js\";\nimport {\n resolveGlobPatterns,\n detectDdev,\n getDdevSiteUrl,\n writeHotFile,\n removeHotFile,\n appendBrowserEntry,\n browserEntry,\n type ForwardConsolePayload,\n type SourcePosition,\n} from \"./utils/index.js\";\n\n/**\n * The origins Vite allows by default (`defaultAllowedOrigins`, exported by Vite\n * 6.0.9 and later only).\n */\nconst LOCALHOST_ORIGINS = /^https?:\\/\\/(?:(?:[^:]+\\.)?localhost|127\\.0\\.0\\.1|\\[::1\\])(?::\\d+)?$/;\n\n/** Signals that end the process without Vite closing the server first. */\nconst EXIT_SIGNALS = [\"SIGINT\", \"SIGHUP\"] as const;\n\n/**\n * Creates the Føhn Vite plugin.\n */\nexport function foehn(options: FoehnPluginOptions): Plugin[] {\n const resolvedOptions = resolveOptions(options);\n const outDir = resolve(resolvedOptions.themeDir, resolvedOptions.outDir);\n // Inside the build output, where `ViteManifest` looks for it.\n const hotPath = resolve(outDir, resolvedOptions.hotFile);\n let config: ResolvedConfig;\n\n const mainPlugin: Plugin = {\n name: \"foehn\",\n enforce: \"pre\",\n\n async config(userConfig) {\n const entries = await resolveGlobPatterns(\n resolvedOptions.input,\n resolvedOptions.themeDir,\n );\n\n // Detect DDEV for proxy configuration\n const ddevConfig = await detectDdev(resolvedOptions.themeDir);\n const proxyTarget = ddevConfig ? getDdevSiteUrl(ddevConfig) : undefined;\n\n return {\n build: {\n manifest: true,\n outDir,\n rollupOptions: {\n input: entries,\n },\n },\n server: {\n // Vite 8 turns it on only when it runs inside a coding agent. On,\n // the page sends its console errors and uncaught errors to the\n // server, which writes them to the browser log for any agent.\n forwardConsole: userConfig.server?.forwardConsole ?? true,\n // A page opened on the DDEV URL loads `/@vite/client` from the dev\n // server, which Vite allows only for localhost pages by default.\n cors:\n userConfig.server?.cors ??\n (proxyTarget\n ? { origin: [LOCALHOST_ORIGINS, new URL(proxyTarget).origin] }\n : undefined),\n proxy: proxyTarget\n ? {\n // Vite answers what it can serve, DDEV the rest\n \"/\": {\n target: proxyTarget,\n changeOrigin: true,\n secure: false,\n bypass: (req) =>\n isServedByVite(req, config) ? req.url : undefined,\n },\n }\n : undefined,\n },\n };\n },\n\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n\n configureServer(server: ViteDevServer) {\n // Beside the hot file, where `wp foehn errors --browser` reads it\n const client = server.environments.client;\n client.hot.on(\"vite:forward-console\", (payload: ForwardConsolePayload) => {\n browserEntry(payload, (url, line, column) =>\n findSource(client, config.root, url, line, column),\n )\n .then((entry) => appendBrowserEntry(outDir, entry))\n .catch((error: Error) =>\n config.logger.warn(\n `[foehn] Cannot write the browser log: ${error.message}`,\n ),\n );\n });\n\n const httpServer = server.httpServer;\n if (!httpServer) {\n return;\n }\n\n // Write hot file when server starts, with the address it listens on\n httpServer.once(\"listening\", async () => {\n const address = httpServer.address();\n if (typeof address === \"object\" && address) {\n await writeHotFile(hotPath, getServerUrl(address, config));\n }\n });\n\n // Vite closes the server on SIGTERM only. Ctrl+C (SIGINT) and a\n // closed terminal (SIGHUP) kill the process, and a hot file left\n // behind points every WordPress page at a dead server.\n const onSignal = (signal: NodeJS.Signals) => {\n removeHotFile(hotPath);\n process.exit(128 + constants.signals[signal]);\n };\n for (const signal of EXIT_SIGNALS) {\n process.on(signal, onSignal);\n }\n\n // Remove hot file when server closes\n httpServer.on(\"close\", () => {\n removeHotFile(hotPath);\n for (const signal of EXIT_SIGNALS) {\n process.off(signal, onSignal);\n }\n });\n },\n\n buildEnd() {\n // Ensure hot file is removed after build\n if (config.command === \"build\") {\n removeHotFile(hotPath);\n }\n },\n };\n\n // Separate plugin for file watching (full reload)\n const reloadPlugin = createReloadPlugin(resolvedOptions);\n\n return [mainPlugin, reloadPlugin];\n}\n\n/**\n * Creates a plugin that watches files for full reload.\n */\nfunction createReloadPlugin(options: ResolvedFoehnPluginOptions): Plugin {\n return {\n name: \"foehn:reload\",\n\n configureServer(server: ViteDevServer) {\n // Watch files for full reload\n for (const pattern of options.reload) {\n const fullPattern = resolve(options.themeDir, pattern);\n server.watcher.add(fullPattern);\n }\n\n server.watcher.on(\"change\", (file) => {\n // Check if the changed file matches any reload pattern\n const shouldReload = options.reload.some((pattern) => {\n const fullPattern = resolve(options.themeDir, pattern);\n return matchPattern(file, fullPattern);\n });\n\n if (shouldReload) {\n server.ws.send({ type: \"full-reload\" });\n }\n });\n },\n };\n}\n\n/**\n * Simple pattern matching for file paths.\n */\nfunction matchPattern(file: string, pattern: string): boolean {\n // Convert glob pattern to regex\n const regexPattern = pattern\n .replace(/\\*\\*/g, \"<<<GLOBSTAR>>>\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/<<<GLOBSTAR>>>/g, \".*\")\n .replace(/\\?/g, \".\");\n\n return new RegExp(`^${regexPattern}$`).test(file);\n}\n\n/**\n * Whether the dev server answers a request itself: its internal routes\n * (`/@vite/client`, `/@fs/`, `/@id/`, `/__open-in-editor`), dependencies, the\n * HMR ping, and every file under the root or the public directory, whatever\n * the query (`?import`, `?direct`, `?v=`).\n */\nfunction isServedByVite(req: IncomingMessage, config: ResolvedConfig): boolean {\n if (req.headers.accept === \"text/x-vite-ping\") {\n return true;\n }\n\n let path: string;\n try {\n path = decodeURIComponent((req.url ?? \"/\").split(/[?#]/)[0]);\n } catch {\n // A malformed URL is not a module, let WordPress answer it\n return false;\n }\n\n if (path.startsWith(\"/@\") || path.startsWith(\"/__\") || path.startsWith(\"/node_modules/\")) {\n return true;\n }\n\n return [config.root, config.publicDir].some(\n (dir) => dir !== \"\" && statSync(join(dir, path), { throwIfNoEntry: false })?.isFile(),\n );\n}\n\n/**\n * The place in the project's source of a position in a module the browser loaded:\n * the module's file relative to the Vite root, and the line mapped back through\n * the module's source map (TypeScript, JSX and Vue change the line numbers).\n * `null` for a module of a dependency, a URL of another server, or a module the\n * dev server has not served.\n */\nasync function findSource(\n environment: DevEnvironment,\n root: string,\n url: string,\n line: number,\n column: number,\n): Promise<SourcePosition | null> {\n let path: string;\n try {\n // With the query: a Vue block (`?vue&type=script`) is a module of its own.\n // Vite drops the `?t=` of a hot update and the `?import` itself.\n const parsed = new URL(url);\n path = decodeURIComponent(parsed.pathname) + parsed.search;\n } catch {\n return null;\n }\n\n const module = await environment.moduleGraph.getModuleByUrl(path);\n const file = module?.file ? relative(root, module.file) : \"\";\n\n if (file === \"\" || file.startsWith(\"..\") || isAbsolute(file) || file.includes(\"node_modules\")) {\n return null;\n }\n\n const map = module?.transformResult?.map;\n\n if (map && map.mappings !== \"\") {\n const original = originalPositionFor(new TraceMap(map as SourceMapInput), {\n line,\n column: Math.max(column - 1, 0),\n });\n\n if (original.line !== null) {\n return { file, line: original.line };\n }\n }\n\n return { file, line };\n}\n\n/**\n * Get the URL a browser reaches the dev server at.\n */\nfunction getServerUrl(address: AddressInfo, config: ResolvedConfig): string {\n const protocol = config.server.https ? \"https\" : \"http\";\n const host = [\"::\", \"0.0.0.0\", \"::1\", \"127.0.0.1\"].includes(address.address)\n ? \"localhost\"\n : address.family === \"IPv6\"\n ? `[${address.address}]`\n : address.address;\n return `${protocol}://${host}:${address.port}`;\n}\n"],"mappings":";;;;;;;;;;AAmDA,IAAa,iBAA4D;CACrE,QAAQ,CAAC,qBAAqB;CAC9B,QAAQ;CACR,UAAU,QAA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K,WAAW,IAAI,KAAK,WAAW,IAAI,KAAK,KAAK,SAAS,cAAc,GACxF,OAAO;CAGX,MAAM,MAAM,QAAQ,iBAAiB;CAErC,IAAI,OAAO,IAAI,aAAa,IAAI;EAC5B,MAAM,WAAW,oBAAoB,IAAI,SAAS,GAAqB,GAAG;GACtE;GACA,QAAQ,KAAK,IAAI,SAAS,GAAG,CAAC;EAClC,CAAC;EAED,IAAI,SAAS,SAAS,MAClB,OAAO;GAAE;GAAM,MAAM,SAAS;EAAK;CAE3C;CAEA,OAAO;EAAE;EAAM;CAAK;AACxB;;;;AAKA,SAAS,aAAa,SAAsB,QAAgC;CAOxE,OAAO,GANU,OAAO,OAAO,QAAQ,UAAU,OAM9B,KALN;EAAC;EAAM;EAAW;EAAO;CAAW,CAAC,CAAC,SAAS,QAAQ,OAAO,IACrE,cACA,QAAQ,WAAW,SACjB,IAAI,QAAQ,QAAQ,KACpB,QAAQ,QACa,GAAG,QAAQ;AAC5C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@studiometa/foehn-vite-plugin",
3
- "version": "0.7.1",
3
+ "version": "0.8.1",
4
4
  "description": "Vite plugin for Føhn WordPress framework",
5
5
  "type": "module",
6
6
  "exports": {
@@ -12,7 +12,8 @@
12
12
  "main": "./dist/index.js",
13
13
  "types": "./dist/index.d.ts",
14
14
  "files": [
15
- "dist"
15
+ "dist",
16
+ "skills"
16
17
  ],
17
18
  "publishConfig": {
18
19
  "access": "public"
@@ -47,6 +48,7 @@
47
48
  },
48
49
  "homepage": "https://github.com/studiometa/foehn-framework/tree/main/packages/vite-plugin#readme",
49
50
  "dependencies": {
51
+ "@jridgewell/trace-mapping": "^0.3.31",
50
52
  "fast-glob": "^3.3.0"
51
53
  },
52
54
  "peerDependencies": {
@@ -0,0 +1,196 @@
1
+ ---
2
+ name: foehn-vite-plugin
3
+ description: 'Configure the Vite build of a Føhn theme with @studiometa/foehn-vite-plugin (the `foehn()` plugin in vite.config.js and its `input`, `reload`, `outDir`, `themeDir` and `hotFile` options) and enqueue its output on the PHP side with `Studiometa\Foehn\Assets\ViteManifest` (`fromTheme()`, `fromChildTheme()`, `enqueue()`, `exists()`, `isDevServer()`). Load it when editing vite.config.js, adding a JS or CSS entry, wiring `npm run dev` / HMR or the `hot` file, reading the browser console errors of the page (`wp foehn errors --browser`), debugging missing or unstyled assets, or touching an `AssetHooks` class in a theme built from studiometa/foehn-starter.'
4
+ ---
5
+
6
+ # Føhn Vite plugin
7
+
8
+ `@studiometa/foehn-vite-plugin` builds the theme's JavaScript and CSS with Vite. `Studiometa\Foehn\Assets\ViteManifest` (in `studiometa/foehn`) puts that build on the page. The two halves meet through files on disk, never through imports. For hooks, `#[AsAction]` and the rest of the PHP side, load the `foehn` skill.
9
+
10
+ Full guide: https://studiometa.github.io/foehn-framework/guide/assets.md
11
+
12
+ ## Mental model
13
+
14
+ The plugin writes one of two things. `ViteManifest` reads whichever one exists:
15
+
16
+ | Command | Plugin writes | `ViteManifest` then |
17
+ | --------------- | --------------------------------------------- | ----------------------------------------------------------------- |
18
+ | `npm run build` | `<outDir>/.vite/manifest.json` (hashed files) | enqueues the hashed files, plus the CSS each JS chunk imported |
19
+ | `npm run dev` | `<outDir>/hot` holding the dev server URL | enqueues `/@vite/client` and each entry from the dev server (HMR) |
20
+ | neither | nothing | enqueues nothing, no error |
21
+
22
+ The hot file wins: when it exists and is not empty, the manifest is not read. The plugin removes the hot file when the dev server closes, on Ctrl+C, when the terminal closes, and at the end of a build.
23
+
24
+ The **entry name** is the key that joins the two halves. It is the path given to `input`, relative to the Vite project root (the directory that holds `vite.config.js`, usually the project root, not the theme). In the starter, that is `theme/assets/js/app.js`, not `assets/js/app.js`.
25
+
26
+ ## Project layout (starter)
27
+
28
+ ```
29
+ my-project/
30
+ ├── vite.config.js
31
+ ├── package.json # "dev": "vite", "build": "vite build"
32
+ ├── .ddev/config.yaml
33
+ └── theme/ # the only directory the web server serves
34
+ ├── app/Hooks/AssetHooks.php
35
+ ├── assets/
36
+ │ ├── js/app.js
37
+ │ └── css/app.css
38
+ ├── templates/
39
+ └── dist/ # build output, git-ignored
40
+ └── .vite/manifest.json
41
+ ```
42
+
43
+ ## vite.config.js
44
+
45
+ This is the starter's configuration:
46
+
47
+ ```js
48
+ import { defineConfig } from "vite";
49
+ import tailwindcss from "@tailwindcss/vite";
50
+ import foehn from "@studiometa/foehn-vite-plugin";
51
+
52
+ export default defineConfig({
53
+ plugins: [
54
+ foehn({
55
+ input: ["theme/assets/js/app.js", "theme/assets/css/app.css"],
56
+ reload: ["theme/templates/**/*.twig", "theme/app/**/*.php"],
57
+ // Into the theme: only `theme/` is served, a build beside it is unreachable.
58
+ outDir: "theme/dist",
59
+ }),
60
+ tailwindcss(),
61
+ ],
62
+ });
63
+ ```
64
+
65
+ The package has a default export and a named export (`import { foehn } from '@studiometa/foehn-vite-plugin'`). `foehn()` returns an array of two plugins (`foehn` and `foehn:reload`); put it in `plugins` as is. The types `FoehnPluginOptions` and `ResolvedFoehnPluginOptions` are exported.
66
+
67
+ ### Options
68
+
69
+ | Option | Type | Default | What it does |
70
+ | ---------- | -------------------- | ------------------------- | ------------------------------------------------------------------------------------------- |
71
+ | `input` | `string \| string[]` | required | Entry files or globs. Becomes `build.rollupOptions.input`. |
72
+ | `reload` | `string \| string[]` | `["templates/**/*.twig"]` | Globs watched by the dev server. A change sends a full page reload. |
73
+ | `outDir` | `string` | `"dist"` | Build output, resolved against `themeDir`. Becomes `build.outDir`. |
74
+ | `themeDir` | `string` | `process.cwd()` | Base directory for `input` globs, `reload`, `outDir`, the hot file and the `.ddev/` lookup. |
75
+ | `hotFile` | `string` | `"hot"` | Hot file name, written inside `outDir`. |
76
+
77
+ The plugin also sets `build.manifest: true`. Do not set `build.outDir`, `build.manifest` or `build.rollupOptions.input` yourself; the plugin owns them. In dev it sets `server.forwardConsole: true` and, with DDEV, `server.cors` to the localhost origins and the DDEV site, unless `vite.config.js` sets them.
78
+
79
+ `themeDir` does not change the Vite root. Manifest keys stay relative to the Vite root, but `input` paths are relative to `themeDir`. When you set `themeDir` to a subdirectory, the entry name in PHP is the path from the Vite root, not the string in `input`.
80
+
81
+ ### Globs in `input`
82
+
83
+ An `input` item that contains `*`, `?` or `{` is expanded with fast-glob against `themeDir`:
84
+
85
+ ```js
86
+ foehn({
87
+ input: ["theme/assets/js/*.js", "theme/assets/css/app.css"],
88
+ outDir: "theme/dist",
89
+ });
90
+ ```
91
+
92
+ Each file becomes its own entry. Enqueue each one by its own path (for example `theme/assets/js/editor.js`). Do not glob a directory of modules that `app.js` imports (such as `components/`): each match then becomes a separate entry.
93
+
94
+ ## PHP side: AssetHooks
95
+
96
+ The starter's hook class:
97
+
98
+ ```php
99
+ <?php
100
+
101
+ declare(strict_types=1);
102
+
103
+ namespace App\Hooks;
104
+
105
+ use Studiometa\Foehn\Assets\ViteManifest;
106
+ use Studiometa\Foehn\Attributes\AsAction;
107
+
108
+ final class AssetHooks
109
+ {
110
+ #[AsAction('wp_enqueue_scripts')]
111
+ public function enqueue(): void
112
+ {
113
+ ViteManifest::fromTheme()
114
+ ->enqueue('theme/assets/css/app.css', handle: 'starter-styles')
115
+ ->enqueue('theme/assets/js/app.js', handle: 'starter-app', inFooter: true);
116
+ }
117
+ }
118
+ ```
119
+
120
+ ### API
121
+
122
+ - `ViteManifest::fromTheme(string $distPath = 'dist', string $hotFile = 'hot')`: reads `<parent theme>/<distPath>/`. `$distPath` is relative to the theme directory, so with `outDir: 'theme/dist'` keep the default `'dist'`.
123
+ - `ViteManifest::fromChildTheme(string $distPath = 'dist', string $hotFile = 'hot')`: the same against the child theme.
124
+ - `new ViteManifest(string $distPath, string $distUri, string $hotFile = 'hot')`: absolute directory path and its public URI, for any other layout.
125
+ - `enqueue(string $entry, string $handle, bool $inFooter = false, array $deps = [], string $media = 'all'): self`: fluent.
126
+ - `exists(): bool`: a hot file or a manifest was found.
127
+ - `isDevServer(): bool`: the hot file was found.
128
+
129
+ What `enqueue()` does from a build:
130
+
131
+ - A CSS entry: `wp_enqueue_style("{$handle}-style", ...)`.
132
+ - A JS entry: `wp_enqueue_script($handle, ...)` with a `type="module"` tag, plus one style per file in the chunk's `css` array (`{$handle}-style`, `{$handle}-style-1`, ...).
133
+ - An entry name that is not in the manifest: nothing, silently.
134
+ - Versions are `null`: the file names are content-hashed.
135
+
136
+ From the dev server, every entry (CSS too) is enqueued as a module script from the server URL, after one `vite-client` script. `$inFooter` and `$media` are not used in that mode.
137
+
138
+ ### Conditional and extra entries
139
+
140
+ Add the file to `input`, then enqueue it where it is needed:
141
+
142
+ ```php
143
+ #[AsAction('wp_enqueue_scripts')]
144
+ public function enqueue(): void
145
+ {
146
+ $vite = ViteManifest::fromTheme();
147
+
148
+ $vite->enqueue('theme/assets/css/app.css', handle: 'theme-styles')
149
+ ->enqueue('theme/assets/js/app.js', handle: 'theme-app', inFooter: true);
150
+
151
+ if (is_singular('post')) {
152
+ $vite->enqueue('theme/assets/js/article.js', handle: 'theme-article', inFooter: true);
153
+ }
154
+ }
155
+ ```
156
+
157
+ Use one `ViteManifest` instance per request where you can. Each instance adds its own `script_loader_tag` filter, which rewrites only the handles that instance enqueued.
158
+
159
+ ## JavaScript entry (starter)
160
+
161
+ `theme/assets/js/app.js` registers components by discovery, with `@studiometa/js-toolkit`:
162
+
163
+ ```js
164
+ import { defineManifest, fromMetaGlob, registerManifests } from "@studiometa/js-toolkit";
165
+ import "@studiometa/ui/autoload";
166
+
167
+ const manifest = defineManifest({
168
+ packageName: "starter-theme",
169
+ modules: fromMetaGlob(import.meta.glob("./components/*.js")),
170
+ });
171
+
172
+ registerManifests(manifest);
173
+ ```
174
+
175
+ To add a component, add a file in `theme/assets/js/components/` and put `data-component="ClassName"` in the Twig markup. Do not change `app.js` or `input`. `import.meta.glob` makes lazy chunks, which the manifest and `ViteManifest` handle with no change.
176
+
177
+ ## Gotchas
178
+
179
+ - **Wrong entry name.** `enqueue('assets/js/app.js', ...)` when `input` says `theme/assets/js/app.js` enqueues nothing, with no error. With the default `themeDir`, copy the exact string from `input`. Open `theme/dist/.vite/manifest.json` to see the keys.
180
+ - **Build outside the theme.** `outDir` must be inside the served theme directory (`theme/dist` in the starter). The default `dist` is relative to `themeDir`, which is the project root by default.
181
+ - **Custom hot file name.** The plugin writes the hot file at `<outDir>/<hotFile>`, which is where `ViteManifest::fromTheme()` reads it. If you change `hotFile`, pass the same name as the second argument of `fromTheme()` / `fromChildTheme()`, or `isDevServer()` stays `false`. See [references/dev-server.md](references/dev-server.md).
182
+ - **Stale hot file.** The hot file wins over the manifest. If the page loads from `localhost:5173` after you stop the dev server, a hot file was left behind, for example by a killed or crashed process: delete it.
183
+ - **No assets at all.** No manifest and no hot file means nothing is enqueued. Run `npm run build`, then check `ViteManifest::fromTheme()->exists()`.
184
+ - **Do not add `type="module"` yourself.** `wp_script_add_data($handle, 'type', 'module')` has no effect in WordPress. `ViteManifest` already rewrites the tag.
185
+ - **Do not enqueue the imported CSS by hand.** A JS entry's imported CSS is enqueued by `enqueue()`. A separate CSS `input` (like `app.css`) is its own entry and needs its own `enqueue()` call.
186
+ - **`reload` globs are relative to `themeDir`.** The default `templates/**/*.twig` does not match the starter's `theme/templates/`. Set `reload` explicitly, as the starter does.
187
+ - **`reload` matching is simple.** Changed files are matched with `**`, `*` and `?` only. Brace patterns like `{php,twig}` are watched but never trigger a reload; write one glob per extension.
188
+ - **Browser errors are in a file, not only in the Vite terminal.** With Vite 8 the page sends its console errors and warnings, uncaught errors and unhandled rejections to the dev server. The plugin writes them to `<outDir>/browser-errors.jsonl` with the source file and line. Read them with `wp foehn errors --browser` (`--format=json`, `--level=error,rejection,console`), not by asking for the terminal. `server.forwardConsole: false` turns it off. See [references/dev-server.md](references/dev-server.md#browser-errors).
189
+ - **DDEV proxy.** When `<themeDir>/.ddev/config.yaml` exists, the dev server serves its own routes and every file under the Vite root, and proxies the other requests to the DDEV site. See [references/dev-server.md](references/dev-server.md).
190
+
191
+ ## Related
192
+
193
+ - `foehn` skill: hooks (`#[AsAction]`), the kernel, Twig and the rest of the PHP side.
194
+ - Assets guide: https://studiometa.github.io/foehn-framework/guide/assets.md
195
+ - Starter theme guide: https://studiometa.github.io/foehn-framework/guide/starter-theme.md
196
+ - Hooks guide: https://studiometa.github.io/foehn-framework/guide/hooks.md
@@ -0,0 +1,57 @@
1
+ # Dev server, hot file and DDEV
2
+
3
+ How `npm run dev` (`vite`) works with `@studiometa/foehn-vite-plugin`, and what to check when HMR does not reach WordPress.
4
+
5
+ ## Sequence
6
+
7
+ 1. Vite starts. The plugin's `config` hook expands `input` globs and looks for `<themeDir>/.ddev/config.yaml`.
8
+ 2. When the HTTP server is listening, the plugin writes the hot file at `<themeDir>/<outDir>/<hotFile>` (`theme/dist/hot` in the starter). It creates `outDir` first, so you do not have to build before `npm run dev`. The content is the URL the server listens on, for example `http://localhost:5173`: `https` when you set `server.https`, the port Vite actually took, and `localhost` for a wildcard or loopback host.
9
+ 3. WordPress renders a page. `ViteManifest` finds the hot file in `<distPath>/<hotFile>`, then enqueues `<url>/@vite/client` (handle `vite-client`) and `<url>/<entry>` for each `enqueue()` call, all as `type="module"`.
10
+ 4. A change to a file that matches `reload` sends a full page reload. Changes to JS and CSS go through normal Vite HMR. With Vite 8, the client in the page also sends its console errors and uncaught errors to the server (see [Browser errors](#browser-errors)).
11
+ 5. When the server closes, the plugin deletes the hot file. It also deletes it when Ctrl+C (`SIGINT`) or a closed terminal (`SIGHUP`) stops the process, because Vite closes the server only on `SIGTERM`. `vite build` also deletes it at the end of the build. Only a process that is killed (`SIGKILL`) or crashes leaves the file behind.
12
+
13
+ ## Hot file name
14
+
15
+ `hotFile` is a file name, not a path. The plugin and `ViteManifest` both look for it inside the dist directory, so the defaults agree: `outDir: 'theme/dist'` in `vite.config.js` and `ViteManifest::fromTheme()` with no arguments. If you change `hotFile`, pass the same name as the second argument of `fromTheme()` / `fromChildTheme()`.
16
+
17
+ To check where PHP looks:
18
+
19
+ ```php
20
+ // From wp shell or a test
21
+ $vite = \Studiometa\Foehn\Assets\ViteManifest::fromTheme();
22
+ var_dump($vite->isDevServer());
23
+ ```
24
+
25
+ ## DDEV proxy
26
+
27
+ When `<themeDir>/.ddev/config.yaml` exists, the plugin reads `name` and `router_https_port` from it and sets `server.proxy`:
28
+
29
+ - Target: `https://<name>.ddev.site`, with `:<router_https_port>` when that port is not `443`. The plugin always uses the `ddev.site` domain: it does not read `project_tld` or `additional_fqdns`.
30
+ - `changeOrigin: true`, `secure: false`.
31
+ - Vite keeps every request it can serve: its own routes (`/@vite/client`, `/@fs/`, `/@id/`, `/__…`), `/node_modules/`, the HMR ping, and any path that is a file under the Vite root or the public directory, whatever the query (`?import`, `?direct`, `?v=`). The entries `ViteManifest` enqueues are files under the root, so Vite serves them.
32
+ - Every other request (WordPress pages, the admin, a file that does not exist) goes to DDEV. The HMR websocket stays on Vite.
33
+ - `server.cors` is set to the localhost origins and the DDEV site, unless `vite.config.js` sets it. Vite allows only localhost pages by default, so a page opened on `https://<name>.ddev.site` could not load `/@vite/client` and had no HMR.
34
+
35
+ So you can open the Vite server URL and get the WordPress site through it. Know this when you debug:
36
+
37
+ - The plugin looks for `.ddev/` in `themeDir`, not in parent directories. With the default `themeDir` (the directory you run `vite` from), that is the project root, where the starter keeps `.ddev/`.
38
+ - The proxy is set only when the file exists. Without DDEV, no proxy is set.
39
+
40
+ ## Browser errors
41
+
42
+ The plugin sets `server.forwardConsole: true` when `vite.config.js` does not set it. Vite 8 turns it on by itself only when the Vite process runs inside a coding agent (`AI_AGENT` and similar variables), and a developer usually runs `npm run dev` in their own terminal.
43
+
44
+ - The Vite client in the page wraps `console.error` and `console.warn` and listens for `error` and `unhandledrejection`. It sends each event over the HMR websocket. The server prints it in its terminal as `[vite] (client) [console.error] …`.
45
+ - The plugin listens for the same `vite:forward-console` event and appends one JSON line to `<outDir>/browser-errors.jsonl`: `time`, `level` (`error`, `rejection`, `console`), `class` (`TypeError`, `console.warn`), `message` (2000 characters), `file` and `line` of the first own frame, `stack` (own frames, 8 at most, then `+N other frames`). Own frames are modules under the Vite root outside `node_modules`. Their line is mapped through the module's source map, so a TypeScript file gives the source line. The file is rotated at 256 KB, 3 files at most. `vite build` empties `outDir`, and the log with it.
46
+ - `wp foehn errors --browser` reads `<parent theme>/dist/browser-errors.jsonl`. It has the same options as `wp foehn errors`, with `--level=error,rejection,console`.
47
+ - Other `logLevels` (`server.forwardConsole: { logLevels: ['error', 'warn', 'log'] }`) are written with the class `console.<level>`, such as `console.log`. `server.forwardConsole: false` turns off the terminal output and the file.
48
+ - With Vite 6 or 7 the option does not exist: nothing is sent, and the file is not written.
49
+ - Nothing is written when the page does not load the Vite client: a page from the build, or a page on the DDEV URL whose browser blocks the client (see the `server.cors` line in [DDEV proxy](#ddev-proxy)).
50
+
51
+ ## Checklist when the page has no assets in dev
52
+
53
+ 1. `npm run dev` is running, and `theme/dist/hot` (or `<outDir>/<hotFile>`) exists.
54
+ 2. The hot file holds a URL the browser can reach (the browser loads from it, not PHP).
55
+ 3. The entry names in `enqueue()` are the exact strings in `input`.
56
+ 4. The page HTML has `<script type="module" src=".../@vite/client" id="vite-client">`.
57
+ 5. If you stopped the dev server and the page still points to it, delete the stale hot file.